1 /*
2 * Copyright 2021 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 "modules/svg/include/SkSVGMask.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColorFilter.h"
12 #include "include/effects/SkLumaColorFilter.h"
13 #include "modules/svg/include/SkSVGRenderContext.h"
14
parseAndSetAttribute(const char * n,const char * v)15 bool SkSVGMask::parseAndSetAttribute(const char* n, const char* v) {
16 return INHERITED::parseAndSetAttribute(n, v) ||
17 this->setX(SkSVGAttributeParser::parse<SkSVGLength>("x", n, v)) ||
18 this->setY(SkSVGAttributeParser::parse<SkSVGLength>("y", n, v)) ||
19 this->setWidth(SkSVGAttributeParser::parse<SkSVGLength>("width", n, v)) ||
20 this->setHeight(SkSVGAttributeParser::parse<SkSVGLength>("height", n, v)) ||
21 this->setMaskUnits(
22 SkSVGAttributeParser::parse<SkSVGObjectBoundingBoxUnits>("maskUnits", n, v)) ||
23 this->setMaskContentUnits(
24 SkSVGAttributeParser::parse<SkSVGObjectBoundingBoxUnits>("maskContentUnits", n, v));
25 }
26
bounds(const SkSVGRenderContext & ctx) const27 SkRect SkSVGMask::bounds(const SkSVGRenderContext& ctx) const {
28 return ctx.resolveOBBRect(fX, fY, fWidth, fHeight, fMaskUnits);
29 }
30
renderMask(const SkSVGRenderContext & ctx) const31 void SkSVGMask::renderMask(const SkSVGRenderContext& ctx) const {
32 // https://www.w3.org/TR/SVG11/masking.html#Masking
33
34 // Propagate any inherited properties that may impact mask effect behavior (e.g.
35 // color-interpolation). We call this explicitly here because the SkSVGMask
36 // nodes do not participate in the normal onRender path, which is when property
37 // propagation currently occurs.
38 // The local context also restores the filter layer created below on scope exit.
39 SkSVGRenderContext lctx(ctx);
40 this->onPrepareToRender(&lctx);
41
42 const auto ci = *lctx.presentationContext().fInherited.fColorInterpolation;
43 auto ci_filter = (ci == SkSVGColorspace::kLinearRGB)
44 ? SkColorFilters::SRGBToLinearGamma()
45 : nullptr;
46
47 SkPaint mask_filter;
48 mask_filter.setColorFilter(
49 SkColorFilters::Compose(SkLumaColorFilter::Make(), std::move(ci_filter)));
50
51 // Mask color filter layer.
52 // Note: We could avoid this extra layer if we invert the stacking order
53 // (mask/content -> content/mask, kSrcIn -> kDstIn) and apply the filter
54 // via the top (mask) layer paint. That requires deferring mask rendering
55 // until after node content, which introduces extra state/complexity.
56 // Something to consider if masking performance ever becomes an issue.
57 lctx.canvas()->saveLayer(nullptr, &mask_filter);
58
59 const auto obbt = ctx.transformForCurrentOBB(fMaskContentUnits);
60 lctx.canvas()->translate(obbt.offset.x, obbt.offset.y);
61 lctx.canvas()->scale(obbt.scale.x, obbt.scale.y);
62
63 for (const auto& child : fChildren) {
64 child->render(lctx);
65 }
66 }
67