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