1cb93a386Sopenharmony_ci/*
2cb93a386Sopenharmony_ci* Copyright 2017 Google Inc.
3cb93a386Sopenharmony_ci*
4cb93a386Sopenharmony_ci* Use of this source code is governed by a BSD-style license that can be
5cb93a386Sopenharmony_ci* found in the LICENSE file.
6cb93a386Sopenharmony_ci*/
7cb93a386Sopenharmony_ci
8cb93a386Sopenharmony_ci#include "include/utils/SkShadowUtils.h"
9cb93a386Sopenharmony_ci
10cb93a386Sopenharmony_ci#include "include/core/SkCanvas.h"
11cb93a386Sopenharmony_ci#include "include/core/SkColorFilter.h"
12cb93a386Sopenharmony_ci#include "include/core/SkMaskFilter.h"
13cb93a386Sopenharmony_ci#include "include/core/SkPath.h"
14cb93a386Sopenharmony_ci#include "include/core/SkString.h"
15cb93a386Sopenharmony_ci#include "include/core/SkVertices.h"
16cb93a386Sopenharmony_ci#include "include/private/SkColorData.h"
17cb93a386Sopenharmony_ci#include "include/private/SkIDChangeListener.h"
18cb93a386Sopenharmony_ci#include "include/private/SkTPin.h"
19cb93a386Sopenharmony_ci#include "include/utils/SkRandom.h"
20cb93a386Sopenharmony_ci#include "src/core/SkBlurMask.h"
21cb93a386Sopenharmony_ci#include "src/core/SkColorFilterBase.h"
22cb93a386Sopenharmony_ci#include "src/core/SkColorFilterPriv.h"
23cb93a386Sopenharmony_ci#include "src/core/SkDevice.h"
24cb93a386Sopenharmony_ci#include "src/core/SkDrawShadowInfo.h"
25cb93a386Sopenharmony_ci#include "src/core/SkEffectPriv.h"
26cb93a386Sopenharmony_ci#include "src/core/SkPathPriv.h"
27cb93a386Sopenharmony_ci#include "src/core/SkRasterPipeline.h"
28cb93a386Sopenharmony_ci#include "src/core/SkResourceCache.h"
29cb93a386Sopenharmony_ci#include "src/core/SkRuntimeEffectPriv.h"
30cb93a386Sopenharmony_ci#include "src/core/SkTLazy.h"
31cb93a386Sopenharmony_ci#include "src/core/SkVM.h"
32cb93a386Sopenharmony_ci#include "src/core/SkVerticesPriv.h"
33cb93a386Sopenharmony_ci#include "src/utils/SkShadowTessellator.h"
34cb93a386Sopenharmony_ci#include <new>
35cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
36cb93a386Sopenharmony_ci#include "src/gpu/effects/GrSkSLFP.h"
37cb93a386Sopenharmony_ci#include "src/gpu/geometry/GrStyledShape.h"
38cb93a386Sopenharmony_ci#endif
39cb93a386Sopenharmony_ci
40cb93a386Sopenharmony_ci/**
41cb93a386Sopenharmony_ci*  Gaussian color filter -- produces a Gaussian ramp based on the color's B value,
42cb93a386Sopenharmony_ci*                           then blends with the color's G value.
43cb93a386Sopenharmony_ci*                           Final result is black with alpha of Gaussian(B)*G.
44cb93a386Sopenharmony_ci*                           The assumption is that the original color's alpha is 1.
45cb93a386Sopenharmony_ci*/
46cb93a386Sopenharmony_ciclass SkGaussianColorFilter : public SkColorFilterBase {
47cb93a386Sopenharmony_cipublic:
48cb93a386Sopenharmony_ci    SkGaussianColorFilter() : INHERITED() {}
49cb93a386Sopenharmony_ci
50cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
51cb93a386Sopenharmony_ci    GrFPResult asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> inputFP,
52cb93a386Sopenharmony_ci                                   GrRecordingContext*, const GrColorInfo&) const override;
53cb93a386Sopenharmony_ci#endif
54cb93a386Sopenharmony_ci
55cb93a386Sopenharmony_ciprotected:
56cb93a386Sopenharmony_ci    void flatten(SkWriteBuffer&) const override {}
57cb93a386Sopenharmony_ci    bool onAppendStages(const SkStageRec& rec, bool shaderIsOpaque) const override {
58cb93a386Sopenharmony_ci        rec.fPipeline->append(SkRasterPipeline::gauss_a_to_rgba);
59cb93a386Sopenharmony_ci        return true;
60cb93a386Sopenharmony_ci    }
61cb93a386Sopenharmony_ci
62cb93a386Sopenharmony_ci    skvm::Color onProgram(skvm::Builder* p, skvm::Color c, const SkColorInfo& dst, skvm::Uniforms*,
63cb93a386Sopenharmony_ci                          SkArenaAlloc*) const override {
64cb93a386Sopenharmony_ci        // x = 1 - x;
65cb93a386Sopenharmony_ci        // exp(-x * x * 4) - 0.018f;
66cb93a386Sopenharmony_ci        // ... now approximate with quartic
67cb93a386Sopenharmony_ci        //
68cb93a386Sopenharmony_ci        skvm::F32 x = p->splat(-2.26661229133605957031f);
69cb93a386Sopenharmony_ci                  x = c.a * x + 2.89795351028442382812f;
70cb93a386Sopenharmony_ci                  x = c.a * x + 0.21345567703247070312f;
71cb93a386Sopenharmony_ci                  x = c.a * x + 0.15489584207534790039f;
72cb93a386Sopenharmony_ci                  x = c.a * x + 0.00030726194381713867f;
73cb93a386Sopenharmony_ci        return {x, x, x, x};
74cb93a386Sopenharmony_ci    }
75cb93a386Sopenharmony_ci
76cb93a386Sopenharmony_ciprivate:
77cb93a386Sopenharmony_ci    SK_FLATTENABLE_HOOKS(SkGaussianColorFilter)
78cb93a386Sopenharmony_ci
79cb93a386Sopenharmony_ci    using INHERITED = SkColorFilterBase;
80cb93a386Sopenharmony_ci};
81cb93a386Sopenharmony_ci
82cb93a386Sopenharmony_cisk_sp<SkFlattenable> SkGaussianColorFilter::CreateProc(SkReadBuffer&) {
83cb93a386Sopenharmony_ci    return SkColorFilterPriv::MakeGaussian();
84cb93a386Sopenharmony_ci}
85cb93a386Sopenharmony_ci
86cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
87cb93a386Sopenharmony_ci
88cb93a386Sopenharmony_ciGrFPResult SkGaussianColorFilter::asFragmentProcessor(std::unique_ptr<GrFragmentProcessor> inputFP,
89cb93a386Sopenharmony_ci                                                      GrRecordingContext*,
90cb93a386Sopenharmony_ci                                                      const GrColorInfo&) const {
91cb93a386Sopenharmony_ci    static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
92cb93a386Sopenharmony_ci        half4 main(half4 inColor) {
93cb93a386Sopenharmony_ci            half factor = 1 - inColor.a;
94cb93a386Sopenharmony_ci            factor = exp(-factor * factor * 4) - 0.018;
95cb93a386Sopenharmony_ci            return half4(factor);
96cb93a386Sopenharmony_ci        }
97cb93a386Sopenharmony_ci    )");
98cb93a386Sopenharmony_ci    SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
99cb93a386Sopenharmony_ci    return GrFPSuccess(
100cb93a386Sopenharmony_ci            GrSkSLFP::Make(effect, "gaussian_fp", std::move(inputFP), GrSkSLFP::OptFlags::kNone));
101cb93a386Sopenharmony_ci}
102cb93a386Sopenharmony_ci#endif
103cb93a386Sopenharmony_ci
104cb93a386Sopenharmony_cisk_sp<SkColorFilter> SkColorFilterPriv::MakeGaussian() {
105cb93a386Sopenharmony_ci    return sk_sp<SkColorFilter>(new SkGaussianColorFilter);
106cb93a386Sopenharmony_ci}
107cb93a386Sopenharmony_ci
108cb93a386Sopenharmony_ci///////////////////////////////////////////////////////////////////////////////////////////////////
109cb93a386Sopenharmony_ci
110cb93a386Sopenharmony_cinamespace {
111cb93a386Sopenharmony_ci
112cb93a386Sopenharmony_ciuint64_t resource_cache_shared_id() {
113cb93a386Sopenharmony_ci    return 0x2020776f64616873llu;  // 'shadow  '
114cb93a386Sopenharmony_ci}
115cb93a386Sopenharmony_ci
116cb93a386Sopenharmony_ci/** Factory for an ambient shadow mesh with particular shadow properties. */
117cb93a386Sopenharmony_cistruct AmbientVerticesFactory {
118cb93a386Sopenharmony_ci    SkScalar fOccluderHeight = SK_ScalarNaN;  // NaN so that isCompatible will fail until init'ed.
119cb93a386Sopenharmony_ci    bool fTransparent;
120cb93a386Sopenharmony_ci    SkVector fOffset;
121cb93a386Sopenharmony_ci
122cb93a386Sopenharmony_ci    bool isCompatible(const AmbientVerticesFactory& that, SkVector* translate) const {
123cb93a386Sopenharmony_ci        if (fOccluderHeight != that.fOccluderHeight || fTransparent != that.fTransparent) {
124cb93a386Sopenharmony_ci            return false;
125cb93a386Sopenharmony_ci        }
126cb93a386Sopenharmony_ci        *translate = that.fOffset;
127cb93a386Sopenharmony_ci        return true;
128cb93a386Sopenharmony_ci    }
129cb93a386Sopenharmony_ci
130cb93a386Sopenharmony_ci    sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
131cb93a386Sopenharmony_ci                                   SkVector* translate, bool isLimitElevation = false) const {
132cb93a386Sopenharmony_ci        SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
133cb93a386Sopenharmony_ci        // pick a canonical place to generate shadow
134cb93a386Sopenharmony_ci        SkMatrix noTrans(ctm);
135cb93a386Sopenharmony_ci        if (!ctm.hasPerspective()) {
136cb93a386Sopenharmony_ci            noTrans[SkMatrix::kMTransX] = 0;
137cb93a386Sopenharmony_ci            noTrans[SkMatrix::kMTransY] = 0;
138cb93a386Sopenharmony_ci        }
139cb93a386Sopenharmony_ci        *translate = fOffset;
140cb93a386Sopenharmony_ci        return SkShadowTessellator::MakeAmbient(path, noTrans, zParams, fTransparent);
141cb93a386Sopenharmony_ci    }
142cb93a386Sopenharmony_ci};
143cb93a386Sopenharmony_ci
144cb93a386Sopenharmony_ci/** Factory for an spot shadow mesh with particular shadow properties. */
145cb93a386Sopenharmony_cistruct SpotVerticesFactory {
146cb93a386Sopenharmony_ci    enum class OccluderType {
147cb93a386Sopenharmony_ci        // The umbra cannot be dropped out because either the occluder is not opaque,
148cb93a386Sopenharmony_ci        // or the center of the umbra is visible.
149cb93a386Sopenharmony_ci        kTransparent,
150cb93a386Sopenharmony_ci        // The umbra can be dropped where it is occluded.
151cb93a386Sopenharmony_ci        kOpaquePartialUmbra,
152cb93a386Sopenharmony_ci        // It is known that the entire umbra is occluded.
153cb93a386Sopenharmony_ci        kOpaqueNoUmbra,
154cb93a386Sopenharmony_ci        // The light is directional
155cb93a386Sopenharmony_ci        kDirectional
156cb93a386Sopenharmony_ci    };
157cb93a386Sopenharmony_ci
158cb93a386Sopenharmony_ci    SkVector fOffset;
159cb93a386Sopenharmony_ci    SkPoint  fLocalCenter;
160cb93a386Sopenharmony_ci    SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
161cb93a386Sopenharmony_ci    SkPoint3 fDevLightPos;
162cb93a386Sopenharmony_ci    SkScalar fLightRadius;
163cb93a386Sopenharmony_ci    OccluderType fOccluderType;
164cb93a386Sopenharmony_ci
165cb93a386Sopenharmony_ci    bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const {
166cb93a386Sopenharmony_ci        if (fOccluderHeight != that.fOccluderHeight || fDevLightPos.fZ != that.fDevLightPos.fZ ||
167cb93a386Sopenharmony_ci            fLightRadius != that.fLightRadius || fOccluderType != that.fOccluderType) {
168cb93a386Sopenharmony_ci            return false;
169cb93a386Sopenharmony_ci        }
170cb93a386Sopenharmony_ci        switch (fOccluderType) {
171cb93a386Sopenharmony_ci            case OccluderType::kTransparent:
172cb93a386Sopenharmony_ci            case OccluderType::kOpaqueNoUmbra:
173cb93a386Sopenharmony_ci                // 'this' and 'that' will either both have no umbra removed or both have all the
174cb93a386Sopenharmony_ci                // umbra removed.
175cb93a386Sopenharmony_ci                *translate = that.fOffset;
176cb93a386Sopenharmony_ci                return true;
177cb93a386Sopenharmony_ci            case OccluderType::kOpaquePartialUmbra:
178cb93a386Sopenharmony_ci                // In this case we partially remove the umbra differently for 'this' and 'that'
179cb93a386Sopenharmony_ci                // if the offsets don't match.
180cb93a386Sopenharmony_ci                if (fOffset == that.fOffset) {
181cb93a386Sopenharmony_ci                    translate->set(0, 0);
182cb93a386Sopenharmony_ci                    return true;
183cb93a386Sopenharmony_ci                }
184cb93a386Sopenharmony_ci                return false;
185cb93a386Sopenharmony_ci            case OccluderType::kDirectional:
186cb93a386Sopenharmony_ci                *translate = that.fOffset - fOffset;
187cb93a386Sopenharmony_ci                return true;
188cb93a386Sopenharmony_ci        }
189cb93a386Sopenharmony_ci        SK_ABORT("Uninitialized occluder type?");
190cb93a386Sopenharmony_ci    }
191cb93a386Sopenharmony_ci
192cb93a386Sopenharmony_ci    sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
193cb93a386Sopenharmony_ci                                   SkVector* translate, bool isLimitElevation = false) const {
194cb93a386Sopenharmony_ci        bool transparent = OccluderType::kTransparent == fOccluderType;
195cb93a386Sopenharmony_ci        bool directional = OccluderType::kDirectional == fOccluderType;
196cb93a386Sopenharmony_ci        SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
197cb93a386Sopenharmony_ci        if (directional) {
198cb93a386Sopenharmony_ci            translate->set(0, 0);
199cb93a386Sopenharmony_ci            return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
200cb93a386Sopenharmony_ci                                                 transparent, true, isLimitElevation);
201cb93a386Sopenharmony_ci        } else if (ctm.hasPerspective() || OccluderType::kOpaquePartialUmbra == fOccluderType) {
202cb93a386Sopenharmony_ci            translate->set(0, 0);
203cb93a386Sopenharmony_ci            return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
204cb93a386Sopenharmony_ci                                                 transparent, false, isLimitElevation);
205cb93a386Sopenharmony_ci        } else {
206cb93a386Sopenharmony_ci            // pick a canonical place to generate shadow, with light centered over path
207cb93a386Sopenharmony_ci            SkMatrix noTrans(ctm);
208cb93a386Sopenharmony_ci            noTrans[SkMatrix::kMTransX] = 0;
209cb93a386Sopenharmony_ci            noTrans[SkMatrix::kMTransY] = 0;
210cb93a386Sopenharmony_ci            SkPoint devCenter(fLocalCenter);
211cb93a386Sopenharmony_ci            noTrans.mapPoints(&devCenter, 1);
212cb93a386Sopenharmony_ci            SkPoint3 centerLightPos = SkPoint3::Make(devCenter.fX, devCenter.fY, fDevLightPos.fZ);
213cb93a386Sopenharmony_ci            *translate = fOffset;
214cb93a386Sopenharmony_ci            return SkShadowTessellator::MakeSpot(path, noTrans, zParams,
215cb93a386Sopenharmony_ci                                                 centerLightPos, fLightRadius, transparent, false, isLimitElevation);
216cb93a386Sopenharmony_ci        }
217cb93a386Sopenharmony_ci    }
218cb93a386Sopenharmony_ci};
219cb93a386Sopenharmony_ci
220cb93a386Sopenharmony_ci/**
221cb93a386Sopenharmony_ci * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache
222cb93a386Sopenharmony_ci * records are immutable this is not itself a Rec. When we need to update it we return this on
223cb93a386Sopenharmony_ci * the FindVisitor and let the cache destroy the Rec. We'll update the tessellations and then add
224cb93a386Sopenharmony_ci * a new Rec with an adjusted size for any deletions/additions.
225cb93a386Sopenharmony_ci */
226cb93a386Sopenharmony_ciclass CachedTessellations : public SkRefCnt {
227cb93a386Sopenharmony_cipublic:
228cb93a386Sopenharmony_ci    size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
229cb93a386Sopenharmony_ci
230cb93a386Sopenharmony_ci    sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
231cb93a386Sopenharmony_ci                           SkVector* translate) const {
232cb93a386Sopenharmony_ci        return fAmbientSet.find(ambient, matrix, translate);
233cb93a386Sopenharmony_ci    }
234cb93a386Sopenharmony_ci
235cb93a386Sopenharmony_ci    sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient,
236cb93a386Sopenharmony_ci                          const SkMatrix& matrix, SkVector* translate,
237cb93a386Sopenharmony_ci                          bool isLimitElevation = false) {
238cb93a386Sopenharmony_ci        return fAmbientSet.add(devPath, ambient, matrix, translate, isLimitElevation);
239cb93a386Sopenharmony_ci    }
240cb93a386Sopenharmony_ci
241cb93a386Sopenharmony_ci    sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
242cb93a386Sopenharmony_ci                           SkVector* translate) const {
243cb93a386Sopenharmony_ci        return fSpotSet.find(spot, matrix, translate);
244cb93a386Sopenharmony_ci    }
245cb93a386Sopenharmony_ci
246cb93a386Sopenharmony_ci    sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot,
247cb93a386Sopenharmony_ci                          const SkMatrix& matrix, SkVector* translate,
248cb93a386Sopenharmony_ci                          bool isLimitElevation = false) {
249cb93a386Sopenharmony_ci        return fSpotSet.add(devPath, spot, matrix, translate, isLimitElevation);
250cb93a386Sopenharmony_ci    }
251cb93a386Sopenharmony_ci
252cb93a386Sopenharmony_ciprivate:
253cb93a386Sopenharmony_ci    template <typename FACTORY, int MAX_ENTRIES>
254cb93a386Sopenharmony_ci    class Set {
255cb93a386Sopenharmony_ci    public:
256cb93a386Sopenharmony_ci        size_t size() const { return fSize; }
257cb93a386Sopenharmony_ci
258cb93a386Sopenharmony_ci        sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
259cb93a386Sopenharmony_ci                               SkVector* translate) const {
260cb93a386Sopenharmony_ci            for (int i = 0; i < MAX_ENTRIES; ++i) {
261cb93a386Sopenharmony_ci                if (fEntries[i].fFactory.isCompatible(factory, translate)) {
262cb93a386Sopenharmony_ci                    const SkMatrix& m = fEntries[i].fMatrix;
263cb93a386Sopenharmony_ci                    if (matrix.hasPerspective() || m.hasPerspective()) {
264cb93a386Sopenharmony_ci                        if (matrix != fEntries[i].fMatrix) {
265cb93a386Sopenharmony_ci                            continue;
266cb93a386Sopenharmony_ci                        }
267cb93a386Sopenharmony_ci                    } else if (matrix.getScaleX() != m.getScaleX() ||
268cb93a386Sopenharmony_ci                               matrix.getSkewX() != m.getSkewX() ||
269cb93a386Sopenharmony_ci                               matrix.getScaleY() != m.getScaleY() ||
270cb93a386Sopenharmony_ci                               matrix.getSkewY() != m.getSkewY()) {
271cb93a386Sopenharmony_ci                        continue;
272cb93a386Sopenharmony_ci                    }
273cb93a386Sopenharmony_ci                    return fEntries[i].fVertices;
274cb93a386Sopenharmony_ci                }
275cb93a386Sopenharmony_ci            }
276cb93a386Sopenharmony_ci            return nullptr;
277cb93a386Sopenharmony_ci        }
278cb93a386Sopenharmony_ci
279cb93a386Sopenharmony_ci        sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix,
280cb93a386Sopenharmony_ci                              SkVector* translate, bool isLimitElevation = false) {
281cb93a386Sopenharmony_ci            sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix, translate, isLimitElevation);
282cb93a386Sopenharmony_ci            if (!vertices) {
283cb93a386Sopenharmony_ci                return nullptr;
284cb93a386Sopenharmony_ci            }
285cb93a386Sopenharmony_ci            int i;
286cb93a386Sopenharmony_ci            if (fCount < MAX_ENTRIES) {
287cb93a386Sopenharmony_ci                i = fCount++;
288cb93a386Sopenharmony_ci            } else {
289cb93a386Sopenharmony_ci                i = fRandom.nextULessThan(MAX_ENTRIES);
290cb93a386Sopenharmony_ci                fSize -= fEntries[i].fVertices->approximateSize();
291cb93a386Sopenharmony_ci            }
292cb93a386Sopenharmony_ci            fEntries[i].fFactory = factory;
293cb93a386Sopenharmony_ci            fEntries[i].fVertices = vertices;
294cb93a386Sopenharmony_ci            fEntries[i].fMatrix = matrix;
295cb93a386Sopenharmony_ci            fSize += vertices->approximateSize();
296cb93a386Sopenharmony_ci            return vertices;
297cb93a386Sopenharmony_ci        }
298cb93a386Sopenharmony_ci
299cb93a386Sopenharmony_ci    private:
300cb93a386Sopenharmony_ci        struct Entry {
301cb93a386Sopenharmony_ci            FACTORY fFactory;
302cb93a386Sopenharmony_ci            sk_sp<SkVertices> fVertices;
303cb93a386Sopenharmony_ci            SkMatrix fMatrix;
304cb93a386Sopenharmony_ci        };
305cb93a386Sopenharmony_ci        Entry fEntries[MAX_ENTRIES];
306cb93a386Sopenharmony_ci        int fCount = 0;
307cb93a386Sopenharmony_ci        size_t fSize = 0;
308cb93a386Sopenharmony_ci        SkRandom fRandom;
309cb93a386Sopenharmony_ci    };
310cb93a386Sopenharmony_ci
311cb93a386Sopenharmony_ci    Set<AmbientVerticesFactory, 4> fAmbientSet;
312cb93a386Sopenharmony_ci    Set<SpotVerticesFactory, 4> fSpotSet;
313cb93a386Sopenharmony_ci};
314cb93a386Sopenharmony_ci
315cb93a386Sopenharmony_ci/**
316cb93a386Sopenharmony_ci * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular
317cb93a386Sopenharmony_ci * path. The key represents the path's geometry and not any shadow params.
318cb93a386Sopenharmony_ci */
319cb93a386Sopenharmony_ciclass CachedTessellationsRec : public SkResourceCache::Rec {
320cb93a386Sopenharmony_cipublic:
321cb93a386Sopenharmony_ci    CachedTessellationsRec(const SkResourceCache::Key& key,
322cb93a386Sopenharmony_ci                           sk_sp<CachedTessellations> tessellations)
323cb93a386Sopenharmony_ci            : fTessellations(std::move(tessellations)) {
324cb93a386Sopenharmony_ci        fKey.reset(new uint8_t[key.size()]);
325cb93a386Sopenharmony_ci        memcpy(fKey.get(), &key, key.size());
326cb93a386Sopenharmony_ci    }
327cb93a386Sopenharmony_ci
328cb93a386Sopenharmony_ci    const Key& getKey() const override {
329cb93a386Sopenharmony_ci        return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
330cb93a386Sopenharmony_ci    }
331cb93a386Sopenharmony_ci
332cb93a386Sopenharmony_ci    size_t bytesUsed() const override { return fTessellations->size(); }
333cb93a386Sopenharmony_ci
334cb93a386Sopenharmony_ci    const char* getCategory() const override { return "tessellated shadow masks"; }
335cb93a386Sopenharmony_ci
336cb93a386Sopenharmony_ci    sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
337cb93a386Sopenharmony_ci
338cb93a386Sopenharmony_ci    template <typename FACTORY>
339cb93a386Sopenharmony_ci    sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
340cb93a386Sopenharmony_ci                           SkVector* translate) const {
341cb93a386Sopenharmony_ci        return fTessellations->find(factory, matrix, translate);
342cb93a386Sopenharmony_ci    }
343cb93a386Sopenharmony_ci
344cb93a386Sopenharmony_ciprivate:
345cb93a386Sopenharmony_ci    std::unique_ptr<uint8_t[]> fKey;
346cb93a386Sopenharmony_ci    sk_sp<CachedTessellations> fTessellations;
347cb93a386Sopenharmony_ci};
348cb93a386Sopenharmony_ci
349cb93a386Sopenharmony_ci/**
350cb93a386Sopenharmony_ci * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the
351cb93a386Sopenharmony_ci * vertices and a translation vector. If the CachedTessellations does not contain a suitable
352cb93a386Sopenharmony_ci * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations
353cb93a386Sopenharmony_ci * to the caller. The caller will update it and reinsert it back into the cache.
354cb93a386Sopenharmony_ci */
355cb93a386Sopenharmony_citemplate <typename FACTORY>
356cb93a386Sopenharmony_cistruct FindContext {
357cb93a386Sopenharmony_ci    FindContext(const SkMatrix* viewMatrix, const FACTORY* factory)
358cb93a386Sopenharmony_ci            : fViewMatrix(viewMatrix), fFactory(factory) {}
359cb93a386Sopenharmony_ci    const SkMatrix* const fViewMatrix;
360cb93a386Sopenharmony_ci    // If this is valid after Find is called then we found the vertices and they should be drawn
361cb93a386Sopenharmony_ci    // with fTranslate applied.
362cb93a386Sopenharmony_ci    sk_sp<SkVertices> fVertices;
363cb93a386Sopenharmony_ci    SkVector fTranslate = {0, 0};
364cb93a386Sopenharmony_ci
365cb93a386Sopenharmony_ci    // If this is valid after Find then the caller should add the vertices to the tessellation set
366cb93a386Sopenharmony_ci    // and create a new CachedTessellationsRec and insert it into SkResourceCache.
367cb93a386Sopenharmony_ci    sk_sp<CachedTessellations> fTessellationsOnFailure;
368cb93a386Sopenharmony_ci
369cb93a386Sopenharmony_ci    const FACTORY* fFactory;
370cb93a386Sopenharmony_ci};
371cb93a386Sopenharmony_ci
372cb93a386Sopenharmony_ci/**
373cb93a386Sopenharmony_ci * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of
374cb93a386Sopenharmony_ci * the FindContext are used to determine if the vertices are reusable. If so the vertices and
375cb93a386Sopenharmony_ci * necessary translation vector are set on the FindContext.
376cb93a386Sopenharmony_ci */
377cb93a386Sopenharmony_citemplate <typename FACTORY>
378cb93a386Sopenharmony_cibool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) {
379cb93a386Sopenharmony_ci    FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx;
380cb93a386Sopenharmony_ci    const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec);
381cb93a386Sopenharmony_ci    findContext->fVertices =
382cb93a386Sopenharmony_ci            rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate);
383cb93a386Sopenharmony_ci    if (findContext->fVertices) {
384cb93a386Sopenharmony_ci        return true;
385cb93a386Sopenharmony_ci    }
386cb93a386Sopenharmony_ci    // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been
387cb93a386Sopenharmony_ci    // manipulated we will add a new Rec.
388cb93a386Sopenharmony_ci    findContext->fTessellationsOnFailure = rec.refTessellations();
389cb93a386Sopenharmony_ci    return false;
390cb93a386Sopenharmony_ci}
391cb93a386Sopenharmony_ci
392cb93a386Sopenharmony_ciclass ShadowedPath {
393cb93a386Sopenharmony_cipublic:
394cb93a386Sopenharmony_ci    ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix)
395cb93a386Sopenharmony_ci            : fPath(path)
396cb93a386Sopenharmony_ci            , fViewMatrix(viewMatrix)
397cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
398cb93a386Sopenharmony_ci            , fShapeForKey(*path, GrStyle::SimpleFill())
399cb93a386Sopenharmony_ci#endif
400cb93a386Sopenharmony_ci    {}
401cb93a386Sopenharmony_ci
402cb93a386Sopenharmony_ci    const SkPath& path() const { return *fPath; }
403cb93a386Sopenharmony_ci    const SkMatrix& viewMatrix() const { return *fViewMatrix; }
404cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
405cb93a386Sopenharmony_ci    /** Negative means the vertices should not be cached for this path. */
406cb93a386Sopenharmony_ci    int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); }
407cb93a386Sopenharmony_ci    void writeKey(void* key) const {
408cb93a386Sopenharmony_ci        fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
409cb93a386Sopenharmony_ci    }
410cb93a386Sopenharmony_ci    bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr, nullptr, nullptr); }
411cb93a386Sopenharmony_ci#else
412cb93a386Sopenharmony_ci    int keyBytes() const { return -1; }
413cb93a386Sopenharmony_ci    void writeKey(void* key) const { SK_ABORT("Should never be called"); }
414cb93a386Sopenharmony_ci    bool isRRect(SkRRect* rrect) { return false; }
415cb93a386Sopenharmony_ci#endif
416cb93a386Sopenharmony_ci
417cb93a386Sopenharmony_ciprivate:
418cb93a386Sopenharmony_ci    const SkPath* fPath;
419cb93a386Sopenharmony_ci    const SkMatrix* fViewMatrix;
420cb93a386Sopenharmony_ci#if SK_SUPPORT_GPU
421cb93a386Sopenharmony_ci    GrStyledShape fShapeForKey;
422cb93a386Sopenharmony_ci#endif
423cb93a386Sopenharmony_ci};
424cb93a386Sopenharmony_ci
425cb93a386Sopenharmony_ci// This creates a domain of keys in SkResourceCache used by this file.
426cb93a386Sopenharmony_cistatic void* kNamespace;
427cb93a386Sopenharmony_ci
428cb93a386Sopenharmony_ci// When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
429cb93a386Sopenharmony_ciclass ShadowInvalidator : public SkIDChangeListener {
430cb93a386Sopenharmony_cipublic:
431cb93a386Sopenharmony_ci    ShadowInvalidator(const SkResourceCache::Key& key) {
432cb93a386Sopenharmony_ci        fKey.reset(new uint8_t[key.size()]);
433cb93a386Sopenharmony_ci        memcpy(fKey.get(), &key, key.size());
434cb93a386Sopenharmony_ci    }
435cb93a386Sopenharmony_ci
436cb93a386Sopenharmony_ciprivate:
437cb93a386Sopenharmony_ci    const SkResourceCache::Key& getKey() const {
438cb93a386Sopenharmony_ci        return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
439cb93a386Sopenharmony_ci    }
440cb93a386Sopenharmony_ci
441cb93a386Sopenharmony_ci    // always purge
442cb93a386Sopenharmony_ci    static bool FindVisitor(const SkResourceCache::Rec&, void*) {
443cb93a386Sopenharmony_ci        return false;
444cb93a386Sopenharmony_ci    }
445cb93a386Sopenharmony_ci
446cb93a386Sopenharmony_ci    void changed() override {
447cb93a386Sopenharmony_ci        SkResourceCache::Find(this->getKey(), ShadowInvalidator::FindVisitor, nullptr);
448cb93a386Sopenharmony_ci    }
449cb93a386Sopenharmony_ci
450cb93a386Sopenharmony_ci    std::unique_ptr<uint8_t[]> fKey;
451cb93a386Sopenharmony_ci};
452cb93a386Sopenharmony_ci
453cb93a386Sopenharmony_ci/**
454cb93a386Sopenharmony_ci * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
455cb93a386Sopenharmony_ci * they are first found in SkResourceCache.
456cb93a386Sopenharmony_ci */
457cb93a386Sopenharmony_citemplate <typename FACTORY>
458cb93a386Sopenharmony_cibool draw_shadow(const FACTORY& factory,
459cb93a386Sopenharmony_ci                 std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
460cb93a386Sopenharmony_ci                 SkScalar tx, SkScalar ty, bool)> drawProc, ShadowedPath& path,
461cb93a386Sopenharmony_ci                 SkColor color, bool isLimitElevation = false) {
462cb93a386Sopenharmony_ci    FindContext<FACTORY> context(&path.viewMatrix(), &factory);
463cb93a386Sopenharmony_ci
464cb93a386Sopenharmony_ci    SkResourceCache::Key* key = nullptr;
465cb93a386Sopenharmony_ci    SkAutoSTArray<32 * 4, uint8_t> keyStorage;
466cb93a386Sopenharmony_ci    int keyDataBytes = path.keyBytes();
467cb93a386Sopenharmony_ci    if (keyDataBytes >= 0) {
468cb93a386Sopenharmony_ci        keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
469cb93a386Sopenharmony_ci        key = new (keyStorage.begin()) SkResourceCache::Key();
470cb93a386Sopenharmony_ci        path.writeKey((uint32_t*)(keyStorage.begin() + sizeof(*key)));
471cb93a386Sopenharmony_ci        key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
472cb93a386Sopenharmony_ci        SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
473cb93a386Sopenharmony_ci    }
474cb93a386Sopenharmony_ci
475cb93a386Sopenharmony_ci    sk_sp<SkVertices> vertices;
476cb93a386Sopenharmony_ci    bool foundInCache = SkToBool(context.fVertices);
477cb93a386Sopenharmony_ci    if (foundInCache) {
478cb93a386Sopenharmony_ci        vertices = std::move(context.fVertices);
479cb93a386Sopenharmony_ci    } else {
480cb93a386Sopenharmony_ci        // TODO: handle transforming the path as part of the tessellator
481cb93a386Sopenharmony_ci        if (key) {
482cb93a386Sopenharmony_ci            // Update or initialize a tessellation set and add it to the cache.
483cb93a386Sopenharmony_ci            sk_sp<CachedTessellations> tessellations;
484cb93a386Sopenharmony_ci            if (context.fTessellationsOnFailure) {
485cb93a386Sopenharmony_ci                tessellations = std::move(context.fTessellationsOnFailure);
486cb93a386Sopenharmony_ci            } else {
487cb93a386Sopenharmony_ci                tessellations.reset(new CachedTessellations());
488cb93a386Sopenharmony_ci            }
489cb93a386Sopenharmony_ci            vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
490cb93a386Sopenharmony_ci                                          &context.fTranslate, isLimitElevation);
491cb93a386Sopenharmony_ci            if (!vertices) {
492cb93a386Sopenharmony_ci                return false;
493cb93a386Sopenharmony_ci            }
494cb93a386Sopenharmony_ci            auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
495cb93a386Sopenharmony_ci            SkPathPriv::AddGenIDChangeListener(path.path(), sk_make_sp<ShadowInvalidator>(*key));
496cb93a386Sopenharmony_ci            SkResourceCache::Add(rec);
497cb93a386Sopenharmony_ci        } else {
498cb93a386Sopenharmony_ci            vertices = factory.makeVertices(path.path(), path.viewMatrix(),
499cb93a386Sopenharmony_ci                                            &context.fTranslate);
500cb93a386Sopenharmony_ci            if (!vertices) {
501cb93a386Sopenharmony_ci                return false;
502cb93a386Sopenharmony_ci            }
503cb93a386Sopenharmony_ci        }
504cb93a386Sopenharmony_ci    }
505cb93a386Sopenharmony_ci
506cb93a386Sopenharmony_ci    SkPaint paint;
507cb93a386Sopenharmony_ci    // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
508cb93a386Sopenharmony_ci    // that against our 'color' param.
509cb93a386Sopenharmony_ci    paint.setColorFilter(
510cb93a386Sopenharmony_ci         SkColorFilters::Blend(color, SkBlendMode::kModulate)->makeComposed(
511cb93a386Sopenharmony_ci                                                                SkColorFilterPriv::MakeGaussian()));
512cb93a386Sopenharmony_ci
513cb93a386Sopenharmony_ci    drawProc(vertices.get(), SkBlendMode::kModulate, paint,
514cb93a386Sopenharmony_ci             context.fTranslate.fX, context.fTranslate.fY, path.viewMatrix().hasPerspective());
515cb93a386Sopenharmony_ci
516cb93a386Sopenharmony_ci    return true;
517cb93a386Sopenharmony_ci}
518cb93a386Sopenharmony_ci}  // namespace
519cb93a386Sopenharmony_ci
520cb93a386Sopenharmony_cistatic bool tilted(const SkPoint3& zPlaneParams) {
521cb93a386Sopenharmony_ci    return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
522cb93a386Sopenharmony_ci}
523cb93a386Sopenharmony_ci
524cb93a386Sopenharmony_civoid SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
525cb93a386Sopenharmony_ci                                       SkColor* outAmbientColor, SkColor* outSpotColor) {
526cb93a386Sopenharmony_ci    // For tonal color we only compute color values for the spot shadow.
527cb93a386Sopenharmony_ci    // The ambient shadow is greyscale only.
528cb93a386Sopenharmony_ci
529cb93a386Sopenharmony_ci    // Ambient
530cb93a386Sopenharmony_ci    *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
531cb93a386Sopenharmony_ci
532cb93a386Sopenharmony_ci    // Spot
533cb93a386Sopenharmony_ci    int spotR = SkColorGetR(inSpotColor);
534cb93a386Sopenharmony_ci    int spotG = SkColorGetG(inSpotColor);
535cb93a386Sopenharmony_ci    int spotB = SkColorGetB(inSpotColor);
536cb93a386Sopenharmony_ci    int max = std::max(std::max(spotR, spotG), spotB);
537cb93a386Sopenharmony_ci    int min = std::min(std::min(spotR, spotG), spotB);
538cb93a386Sopenharmony_ci    SkScalar luminance = 0.5f*(max + min)/255.f;
539cb93a386Sopenharmony_ci    SkScalar origA = SkColorGetA(inSpotColor)/255.f;
540cb93a386Sopenharmony_ci
541cb93a386Sopenharmony_ci    // We compute a color alpha value based on the luminance of the color, scaled by an
542cb93a386Sopenharmony_ci    // adjusted alpha value. We want the following properties to match the UX examples
543cb93a386Sopenharmony_ci    // (assuming a = 0.25) and to ensure that we have reasonable results when the color
544cb93a386Sopenharmony_ci    // is black and/or the alpha is 0:
545cb93a386Sopenharmony_ci    //     f(0, a) = 0
546cb93a386Sopenharmony_ci    //     f(luminance, 0) = 0
547cb93a386Sopenharmony_ci    //     f(1, 0.25) = .5
548cb93a386Sopenharmony_ci    //     f(0.5, 0.25) = .4
549cb93a386Sopenharmony_ci    //     f(1, 1) = 1
550cb93a386Sopenharmony_ci    // The following functions match this as closely as possible.
551cb93a386Sopenharmony_ci    SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
552cb93a386Sopenharmony_ci    SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
553cb93a386Sopenharmony_ci    colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
554cb93a386Sopenharmony_ci
555cb93a386Sopenharmony_ci    // Similarly, we set the greyscale alpha based on luminance and alpha so that
556cb93a386Sopenharmony_ci    //     f(0, a) = a
557cb93a386Sopenharmony_ci    //     f(luminance, 0) = 0
558cb93a386Sopenharmony_ci    //     f(1, 0.25) = 0.15
559cb93a386Sopenharmony_ci    SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
560cb93a386Sopenharmony_ci
561cb93a386Sopenharmony_ci    // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
562cb93a386Sopenharmony_ci    // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
563cb93a386Sopenharmony_ci    // which is an adjusted value of 'a'.  Assuming SrcOver, a background color of B_rgb, and
564cb93a386Sopenharmony_ci    // ignoring edge falloff, this becomes
565cb93a386Sopenharmony_ci    //
566cb93a386Sopenharmony_ci    //      (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
567cb93a386Sopenharmony_ci    //
568cb93a386Sopenharmony_ci    // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
569cb93a386Sopenharmony_ci    // set the alpha to (S_a + C_a - S_a*C_a).
570cb93a386Sopenharmony_ci    SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
571cb93a386Sopenharmony_ci    SkScalar tonalAlpha = colorScale + greyscaleAlpha;
572cb93a386Sopenharmony_ci    SkScalar unPremulScale = colorScale / tonalAlpha;
573cb93a386Sopenharmony_ci    *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
574cb93a386Sopenharmony_ci                                   unPremulScale*spotR,
575cb93a386Sopenharmony_ci                                   unPremulScale*spotG,
576cb93a386Sopenharmony_ci                                   unPremulScale*spotB);
577cb93a386Sopenharmony_ci}
578cb93a386Sopenharmony_ci
579cb93a386Sopenharmony_cistatic bool fill_shadow_rec(const SkPath& path, const SkPoint3& zPlaneParams,
580cb93a386Sopenharmony_ci                            const SkPoint3& lightPos, SkScalar lightRadius,
581cb93a386Sopenharmony_ci                            SkColor ambientColor, SkColor spotColor,
582cb93a386Sopenharmony_ci                            uint32_t flags, const SkMatrix& ctm, SkDrawShadowRec* rec) {
583cb93a386Sopenharmony_ci    SkPoint pt = { lightPos.fX, lightPos.fY };
584cb93a386Sopenharmony_ci    if (!SkToBool(flags & kDirectionalLight_ShadowFlag)) {
585cb93a386Sopenharmony_ci        // If light position is in device space, need to transform to local space
586cb93a386Sopenharmony_ci        // before applying to SkCanvas.
587cb93a386Sopenharmony_ci        SkMatrix inverse;
588cb93a386Sopenharmony_ci        if (!ctm.invert(&inverse)) {
589cb93a386Sopenharmony_ci            return false;
590cb93a386Sopenharmony_ci        }
591cb93a386Sopenharmony_ci        inverse.mapPoints(&pt, 1);
592cb93a386Sopenharmony_ci    }
593cb93a386Sopenharmony_ci
594cb93a386Sopenharmony_ci    rec->fZPlaneParams   = zPlaneParams;
595cb93a386Sopenharmony_ci    rec->fLightPos       = { pt.fX, pt.fY, lightPos.fZ };
596cb93a386Sopenharmony_ci    rec->fLightRadius    = lightRadius;
597cb93a386Sopenharmony_ci    rec->fAmbientColor   = ambientColor;
598cb93a386Sopenharmony_ci    rec->fSpotColor      = spotColor;
599cb93a386Sopenharmony_ci    rec->fFlags          = flags;
600cb93a386Sopenharmony_ci
601cb93a386Sopenharmony_ci    return true;
602cb93a386Sopenharmony_ci}
603cb93a386Sopenharmony_ci
604cb93a386Sopenharmony_ci// Draw an offset spot shadow and outlining ambient shadow for the given path.
605cb93a386Sopenharmony_civoid SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
606cb93a386Sopenharmony_ci                               const SkPoint3& lightPos, SkScalar lightRadius,
607cb93a386Sopenharmony_ci                               SkColor ambientColor, SkColor spotColor,
608cb93a386Sopenharmony_ci                               uint32_t flags) {
609cb93a386Sopenharmony_ci    DrawShadowStyle(canvas, path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor, flags, false);
610cb93a386Sopenharmony_ci}
611cb93a386Sopenharmony_ci
612cb93a386Sopenharmony_civoid SkShadowUtils::DrawShadowStyle(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
613cb93a386Sopenharmony_ci                                    const SkPoint3& lightPos, SkScalar lightRadius,
614cb93a386Sopenharmony_ci                                    SkColor ambientColor, SkColor spotColor,
615cb93a386Sopenharmony_ci                                    uint32_t flags, bool isLimitElevation) {
616cb93a386Sopenharmony_ci    SkDrawShadowRec rec;
617cb93a386Sopenharmony_ci    rec.isLimitElevation = isLimitElevation;
618cb93a386Sopenharmony_ci    if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor,
619cb93a386Sopenharmony_ci                         flags, canvas->getTotalMatrix(), &rec)) {
620cb93a386Sopenharmony_ci        return;
621cb93a386Sopenharmony_ci    }
622cb93a386Sopenharmony_ci
623cb93a386Sopenharmony_ci    canvas->private_draw_shadow_rec(path, rec);
624cb93a386Sopenharmony_ci}
625cb93a386Sopenharmony_ci
626cb93a386Sopenharmony_cibool SkShadowUtils::GetLocalBounds(const SkMatrix& ctm, const SkPath& path,
627cb93a386Sopenharmony_ci                                   const SkPoint3& zPlaneParams, const SkPoint3& lightPos,
628cb93a386Sopenharmony_ci                                   SkScalar lightRadius, uint32_t flags, SkRect* bounds) {
629cb93a386Sopenharmony_ci    SkDrawShadowRec rec;
630cb93a386Sopenharmony_ci    if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, SK_ColorBLACK, SK_ColorBLACK,
631cb93a386Sopenharmony_ci                         flags, ctm, &rec)) {
632cb93a386Sopenharmony_ci        return false;
633cb93a386Sopenharmony_ci    }
634cb93a386Sopenharmony_ci
635cb93a386Sopenharmony_ci    SkDrawShadowMetrics::GetLocalBounds(path, rec, ctm, bounds);
636cb93a386Sopenharmony_ci
637cb93a386Sopenharmony_ci    return true;
638cb93a386Sopenharmony_ci}
639cb93a386Sopenharmony_ci
640cb93a386Sopenharmony_ci//////////////////////////////////////////////////////////////////////////////////////////////
641cb93a386Sopenharmony_ci
642cb93a386Sopenharmony_cistatic bool validate_rec(const SkDrawShadowRec& rec) {
643cb93a386Sopenharmony_ci    return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
644cb93a386Sopenharmony_ci           SkScalarIsFinite(rec.fLightRadius);
645cb93a386Sopenharmony_ci}
646cb93a386Sopenharmony_ci
647cb93a386Sopenharmony_civoid SkBaseDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
648cb93a386Sopenharmony_ci    auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
649cb93a386Sopenharmony_ci                                SkScalar tx, SkScalar ty, bool hasPerspective) {
650cb93a386Sopenharmony_ci        if (vertices->priv().vertexCount()) {
651cb93a386Sopenharmony_ci            // For perspective shadows we've already computed the shadow in world space,
652cb93a386Sopenharmony_ci            // and we can't translate it without changing it. Otherwise we concat the
653cb93a386Sopenharmony_ci            // change in translation from the cached version.
654cb93a386Sopenharmony_ci            SkAutoDeviceTransformRestore adr(
655cb93a386Sopenharmony_ci                    this,
656cb93a386Sopenharmony_ci                    hasPerspective ? SkMatrix::I()
657cb93a386Sopenharmony_ci                                   : this->localToDevice() * SkMatrix::Translate(tx, ty));
658cb93a386Sopenharmony_ci            this->drawVertices(vertices, mode, paint);
659cb93a386Sopenharmony_ci        }
660cb93a386Sopenharmony_ci    };
661cb93a386Sopenharmony_ci
662cb93a386Sopenharmony_ci    if (!validate_rec(rec)) {
663cb93a386Sopenharmony_ci        return;
664cb93a386Sopenharmony_ci    }
665cb93a386Sopenharmony_ci
666cb93a386Sopenharmony_ci    SkMatrix viewMatrix = this->localToDevice();
667cb93a386Sopenharmony_ci    SkAutoDeviceTransformRestore adr(this, SkMatrix::I());
668cb93a386Sopenharmony_ci
669cb93a386Sopenharmony_ci    ShadowedPath shadowedPath(&path, &viewMatrix);
670cb93a386Sopenharmony_ci
671cb93a386Sopenharmony_ci    bool tiltZPlane = tilted(rec.fZPlaneParams);
672cb93a386Sopenharmony_ci    bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
673cb93a386Sopenharmony_ci    bool directional = SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag);
674cb93a386Sopenharmony_ci    bool uncached = tiltZPlane || path.isVolatile();
675cb93a386Sopenharmony_ci
676cb93a386Sopenharmony_ci    SkPoint3 zPlaneParams = rec.fZPlaneParams;
677cb93a386Sopenharmony_ci    SkPoint3 devLightPos = rec.fLightPos;
678cb93a386Sopenharmony_ci    if (!directional) {
679cb93a386Sopenharmony_ci        viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
680cb93a386Sopenharmony_ci    }
681cb93a386Sopenharmony_ci    float lightRadius = rec.fLightRadius;
682cb93a386Sopenharmony_ci
683cb93a386Sopenharmony_ci    if (SkColorGetA(rec.fAmbientColor) > 0) {
684cb93a386Sopenharmony_ci        bool success = false;
685cb93a386Sopenharmony_ci        if (uncached) {
686cb93a386Sopenharmony_ci            sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
687cb93a386Sopenharmony_ci                                                                          zPlaneParams,
688cb93a386Sopenharmony_ci                                                                          transparent);
689cb93a386Sopenharmony_ci            if (vertices) {
690cb93a386Sopenharmony_ci                SkPaint paint;
691cb93a386Sopenharmony_ci                // Run the vertex color through a GaussianColorFilter and then modulate the
692cb93a386Sopenharmony_ci                // grayscale result of that against our 'color' param.
693cb93a386Sopenharmony_ci                paint.setColorFilter(
694cb93a386Sopenharmony_ci                    SkColorFilters::Blend(rec.fAmbientColor,
695cb93a386Sopenharmony_ci                                                  SkBlendMode::kModulate)->makeComposed(
696cb93a386Sopenharmony_ci                                                               SkColorFilterPriv::MakeGaussian()));
697cb93a386Sopenharmony_ci                this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
698cb93a386Sopenharmony_ci                success = true;
699cb93a386Sopenharmony_ci            }
700cb93a386Sopenharmony_ci        }
701cb93a386Sopenharmony_ci
702cb93a386Sopenharmony_ci        if (!success) {
703cb93a386Sopenharmony_ci            AmbientVerticesFactory factory;
704cb93a386Sopenharmony_ci            factory.fOccluderHeight = zPlaneParams.fZ;
705cb93a386Sopenharmony_ci            factory.fTransparent = transparent;
706cb93a386Sopenharmony_ci            if (viewMatrix.hasPerspective()) {
707cb93a386Sopenharmony_ci                factory.fOffset.set(0, 0);
708cb93a386Sopenharmony_ci            } else {
709cb93a386Sopenharmony_ci                factory.fOffset.fX = viewMatrix.getTranslateX();
710cb93a386Sopenharmony_ci                factory.fOffset.fY = viewMatrix.getTranslateY();
711cb93a386Sopenharmony_ci            }
712cb93a386Sopenharmony_ci
713cb93a386Sopenharmony_ci            if (!draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor)) {
714cb93a386Sopenharmony_ci                // Pretransform the path to avoid transforming the stroke, below.
715cb93a386Sopenharmony_ci                SkPath devSpacePath;
716cb93a386Sopenharmony_ci                path.transform(viewMatrix, &devSpacePath);
717cb93a386Sopenharmony_ci                devSpacePath.setIsVolatile(true);
718cb93a386Sopenharmony_ci
719cb93a386Sopenharmony_ci                // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
720cb93a386Sopenharmony_ci                // the tesselation, and sets the alpha on the path to 1/AmbientRecipAlpha (or 'a').
721cb93a386Sopenharmony_ci                //
722cb93a386Sopenharmony_ci                // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
723cb93a386Sopenharmony_ci                // can be calculated by interpolating:
724cb93a386Sopenharmony_ci                //
725cb93a386Sopenharmony_ci                //            original edge        outer edge
726cb93a386Sopenharmony_ci                //         |       |<---------- r ------>|
727cb93a386Sopenharmony_ci                //         |<------|--- f -------------->|
728cb93a386Sopenharmony_ci                //         |       |                     |
729cb93a386Sopenharmony_ci                //    alpha = 1  alpha = a          alpha = 0
730cb93a386Sopenharmony_ci                //
731cb93a386Sopenharmony_ci                // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
732cb93a386Sopenharmony_ci                //
733cb93a386Sopenharmony_ci                // We now need to outset the path to place the new edge in the center of the
734cb93a386Sopenharmony_ci                // blur region:
735cb93a386Sopenharmony_ci                //
736cb93a386Sopenharmony_ci                //             original   new
737cb93a386Sopenharmony_ci                //         |       |<------|--- r ------>|
738cb93a386Sopenharmony_ci                //         |<------|--- f -|------------>|
739cb93a386Sopenharmony_ci                //         |       |<- o ->|<--- f/2 --->|
740cb93a386Sopenharmony_ci                //
741cb93a386Sopenharmony_ci                //     r = o + f/2, so o = r - f/2
742cb93a386Sopenharmony_ci                //
743cb93a386Sopenharmony_ci                // We outset by using the stroker, so the strokeWidth is o/2.
744cb93a386Sopenharmony_ci                //
745cb93a386Sopenharmony_ci                SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
746cb93a386Sopenharmony_ci                SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
747cb93a386Sopenharmony_ci                SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
748cb93a386Sopenharmony_ci                SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
749cb93a386Sopenharmony_ci
750cb93a386Sopenharmony_ci                // Now draw with blur
751cb93a386Sopenharmony_ci                SkPaint paint;
752cb93a386Sopenharmony_ci                paint.setColor(rec.fAmbientColor);
753cb93a386Sopenharmony_ci                paint.setStrokeWidth(strokeWidth);
754cb93a386Sopenharmony_ci                paint.setStyle(SkPaint::kStrokeAndFill_Style);
755cb93a386Sopenharmony_ci                SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(blurRadius);
756cb93a386Sopenharmony_ci                bool respectCTM = false;
757cb93a386Sopenharmony_ci                paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
758cb93a386Sopenharmony_ci                this->drawPath(devSpacePath, paint);
759cb93a386Sopenharmony_ci            }
760cb93a386Sopenharmony_ci        }
761cb93a386Sopenharmony_ci    }
762cb93a386Sopenharmony_ci
763cb93a386Sopenharmony_ci    if (SkColorGetA(rec.fSpotColor) > 0) {
764cb93a386Sopenharmony_ci        bool success = false;
765cb93a386Sopenharmony_ci        if (uncached) {
766cb93a386Sopenharmony_ci            sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
767cb93a386Sopenharmony_ci                                                                       zPlaneParams,
768cb93a386Sopenharmony_ci                                                                       devLightPos, lightRadius,
769cb93a386Sopenharmony_ci                                                                       transparent,
770cb93a386Sopenharmony_ci                                                                       directional, rec.isLimitElevation);
771cb93a386Sopenharmony_ci            if (vertices) {
772cb93a386Sopenharmony_ci                SkPaint paint;
773cb93a386Sopenharmony_ci                // Run the vertex color through a GaussianColorFilter and then modulate the
774cb93a386Sopenharmony_ci                // grayscale result of that against our 'color' param.
775cb93a386Sopenharmony_ci                paint.setColorFilter(
776cb93a386Sopenharmony_ci                    SkColorFilters::Blend(rec.fSpotColor,
777cb93a386Sopenharmony_ci                                                  SkBlendMode::kModulate)->makeComposed(
778cb93a386Sopenharmony_ci                                                      SkColorFilterPriv::MakeGaussian()));
779cb93a386Sopenharmony_ci                this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
780cb93a386Sopenharmony_ci                success = true;
781cb93a386Sopenharmony_ci            }
782cb93a386Sopenharmony_ci        }
783cb93a386Sopenharmony_ci
784cb93a386Sopenharmony_ci        if (!success) {
785cb93a386Sopenharmony_ci            SpotVerticesFactory factory;
786cb93a386Sopenharmony_ci            factory.fOccluderHeight = zPlaneParams.fZ;
787cb93a386Sopenharmony_ci            factory.fDevLightPos = devLightPos;
788cb93a386Sopenharmony_ci            factory.fLightRadius = lightRadius;
789cb93a386Sopenharmony_ci
790cb93a386Sopenharmony_ci            SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
791cb93a386Sopenharmony_ci            factory.fLocalCenter = center;
792cb93a386Sopenharmony_ci            viewMatrix.mapPoints(&center, 1);
793cb93a386Sopenharmony_ci            SkScalar radius, scale;
794cb93a386Sopenharmony_ci            if (SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag)) {
795cb93a386Sopenharmony_ci                SkDrawShadowMetrics::GetDirectionalParams(zPlaneParams.fZ, devLightPos.fX,
796cb93a386Sopenharmony_ci                                                          devLightPos.fY, devLightPos.fZ,
797cb93a386Sopenharmony_ci                                                          lightRadius, &radius, &scale,
798cb93a386Sopenharmony_ci                                                          &factory.fOffset);
799cb93a386Sopenharmony_ci            } else {
800cb93a386Sopenharmony_ci                SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
801cb93a386Sopenharmony_ci                                                   devLightPos.fY - center.fY, devLightPos.fZ,
802cb93a386Sopenharmony_ci                                                   lightRadius, &radius, &scale, &factory.fOffset,
803cb93a386Sopenharmony_ci                                                   rec.isLimitElevation);
804cb93a386Sopenharmony_ci            }
805cb93a386Sopenharmony_ci
806cb93a386Sopenharmony_ci            SkRect devBounds;
807cb93a386Sopenharmony_ci            viewMatrix.mapRect(&devBounds, path.getBounds());
808cb93a386Sopenharmony_ci            if (directional) {
809cb93a386Sopenharmony_ci                factory.fOccluderType = SpotVerticesFactory::OccluderType::kDirectional;
810cb93a386Sopenharmony_ci            } else if (transparent ||
811cb93a386Sopenharmony_ci                       SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
812cb93a386Sopenharmony_ci                       SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
813cb93a386Sopenharmony_ci                // if the translation of the shadow is big enough we're going to end up
814cb93a386Sopenharmony_ci                // filling the entire umbra, so we can treat these as all the same
815cb93a386Sopenharmony_ci                factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent;
816cb93a386Sopenharmony_ci            } else if (factory.fOffset.length()*scale + scale < radius) {
817cb93a386Sopenharmony_ci                // if we don't translate more than the blur distance, can assume umbra is covered
818cb93a386Sopenharmony_ci                factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaqueNoUmbra;
819cb93a386Sopenharmony_ci            } else if (path.isConvex()) {
820cb93a386Sopenharmony_ci                factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaquePartialUmbra;
821cb93a386Sopenharmony_ci            } else {
822cb93a386Sopenharmony_ci                factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent;
823cb93a386Sopenharmony_ci            }
824cb93a386Sopenharmony_ci            // need to add this after we classify the shadow
825cb93a386Sopenharmony_ci            factory.fOffset.fX += viewMatrix.getTranslateX();
826cb93a386Sopenharmony_ci            factory.fOffset.fY += viewMatrix.getTranslateY();
827cb93a386Sopenharmony_ci
828cb93a386Sopenharmony_ci            SkColor color = rec.fSpotColor;
829cb93a386Sopenharmony_ci#ifdef DEBUG_SHADOW_CHECKS
830cb93a386Sopenharmony_ci            switch (factory.fOccluderType) {
831cb93a386Sopenharmony_ci                case SpotVerticesFactory::OccluderType::kTransparent:
832cb93a386Sopenharmony_ci                    color = 0xFFD2B48C;  // tan for transparent
833cb93a386Sopenharmony_ci                    break;
834cb93a386Sopenharmony_ci                case SpotVerticesFactory::OccluderType::kOpaquePartialUmbra:
835cb93a386Sopenharmony_ci                    color = 0xFFFFA500;   // orange for opaque
836cb93a386Sopenharmony_ci                    break;
837cb93a386Sopenharmony_ci                case SpotVerticesFactory::OccluderType::kOpaqueNoUmbra:
838cb93a386Sopenharmony_ci                    color = 0xFFE5E500;  // corn yellow for covered
839cb93a386Sopenharmony_ci                    break;
840cb93a386Sopenharmony_ci                case SpotVerticesFactory::OccluderType::kDirectional:
841cb93a386Sopenharmony_ci                    color = 0xFF550000;  // dark red for directional
842cb93a386Sopenharmony_ci                    break;
843cb93a386Sopenharmony_ci            }
844cb93a386Sopenharmony_ci#endif
845cb93a386Sopenharmony_ci            if (!draw_shadow(factory, drawVertsProc, shadowedPath, color, rec.isLimitElevation)) {
846cb93a386Sopenharmony_ci                // draw with blur
847cb93a386Sopenharmony_ci                SkMatrix shadowMatrix;
848cb93a386Sopenharmony_ci                if (!SkDrawShadowMetrics::GetSpotShadowTransform(devLightPos, lightRadius,
849cb93a386Sopenharmony_ci                                                                 viewMatrix, zPlaneParams,
850cb93a386Sopenharmony_ci                                                                 path.getBounds(), directional,
851cb93a386Sopenharmony_ci                                                                 &shadowMatrix, &radius, rec.isLimitElevation)) {
852cb93a386Sopenharmony_ci                    return;
853cb93a386Sopenharmony_ci                }
854cb93a386Sopenharmony_ci                SkAutoDeviceTransformRestore adr2(this, shadowMatrix);
855cb93a386Sopenharmony_ci
856cb93a386Sopenharmony_ci                SkPaint paint;
857cb93a386Sopenharmony_ci                paint.setColor(rec.fSpotColor);
858cb93a386Sopenharmony_ci                SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
859cb93a386Sopenharmony_ci                bool respectCTM = false;
860cb93a386Sopenharmony_ci                paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
861cb93a386Sopenharmony_ci                this->drawPath(path, paint);
862cb93a386Sopenharmony_ci            }
863cb93a386Sopenharmony_ci        }
864cb93a386Sopenharmony_ci    }
865cb93a386Sopenharmony_ci}
866