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 #ifndef SkShaderBase_DEFINED
9 #define SkShaderBase_DEFINED
10 
11 #include "SkFilterQuality.h"
12 #include "SkMask.h"
13 #include "SkMatrix.h"
14 #include "SkNoncopyable.h"
15 #include "SkShader.h"
16 #include "SkTLazy.h"
17 
18 #if SK_SUPPORT_GPU
19 #include "GrFPArgs.h"
20 #endif
21 
22 class GrContext;
23 class GrColorSpaceInfo;
24 class GrFragmentProcessor;
25 class SkArenaAlloc;
26 class SkColorSpace;
27 class SkColorSpaceXformer;
28 class SkImage;
29 struct SkImageInfo;
30 class SkPaint;
31 class SkRasterPipeline;
32 
33 class SkShaderBase : public SkShader {
34 public:
35     ~SkShaderBase() override;
36 
37     /**
38      *  Returns true if the shader is guaranteed to produce only a single color.
39      *  Subclasses can override this to allow loop-hoisting optimization.
40      */
isConstant()41     virtual bool isConstant() const { return false; }
42 
getLocalMatrix()43     const SkMatrix& getLocalMatrix() const { return fLocalMatrix; }
44 
45     enum Flags {
46         //!< set if all of the colors will be opaque
47         kOpaqueAlpha_Flag = 1 << 0,
48 
49         /** set if the spans only vary in X (const in Y).
50             e.g. an Nx1 bitmap that is being tiled in Y, or a linear-gradient
51             that varies from left-to-right. This flag specifies this for
52             shadeSpan().
53          */
54         kConstInY32_Flag = 1 << 1,
55 
56         /** hint for the blitter that 4f is the preferred shading mode.
57          */
58         kPrefers4f_Flag  = 1 << 2,
59     };
60 
61     /**
62      *  ContextRec acts as a parameter bundle for creating Contexts.
63      */
64     struct ContextRec {
ContextRecContextRec65         ContextRec(const SkPaint& paint, const SkMatrix& matrix, const SkMatrix* localM,
66                    SkColorType dstColorType, SkColorSpace* dstColorSpace)
67             : fPaint(&paint)
68             , fMatrix(&matrix)
69             , fLocalMatrix(localM)
70             , fDstColorType(dstColorType)
71             , fDstColorSpace(dstColorSpace) {}
72 
73         const SkPaint*  fPaint;            // the current paint associated with the draw
74         const SkMatrix* fMatrix;           // the current matrix in the canvas
75         const SkMatrix* fLocalMatrix;      // optional local matrix
76         SkColorType     fDstColorType;     // the color type of the dest surface
77         SkColorSpace*   fDstColorSpace;    // the color space of the dest surface (if any)
78     };
79 
80     class Context : public ::SkNoncopyable {
81     public:
82         Context(const SkShaderBase& shader, const ContextRec&);
83 
84         virtual ~Context();
85 
86         /**
87          *  Called sometimes before drawing with this shader. Return the type of
88          *  alpha your shader will return. The default implementation returns 0.
89          *  Your subclass should override if it can (even sometimes) report a
90          *  non-zero value, since that will enable various blitters to perform
91          *  faster.
92          */
getFlags()93         virtual uint32_t getFlags() const { return 0; }
94 
95         /**
96          *  Called for each span of the object being drawn. Your subclass should
97          *  set the appropriate colors (with premultiplied alpha) that correspond
98          *  to the specified device coordinates.
99          */
100         virtual void shadeSpan(int x, int y, SkPMColor[], int count) = 0;
101 
102     protected:
103         // Reference to shader, so we don't have to dupe information.
104         const SkShaderBase& fShader;
105 
getPaintAlpha()106         uint8_t         getPaintAlpha() const { return fPaintAlpha; }
getTotalInverse()107         const SkMatrix& getTotalInverse() const { return fTotalInverse; }
getCTM()108         const SkMatrix& getCTM() const { return fCTM; }
109 
110     private:
111         SkMatrix    fCTM;
112         SkMatrix    fTotalInverse;
113         uint8_t     fPaintAlpha;
114 
115         typedef SkNoncopyable INHERITED;
116     };
117 
118     /**
119      * Make a context using the memory provided by the arena.
120      *
121      * @return pointer to context or nullptr if can't be created
122      */
123     Context* makeContext(const ContextRec&, SkArenaAlloc*) const;
124 
125 #if SK_SUPPORT_GPU
126     /**
127      *  Returns a GrFragmentProcessor that implements the shader for the GPU backend. NULL is
128      *  returned if there is no GPU implementation.
129      *
130      *  The GPU device does not call SkShader::createContext(), instead we pass the view matrix,
131      *  local matrix, and filter quality directly.
132      *
133      *  The GrContext may be used by the to create textures that are required by the returned
134      *  processor.
135      *
136      *  The returned GrFragmentProcessor should expect an unpremultiplied input color and
137      *  produce a premultiplied output.
138      */
139     virtual std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const;
140 #endif
141 
142     /**
143      *  If the shader can represent its "average" luminance in a single color, return true and
144      *  if color is not NULL, return that color. If it cannot, return false and ignore the color
145      *  parameter.
146      *
147      *  Note: if this returns true, the returned color will always be opaque, as only the RGB
148      *  components are used to compute luminance.
149      */
150     bool asLuminanceColor(SkColor*) const;
151 
152     /**
153      *  Returns a shader transformed into a new color space via the |xformer|.
154      */
makeColorSpace(SkColorSpaceXformer * xformer)155     sk_sp<SkShader> makeColorSpace(SkColorSpaceXformer* xformer) const {
156         return this->onMakeColorSpace(xformer);
157     }
158 
159     struct StageRec {
160         SkRasterPipeline*   fPipeline;
161         SkArenaAlloc*       fAlloc;
162         SkColorType         fDstColorType;
163         SkColorSpace*       fDstCS;         // may be nullptr
164         const SkPaint&      fPaint;
165         const SkMatrix*     fLocalM;        // may be nullptr
166         SkMatrix            fCTM;
167     };
168 
169     // If this returns false, then we draw nothing (do not fall back to shader context)
170     bool appendStages(const StageRec&) const;
171 
172     bool SK_WARN_UNUSED_RESULT computeTotalInverse(const SkMatrix& ctm,
173                                                    const SkMatrix* outerLocalMatrix,
174                                                    SkMatrix* totalInverse) const;
175 
176     // Returns the total local matrix for this shader:
177     //
178     //   M = postLocalMatrix x shaderLocalMatrix x preLocalMatrix
179     //
180     SkTCopyOnFirstWrite<SkMatrix> totalLocalMatrix(const SkMatrix* preLocalMatrix,
181                                                    const SkMatrix* postLocalMatrix = nullptr) const;
182 
onIsAImage(SkMatrix *,TileMode[2])183     virtual SkImage* onIsAImage(SkMatrix*, TileMode[2]) const {
184         return nullptr;
185     }
186 
GetFlattenableType()187     static Type GetFlattenableType() { return kSkShaderBase_Type; }
getFlattenableType()188     Type getFlattenableType() const override { return GetFlattenableType(); }
189 
190     static sk_sp<SkShaderBase> Deserialize(const void* data, size_t size,
191                                              const SkDeserialProcs* procs = nullptr) {
192         return sk_sp<SkShaderBase>(static_cast<SkShaderBase*>(
193                 SkFlattenable::Deserialize(GetFlattenableType(), data, size, procs).release()));
194     }
195     static void RegisterFlattenables();
196 
197 protected:
198     SkShaderBase(const SkMatrix* localMatrix = nullptr);
199 
200     void flatten(SkWriteBuffer&) const override;
201 
202 #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
203     /**
204      * Specialize creating a SkShader context using the supplied allocator.
205      * @return pointer to context owned by the arena allocator.
206      */
onMakeContext(const ContextRec &,SkArenaAlloc *)207     virtual Context* onMakeContext(const ContextRec&, SkArenaAlloc*) const {
208         return nullptr;
209     }
210 
211     /**
212      * Overriden by shaders which prefer burst mode.
213      */
onMakeBurstPipelineContext(const ContextRec &,SkArenaAlloc *)214     virtual Context* onMakeBurstPipelineContext(const ContextRec&, SkArenaAlloc*) const {
215         return nullptr;
216     }
217 #endif
218 
onAsLuminanceColor(SkColor *)219     virtual bool onAsLuminanceColor(SkColor*) const {
220         return false;
221     }
222 
onMakeColorSpace(SkColorSpaceXformer *)223     virtual sk_sp<SkShader> onMakeColorSpace(SkColorSpaceXformer*) const {
224         return sk_ref_sp(const_cast<SkShaderBase*>(this));
225     }
226 
227     // Default impl creates shadercontext and calls that (not very efficient)
228     virtual bool onAppendStages(const StageRec&) const;
229 
230 private:
231     // This is essentially const, but not officially so it can be modified in constructors.
232     SkMatrix fLocalMatrix;
233 
234     typedef SkShader INHERITED;
235 };
236 
as_SB(SkShader * shader)237 inline SkShaderBase* as_SB(SkShader* shader) {
238     return static_cast<SkShaderBase*>(shader);
239 }
240 
as_SB(const SkShader * shader)241 inline const SkShaderBase* as_SB(const SkShader* shader) {
242     return static_cast<const SkShaderBase*>(shader);
243 }
244 
as_SB(const sk_sp<SkShader> & shader)245 inline const SkShaderBase* as_SB(const sk_sp<SkShader>& shader) {
246     return static_cast<SkShaderBase*>(shader.get());
247 }
248 
249 #endif // SkShaderBase_DEFINED
250