SkRasterPipeline in SkArenaAlloc
[platform/upstream/libSkiaSharp.git] / src / core / SkDraw_vertices.cpp
1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkArenaAlloc.h"
9 #include "SkAutoBlitterChoose.h"
10 #include "SkColorShader.h"
11 #include "SkDraw.h"
12 #include "SkNx.h"
13 #include "SkPM4fPriv.h"
14 #include "SkRasterClip.h"
15 #include "SkScan.h"
16 #include "SkShader.h"
17 #include "SkString.h"
18 #include "SkVertState.h"
19
20 #include "SkRasterPipeline.h"
21 #include "SkArenaAlloc.h"
22 #include "SkCoreBlitters.h"
23 #include "SkColorSpaceXform.h"
24 #include "SkColorSpace_Base.h"
25
26 struct Matrix43 {
27     float fMat[12];    // column major
28
29     Sk4f map(float x, float y) const {
30         return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]);
31     }
32
33     void setConcat(const Matrix43& a, const SkMatrix& b) {
34         fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY());
35         fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY());
36         fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY());
37         fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY());
38
39         fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY());
40         fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY());
41         fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY());
42         fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY());
43
44         fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8];
45         fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9];
46         fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10];
47         fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11];
48     }
49
50 private:
51     float dot(int index, float x, float y) const {
52         return fMat[index + 0] * x + fMat[index + 4] * y;
53     }
54 };
55
56 static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) {
57     return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine;
58 }
59
60 static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
61                               const SkPoint texs[], SkMatrix* matrix) {
62     SkPoint src[3], dst[3];
63
64     src[0] = texs[state.f0];
65     src[1] = texs[state.f1];
66     src[2] = texs[state.f2];
67     dst[0] = verts[state.f0];
68     dst[1] = verts[state.f1];
69     dst[2] = verts[state.f2];
70     return matrix->setPolyToPoly(src, dst, 3);
71 }
72
73 class SkTriColorShader : public SkShader {
74 public:
75     SkTriColorShader();
76
77     class TriColorShaderContext : public SkShader::Context {
78     public:
79         TriColorShaderContext(const SkTriColorShader& shader, const ContextRec&);
80         ~TriColorShaderContext() override;
81         void shadeSpan(int x, int y, SkPMColor dstC[], int count) override;
82         void shadeSpan4f(int x, int y, SkPM4f dstC[], int count) override;
83
84     private:
85         bool setup(const SkPoint pts[], const SkColor colors[], int, int, int);
86
87         SkMatrix    fDstToUnit;
88         SkPMColor   fColors[3];
89         bool fSetup;
90
91         Matrix43 fM43;
92
93         typedef SkShader::Context INHERITED;
94     };
95
96     struct TriColorShaderData {
97         const SkPoint* pts;
98         const SkColor* colors;
99         const VertState *state;
100     };
101
102     SK_TO_STRING_OVERRIDE()
103
104     // For serialization.  This will never be called.
105     Factory getFactory() const override { sk_throw(); return nullptr; }
106
107     // Supply setup data to context from drawing setup
108     void bindSetupData(TriColorShaderData* setupData) { fSetupData = setupData; }
109
110     // Take the setup data from context when needed.
111     TriColorShaderData* takeSetupData() {
112         TriColorShaderData *data = fSetupData;
113         fSetupData = NULL;
114         return data;
115     }
116
117 protected:
118     Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
119         return alloc->make<TriColorShaderContext>(*this, rec);
120     }
121
122 private:
123     TriColorShaderData *fSetupData;
124
125     typedef SkShader INHERITED;
126 };
127
128 bool SkTriColorShader::TriColorShaderContext::setup(const SkPoint pts[], const SkColor colors[],
129                                                     int index0, int index1, int index2) {
130
131     fColors[0] = SkPreMultiplyColor(colors[index0]);
132     fColors[1] = SkPreMultiplyColor(colors[index1]);
133     fColors[2] = SkPreMultiplyColor(colors[index2]);
134
135     SkMatrix m, im;
136     m.reset();
137     m.set(0, pts[index1].fX - pts[index0].fX);
138     m.set(1, pts[index2].fX - pts[index0].fX);
139     m.set(2, pts[index0].fX);
140     m.set(3, pts[index1].fY - pts[index0].fY);
141     m.set(4, pts[index2].fY - pts[index0].fY);
142     m.set(5, pts[index0].fY);
143     if (!m.invert(&im)) {
144         return false;
145     }
146     // We can't call getTotalInverse(), because we explicitly don't want to look at the localmatrix
147     // as our interators are intrinsically tied to the vertices, and nothing else.
148     SkMatrix ctmInv;
149     if (!this->getCTM().invert(&ctmInv)) {
150         return false;
151     }
152     // TODO replace INV(m) * INV(ctm) with INV(ctm * m)
153     fDstToUnit.setConcat(im, ctmInv);
154
155     Sk4f alpha(this->getPaintAlpha() * (1.0f / 255)),
156     c0 = SkPM4f::FromPMColor(fColors[0]).to4f() * alpha,
157     c1 = SkPM4f::FromPMColor(fColors[1]).to4f() * alpha,
158     c2 = SkPM4f::FromPMColor(fColors[2]).to4f() * alpha;
159
160     Matrix43 colorm;
161     (c1 - c0).store(&colorm.fMat[0]);
162     (c2 - c0).store(&colorm.fMat[4]);
163     c0.store(&colorm.fMat[8]);
164     fM43.setConcat(colorm, fDstToUnit);
165
166     return true;
167 }
168
169 #include "SkColorPriv.h"
170 #include "SkComposeShader.h"
171
172 static int ScalarTo256(SkScalar v) {
173     return static_cast<int>(SkScalarPin(v, 0, 1) * 256 + 0.5);
174 }
175
176 SkTriColorShader::SkTriColorShader()
177 : INHERITED(NULL)
178 , fSetupData(NULL) {}
179
180 SkTriColorShader::TriColorShaderContext::TriColorShaderContext(const SkTriColorShader& shader,
181                                                                const ContextRec& rec)
182 : INHERITED(shader, rec)
183 , fSetup(false) {}
184
185 SkTriColorShader::TriColorShaderContext::~TriColorShaderContext() {}
186
187 void SkTriColorShader::TriColorShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
188     SkTriColorShader* parent = static_cast<SkTriColorShader*>(const_cast<SkShader*>(&fShader));
189     TriColorShaderData* set = parent->takeSetupData();
190     if (set) {
191         fSetup = setup(set->pts, set->colors, set->state->f0, set->state->f1, set->state->f2);
192     }
193
194     if (!fSetup) {
195         // Invalid matrices. Not checked before so no need to assert.
196         return;
197     }
198
199     const int alphaScale = Sk255To256(this->getPaintAlpha());
200
201     SkPoint src;
202
203     fDstToUnit.mapXY(SkIntToScalar(x) + 0.5, SkIntToScalar(y) + 0.5, &src);
204     for (int i = 0; i < count; i++) {
205         int scale1 = ScalarTo256(src.fX);
206         int scale2 = ScalarTo256(src.fY);
207         int scale0 = 256 - scale1 - scale2;
208         if (scale0 < 0) {
209             if (scale1 > scale2) {
210                 scale2 = 256 - scale1;
211             } else {
212                 scale1 = 256 - scale2;
213             }
214             scale0 = 0;
215         }
216
217         if (256 != alphaScale) {
218             scale0 = SkAlphaMul(scale0, alphaScale);
219             scale1 = SkAlphaMul(scale1, alphaScale);
220             scale2 = SkAlphaMul(scale2, alphaScale);
221         }
222
223         dstC[i] = SkAlphaMulQ(fColors[0], scale0) +
224         SkAlphaMulQ(fColors[1], scale1) +
225         SkAlphaMulQ(fColors[2], scale2);
226
227         src.fX += fDstToUnit.getScaleX();
228         src.fY += fDstToUnit.getSkewY();
229     }
230 }
231
232 void SkTriColorShader::TriColorShaderContext::shadeSpan4f(int x, int y, SkPM4f dstC[], int count) {
233     SkTriColorShader* parent = static_cast<SkTriColorShader*>(const_cast<SkShader*>(&fShader));
234     TriColorShaderData* set = parent->takeSetupData();
235     if (set) {
236         fSetup = setup(set->pts, set->colors, set->state->f0, set->state->f1, set->state->f2);
237     }
238
239     if (!fSetup) {
240         // Invalid matrices. Not checked before so no need to assert.
241         return;
242     }
243
244     Sk4f c  = fM43.map(SkIntToScalar(x) + 0.5, SkIntToScalar(y) + 0.5),
245     dc = Sk4f::Load(&fM43.fMat[0]),
246     zero(0.0f),
247     one(1.0f);
248
249     for (int i = 0; i < count; i++) {
250         // We don't expect to be wildly out of 0...1, but we pin just because of minor
251         // numerical imprecision.
252         Sk4f::Min(Sk4f::Max(c, zero), Sk4f::Min(c[3], one)).store(dstC + i);
253         c += dc;
254     }
255 }
256
257 #ifndef SK_IGNORE_TO_STRING
258 void SkTriColorShader::toString(SkString* str) const {
259     str->append("SkTriColorShader: (");
260
261     this->INHERITED::toString(str);
262
263     str->append(")");
264 }
265 #endif
266
267
268 namespace {
269
270     // Similar to SkLocalMatrixShader, but composes the local matrix with the CTM (instead
271     // of composing with the inherited local matrix):
272     //
273     //   rec' = {rec.ctm x localMatrix, rec.localMatrix}
274     //
275     // (as opposed to rec' = {rec.ctm, rec.localMatrix x localMatrix})
276     //
277     class SkLocalInnerMatrixShader final : public SkShader {
278     public:
279         SkLocalInnerMatrixShader(sk_sp<SkShader> proxy, const SkMatrix& localMatrix)
280         : INHERITED(&localMatrix)
281         , fProxyShader(std::move(proxy)) {}
282
283         Factory getFactory() const override {
284             SkASSERT(false);
285             return nullptr;
286         }
287
288     protected:
289         void flatten(SkWriteBuffer&) const override {
290             SkASSERT(false);
291         }
292
293         Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
294             SkMatrix adjustedCTM = SkMatrix::Concat(*rec.fMatrix, this->getLocalMatrix());
295             ContextRec newRec(rec);
296             newRec.fMatrix = &adjustedCTM;
297             return fProxyShader->makeContext(newRec, alloc);
298         }
299
300         bool onAppendStages(SkRasterPipeline* p, SkColorSpace* cs, SkArenaAlloc* alloc,
301                             const SkMatrix& ctm, const SkPaint& paint,
302                             const SkMatrix* localM) const override {
303             // We control the shader graph ancestors, so we know there's no local matrix being
304             // injected before this.
305             SkASSERT(!localM);
306
307             SkMatrix adjustedCTM = SkMatrix::Concat(ctm, this->getLocalMatrix());
308             return fProxyShader->appendStages(p, cs, alloc, adjustedCTM, paint);
309         }
310
311     private:
312         sk_sp<SkShader> fProxyShader;
313
314         typedef SkShader INHERITED;
315     };
316
317     sk_sp<SkShader> MakeTextureShader(const VertState& state, const SkPoint verts[],
318                                       const SkPoint texs[], const SkPaint& paint,
319                                       SkColorSpace* dstColorSpace,
320                                       SkArenaAlloc* alloc) {
321         SkASSERT(paint.getShader());
322
323         const auto& p0 = texs[state.f0],
324         p1 = texs[state.f1],
325         p2 = texs[state.f2];
326
327         if (p0 != p1 || p0 != p2) {
328             // Common case (non-collapsed texture coordinates).
329             // Map the texture to vertices using a local transform.
330
331             // We cannot use a plain SkLocalMatrix shader, because we need the texture matrix
332             // to compose next to the CTM.
333             SkMatrix localMatrix;
334             return texture_to_matrix(state, verts, texs, &localMatrix)
335             ? alloc->makeSkSp<SkLocalInnerMatrixShader>(paint.refShader(), localMatrix)
336             : nullptr;
337         }
338
339         // Collapsed texture coordinates special case.
340         // The texture is a solid color, sampled at the given point.
341         SkMatrix shaderInvLocalMatrix;
342         SkAssertResult(paint.getShader()->getLocalMatrix().invert(&shaderInvLocalMatrix));
343
344         const auto sample       = SkPoint::Make(0.5f, 0.5f);
345         const auto mappedSample = shaderInvLocalMatrix.mapXY(sample.x(), sample.y()),
346         mappedPoint  = shaderInvLocalMatrix.mapXY(p0.x(), p0.y());
347         const auto localMatrix  = SkMatrix::MakeTrans(mappedSample.x() - mappedPoint.x(),
348                                                       mappedSample.y() - mappedPoint.y());
349
350         SkShader::ContextRec rec(paint, SkMatrix::I(), &localMatrix,
351                                  SkShader::ContextRec::kPMColor_DstType, dstColorSpace);
352         auto* ctx = paint.getShader()->makeContext(rec, alloc);
353         if (!ctx) {
354             return nullptr;
355         }
356
357         SkPMColor pmColor;
358         ctx->shadeSpan(SkScalarFloorToInt(sample.x()), SkScalarFloorToInt(sample.y()), &pmColor, 1);
359
360         // no need to keep this temp context around.
361         alloc->reset();
362
363         return alloc->makeSkSp<SkColorShader>(SkUnPreMultiply::PMColorToColor(pmColor));
364     }
365 } // anonymous ns
366
367 static bool update_tricolor_matrix(const SkMatrix& ctmInv,
368                                    const SkPoint pts[], const SkPM4f colors[],
369                                    int index0, int index1, int index2, Matrix43* result) {
370     SkMatrix m, im;
371     m.reset();
372     m.set(0, pts[index1].fX - pts[index0].fX);
373     m.set(1, pts[index2].fX - pts[index0].fX);
374     m.set(2, pts[index0].fX);
375     m.set(3, pts[index1].fY - pts[index0].fY);
376     m.set(4, pts[index2].fY - pts[index0].fY);
377     m.set(5, pts[index0].fY);
378     if (!m.invert(&im)) {
379         return false;
380     }
381
382     SkMatrix dstToUnit;
383     dstToUnit.setConcat(im, ctmInv);
384
385     Sk4f c0 = colors[index0].to4f(),
386          c1 = colors[index1].to4f(),
387          c2 = colors[index2].to4f();
388
389     Matrix43 colorm;
390     (c1 - c0).store(&colorm.fMat[0]);
391     (c2 - c0).store(&colorm.fMat[4]);
392     c0.store(&colorm.fMat[8]);
393     result->setConcat(colorm, dstToUnit);
394     return true;
395 }
396
397 static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS,
398                               SkArenaAlloc* alloc) {
399     SkPM4f* dst = alloc->makeArray<SkPM4f>(count);
400     if (!deviceCS) {
401         for (int i = 0; i < count; ++i) {
402             dst[i] = SkPM4f_from_SkColor(src[i], nullptr);
403         }
404     } else {
405         auto srcCS = SkColorSpace::MakeSRGB();
406         auto dstCS = as_CSB(deviceCS)->makeLinearGamma();
407         SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst,
408                                  srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src,
409                                  count, SkColorSpaceXform::kPremul_AlphaOp);
410     }
411     return dst;
412 }
413
414 static bool compute_is_opaque(const SkColor colors[], int count) {
415     uint32_t c = ~0;
416     for (int i = 0; i < count; ++i) {
417         c &= colors[i];
418     }
419     return SkColorGetA(c) == 0xFF;
420 }
421
422 void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count,
423                           const SkPoint vertices[], const SkPoint textures[],
424                           const SkColor colors[], SkBlendMode bmode,
425                           const uint16_t indices[], int indexCount,
426                           const SkPaint& paint) const {
427     SkASSERT(0 == count || vertices);
428
429     // abort early if there is nothing to draw
430     if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) {
431         return;
432     }
433     SkMatrix ctmInv;
434     if (!fMatrix->invert(&ctmInv)) {
435         return;
436     }
437
438     // transform out vertices into device coordinates
439     SkAutoSTMalloc<16, SkPoint> storage(count);
440     SkPoint* devVerts = storage.get();
441     fMatrix->mapPoints(devVerts, vertices, count);
442
443     /*
444      We can draw the vertices in 1 of 4 ways:
445
446      - solid color (no shader/texture[], no colors[])
447      - just colors (no shader/texture[], has colors[])
448      - just texture (has shader/texture[], no colors[])
449      - colors * texture (has shader/texture[], has colors[])
450
451      Thus for texture drawing, we need both texture[] and a shader.
452      */
453
454     if (colors && !textures) {
455         char             arenaStorage[4096];
456         SkArenaAlloc     alloc(arenaStorage, sizeof(storage));
457         Matrix43         matrix43;
458         SkRasterPipeline shaderPipeline(&alloc);
459
460         // Convert the SkColors into float colors. The conversion depends on some conditions:
461         // - If the pixmap has a dst colorspace, we have to be "color-correct".
462         //   Do we map into dst-colorspace before or after we interpolate?
463         // - We have to decide when to apply per-color alpha (before or after we interpolate)
464         //
465         // For now, we will take a simple approach, but recognize this is just a start:
466         // - convert colors into dst colorspace before interpolation (matches gradients)
467         // - apply per-color alpha before interpolation (matches old version of vertices)
468         //
469         SkPM4f* dstColors = convert_colors(colors, count, fDst.colorSpace(), &alloc);
470
471         bool is_opaque;
472         if (paint.getAlpha() == 0xff) {
473             is_opaque = compute_is_opaque(colors, count);
474         } else {
475             is_opaque = false;
476             Sk4f alpha = paint.getAlpha() * (1/255.0f);
477             for (int i = 0; i < count; i++) {
478                 (dstColors[i].to4f() * alpha).store(dstColors + i);
479             }
480         }
481
482         shaderPipeline.append(SkRasterPipeline::matrix_4x3, &matrix43);
483         // In theory we should never need to clamp. However, either due to imprecision in our
484         // matrix43, or the scan converter passing us pixel centers that in fact are not within
485         // the triangle, we do see occasional (slightly) out-of-range values, so we add these
486         // clamp stages. It would be nice to find a way to detect when these are not needed.
487         shaderPipeline.append(SkRasterPipeline::clamp_0);
488         shaderPipeline.append(SkRasterPipeline::clamp_a);
489
490         bool wants_dither = paint.isDither();
491         auto blitter = SkCreateRasterPipelineBlitter(fDst, paint, shaderPipeline,
492                                                      is_opaque, wants_dither, &alloc);
493         SkASSERT(!blitter->isNullBlitter());
494
495         // setup our state and function pointer for iterating triangles
496         VertState       state(count, indices, indexCount);
497         VertState::Proc vertProc = state.chooseProc(vmode);
498
499         while (vertProc(&state)) {
500             SkPoint tmp[] = {
501                 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
502             };
503             if (update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2,
504                                        &matrix43)) {
505                 SkScan::FillTriangle(tmp, *fRC, blitter);
506             }
507         }
508         return;
509     }
510
511     auto triShader = sk_make_sp<SkTriColorShader>();
512     SkPaint p(paint);
513
514     SkShader* shader = p.getShader();
515     if (nullptr == shader) {
516         // if we have no shader, we ignore the texture coordinates
517         textures = nullptr;
518     } else if (nullptr == textures) {
519         // if we don't have texture coordinates, ignore the shader
520         p.setShader(nullptr);
521         shader = nullptr;
522     }
523
524     // setup the custom shader (if needed)
525     if (colors) {
526         if (nullptr == textures) {
527             // just colors (no texture)
528             p.setShader(triShader);
529         } else {
530             // colors * texture
531             SkASSERT(shader);
532             p.setShader(SkShader::MakeComposeShader(triShader, sk_ref_sp(shader), bmode));
533         }
534     }
535
536     SkAutoBlitterChoose blitter(fDst, *fMatrix, p);
537     // Abort early if we failed to create a shader context.
538     if (blitter->isNullBlitter()) {
539         return;
540     }
541
542     // setup our state and function pointer for iterating triangles
543     VertState       state(count, indices, indexCount);
544     VertState::Proc vertProc = state.chooseProc(vmode);
545
546     if (textures || colors) {
547         SkTriColorShader::TriColorShaderData verticesSetup = { vertices, colors, &state };
548
549         while (vertProc(&state)) {
550             auto* blitterPtr = blitter.get();
551
552             // We're going to allocate at most
553             //
554             //   * one SkLocalMatrixShader OR one SkColorShader
555             //   * one SkComposeShader
556             //   * one SkAutoBlitterChoose
557             //
558             static constexpr size_t kAllocSize =
559             sizeof(SkAutoBlitterChoose) + sizeof(SkComposeShader) +
560             SkTMax(sizeof(SkLocalInnerMatrixShader), sizeof(SkColorShader));
561             char allocBuffer[kAllocSize];
562             SkArenaAlloc alloc(allocBuffer);
563
564             if (textures) {
565                 sk_sp<SkShader> texShader = MakeTextureShader(state, vertices, textures, paint,
566                                                               fDst.colorSpace(), &alloc);
567                 if (texShader) {
568                     SkPaint localPaint(p);
569                     localPaint.setShader(colors
570                                          ? alloc.makeSkSp<SkComposeShader>(triShader, std::move(texShader), bmode)
571                                          : std::move(texShader));
572
573                     blitterPtr = alloc.make<SkAutoBlitterChoose>(fDst, *fMatrix, localPaint)->get();
574                     if (blitterPtr->isNullBlitter()) {
575                         continue;
576                     }
577                 }
578             }
579             if (colors) {
580                 triShader->bindSetupData(&verticesSetup);
581             }
582
583             SkPoint tmp[] = {
584                 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
585             };
586             SkScan::FillTriangle(tmp, *fRC, blitterPtr);
587             triShader->bindSetupData(nullptr);
588         }
589     } else {
590         // no colors[] and no texture, stroke hairlines with paint's color.
591         SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias());
592         const SkRasterClip& clip = *fRC;
593         while (vertProc(&state)) {
594             SkPoint array[] = {
595                 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0]
596             };
597             hairProc(array, 4, clip, blitter.get());
598         }
599     }
600 }