• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "include/core/SkMallocPixelRef.h"
9 #include "include/core/SkPaint.h"
10 #include "include/core/SkPicture.h"
11 #include "include/core/SkScalar.h"
12 #include "src/core/SkArenaAlloc.h"
13 #include "src/core/SkColorSpacePriv.h"
14 #include "src/core/SkColorSpaceXformSteps.h"
15 #include "src/core/SkMatrixProvider.h"
16 #include "src/core/SkRasterPipeline.h"
17 #include "src/core/SkReadBuffer.h"
18 #include "src/core/SkTLazy.h"
19 #include "src/core/SkVM.h"
20 #include "src/core/SkWriteBuffer.h"
21 #include "src/shaders/SkBitmapProcShader.h"
22 #include "src/shaders/SkColorShader.h"
23 #include "src/shaders/SkEmptyShader.h"
24 #include "src/shaders/SkImageShader.h"
25 #include "src/shaders/SkPictureShader.h"
26 #include "src/shaders/SkShaderBase.h"
27 
28 #if SK_SUPPORT_GPU
29 #include "src/gpu/GrFragmentProcessor.h"
30 #endif
31 
SkShaderBase(const SkMatrix * localMatrix)32 SkShaderBase::SkShaderBase(const SkMatrix* localMatrix)
33     : fLocalMatrix(localMatrix ? *localMatrix : SkMatrix::I()) {
34     // Pre-cache so future calls to fLocalMatrix.getType() are threadsafe.
35     (void)fLocalMatrix.getType();
36 }
37 
~SkShaderBase()38 SkShaderBase::~SkShaderBase() {}
39 
flatten(SkWriteBuffer & buffer) const40 void SkShaderBase::flatten(SkWriteBuffer& buffer) const {
41     this->INHERITED::flatten(buffer);
42     bool hasLocalM = !fLocalMatrix.isIdentity();
43     buffer.writeBool(hasLocalM);
44     if (hasLocalM) {
45         buffer.writeMatrix(fLocalMatrix);
46     }
47 }
48 
49 SkTCopyOnFirstWrite<SkMatrix>
totalLocalMatrix(const SkMatrix * preLocalMatrix) const50 SkShaderBase::totalLocalMatrix(const SkMatrix* preLocalMatrix) const {
51     SkTCopyOnFirstWrite<SkMatrix> m(fLocalMatrix);
52 
53     if (preLocalMatrix) {
54         m.writable()->preConcat(*preLocalMatrix);
55     }
56 
57     return m;
58 }
59 
computeTotalInverse(const SkMatrix & ctm,const SkMatrix * outerLocalMatrix,SkMatrix * totalInverse) const60 bool SkShaderBase::computeTotalInverse(const SkMatrix& ctm,
61                                        const SkMatrix* outerLocalMatrix,
62                                        SkMatrix* totalInverse) const {
63     return SkMatrix::Concat(ctm, *this->totalLocalMatrix(outerLocalMatrix)).invert(totalInverse);
64 }
65 
asLuminanceColor(SkColor * colorPtr) const66 bool SkShaderBase::asLuminanceColor(SkColor* colorPtr) const {
67     SkColor storage;
68     if (nullptr == colorPtr) {
69         colorPtr = &storage;
70     }
71     if (this->onAsLuminanceColor(colorPtr)) {
72         *colorPtr = SkColorSetA(*colorPtr, 0xFF);   // we only return opaque
73         return true;
74     }
75     return false;
76 }
77 
makeContext(const ContextRec & rec,SkArenaAlloc * alloc) const78 SkShaderBase::Context* SkShaderBase::makeContext(const ContextRec& rec, SkArenaAlloc* alloc) const {
79 #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
80     // We always fall back to raster pipeline when perspective is present.
81     if (rec.fMatrix->hasPerspective() ||
82         fLocalMatrix.hasPerspective() ||
83         (rec.fLocalMatrix && rec.fLocalMatrix->hasPerspective()) ||
84         !this->computeTotalInverse(*rec.fMatrix, rec.fLocalMatrix, nullptr)) {
85         return nullptr;
86     }
87 
88     return this->onMakeContext(rec, alloc);
89 #else
90     return nullptr;
91 #endif
92 }
93 
Context(const SkShaderBase & shader,const ContextRec & rec)94 SkShaderBase::Context::Context(const SkShaderBase& shader, const ContextRec& rec)
95     : fShader(shader), fCTM(*rec.fMatrix)
96 {
97     // We should never use a context with perspective.
98     SkASSERT(!rec.fMatrix->hasPerspective());
99     SkASSERT(!rec.fLocalMatrix || !rec.fLocalMatrix->hasPerspective());
100     SkASSERT(!shader.getLocalMatrix().hasPerspective());
101 
102     // Because the context parameters must be valid at this point, we know that the matrix is
103     // invertible.
104     SkAssertResult(fShader.computeTotalInverse(*rec.fMatrix, rec.fLocalMatrix, &fTotalInverse));
105 
106     fPaintAlpha = rec.fPaintAlpha;
107 }
108 
~Context()109 SkShaderBase::Context::~Context() {}
110 
isLegacyCompatible(SkColorSpace * shaderColorSpace) const111 bool SkShaderBase::ContextRec::isLegacyCompatible(SkColorSpace* shaderColorSpace) const {
112     // In legacy pipelines, shaders always produce premul (or opaque) and the destination is also
113     // always premul (or opaque).  (And those "or opaque" caveats won't make any difference here.)
114     SkAlphaType shaderAT = kPremul_SkAlphaType,
115                    dstAT = kPremul_SkAlphaType;
116     return 0 == SkColorSpaceXformSteps{shaderColorSpace, shaderAT,
117                                          fDstColorSpace,    dstAT}.flags.mask();
118 }
119 
isAImage(SkMatrix * localMatrix,SkTileMode xy[2]) const120 SkImage* SkShader::isAImage(SkMatrix* localMatrix, SkTileMode xy[2]) const {
121     return as_SB(this)->onIsAImage(localMatrix, xy);
122 }
123 
asAGradient(GradientInfo * info) const124 SkShader::GradientType SkShader::asAGradient(GradientInfo* info) const {
125     return kNone_GradientType;
126 }
127 
128 #if SK_SUPPORT_GPU
asFragmentProcessor(const GrFPArgs &) const129 std::unique_ptr<GrFragmentProcessor> SkShaderBase::asFragmentProcessor(const GrFPArgs&) const {
130     return nullptr;
131 }
132 #endif
133 
makeAsALocalMatrixShader(SkMatrix *) const134 sk_sp<SkShader> SkShaderBase::makeAsALocalMatrixShader(SkMatrix*) const {
135     return nullptr;
136 }
137 
Empty()138 sk_sp<SkShader> SkShaders::Empty() { return sk_make_sp<SkEmptyShader>(); }
Color(SkColor color)139 sk_sp<SkShader> SkShaders::Color(SkColor color) { return sk_make_sp<SkColorShader>(color); }
140 
makeShader(SkTileMode tmx,SkTileMode tmy,const SkSamplingOptions & sampling,const SkMatrix * lm) const141 sk_sp<SkShader> SkBitmap::makeShader(SkTileMode tmx, SkTileMode tmy,
142                                      const SkSamplingOptions& sampling,
143                                      const SkMatrix* lm) const {
144     if (lm && !lm->invert(nullptr)) {
145         return nullptr;
146     }
147     return SkImageShader::Make(SkMakeImageFromRasterBitmap(*this, kIfMutable_SkCopyPixelsMode),
148                                tmx, tmy, sampling, lm);
149 }
150 
appendStages(const SkStageRec & rec) const151 bool SkShaderBase::appendStages(const SkStageRec& rec) const {
152     return this->onAppendStages(rec);
153 }
154 
onAppendStages(const SkStageRec & rec) const155 bool SkShaderBase::onAppendStages(const SkStageRec& rec) const {
156     // SkShader::Context::shadeSpan() handles the paint opacity internally,
157     // but SkRasterPipelineBlitter applies it as a separate stage.
158     // We skip the internal shadeSpan() step by forcing the paint opaque.
159     SkTCopyOnFirstWrite<SkPaint> opaquePaint(rec.fPaint);
160     if (rec.fPaint.getAlpha() != SK_AlphaOPAQUE) {
161         opaquePaint.writable()->setAlpha(SK_AlphaOPAQUE);
162     }
163 
164     ContextRec cr(*opaquePaint, rec.fMatrixProvider.localToDevice(), rec.fLocalM, rec.fDstColorType,
165                   sk_srgb_singleton());
166 
167     struct CallbackCtx : SkRasterPipeline_CallbackCtx {
168         sk_sp<const SkShader> shader;
169         Context*              ctx;
170     };
171     auto cb = rec.fAlloc->make<CallbackCtx>();
172     cb->shader = sk_ref_sp(this);
173     cb->ctx = as_SB(this)->makeContext(cr, rec.fAlloc);
174     cb->fn  = [](SkRasterPipeline_CallbackCtx* self, int active_pixels) {
175         auto c = (CallbackCtx*)self;
176         int x = (int)c->rgba[0],
177             y = (int)c->rgba[1];
178         SkPMColor tmp[SkRasterPipeline_kMaxStride];
179         c->ctx->shadeSpan(x,y, tmp, active_pixels);
180 
181         for (int i = 0; i < active_pixels; i++) {
182             auto rgba_4f = SkPMColor4f::FromPMColor(tmp[i]);
183             memcpy(c->rgba + 4*i, rgba_4f.vec(), 4*sizeof(float));
184         }
185     };
186 
187     if (cb->ctx) {
188         rec.fPipeline->append(SkRasterPipeline::seed_shader);
189         rec.fPipeline->append(SkRasterPipeline::callback, cb);
190         rec.fAlloc->make<SkColorSpaceXformSteps>(sk_srgb_singleton(), kPremul_SkAlphaType,
191                                                  rec.fDstCS,          kPremul_SkAlphaType)
192             ->apply(rec.fPipeline);
193         return true;
194     }
195     return false;
196 }
197 
program(skvm::Builder * p,skvm::Coord device,skvm::Coord local,skvm::Color paint,const SkMatrixProvider & matrices,const SkMatrix * localM,const SkColorInfo & dst,skvm::Uniforms * uniforms,SkArenaAlloc * alloc) const198 skvm::Color SkShaderBase::program(skvm::Builder* p,
199                                   skvm::Coord device, skvm::Coord local, skvm::Color paint,
200                                   const SkMatrixProvider& matrices, const SkMatrix* localM,
201                                   const SkColorInfo& dst,
202                                   skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const {
203     // Shader subclasses should always act as if the destination were premul or opaque.
204     // SkVMBlitter handles all the coordination of unpremul itself, via premul.
205     SkColorInfo tweaked = dst.alphaType() == kUnpremul_SkAlphaType
206                            ? dst.makeAlphaType(kPremul_SkAlphaType)
207                            : dst;
208 
209     // Force opaque alpha for all opaque shaders.
210     //
211     // This is primarily nice in that we usually have a 1.0f constant splat
212     // somewhere in the program anyway, and this will let us drop the work the
213     // shader notionally does to produce alpha, p->extract(...), etc. in favor
214     // of that simple hoistable splat.
215     //
216     // More subtly, it makes isOpaque() a parameter to all shader program
217     // generation, guaranteeing that is-opaque bit is mixed into the overall
218     // shader program hash and blitter Key.  This makes it safe for us to use
219     // that bit to make decisions when constructing an SkVMBlitter, like doing
220     // SrcOver -> Src strength reduction.
221     if (auto color = this->onProgram(p, device,local, paint, matrices,localM, tweaked,
222                                      uniforms,alloc)) {
223         if (this->isOpaque()) {
224             color.a = p->splat(1.0f);
225         }
226         return color;
227     }
228     return {};
229 }
230 
231 // need a cheap way to invert the alpha channel of a shader (i.e. 1 - a)
makeInvertAlpha() const232 sk_sp<SkShader> SkShaderBase::makeInvertAlpha() const {
233     return this->makeWithColorFilter(SkColorFilters::Blend(0xFFFFFFFF, SkBlendMode::kSrcOut));
234 }
235 
236 
ApplyMatrix(skvm::Builder * p,const SkMatrix & m,skvm::Coord coord,skvm::Uniforms * uniforms)237 skvm::Coord SkShaderBase::ApplyMatrix(skvm::Builder* p, const SkMatrix& m,
238                                       skvm::Coord coord, skvm::Uniforms* uniforms) {
239     skvm::F32 x = coord.x,
240               y = coord.y;
241     if (m.isIdentity()) {
242         // That was easy.
243     } else if (m.isTranslate()) {
244         x = p->add(x, p->uniformF(uniforms->pushF(m[2])));
245         y = p->add(y, p->uniformF(uniforms->pushF(m[5])));
246     } else if (m.isScaleTranslate()) {
247         x = p->mad(x, p->uniformF(uniforms->pushF(m[0])), p->uniformF(uniforms->pushF(m[2])));
248         y = p->mad(y, p->uniformF(uniforms->pushF(m[4])), p->uniformF(uniforms->pushF(m[5])));
249     } else {  // Affine or perspective.
250         auto dot = [&,x,y](int row) {
251             return p->mad(x, p->uniformF(uniforms->pushF(m[3*row+0])),
252                    p->mad(y, p->uniformF(uniforms->pushF(m[3*row+1])),
253                              p->uniformF(uniforms->pushF(m[3*row+2]))));
254         };
255         x = dot(0);
256         y = dot(1);
257         if (m.hasPerspective()) {
258             x = x * (1.0f / dot(2));
259             y = y * (1.0f / dot(2));
260         }
261     }
262     return {x,y};
263 }
264 
265 ///////////////////////////////////////////////////////////////////////////////////////////////////
266 
onProgram(skvm::Builder *,skvm::Coord,skvm::Coord,skvm::Color,const SkMatrixProvider &,const SkMatrix *,const SkColorInfo &,skvm::Uniforms *,SkArenaAlloc *) const267 skvm::Color SkEmptyShader::onProgram(skvm::Builder*, skvm::Coord, skvm::Coord, skvm::Color,
268                                      const SkMatrixProvider&, const SkMatrix*, const SkColorInfo&,
269                                      skvm::Uniforms*, SkArenaAlloc*) const {
270     return {};  // signal failure
271 }
272 
CreateProc(SkReadBuffer &)273 sk_sp<SkFlattenable> SkEmptyShader::CreateProc(SkReadBuffer&) {
274     return SkShaders::Empty();
275 }
276