dcshader.cpp revision 9cc1775e7230579ad15345bdcb59fa517c17f870
1
2/*
3 * Copyright 2014 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9#include "gm.h"
10#if SK_SUPPORT_GPU
11#include "GrFragmentProcessor.h"
12#include "GrCoordTransform.h"
13#include "gl/GrGLProcessor.h"
14#include "gl/builders/GrGLProgramBuilder.h"
15#include "Resources.h"
16#include "SkReadBuffer.h"
17#include "SkShader.h"
18#include "SkStream.h"
19#include "SkTypeface.h"
20#include "SkWriteBuffer.h"
21
22namespace skiagm {
23
24///////////////////////////////////////////////////////////////////////////////
25
26class DCShader : public SkShader {
27public:
28    DCShader(const SkMatrix& matrix) : fDeviceMatrix(matrix) {}
29
30    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(DCShader);
31
32    void flatten(SkWriteBuffer& buf) const override {
33        buf.writeMatrix(fDeviceMatrix);
34    }
35
36    bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
37                             const SkMatrix* localMatrix, GrColor* color, GrProcessorDataManager*,
38                             GrFragmentProcessor** fp) const override;
39
40#ifndef SK_IGNORE_TO_STRING
41    void toString(SkString* str) const override {
42        str->appendf("DCShader: ()");
43    }
44#endif
45
46private:
47    const SkMatrix fDeviceMatrix;
48};
49
50SkFlattenable* DCShader::CreateProc(SkReadBuffer& buf) {
51    SkMatrix matrix;
52    buf.readMatrix(&matrix);
53    return SkNEW_ARGS(DCShader, (matrix));
54}
55
56class DCFP : public GrFragmentProcessor {
57public:
58    DCFP(GrProcessorDataManager*, const SkMatrix& m) : fDeviceTransform(kDevice_GrCoordSet, m) {
59        this->addCoordTransform(&fDeviceTransform);
60        this->initClassID<DCFP>();
61    }
62
63    void getGLProcessorKey(const GrGLSLCaps& caps,
64                            GrProcessorKeyBuilder* b) const override {}
65
66    GrGLFragmentProcessor* createGLInstance() const override {
67        class DCGLFP : public GrGLFragmentProcessor {
68            void emitCode(GrGLFPBuilder* builder,
69                            const GrFragmentProcessor& fp,
70                            const char* outputColor,
71                            const char* inputColor,
72                            const TransformedCoordsArray& coords,
73                            const TextureSamplerArray& samplers) {
74                GrGLFragmentBuilder* fpb = builder->getFragmentShaderBuilder();
75                fpb->codeAppendf("vec2 c = %s;", fpb->ensureFSCoords2D(coords, 0).c_str());
76                fpb->codeAppend("vec2 r = mod(c, vec2(20.0));");
77                fpb->codeAppend("vec4 color = vec4(0.5*sin(c.x / 15.0) + 0.5,"
78                                                    "0.5*cos((c.x + c.y) / 15.0) + 0.5,"
79                                                    "(r.x + r.y) / 20.0,"
80                                                    "distance(r, vec2(15.0)) / 20.0 + 0.2);");
81                fpb->codeAppendf("color.rgb *= color.a;"
82                                    "%s = color * %s;",
83                                    outputColor, GrGLSLExpr4(inputColor).c_str());
84            }
85            void setData(const GrGLProgramDataManager&, const GrProcessor&) override {}
86        };
87        return SkNEW(DCGLFP);
88    }
89
90    const char* name() const override { return "DCFP"; }
91
92    void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
93        inout->mulByUnknownFourComponents();
94    }
95
96private:
97    bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
98
99    GrCoordTransform fDeviceTransform;
100};
101
102bool DCShader::asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
103                                   const SkMatrix* localMatrix, GrColor* color,
104                                   GrProcessorDataManager* procDataManager,
105                                   GrFragmentProcessor** fp) const {
106    *fp = SkNEW_ARGS(DCFP, (procDataManager, fDeviceMatrix));
107    *color = GrColorPackA4(paint.getAlpha());
108    return true;
109}
110
111class DCShaderGM : public GM {
112public:
113    DCShaderGM() {
114        this->setBGColor(sk_tool_utils::color_to_565(0xFFAABBCC));
115    }
116
117    ~DCShaderGM() override {
118        for (int i = 0; i < fPrims.count(); ++i) {
119            SkDELETE(fPrims[i]);
120        }
121    }
122
123protected:
124
125    SkString onShortName() override {
126        return SkString("dcshader");
127    }
128
129    SkISize onISize() override { return SkISize::Make(1000, 900); }
130
131    void onOnceBeforeDraw() override {
132        struct Rect : public Prim {
133            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
134                SkRect rect = SkRect::MakeXYWH(0, 0, 50, 50);
135                canvas->drawRect(rect, paint);
136                return rect;
137            }
138        };
139
140        struct Circle : public Prim {
141            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
142                static const SkScalar radius = 25;
143                canvas->drawCircle(radius, radius, radius, paint);
144                return SkRect::MakeXYWH(0, 0, 2 * radius, 2 * radius);
145            }
146        };
147
148        struct RRect : public Prim {
149            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
150                SkRRect rrect;
151                rrect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 10, 10);
152                canvas->drawRRect(rrect, paint);
153                return rrect.getBounds();
154            }
155        };
156
157        struct DRRect : public Prim {
158            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
159                SkRRect outerRRect;
160                outerRRect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 5, 5);
161                SkRRect innerRRect;
162                innerRRect.setRectXY(SkRect::MakeXYWH(5, 8, 35, 30), 8, 3);
163                canvas->drawDRRect(outerRRect, innerRRect, paint);
164                return outerRRect.getBounds();
165            }
166        };
167        struct Path : public Prim {
168            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
169                SkPath path;
170                path.addCircle(15, 15, 10);
171                path.addOval(SkRect::MakeXYWH(2, 2, 22, 37));
172                path.setFillType(SkPath::kEvenOdd_FillType);
173                canvas->drawPath(path, paint);
174                return path.getBounds();
175            }
176        };
177
178        struct Points : public Prim {
179            Points(SkCanvas::PointMode mode) : fMode(mode) {}
180
181            SkRect draw(SkCanvas* canvas, const SkPaint& paint) override {
182                SkRandom random;
183                SkPoint points[500];
184                SkRect bounds = SkRect::MakeWH(50, 50);
185                int count = SkToInt(SK_ARRAY_COUNT(points));
186                if (SkCanvas::kPoints_PointMode != fMode) {
187                    count = SkTMin(count, 10);
188                }
189                for (int p = 0; p < count; ++p) {
190                    points[p].fX = random.nextUScalar1() * bounds.width();
191                    points[p].fY = random.nextUScalar1() * bounds.width();
192                }
193                canvas->drawPoints(fMode, count, points, paint);
194                return bounds;
195            }
196            SkCanvas::PointMode fMode;
197        };
198
199        struct Text : public Prim {
200            SkRect draw(SkCanvas* canvas, const SkPaint& origPaint) override {
201                SkPaint paint = origPaint;
202                paint.setTextSize(30.f);
203                this->setFont(&paint);
204                const char* text = this->text();
205                static const SkVector offset = SkVector::Make(10, 10);
206                canvas->drawText(text, strlen(text), offset.fX, offset.fY, paint);
207                SkRect bounds;
208                paint.measureText(text, strlen(text), &bounds);
209                bounds.offset(offset);
210                return bounds;
211            }
212
213            virtual void setFont(SkPaint* paint) {
214                sk_tool_utils::set_portable_typeface_always(paint);
215            }
216
217            virtual const char* text() const { return "Hello, Skia!"; }
218        };
219
220        struct BmpText : public Text {
221           void setFont(SkPaint* paint) override {
222               if (!fTypeface) {
223                    fTypeface.reset(GetResourceAsTypeface("/fonts/Funkster.ttf"));
224               }
225               paint->setTypeface(fTypeface);
226            }
227
228            const char* text() const override { return "Hi, Skia!"; }
229
230            SkAutoTUnref<SkTypeface> fTypeface;
231        };
232        fPrims.push_back(SkNEW(Rect));
233        fPrims.push_back(SkNEW(Circle));
234        fPrims.push_back(SkNEW(RRect));
235        fPrims.push_back(SkNEW(DRRect));
236        fPrims.push_back(SkNEW(Path));
237        fPrims.push_back(SkNEW(Points(SkCanvas::kPoints_PointMode)));
238        fPrims.push_back(SkNEW(Points(SkCanvas::kLines_PointMode)));
239        fPrims.push_back(SkNEW(Points(SkCanvas::kPolygon_PointMode)));
240        fPrims.push_back(SkNEW(Text));
241        fPrims.push_back(SkNEW(BmpText));
242    }
243
244    void onDraw(SkCanvas* canvas) override {
245        // This GM exists to test a specific feature of the GPU backend. It does not work with the
246        // sw rasterizer, tile modes, etc.
247        if (NULL == canvas->getGrContext()) {
248            this->drawGpuOnlyMessage(canvas);
249            return;
250        }
251        SkPaint paint;
252        SkTArray<SkMatrix> devMats;
253        devMats.push_back().reset();
254        devMats.push_back().setRotate(45, 500, 500);
255        devMats.push_back().setRotate(-30, 200, 200);
256        devMats.back().setPerspX(-SK_Scalar1 / 2000);
257        devMats.back().setPerspY(SK_Scalar1 / 1000);
258
259
260        SkTArray<SkMatrix> viewMats;
261        viewMats.push_back().setScale(0.75f, 0.75f);
262        viewMats.push_back().setRotate(45, 50, 50);
263        viewMats.back().postScale(0.5f, 1.1f);
264
265        canvas->translate(10, 20);
266        canvas->save();
267        SkScalar tx = 0, maxTy = 0;
268        static const SkScalar kW = 900;
269
270        for (int aa = 0; aa < 2; ++aa) {
271            for (int i = 0; i < fPrims.count(); ++i) {
272                for (int j = 0; j < devMats.count(); ++j) {
273                    for (int k = 0; k < viewMats.count(); ++k) {
274                        paint.setShader(SkNEW_ARGS(DCShader, (devMats[j])))->unref();
275                        paint.setAntiAlias(SkToBool(aa));
276                        canvas->save();
277                        canvas->concat(viewMats[k]);
278                        SkRect bounds = fPrims[i]->draw(canvas, paint);
279                        canvas->restore();
280                        viewMats[k].mapRect(&bounds);
281                        // add margins
282                        bounds.fRight += 20;
283                        bounds.fBottom += 20;
284                        canvas->translate(bounds.fRight, 0);
285                        tx += bounds.fRight;
286                        maxTy = SkTMax(bounds.fBottom, maxTy);
287                        if (tx > kW) {
288                            tx = 0;
289                            canvas->restore();
290                            canvas->translate(0, maxTy);
291                            canvas->save();
292                            maxTy = 0;
293                        }
294                    }
295                }
296            }
297        }
298        canvas->restore();
299    }
300
301private:
302    struct Prim {
303        virtual ~Prim() {}
304        virtual SkRect draw(SkCanvas*, const SkPaint&) = 0;
305    };
306
307    SkTArray<Prim*> fPrims;
308
309    typedef GM INHERITED;
310};
311
312DEF_GM( return SkNEW(DCShaderGM); )
313}
314#endif
315