Debian Codegraph @

src/gpu/graphite/render/CoverageMaskRenderStep.cpp

raw
1 /*
2 * Copyright 2023 Google LLC
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 #include "src/gpu/graphite/render/CoverageMaskRenderStep.h"
8
9 #include "include/core/SkM44.h"
10 #include "include/core/SkMatrix.h"
11 #include "include/core/SkRefCnt.h"
12 #include "include/core/SkSamplingOptions.h"
13 #include "include/core/SkScalar.h"
14 #include "include/core/SkSize.h"
15 #include "include/core/SkTileMode.h"
16 #include "include/private/base/SkAssert.h"
17 #include "include/private/base/SkDebug.h"
18 #include "src/base/SkEnumBitMask.h"
19 #include "src/core/SkSLTypeShared.h"
20 #include "src/gpu/BufferWriter.h"
21 #include "src/gpu/graphite/Attribute.h"
22 #include "src/gpu/graphite/ContextUtils.h"
23 #include "src/gpu/graphite/DrawOrder.h"
24 #include "src/gpu/graphite/DrawParams.h"
25 #include "src/gpu/graphite/DrawTypes.h"
26 #include "src/gpu/graphite/DrawWriter.h"
27 #include "src/gpu/graphite/PipelineData.h"
28 #include "src/gpu/graphite/TextureProxy.h"
29 #include "src/gpu/graphite/geom/CoverageMaskShape.h"
30 #include "src/gpu/graphite/geom/Geometry.h"
31 #include "src/gpu/graphite/geom/Rect.h"
32 #include "src/gpu/graphite/geom/Transform.h"
33 #include "src/gpu/graphite/render/CommonDepthStencilSettings.h"
34
35 #include <cstdint>
36
37 namespace skgpu::graphite {
38
39 // The device origin is applied *before* the maskToDeviceRemainder matrix so that it can be
40 // combined with the mask atlas origin. This is necessary so that the mask bounds can be inset or
41 // outset for clamping w/o affecting the alignment of the mask sampling.
42 static skvx::float2 get_device_translation(const SkM44& localToDevice) {
43 float m00 = localToDevice.rc(0,0), m01 = localToDevice.rc(0,1);
44 float m10 = localToDevice.rc(1,0), m11 = localToDevice.rc(1,1);
45
46 float det = m00*m11 - m01*m10;
47 if (SkScalarNearlyZero(det)) {
48 // We can't extract any pre-translation, since the upper 2x2 is not invertible. Return (0,0)
49 // so that the maskToDeviceRemainder matrix remains the full transform.
50 return {0.f, 0.f};
51 }
52
53 // Calculate inv([[m00,m01][m10,m11]])*[[m30][m31]] to get the pre-remainder device translation.
54 float tx = localToDevice.rc(0,3), ty = localToDevice.rc(1,3);
55 skvx::float4 invT = skvx::float4{m11, -m10, -m01, m00} * skvx::float4{tx,tx,ty,ty};
56 return (invT.xy() + invT.zw()) / det;
57 }
58
59 CoverageMaskRenderStep::CoverageMaskRenderStep(Layout layout)
60 : RenderStep(layout,
61 RenderStepID::kCoverageMask,
62 // The mask will have AA outsets baked in, but the original bounds for clipping
63 // still require the outset for analytic coverage.
64 Flags::kPerformsShading |
65 Flags::kHasTextures |
66 Flags::kEmitsCoverage |
67 Flags::kOutsetBoundsForAA |
68 Flags::kInverseFillsScissor |
69 Flags::kAppendInstances,
70 /*uniforms=*/{{"maskToDeviceRemainder", SkSLType::kFloat3x3}},
71 PrimitiveType::kTriangleStrip,
72 kDirectDepthLessPass,
73 /*staticAttrs=*/ {},
74 /*appendAttrs=*/
75 // Draw bounds and mask bounds are in normalized relative to the mask texture,
76 // but 'drawBounds' is stored in float since the coords may map outside of
77 // [0,1] for inverse-filled masks. 'drawBounds' is relative to the logical mask
78 // entry's origin, while 'maskBoundsIn' is atlas-relative. Inverse fills swap
79 // the order in 'maskBoundsIn' to be RBLT.
80 {{{"drawBounds", VertexAttribType::kFloat4 , SkSLType::kFloat4}, // ltrb
81 {"maskBoundsIn", VertexAttribType::kUShort4_norm, SkSLType::kFloat4},
82 // Remaining translation extracted from actual 'maskToDevice' transform.
83 {"deviceOrigin", VertexAttribType::kFloat2, SkSLType::kFloat2},
84 {"depth" , VertexAttribType::kFloat, SkSLType::kFloat},
85 {"ssboIndex", VertexAttribType::kUInt, SkSLType::kUInt},
86 // deviceToLocal matrix for producing local coords for shader evaluation
87 {"mat0", VertexAttribType::kFloat3, SkSLType::kFloat3},
88 {"mat1", VertexAttribType::kFloat3, SkSLType::kFloat3},
89 {"mat2", VertexAttribType::kFloat3, SkSLType::kFloat3}}},
90 /*varyings=*/
91 {{// `maskBounds` are the atlas-relative, sorted bounds of the coverage mask.
92 // `textureCoords` are the atlas-relative UV coordinates of the draw, which
93 // can spill beyond `maskBounds` for inverse fills.
94 // TODO: maskBounds is constant for all fragments for a given instance,
95 // could we store them in the draw's SSBO?
96 {"maskBounds" , SkSLType::kFloat4},
97 {"textureCoords", SkSLType::kFloat2},
98 // 'invert' is set to 0 use unmodified coverage, and set to 1 for "1-c".
99 {"invert", SkSLType::kHalf}}}) {}
100
101 std::string CoverageMaskRenderStep::vertexSkSL() const {
102 // Returns the body of a vertex function, which must define a float4 devPosition variable and
103 // must write to an already-defined float2 stepLocalCoords variable.
104 return "float4 devPosition = coverage_mask_vertex_fn("
105 "float2(sk_VertexID >> 1, sk_VertexID & 1), "
106 "maskToDeviceRemainder, drawBounds, maskBoundsIn, deviceOrigin, "
107 "depth, float3x3(mat0, mat1, mat2), "
108 "maskBounds, textureCoords, invert, stepLocalCoords);\n";
109 }
110
111 std::string CoverageMaskRenderStep::texturesAndSamplersSkSL(
112 const ResourceBindingRequirements& bindingReqs, int* nextBindingIndex) const {
113 return EmitSamplerLayout(bindingReqs, nextBindingIndex) + " sampler2D pathAtlas;";
114 }
115
116 const char* CoverageMaskRenderStep::fragmentCoverageSkSL() const {
117 return
118 "half c = sample(pathAtlas, clamp(textureCoords, maskBounds.LT, maskBounds.RB)).r;\n"
119 "outputCoverage = half4(mix(c, 1 - c, invert));\n";
120 }
121
122 bool CoverageMaskRenderStep::usesUniformsInFragmentSkSL() const { return false; }
123
124 void CoverageMaskRenderStep::writeVertices(DrawWriter* dw,
125 const DrawParams& params,
126 uint32_t ssboIndex) const {
127 const CoverageMaskShape& coverageMask = params.geometry().coverageMaskShape();
128 const TextureProxy* proxy = coverageMask.textureProxy();
129 SkASSERT(proxy);
130
131 // A quad is a 4-vertex instance. The coordinates are derived from the vertex IDs.
132 DrawWriter::Instances instances(*dw, {}, {}, 4);
133
134 // The device origin is the translation extracted from the mask-to-device matrix so
135 // that the remaining matrix uniform has less variance between draws.
136 const auto& maskToDevice = params.transform().matrix();
137 skvx::float2 deviceOrigin = get_device_translation(maskToDevice);
138
139 // Relative to mask space (device origin and mask-to-device remainder must be applied in shader)
140 skvx::float4 maskBounds = coverageMask.bounds().ltrb();
141 skvx::float4 drawBounds;
142
143 if (coverageMask.inverted()) {
144 // Only mask filters trigger complex transforms, and they are never inverse filled. Since
145 // we know this is an inverted mask, then we can exactly map the draw's clip bounds to mask
146 // space so that the clip is still fully covered without branching in the vertex shader.
147 SkASSERT(maskToDevice == SkM44::Translate(deviceOrigin.x(), deviceOrigin.y()));
148 drawBounds = params.drawBounds().makeOffset(-deviceOrigin).ltrb();
149
150 // If the mask is fully clipped out, then the shape's mask info should be (0,0,0,0).
151 // If it's not fully clipped out, then the mask info should be non-empty.
152 const bool emptyMask = all(maskBounds == 0.f);
153 SkDEBUGCODE(Rect clippedShapeBounds =
154 params.transformedShapeBounds().makeIntersect(params.scissor()));
155 SkASSERT(!clippedShapeBounds.isEmptyNegativeOrNaN() ^ emptyMask);
156
157 if (emptyMask) {
158 // The inversion check is strict inequality, so (0,0,0,0) would not be detected. Adjust
159 // to (0,0,1/2,1/2) to restrict sampling to the top-left quarter of the top-left pixel,
160 // which should have a value of 0 regardless of filtering mode.
161 maskBounds = skvx::float4{0.f, 0.f, 0.5f, 0.5f};
162 } else {
163 // Add 1/2px outset to the mask bounds so that clamped coordinates sample the texel
164 // center of the padding around the atlas entry.
165 maskBounds += skvx::float4{-0.5f, -0.5f, 0.5f, 0.5f};
166 }
167
168 // and store RBLT so that the 'maskBoundsIn' attribute has xy > zw to detect inverse fill.
169 maskBounds = skvx::shuffle<2,3,0,1>(maskBounds);
170 } else {
171 // If we aren't inverted, then the originally assigned values don't need to be adjusted, but
172 // also ensure the mask isn't empty (otherwise the draw should have been skipped earlier).
173 SkASSERT(!coverageMask.bounds().isEmptyNegativeOrNaN());
174 SkASSERT(all(maskBounds.xy() < maskBounds.zw()));
175
176 // Since the mask bounds and draw bounds are 1-to-1 with each other, the clamping of texture
177 // coords is mostly a formality. We inset the mask bounds by 1/2px so that we clamp to the
178 // texel center of the outer row/column of the mask. This should be a no-op for nearest
179 // sampling but prevents any linear sampling from incorporating adjacent data; for atlases
180 // this would just be 0 but for non-atlas coverage masks that might not have padding this
181 // avoids filtering unknown values in an approx-fit texture.
182 drawBounds = maskBounds;
183 maskBounds -= skvx::float4{-0.5f, -0.5f, 0.5f, 0.5f};
184 }
185
186 // Move 'drawBounds' and 'maskBounds' into the atlas coordinate space, then adjust the
187 // device translation to undo the atlas origin automatically in the vertex shader.
188 skvx::float2 textureOrigin = skvx::cast<float>(coverageMask.textureOrigin());
189 maskBounds += textureOrigin.xyxy();
190 drawBounds += textureOrigin.xyxy();
191 deviceOrigin -= textureOrigin;
192
193 // Normalize drawBounds and maskBounds after possibly correcting drawBounds for inverse fills.
194 // The maskToDevice matrix uniform will handle de-normalizing drawBounds for vertex positions.
195 auto atlasSizeInv = skvx::float2{1.f / proxy->dimensions().width(),
196 1.f / proxy->dimensions().height()};
197 drawBounds *= atlasSizeInv.xyxy();
198 maskBounds *= atlasSizeInv.xyxy();
199 deviceOrigin *= atlasSizeInv;
200
201 // Since the mask bounds define normalized texels of the texture, we can encode them as
202 // ushort_norm without losing precision to save space.
203 SkASSERT(all((maskBounds >= 0.f) & (maskBounds <= 1.f)));
204 maskBounds = 65535.f * maskBounds + 0.5f;
205
206 const SkM44& m = coverageMask.deviceToLocal();
207 instances.append(1) << drawBounds << skvx::cast<uint16_t>(maskBounds) << deviceOrigin
208 << params.order().depthAsFloat() << ssboIndex
209 << m.rc(0,0) << m.rc(1,0) << m.rc(3,0) // mat0
210 << m.rc(0,1) << m.rc(1,1) << m.rc(3,1) // mat1
211 << m.rc(0,3) << m.rc(1,3) << m.rc(3,3); // mat2
212 }
213
214 void CoverageMaskRenderStep::writeUniformsAndTextures(const DrawParams& params,
215 PipelineDataGatherer* gatherer) const {
216 SkDEBUGCODE(gatherer->checkRewind());
217 SkDEBUGCODE(UniformExpectationsValidator uev(gatherer, this->uniforms());)
218
219 const CoverageMaskShape& coverageMask = params.geometry().coverageMaskShape();
220 const TextureProxy* proxy = coverageMask.textureProxy();
221 SkASSERT(proxy);
222
223 // Most coverage masks are aligned with the device pixels, so the params' transform is an
224 // integer translation matrix. This translation is extracted as an instance attribute so that
225 // the remaining transform has a much lower frequency of changing (only complex-transformed
226 // mask filters).
227 skvx::float2 deviceOrigin = get_device_translation(params.transform().matrix());
228 SkMatrix maskToDevice = params.transform().matrix().asM33();
229 maskToDevice.preTranslate(-deviceOrigin.x(), -deviceOrigin.y());
230
231 // The mask coordinates in the vertex shader will be normalized, so scale by the proxy size
232 // to get back to Skia's texel-based coords.
233 maskToDevice.preScale(proxy->dimensions().width(), proxy->dimensions().height());
234
235 // Write uniforms:
236 gatherer->write(maskToDevice);
237
238 // Write textures and samplers:
239 const bool pixelAligned =
240 params.transform().type() <= Transform::Type::kSimpleRectStaysRect &&
241 params.transform().maxScaleFactor() == 1.f &&
242 all(deviceOrigin == floor(deviceOrigin + SK_ScalarNearlyZero));
243 gatherer->add(sk_ref_sp(proxy), {pixelAligned ? SkFilterMode::kNearest : SkFilterMode::kLinear,
244 SkTileMode::kClamp});
245 }
246
247 } // namespace skgpu::graphite