SkRasterPipeline in SkArenaAlloc
[platform/upstream/libSkiaSharp.git] / src / core / SkShader.cpp
1 /*
2  * Copyright 2006 The Android Open Source Project
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 "SkAtomics.h"
10 #include "SkBitmapProcShader.h"
11 #include "SkColorShader.h"
12 #include "SkEmptyShader.h"
13 #include "SkMallocPixelRef.h"
14 #include "SkPaint.h"
15 #include "SkPicture.h"
16 #include "SkPictureShader.h"
17 #include "SkPM4fPriv.h"
18 #include "SkRasterPipeline.h"
19 #include "SkReadBuffer.h"
20 #include "SkScalar.h"
21 #include "SkShader.h"
22 #include "SkTLazy.h"
23 #include "SkWriteBuffer.h"
24 #include "../jumper/SkJumper.h"
25
26 #if SK_SUPPORT_GPU
27 #include "GrFragmentProcessor.h"
28 #endif
29
30 //#define SK_TRACK_SHADER_LIFETIME
31
32 #ifdef SK_TRACK_SHADER_LIFETIME
33     static int32_t gShaderCounter;
34 #endif
35
36 static inline void inc_shader_counter() {
37 #ifdef SK_TRACK_SHADER_LIFETIME
38     int32_t prev = sk_atomic_inc(&gShaderCounter);
39     SkDebugf("+++ shader counter %d\n", prev + 1);
40 #endif
41 }
42 static inline void dec_shader_counter() {
43 #ifdef SK_TRACK_SHADER_LIFETIME
44     int32_t prev = sk_atomic_dec(&gShaderCounter);
45     SkDebugf("--- shader counter %d\n", prev - 1);
46 #endif
47 }
48
49 SkShader::SkShader(const SkMatrix* localMatrix) {
50     inc_shader_counter();
51     if (localMatrix) {
52         fLocalMatrix = *localMatrix;
53     } else {
54         fLocalMatrix.reset();
55     }
56     // Pre-cache so future calls to fLocalMatrix.getType() are threadsafe.
57     (void)fLocalMatrix.getType();
58 }
59
60 SkShader::~SkShader() {
61     dec_shader_counter();
62 }
63
64 void SkShader::flatten(SkWriteBuffer& buffer) const {
65     this->INHERITED::flatten(buffer);
66     bool hasLocalM = !fLocalMatrix.isIdentity();
67     buffer.writeBool(hasLocalM);
68     if (hasLocalM) {
69         buffer.writeMatrix(fLocalMatrix);
70     }
71 }
72
73 bool SkShader::computeTotalInverse(const SkMatrix& ctm,
74                                    const SkMatrix* outerLocalMatrix,
75                                    SkMatrix* totalInverse) const {
76     SkMatrix total = SkMatrix::Concat(ctm, fLocalMatrix);
77     if (outerLocalMatrix) {
78         total.preConcat(*outerLocalMatrix);
79     }
80
81     return total.invert(totalInverse);
82 }
83
84 bool SkShader::asLuminanceColor(SkColor* colorPtr) const {
85     SkColor storage;
86     if (nullptr == colorPtr) {
87         colorPtr = &storage;
88     }
89     if (this->onAsLuminanceColor(colorPtr)) {
90         *colorPtr = SkColorSetA(*colorPtr, 0xFF);   // we only return opaque
91         return true;
92     }
93     return false;
94 }
95
96 SkShader::Context* SkShader::makeContext(const ContextRec& rec, SkArenaAlloc* alloc) const {
97     if (!this->computeTotalInverse(*rec.fMatrix, rec.fLocalMatrix, nullptr)) {
98         return nullptr;
99     }
100     return this->onMakeContext(rec, alloc);
101 }
102
103 SkShader::Context::Context(const SkShader& shader, const ContextRec& rec)
104     : fShader(shader), fCTM(*rec.fMatrix)
105 {
106     // We should never use a context for RP-only shaders.
107     SkASSERT(!shader.isRasterPipelineOnly());
108
109     // Because the context parameters must be valid at this point, we know that the matrix is
110     // invertible.
111     SkAssertResult(fShader.computeTotalInverse(*rec.fMatrix, rec.fLocalMatrix, &fTotalInverse));
112     fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse);
113
114     fPaintAlpha = rec.fPaint->getAlpha();
115 }
116
117 SkShader::Context::~Context() {}
118
119 SkShader::Context::ShadeProc SkShader::Context::asAShadeProc(void** ctx) {
120     return nullptr;
121 }
122
123 void SkShader::Context::shadeSpan4f(int x, int y, SkPM4f dst[], int count) {
124     const int N = 128;
125     SkPMColor tmp[N];
126     while (count > 0) {
127         int n = SkTMin(count, N);
128         this->shadeSpan(x, y, tmp, n);
129         for (int i = 0; i < n; ++i) {
130             dst[i] = SkPM4f::FromPMColor(tmp[i]);
131         }
132         dst += n;
133         x += n;
134         count -= n;
135     }
136 }
137
138 #include "SkColorPriv.h"
139
140 #define kTempColorQuadCount 6   // balance between speed (larger) and saving stack-space
141 #define kTempColorCount     (kTempColorQuadCount << 2)
142
143 #ifdef SK_CPU_BENDIAN
144     #define SkU32BitShiftToByteOffset(shift)    (3 - ((shift) >> 3))
145 #else
146     #define SkU32BitShiftToByteOffset(shift)    ((shift) >> 3)
147 #endif
148
149 void SkShader::Context::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) {
150     SkASSERT(count > 0);
151
152     SkPMColor   colors[kTempColorCount];
153
154     while ((count -= kTempColorCount) >= 0) {
155         this->shadeSpan(x, y, colors, kTempColorCount);
156         x += kTempColorCount;
157
158         const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
159         int quads = kTempColorQuadCount;
160         do {
161             U8CPU a0 = srcA[0];
162             U8CPU a1 = srcA[4];
163             U8CPU a2 = srcA[8];
164             U8CPU a3 = srcA[12];
165             srcA += 4*4;
166             *alpha++ = SkToU8(a0);
167             *alpha++ = SkToU8(a1);
168             *alpha++ = SkToU8(a2);
169             *alpha++ = SkToU8(a3);
170         } while (--quads != 0);
171     }
172     SkASSERT(count < 0);
173     SkASSERT(count + kTempColorCount >= 0);
174     if (count += kTempColorCount) {
175         this->shadeSpan(x, y, colors, count);
176
177         const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
178         do {
179             *alpha++ = *srcA;
180             srcA += 4;
181         } while (--count != 0);
182     }
183 #if 0
184     do {
185         int n = count;
186         if (n > kTempColorCount)
187             n = kTempColorCount;
188         SkASSERT(n > 0);
189
190         this->shadeSpan(x, y, colors, n);
191         x += n;
192         count -= n;
193
194         const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT);
195         do {
196             *alpha++ = *srcA;
197             srcA += 4;
198         } while (--n != 0);
199     } while (count > 0);
200 #endif
201 }
202
203 SkShader::Context::MatrixClass SkShader::Context::ComputeMatrixClass(const SkMatrix& mat) {
204     MatrixClass mc = kLinear_MatrixClass;
205
206     if (mat.hasPerspective()) {
207         if (mat.isFixedStepInX()) {
208             mc = kFixedStepInX_MatrixClass;
209         } else {
210             mc = kPerspective_MatrixClass;
211         }
212     }
213     return mc;
214 }
215
216 //////////////////////////////////////////////////////////////////////////////
217
218 SkShader::GradientType SkShader::asAGradient(GradientInfo* info) const {
219     return kNone_GradientType;
220 }
221
222 #if SK_SUPPORT_GPU
223 sk_sp<GrFragmentProcessor> SkShader::asFragmentProcessor(const AsFPArgs&) const {
224     return nullptr;
225 }
226 #endif
227
228 sk_sp<SkShader> SkShader::makeAsALocalMatrixShader(SkMatrix*) const {
229     return nullptr;
230 }
231
232 sk_sp<SkShader> SkShader::MakeEmptyShader() { return sk_make_sp<SkEmptyShader>(); }
233
234 sk_sp<SkShader> SkShader::MakeColorShader(SkColor color) { return sk_make_sp<SkColorShader>(color); }
235
236 sk_sp<SkShader> SkShader::MakeBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy,
237                                            const SkMatrix* localMatrix) {
238     if (localMatrix && !localMatrix->invert(nullptr)) {
239         return nullptr;
240     }
241     return SkMakeBitmapShader(src, tmx, tmy, localMatrix, kIfMutable_SkCopyPixelsMode);
242 }
243
244 sk_sp<SkShader> SkShader::MakePictureShader(sk_sp<SkPicture> src, TileMode tmx, TileMode tmy,
245                                             const SkMatrix* localMatrix, const SkRect* tile) {
246     if (localMatrix && !localMatrix->invert(nullptr)) {
247         return nullptr;
248     }
249     return SkPictureShader::Make(std::move(src), tmx, tmy, localMatrix, tile);
250 }
251
252 #ifndef SK_IGNORE_TO_STRING
253 void SkShader::toString(SkString* str) const {
254     if (!fLocalMatrix.isIdentity()) {
255         str->append(" ");
256         fLocalMatrix.toString(str);
257     }
258 }
259 #endif
260
261 bool SkShader::appendStages(SkRasterPipeline* p,
262                             SkColorSpace* dstCS,
263                             SkArenaAlloc* alloc,
264                             const SkMatrix& ctm,
265                             const SkPaint& paint,
266                             const SkMatrix* localM) const {
267     SkRasterPipeline_<256> subclass;
268     if (this->onAppendStages(&subclass, dstCS, alloc, ctm, paint, localM)) {
269         p->extend(subclass);
270         return true;
271     }
272
273     // SkShader::Context::shadeSpan4f() handles the paint opacity internally,
274     // but SkRasterPipelineBlitter applies it as a separate stage.
275     // We skip the internal shadeSpan4f() step by forcing the paint opaque.
276     SkTCopyOnFirstWrite<SkPaint> opaquePaint(paint);
277     if (paint.getAlpha() != SK_AlphaOPAQUE) {
278         opaquePaint.writable()->setAlpha(SK_AlphaOPAQUE);
279     }
280
281     ContextRec rec(*opaquePaint, ctm, localM, ContextRec::kPM4f_DstType, dstCS);
282
283     struct CallbackCtx : SkJumper_CallbackCtx {
284         sk_sp<SkShader> shader;
285         Context*        ctx;
286     };
287     auto cb = alloc->make<CallbackCtx>();
288     cb->shader = dstCS ? SkColorSpaceXformer::Make(sk_ref_sp(dstCS))->apply(this)
289                        : sk_ref_sp(const_cast<SkShader*>(this));
290     cb->ctx = cb->shader->makeContext(rec, alloc);
291     cb->fn  = [](SkJumper_CallbackCtx* self, int active_pixels) {
292         auto c = (CallbackCtx*)self;
293         int x = (int)c->rgba[0],
294             y = (int)c->rgba[1];
295         c->ctx->shadeSpan4f(x,y, (SkPM4f*)c->rgba, active_pixels);
296     };
297
298     if (cb->ctx) {
299         p->append(SkRasterPipeline::callback, cb);
300         return true;
301     }
302     return false;
303 }
304
305 bool SkShader::onAppendStages(SkRasterPipeline* p,
306                               SkColorSpace* dstCS,
307                               SkArenaAlloc* alloc,
308                               const SkMatrix& ctm,
309                               const SkPaint& paint,
310                               const SkMatrix* localM) const {
311     return false;
312 }
313
314 ///////////////////////////////////////////////////////////////////////////////////////////////////
315
316 sk_sp<SkFlattenable> SkEmptyShader::CreateProc(SkReadBuffer&) {
317     return SkShader::MakeEmptyShader();
318 }
319
320 #ifndef SK_IGNORE_TO_STRING
321 #include "SkEmptyShader.h"
322
323 void SkEmptyShader::toString(SkString* str) const {
324     str->append("SkEmptyShader: (");
325
326     this->INHERITED::toString(str);
327
328     str->append(")");
329 }
330 #endif