Debian Codegraph @

src/gpu/graphite/geom/AnalyticBlurMask.cpp

raw
1 /*
2 * Copyright 2024 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
8 #include "src/gpu/graphite/geom/AnalyticBlurMask.h"
9
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkBlendMode.h"
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkImageFilter.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkRRect.h"
18 #include "include/core/SkRect.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkSize.h"
21 #include "include/effects/SkImageFilters.h"
22 #include "include/gpu/GpuTypes.h"
23 #include "include/gpu/graphite/Recorder.h"
24 #include "include/private/base/SkAlign.h"
25 #include "include/private/base/SkAssert.h"
26 #include "include/private/base/SkFloatingPoint.h"
27 #include "include/private/base/SkMacros.h"
28 #include "include/private/base/SkPoint_impl.h"
29 #include "src/base/SkFloatBits.h"
30 #include "src/core/SkRRectPriv.h"
31 #include "src/gpu/BlurUtils.h"
32 #include "src/gpu/ResourceKey.h"
33 #include "src/gpu/SkBackingFit.h"
34 #include "src/gpu/graphite/Caps.h"
35 #include "src/gpu/graphite/Image_Graphite.h" // IWYU pragma: keep
36 #include "src/gpu/graphite/ProxyCache.h"
37 #include "src/gpu/graphite/RecorderPriv.h"
38 #include "src/gpu/graphite/Surface_Graphite.h"
39 #include "src/gpu/graphite/geom/Transform.h"
40 #include "src/sksl/SkSLUtil.h"
41
42 #include <algorithm>
43 #include <cmath>
44 #include <cstdint>
45 #include <cstring>
46
47 namespace skgpu::graphite {
48
49 namespace {
50
51 std::optional<Rect> outset_bounds(const SkMatrix& localToDevice,
52 float devSigma,
53 const SkRect& srcRect) {
54 float outsetX = 3.0f * devSigma;
55 float outsetY = 3.0f * devSigma;
56 if (localToDevice.isScaleTranslate()) {
57 outsetX /= std::fabs(localToDevice.getScaleX());
58 outsetY /= std::fabs(localToDevice.getScaleY());
59 } else {
60 SkSize scale;
61 if (!localToDevice.decomposeScale(&scale, nullptr)) {
62 return std::nullopt;
63 }
64 outsetX /= scale.width();
65 outsetY /= scale.height();
66 }
67 return srcRect.makeOutset(outsetX, outsetY);
68 }
69
70 } // anonymous namespace
71
72 std::optional<AnalyticBlurMask> AnalyticBlurMask::Make(Recorder* recorder,
73 const Transform& localToDeviceTransform,
74 float deviceSigma,
75 const SkRRect& srcRRect) {
76 // TODO: Implement SkMatrix functionality used below for Transform.
77 SkMatrix localToDevice = localToDeviceTransform;
78
79 if (srcRRect.isRect() && localToDevice.preservesRightAngles()) {
80 return MakeRect(recorder, localToDevice, deviceSigma, srcRRect.rect());
81 }
82
83 const auto devRRect = srcRRect.transform(localToDevice);
84 if (devRRect.has_value() && SkRRectPriv::IsCircle(*devRRect)) {
85 return MakeCircle(recorder, localToDevice, deviceSigma, srcRRect.rect(), devRRect->rect());
86 }
87
88 // A local-space circle transformed by a rotation matrix will fail SkRRect::transform since it
89 // only supports scale + translate matrices, but is still a valid circle that can be blurred.
90 if (SkRRectPriv::IsCircle(srcRRect) && localToDevice.isSimilarity()) {
91 const SkRect srcRect = srcRRect.rect();
92 const SkPoint devCenter = localToDevice.mapPoint(srcRect.center());
93 const float devRadius = localToDevice.mapVector(0.0f, srcRect.width() / 2.0f).length();
94 const SkRect devRect = {devCenter.x() - devRadius,
95 devCenter.y() - devRadius,
96 devCenter.x() + devRadius,
97 devCenter.y() + devRadius};
98 return MakeCircle(recorder, localToDevice, deviceSigma, srcRect, devRect);
99 }
100
101 if (devRRect.has_value() && SkRRectPriv::IsSimpleCircular(*devRRect) &&
102 localToDevice.isScaleTranslate()) {
103 return MakeRRect(recorder, localToDevice, deviceSigma, srcRRect, *devRRect);
104 }
105
106 return std::nullopt;
107 }
108
109 std::optional<AnalyticBlurMask> AnalyticBlurMask::MakeRect(Recorder* recorder,
110 const SkMatrix& localToDevice,
111 float devSigma,
112 const SkRect& srcRect) {
113 SkASSERT(srcRect.isSorted());
114
115 SkRect devRect;
116 SkMatrix devToScaledShape;
117 if (localToDevice.rectStaysRect()) {
118 // We can do everything in device space when the src rect projects to a rect in device
119 // space.
120 SkAssertResult(localToDevice.mapRect(&devRect, srcRect));
121
122 } else {
123 // The view matrix may scale, perhaps anisotropically. But we want to apply our device space
124 // sigma to the delta of frag coord from the rect edges. Factor out the scaling to define a
125 // space that is purely rotation / translation from device space (and scale from src space).
126 // We'll meet in the middle: pre-scale the src rect to be in this space and then apply the
127 // inverse of the rotation / translation portion to the frag coord.
128 SkMatrix m;
129 SkSize scale;
130 if (!localToDevice.decomposeScale(&scale, &m)) {
131 return std::nullopt;
132 }
133 if (!m.invert(&devToScaledShape)) {
134 return std::nullopt;
135 }
136 devRect = {srcRect.left() * scale.width(),
137 srcRect.top() * scale.height(),
138 srcRect.right() * scale.width(),
139 srcRect.bottom() * scale.height()};
140 }
141
142 if (!recorder->priv().caps()->shaderCaps()->fFloatIs32Bits) {
143 // We promote the math that gets us into the Gaussian space to full float when the rect
144 // coords are large. If we don't have full float then fail. We could probably clip the rect
145 // to an outset device bounds instead.
146 if (std::fabs(devRect.left()) > 16000.0f || std::fabs(devRect.top()) > 16000.0f ||
147 std::fabs(devRect.right()) > 16000.0f || std::fabs(devRect.bottom()) > 16000.0f) {
148 return std::nullopt;
149 }
150 }
151
152 const float sixSigma = 6.0f * devSigma;
153 const int tableWidth = ComputeIntegralTableWidth(sixSigma);
154 UniqueKey key;
155 {
156 static const UniqueKey::Domain kRectBlurDomain = UniqueKey::GenerateDomain();
157 UniqueKey::Builder builder(&key, kRectBlurDomain, 1, "BlurredRectIntegralTable");
158 builder[0] = tableWidth;
159 }
160 sk_sp<TextureProxy> integral = recorder->priv().proxyCache()->findOrCreateCachedProxy(
161 recorder, key, &tableWidth,
162 [](const void* context) {
163 int tableWidth = *static_cast<const int*>(context);
164 return CreateIntegralTable(tableWidth);
165 });
166
167 if (!integral) {
168 return std::nullopt;
169 }
170
171 // In the fast variant we think of the midpoint of the integral texture as aligning with the
172 // closest rect edge both in x and y. To simplify texture coord calculation we inset the rect so
173 // that the edge of the inset rect corresponds to t = 0 in the texture. It actually simplifies
174 // things a bit in the !isFast case, too.
175 const float threeSigma = 3.0f * devSigma;
176 const Rect shapeData = Rect(devRect.left() + threeSigma,
177 devRect.top() + threeSigma,
178 devRect.right() - threeSigma,
179 devRect.bottom() - threeSigma);
180
181 // In our fast variant we find the nearest horizontal and vertical edges and for each do a
182 // lookup in the integral texture for each and multiply them. When the rect is less than 6*sigma
183 // wide then things aren't so simple and we have to consider both the left and right edge of the
184 // rectangle (and similar in y).
185 const bool isFast = shapeData.left() <= shapeData.right() && shapeData.top() <= shapeData.bot();
186
187 const float invSixSigma = 1.0f / sixSigma;
188
189 // Determine how much to outset the draw bounds to ensure we hit pixels within 3*sigma.
190 std::optional<Rect> drawBounds = outset_bounds(localToDevice, devSigma, srcRect);
191 if (!drawBounds) {
192 return std::nullopt;
193 }
194
195 return AnalyticBlurMask(*drawBounds,
196 SkM44(devToScaledShape),
197 ShapeType::kRect,
198 shapeData,
199 {static_cast<float>(isFast), invSixSigma},
200 integral);
201 }
202
203 static float quantize(float deviceSpaceFloat) {
204 // Snap the device-space value to the nearest 1/32 to increase cache hits w/o impacting the
205 // visible output since it should be hard to see a change limited to 1/32 of a pixel.
206 // Clamp the value to 1/32 as identity blurs and points should be caught earlier.
207 return std::max(SkScalarRoundToInt(deviceSpaceFloat * 32.f) / 32.f, 1.f / 32.f);
208 }
209
210 std::optional<AnalyticBlurMask> AnalyticBlurMask::MakeCircle(Recorder* recorder,
211 const SkMatrix& localToDevice,
212 float devSigma,
213 const SkRect& srcRect,
214 const SkRect& devRect) {
215 const float radius = devRect.width() / 2.0f;
216 if (!SkIsFinite(radius) || radius < SK_ScalarNearlyZero) {
217 return std::nullopt;
218 }
219
220 // Pack profile-dependent properties and derived values into a struct that can be passed into
221 // findOrCreateCachedProxy to lazily invoke the profile creation bitmap factories.
222 struct DerivedParams {
223 float fQuantizedRadius;
224 float fQuantizedDevSigma;
225
226 float fSolidRadius;
227 float fTextureRadius;
228
229 bool fUseHalfPlaneApprox;
230
231 DerivedParams(float devSigma, float radius)
232 : fQuantizedRadius(quantize(radius))
233 , fQuantizedDevSigma(quantize(devSigma)) {
234 SkASSERT(fQuantizedRadius > 0.f); // quantization shouldn't have rounded to 0
235
236 // When sigma is really small this becomes a equivalent to convolving a Gaussian with a
237 // half-plane. Similarly, in the extreme high ratio cases circle becomes a point WRT to
238 // the Guassian and the profile texture is a just a Gaussian evaluation. However, we
239 // haven't yet implemented this latter optimization.
240 constexpr float kHalfPlaneThreshold = 0.1f;
241 const float sigmaToRadiusRatio = std::min(fQuantizedDevSigma / fQuantizedRadius, 8.0f);
242 if (sigmaToRadiusRatio <= kHalfPlaneThreshold) {
243 fUseHalfPlaneApprox = true;
244 fSolidRadius = fQuantizedRadius - 3.0f * fQuantizedDevSigma;
245 fTextureRadius = 6.0f * fQuantizedDevSigma;
246 } else {
247 fUseHalfPlaneApprox = false;
248 fQuantizedDevSigma = fQuantizedRadius * sigmaToRadiusRatio;
249 fSolidRadius = 0.0f;
250 fTextureRadius = fQuantizedRadius + 3.0f * fQuantizedDevSigma;
251 }
252 }
253 } params{devSigma, radius};
254
255 UniqueKey key;
256 {
257 static const UniqueKey::Domain kCircleBlurDomain = UniqueKey::GenerateDomain();
258 UniqueKey::Builder builder(&key, kCircleBlurDomain, 2, "BlurredCircleIntegralTable");
259 if (params.fUseHalfPlaneApprox) {
260 // There only ever needs to be one half plane approximation table, so store {0,0} into
261 // the key, which never arises under normal use because we reject radius = 0 above.
262 builder[0] = SkFloat2Bits(0.f);
263 builder[1] = SkFloat2Bits(0.f);
264 } else {
265 builder[0] = SkFloat2Bits(params.fQuantizedDevSigma);
266 builder[1] = SkFloat2Bits(params.fQuantizedRadius);
267 }
268 }
269 sk_sp<TextureProxy> profile = recorder->priv().proxyCache()->findOrCreateCachedProxy(
270 recorder, key, &params,
271 [](const void* context) {
272 constexpr int kProfileTextureWidth = 512;
273 const DerivedParams* params = static_cast<const DerivedParams*>(context);
274 if (params->fUseHalfPlaneApprox) {
275 return CreateHalfPlaneProfile(kProfileTextureWidth);
276 } else {
277 // Rescale params to the size of the texture we're creating.
278 const float scale = kProfileTextureWidth / params->fTextureRadius;
279 return CreateCircleProfile(params->fQuantizedDevSigma * scale,
280 params->fQuantizedRadius * scale,
281 kProfileTextureWidth);
282 }
283 });
284
285 if (!profile) {
286 return std::nullopt;
287 }
288
289 // In the shader we calculate an index into the blur profile
290 // "i = (length(fragCoords - circleCenter) - solidRadius + 0.5) / textureRadius" as
291 // "i = length((fragCoords - circleCenter) / textureRadius) -
292 // (solidRadius - 0.5) / textureRadius"
293 // to avoid passing large values to length() that would overflow. We precalculate
294 // "1 / textureRadius" and "(solidRadius - 0.5) / textureRadius" here.
295 const Rect shapeData = Rect(devRect.centerX(),
296 devRect.centerY(),
297 1.0f / params.fTextureRadius,
298 (params.fSolidRadius - 0.5f) / params.fTextureRadius);
299
300 // Determine how much to outset the draw bounds to ensure we hit pixels within 3*sigma.
301 std::optional<Rect> drawBounds = outset_bounds(localToDevice,
302 params.fQuantizedDevSigma,
303 srcRect);
304 if (!drawBounds) {
305 return std::nullopt;
306 }
307
308 constexpr float kUnusedBlurData = 0.0f;
309 return AnalyticBlurMask(*drawBounds,
310 SkM44(),
311 ShapeType::kCircle,
312 shapeData,
313 {kUnusedBlurData, kUnusedBlurData},
314 profile);
315 }
316
317 std::optional<AnalyticBlurMask> AnalyticBlurMask::MakeRRect(Recorder* recorder,
318 const SkMatrix& localToDevice,
319 float devSigma,
320 const SkRRect& srcRRect,
321 const SkRRect& devRRect) {
322 const int devBlurRadius = 3 * SkScalarCeilToInt(devSigma - 1.0f / 6.0f);
323
324 const SkVector& devRadiiUL = devRRect.radii(SkRRect::kUpperLeft_Corner);
325 const SkVector& devRadiiUR = devRRect.radii(SkRRect::kUpperRight_Corner);
326 const SkVector& devRadiiLR = devRRect.radii(SkRRect::kLowerRight_Corner);
327 const SkVector& devRadiiLL = devRRect.radii(SkRRect::kLowerLeft_Corner);
328
329 const int devLeft = SkScalarCeilToInt(std::max<float>(devRadiiUL.fX, devRadiiLL.fX));
330 const int devTop = SkScalarCeilToInt(std::max<float>(devRadiiUL.fY, devRadiiUR.fY));
331 const int devRight = SkScalarCeilToInt(std::max<float>(devRadiiUR.fX, devRadiiLR.fX));
332 const int devBot = SkScalarCeilToInt(std::max<float>(devRadiiLL.fY, devRadiiLR.fY));
333
334 // This is a conservative check for nine-patchability.
335 const SkRect& devOrig = devRRect.getBounds();
336 if (devOrig.fLeft + devLeft + devBlurRadius >= devOrig.fRight - devRight - devBlurRadius ||
337 devOrig.fTop + devTop + devBlurRadius >= devOrig.fBottom - devBot - devBlurRadius) {
338 return std::nullopt;
339 }
340
341 const int newRRWidth = 2 * devBlurRadius + devLeft + devRight + 1;
342 const int newRRHeight = 2 * devBlurRadius + devTop + devBot + 1;
343
344 const SkRect newRect = SkRect::MakeXYWH(SkIntToScalar(devBlurRadius),
345 SkIntToScalar(devBlurRadius),
346 SkIntToScalar(newRRWidth),
347 SkIntToScalar(newRRHeight));
348 SkVector newRadii[4];
349 newRadii[0] = {SkScalarCeilToScalar(devRadiiUL.fX), SkScalarCeilToScalar(devRadiiUL.fY)};
350 newRadii[1] = {SkScalarCeilToScalar(devRadiiUR.fX), SkScalarCeilToScalar(devRadiiUR.fY)};
351 newRadii[2] = {SkScalarCeilToScalar(devRadiiLR.fX), SkScalarCeilToScalar(devRadiiLR.fY)};
352 newRadii[3] = {SkScalarCeilToScalar(devRadiiLL.fX), SkScalarCeilToScalar(devRadiiLL.fY)};
353
354 // NOTE: SkRRect does not satisfy std::has_unique_object_representation because NaN's in float
355 // values violate that, but all SkRRects that get here will be finite so it's not really a
356 // an issue for hashing the data directly.
357 SK_BEGIN_REQUIRE_DENSE
358 struct DerivedParams {
359 SkRRect fRRectToDraw;
360 SkISize fDimensions;
361 float fDevSigma;
362 } params;
363 SK_END_REQUIRE_DENSE
364
365 params.fRRectToDraw.setRectRadii(newRect, newRadii);
366 params.fDimensions =
367 SkISize::Make(newRRWidth + 2 * devBlurRadius, newRRHeight + 2 * devBlurRadius);
368 params.fDevSigma = devSigma;
369
370 // TODO(b/343684954, b/338032240): This is just generating a blurred rrect mask image on the CPU
371 // and uploading it. We should either generate them on the GPU and cache them here, or if we
372 // have a general-purpose blur mask cache, then there's no reason rrects couldn't just use that
373 // since this "analytic" blur isn't actually simplifying work like the circle and rect case.
374 // That would also allow us to support arbitrary blurred rrects and not just ninepatch rrects.
375 static const UniqueKey::Domain kRRectBlurDomain = UniqueKey::GenerateDomain();
376 UniqueKey key;
377 {
378 static constexpr uint16_t kKeySize = sizeof(DerivedParams) / sizeof(uint32_t);
379 static_assert(SkIsAlign4(sizeof(DerivedParams)));
380 // TODO: We should discretize the sigma to perceptibly meaningful changes to the table,
381 // as well as the underlying the round rect geometry.
382 UniqueKey::Builder builder(&key, kRRectBlurDomain, kKeySize, "BlurredRRectNinePatch");
383 memcpy(&builder[0], &params, sizeof(DerivedParams));
384 }
385
386 sk_sp<TextureProxy> ninePatch = recorder->priv().proxyCache()->findOrCreateCachedProxy(
387 recorder, key, &params,
388 [](Recorder* r, const void* context) -> sk_sp<Image> {
389 const DerivedParams* params = static_cast<const DerivedParams*>(context);
390
391 const SkImageInfo rrectII = SkImageInfo::MakeA8(params->fDimensions.width(),
392 params->fDimensions.height());
393 sk_sp<Surface> surface = Surface::MakeScratch(r, rrectII, "BlurredRRectNinePatch",
394 Budgeted::kYes, Mipmapped::kNo,
395 SkBackingFit::kExact); // for now...
396 if (!surface) {
397 return nullptr;
398 }
399 // Use an image filter directly, not a mask filter, so we don't get stuck in a loop
400 SkPaint blurRRectPaint;
401 blurRRectPaint.setImageFilter(SkImageFilters::Blur(params->fDevSigma,
402 params->fDevSigma,
403 nullptr));
404 blurRRectPaint.setBlendMode(SkBlendMode::kSrc);
405 surface->getCanvas()->drawRRect(params->fRRectToDraw, blurRRectPaint);
406 return surface->asImage();
407 });
408
409 if (!ninePatch) {
410 return std::nullopt;
411 }
412
413 const float blurRadius = 3.0f * SkScalarCeilToScalar(devSigma - 1.0f / 6.0f);
414 const float edgeSize = 2.0f * blurRadius + SkRRectPriv::GetSimpleRadii(devRRect).fX + 0.5f;
415 const Rect shapeData = devRRect.rect().makeOutset(blurRadius, blurRadius);
416
417 // Determine how much to outset the draw bounds to ensure we hit pixels within 3*sigma.
418 std::optional<Rect> drawBounds = outset_bounds(localToDevice, devSigma, srcRRect.rect());
419 if (!drawBounds) {
420 return std::nullopt;
421 }
422
423 constexpr float kUnusedBlurData = 0.0f;
424 return AnalyticBlurMask(*drawBounds,
425 SkM44(),
426 ShapeType::kRRect,
427 shapeData,
428 {edgeSize, kUnusedBlurData},
429 ninePatch);
430 }
431
432 } // namespace skgpu::graphite