1 /*
2  * Copyright 2014 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 "GrConvexPolyEffect.h"
9 #include "SkPathPriv.h"
10 #include "effects/GrAARectEffect.h"
11 #include "effects/GrConstColorProcessor.h"
12 #include "glsl/GrGLSLFragmentProcessor.h"
13 #include "glsl/GrGLSLFragmentShaderBuilder.h"
14 #include "glsl/GrGLSLProgramDataManager.h"
15 #include "glsl/GrGLSLUniformHandler.h"
16 #include "../private/GrGLSL.h"
17 
18 //////////////////////////////////////////////////////////////////////////////
19 
20 class GrGLConvexPolyEffect : public GrGLSLFragmentProcessor {
21 public:
GrGLConvexPolyEffect()22     GrGLConvexPolyEffect() {
23         for (size_t i = 0; i < SK_ARRAY_COUNT(fPrevEdges); ++i) {
24             fPrevEdges[i] = SK_ScalarNaN;
25         }
26     }
27 
28     void emitCode(EmitArgs&) override;
29 
30     static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*);
31 
32 protected:
33     void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
34 
35 private:
36     GrGLSLProgramDataManager::UniformHandle fEdgeUniform;
37     SkScalar                                fPrevEdges[3 * GrConvexPolyEffect::kMaxEdges];
38     typedef GrGLSLFragmentProcessor INHERITED;
39 };
40 
emitCode(EmitArgs & args)41 void GrGLConvexPolyEffect::emitCode(EmitArgs& args) {
42     const GrConvexPolyEffect& cpe = args.fFp.cast<GrConvexPolyEffect>();
43 
44     const char *edgeArrayName;
45     fEdgeUniform = args.fUniformHandler->addUniformArray(kFragment_GrShaderFlag,
46                                                          kHalf3_GrSLType,
47                                                          "edges",
48                                                          cpe.getEdgeCount(),
49                                                          &edgeArrayName);
50     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
51     fragBuilder->codeAppend("\t\thalf alpha = 1.0;\n");
52     fragBuilder->codeAppend("\t\thalf edge;\n");
53     for (int i = 0; i < cpe.getEdgeCount(); ++i) {
54         fragBuilder->codeAppendf("\t\tedge = dot(%s[%d], half3(sk_FragCoord.x, sk_FragCoord.y, "
55                                                              "1));\n",
56                                  edgeArrayName, i);
57         if (GrProcessorEdgeTypeIsAA(cpe.getEdgeType())) {
58             fragBuilder->codeAppend("\t\tedge = clamp(edge, 0.0, 1.0);\n");
59         } else {
60             fragBuilder->codeAppend("\t\tedge = edge >= 0.5 ? 1.0 : 0.0;\n");
61         }
62         fragBuilder->codeAppend("\t\talpha *= edge;\n");
63     }
64 
65     if (GrProcessorEdgeTypeIsInverseFill(cpe.getEdgeType())) {
66         fragBuilder->codeAppend("\talpha = 1.0 - alpha;\n");
67     }
68     fragBuilder->codeAppendf("\t%s = %s * alpha;\n", args.fOutputColor, args.fInputColor);
69 }
70 
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & effect)71 void GrGLConvexPolyEffect::onSetData(const GrGLSLProgramDataManager& pdman,
72                                      const GrFragmentProcessor& effect) {
73     const GrConvexPolyEffect& cpe = effect.cast<GrConvexPolyEffect>();
74     size_t byteSize = 3 * cpe.getEdgeCount() * sizeof(SkScalar);
75     if (0 != memcmp(fPrevEdges, cpe.getEdges(), byteSize)) {
76         pdman.set3fv(fEdgeUniform, cpe.getEdgeCount(), cpe.getEdges());
77         memcpy(fPrevEdges, cpe.getEdges(), byteSize);
78     }
79 }
80 
GenKey(const GrProcessor & processor,const GrShaderCaps &,GrProcessorKeyBuilder * b)81 void GrGLConvexPolyEffect::GenKey(const GrProcessor& processor, const GrShaderCaps&,
82                                   GrProcessorKeyBuilder* b) {
83     const GrConvexPolyEffect& cpe = processor.cast<GrConvexPolyEffect>();
84     GR_STATIC_ASSERT(kGrClipEdgeTypeCnt <= 8);
85     uint32_t key = (cpe.getEdgeCount() << 3) | (int) cpe.getEdgeType();
86     b->add32(key);
87 }
88 
89 //////////////////////////////////////////////////////////////////////////////
90 
Make(GrClipEdgeType type,const SkPath & path)91 std::unique_ptr<GrFragmentProcessor> GrConvexPolyEffect::Make(GrClipEdgeType type,
92                                                               const SkPath& path) {
93     if (GrClipEdgeType::kHairlineAA == type) {
94         return nullptr;
95     }
96     if (path.getSegmentMasks() != SkPath::kLine_SegmentMask ||
97         !path.isConvex()) {
98         return nullptr;
99     }
100 
101     SkPathPriv::FirstDirection dir;
102     // The only way this should fail is if the clip is effectively a infinitely thin line. In that
103     // case nothing is inside the clip. It'd be nice to detect this at a higher level and either
104     // skip the draw or omit the clip element.
105     if (!SkPathPriv::CheapComputeFirstDirection(path, &dir)) {
106         if (GrProcessorEdgeTypeIsInverseFill(type)) {
107             return GrConstColorProcessor::Make(GrColor4f::OpaqueWhite(),
108                                                GrConstColorProcessor::InputMode::kModulateRGBA);
109         }
110         // This could use kIgnore instead of kModulateRGBA but it would trigger a debug print
111         // about a coverage processor not being compatible with the alpha-as-coverage optimization.
112         // We don't really care about this unlikely case so we just use kModulateRGBA to suppress
113         // the print.
114         return GrConstColorProcessor::Make(GrColor4f::TransparentBlack(),
115                                            GrConstColorProcessor::InputMode::kModulateRGBA);
116     }
117 
118     SkScalar        edges[3 * kMaxEdges];
119     SkPoint         pts[4];
120     SkPath::Verb    verb;
121     SkPath::Iter    iter(path, true);
122 
123     // SkPath considers itself convex so long as there is a convex contour within it,
124     // regardless of any degenerate contours such as a string of moveTos before it.
125     // Iterate here to consume any degenerate contours and only process the points
126     // on the actual convex contour.
127     int n = 0;
128     while ((verb = iter.next(pts, true, true)) != SkPath::kDone_Verb) {
129         switch (verb) {
130             case SkPath::kMove_Verb:
131                 SkASSERT(n == 0);
132             case SkPath::kClose_Verb:
133                 break;
134             case SkPath::kLine_Verb: {
135                 if (n >= kMaxEdges) {
136                     return nullptr;
137                 }
138                 SkVector v = pts[1] - pts[0];
139                 v.normalize();
140                 if (SkPathPriv::kCCW_FirstDirection == dir) {
141                     edges[3 * n] = v.fY;
142                     edges[3 * n + 1] = -v.fX;
143                 } else {
144                     edges[3 * n] = -v.fY;
145                     edges[3 * n + 1] = v.fX;
146                 }
147                 edges[3 * n + 2] = -(edges[3 * n] * pts[1].fX + edges[3 * n + 1] * pts[1].fY);
148                 ++n;
149                 break;
150             }
151             default:
152                 return nullptr;
153         }
154     }
155 
156     if (path.isInverseFillType()) {
157         type = GrInvertProcessorEdgeType(type);
158     }
159     return Make(type, n, edges);
160 }
161 
Make(GrClipEdgeType edgeType,const SkRect & rect)162 std::unique_ptr<GrFragmentProcessor> GrConvexPolyEffect::Make(GrClipEdgeType edgeType,
163                                                               const SkRect& rect) {
164     if (GrClipEdgeType::kHairlineAA == edgeType){
165         return nullptr;
166     }
167     return GrAARectEffect::Make(edgeType, rect);
168 }
169 
~GrConvexPolyEffect()170 GrConvexPolyEffect::~GrConvexPolyEffect() {}
171 
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const172 void GrConvexPolyEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
173                                                GrProcessorKeyBuilder* b) const {
174     GrGLConvexPolyEffect::GenKey(*this, caps, b);
175 }
176 
onCreateGLSLInstance() const177 GrGLSLFragmentProcessor* GrConvexPolyEffect::onCreateGLSLInstance() const  {
178     return new GrGLConvexPolyEffect;
179 }
180 
GrConvexPolyEffect(GrClipEdgeType edgeType,int n,const SkScalar edges[])181 GrConvexPolyEffect::GrConvexPolyEffect(GrClipEdgeType edgeType, int n, const SkScalar edges[])
182         : INHERITED(kGrConvexPolyEffect_ClassID, kCompatibleWithCoverageAsAlpha_OptimizationFlag)
183         , fEdgeType(edgeType)
184         , fEdgeCount(n) {
185     // Factory function should have already ensured this.
186     SkASSERT(n <= kMaxEdges);
187     memcpy(fEdges, edges, 3 * n * sizeof(SkScalar));
188     // Outset the edges by 0.5 so that a pixel with center on an edge is 50% covered in the AA case
189     // and 100% covered in the non-AA case.
190     for (int i = 0; i < n; ++i) {
191         fEdges[3 * i + 2] += SK_ScalarHalf;
192     }
193 }
194 
GrConvexPolyEffect(const GrConvexPolyEffect & that)195 GrConvexPolyEffect::GrConvexPolyEffect(const GrConvexPolyEffect& that)
196         : INHERITED(kGrConvexPolyEffect_ClassID, kCompatibleWithCoverageAsAlpha_OptimizationFlag)
197         , fEdgeType(that.fEdgeType)
198         , fEdgeCount(that.fEdgeCount) {
199     memcpy(fEdges, that.fEdges, 3 * that.fEdgeCount * sizeof(SkScalar));
200 }
201 
clone() const202 std::unique_ptr<GrFragmentProcessor> GrConvexPolyEffect::clone() const {
203     return std::unique_ptr<GrFragmentProcessor>(new GrConvexPolyEffect(*this));
204 }
205 
onIsEqual(const GrFragmentProcessor & other) const206 bool GrConvexPolyEffect::onIsEqual(const GrFragmentProcessor& other) const {
207     const GrConvexPolyEffect& cpe = other.cast<GrConvexPolyEffect>();
208     // ignore the fact that 0 == -0 and just use memcmp.
209     return (cpe.fEdgeType == fEdgeType && cpe.fEdgeCount == fEdgeCount &&
210             0 == memcmp(cpe.fEdges, fEdges, 3 * fEdgeCount * sizeof(SkScalar)));
211 }
212 
213 //////////////////////////////////////////////////////////////////////////////
214 
215 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrConvexPolyEffect);
216 
217 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)218 std::unique_ptr<GrFragmentProcessor> GrConvexPolyEffect::TestCreate(GrProcessorTestData* d) {
219     int count = d->fRandom->nextULessThan(kMaxEdges) + 1;
220     SkScalar edges[kMaxEdges * 3];
221     for (int i = 0; i < 3 * count; ++i) {
222         edges[i] = d->fRandom->nextSScalar1();
223     }
224 
225     std::unique_ptr<GrFragmentProcessor> fp;
226     do {
227         GrClipEdgeType edgeType = static_cast<GrClipEdgeType>(
228                 d->fRandom->nextULessThan(kGrClipEdgeTypeCnt));
229         fp = GrConvexPolyEffect::Make(edgeType, count, edges);
230     } while (nullptr == fp);
231     return fp;
232 }
233 #endif
234