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