Debian Codegraph @

src/gpu/BlurUtils.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/BlurUtils.h"
8
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkImageInfo.h"
11 #include "include/core/SkRRect.h"
12 #include "include/core/SkRect.h"
13 #include "include/core/SkScalar.h"
14 #include "include/core/SkSize.h"
15 #include "include/private/base/SkAssert.h"
16 #include "include/private/base/SkFloatingPoint.h"
17 #include "include/private/base/SkMath.h"
18 #include "include/private/base/SkPoint_impl.h"
19 #include "include/private/base/SkTemplates.h"
20 #include "include/private/base/SkTo.h"
21 #include "src/base/SkMathPriv.h"
22 #include "src/core/SkColorPriv.h"
23
24 #include <algorithm>
25 #include <cmath>
26 #include <cstdint>
27 #include <cstring>
28 #include <limits>
29 #include <memory>
30 #include <vector>
31
32 namespace skgpu {
33
34 ///////////////////////////////////////////////////////////////////////////////
35 // Rect Blur
36 ///////////////////////////////////////////////////////////////////////////////
37
38 // TODO: it seems like there should be some synergy with SkBlurMask::ComputeBlurProfile
39 SkBitmap CreateIntegralTable(int width) {
40 SkBitmap table;
41
42 if (width <= 0) {
43 return table;
44 }
45
46 if (!table.tryAllocPixels(SkImageInfo::MakeA8(width, 1))) {
47 return table;
48 }
49 *table.getAddr8(0, 0) = 255;
50 const float invWidth = 1.f / width;
51 for (int i = 1; i < width - 1; ++i) {
52 float x = (i + 0.5f) * invWidth;
53 x = (-6 * x + 3) * SK_ScalarRoot2Over2;
54 float integral = 0.5f * (std::erf(x) + 1.f);
55 *table.getAddr8(i, 0) = SkToU8(sk_float_round2int(255.f * integral));
56 }
57
58 *table.getAddr8(width - 1, 0) = 0;
59 table.setImmutable();
60 return table;
61 }
62
63 int ComputeIntegralTableWidth(float sixSigma) {
64 // Check for NaN/infinity
65 if (!SkIsFinite(sixSigma)) {
66 return 0;
67 }
68 // Avoid overflow, covers both multiplying by 2 and finding next power of 2:
69 // 2*((2^31-1)/4 + 1) = 2*(2^29-1) + 2 = 2^30 and SkNextPow2(2^30) = 2^30
70 if (sixSigma > SK_MaxS32 / 4 + 1) {
71 return 0;
72 }
73 // The texture we're producing represents the integral of a normal distribution over a
74 // six-sigma range centered at zero. We want enough resolution so that the linear
75 // interpolation done in texture lookup doesn't introduce noticeable artifacts. We
76 // conservatively choose to have 2 texels for each dst pixel.
77 int minWidth = 2 * ((int)std::ceil(sixSigma));
78 // Bin by powers of 2 with a minimum so we get good profile reuse.
79 return std::max(SkNextPow2(minWidth), 32);
80 }
81
82 ///////////////////////////////////////////////////////////////////////////////
83 // Circle Blur
84 ///////////////////////////////////////////////////////////////////////////////
85
86 // Computes an unnormalized half kernel (right side). Returns the summation of all the half
87 // kernel values.
88 static float make_unnormalized_half_kernel(float* halfKernel, int halfKernelSize, float sigma) {
89 const float invSigma = 1.0f / sigma;
90 const float b = -0.5f * invSigma * invSigma;
91 float tot = 0.0f;
92 // Compute half kernel values at half pixel steps out from the center.
93 float t = 0.5f;
94 for (int i = 0; i < halfKernelSize; ++i) {
95 float value = expf(t * t * b);
96 tot += value;
97 halfKernel[i] = value;
98 t += 1.0f;
99 }
100 return tot;
101 }
102
103 // Create a Gaussian half-kernel (right side) and a summed area table given a sigma and number
104 // of discrete steps. The half kernel is normalized to sum to 0.5.
105 static void make_half_kernel_and_summed_table(float* halfKernel,
106 float* summedHalfKernel,
107 int halfKernelSize,
108 float sigma) {
109 // The half kernel should sum to 0.5 not 1.0.
110 const float tot = 2.0f * make_unnormalized_half_kernel(halfKernel, halfKernelSize, sigma);
111 float sum = 0.0f;
112 for (int i = 0; i < halfKernelSize; ++i) {
113 halfKernel[i] /= tot;
114 sum += halfKernel[i];
115 summedHalfKernel[i] = sum;
116 }
117 }
118
119 // Applies the 1D half kernel vertically at points along the x axis to a circle centered at the
120 // origin with radius circleR.
121 static void apply_kernel_in_y(float* results,
122 int numSteps,
123 float firstX,
124 float circleR,
125 int halfKernelSize,
126 const float* summedHalfKernelTable) {
127 float x = firstX;
128 for (int i = 0; i < numSteps; ++i, x += 1.0f) {
129 if (x < -circleR || x > circleR) {
130 results[i] = 0;
131 continue;
132 }
133 float y = sqrtf(circleR * circleR - x * x);
134 // In the column at x we exit the circle at +y and -y
135 // The summed table entry j is actually reflects an offset of j + 0.5.
136 y -= 0.5f;
137 int yInt = SkScalarFloorToInt(y);
138 SkASSERT(yInt >= -1);
139 if (y < 0) {
140 results[i] = (y + 0.5f) * summedHalfKernelTable[0];
141 } else if (yInt >= halfKernelSize - 1) {
142 results[i] = 0.5f;
143 } else {
144 float yFrac = y - yInt;
145 results[i] = (1.0f - yFrac) * summedHalfKernelTable[yInt] +
146 yFrac * summedHalfKernelTable[yInt + 1];
147 }
148 }
149 }
150
151 // Apply a Gaussian at point (evalX, 0) to a circle centered at the origin with radius circleR.
152 // This relies on having a half kernel computed for the Gaussian and a table of applications of
153 // the half kernel in y to columns at (evalX - halfKernel, evalX - halfKernel + 1, ..., evalX +
154 // halfKernel) passed in as yKernelEvaluations.
155 static uint8_t eval_at(float evalX,
156 float circleR,
157 const float* halfKernel,
158 int halfKernelSize,
159 const float* yKernelEvaluations) {
160 float acc = 0;
161
162 float x = evalX - halfKernelSize;
163 for (int i = 0; i < halfKernelSize; ++i, x += 1.0f) {
164 if (x < -circleR || x > circleR) {
165 continue;
166 }
167 float verticalEval = yKernelEvaluations[i];
168 acc += verticalEval * halfKernel[halfKernelSize - i - 1];
169 }
170 for (int i = 0; i < halfKernelSize; ++i, x += 1.0f) {
171 if (x < -circleR || x > circleR) {
172 continue;
173 }
174 float verticalEval = yKernelEvaluations[i + halfKernelSize];
175 acc += verticalEval * halfKernel[i];
176 }
177 // Since we applied a half kernel in y we multiply acc by 2 (the circle is symmetric about
178 // the x axis).
179 return SkUnitScalarClampToByte(2.0f * acc);
180 }
181
182 // This function creates a profile of a blurred circle. It does this by computing a kernel for
183 // half the Gaussian and a matching summed area table. The summed area table is used to compute
184 // an array of vertical applications of the half kernel to the circle along the x axis. The
185 // table of y evaluations has 2 * k + n entries where k is the size of the half kernel and n is
186 // the size of the profile being computed. Then for each of the n profile entries we walk out k
187 // steps in each horizontal direction multiplying the corresponding y evaluation by the half
188 // kernel entry and sum these values to compute the profile entry.
189 SkBitmap CreateCircleProfile(float sigma, float radius, int profileWidth) {
190 const int numSteps = profileWidth;
191
192 // The full kernel is 6 sigmas wide. SkScalarCeilToInt saturates to a number large enough to
193 // still detect overflow in the kernel size calcutions.
194 int halfKernelSize = SkScalarCeilToInt(6.0f * sigma);
195 // and this is small enough that the rest of the `halfKernelSize` math won't overflow
196 SkASSERT(halfKernelSize <= SK_MaxS32FitsInFloat &&
197 SK_MaxS32FitsInFloat <= std::numeric_limits<int32_t>::max() - 1);
198 // Round up to next multiple of 2 and then divide by 2.
199 halfKernelSize = ((halfKernelSize + 1) & ~1) >> 1;
200
201 // The full internal allocations will be numSteps + 4*halfKernelSize, so if that would overflow
202 // then return an empty bitmap.
203 static constexpr int kAllocLimit = std::numeric_limits<int32_t>::max() >> 2;
204
205 SkBitmap bitmap;
206 if (numSteps > kAllocLimit || halfKernelSize > (kAllocLimit - numSteps) ||
207 !bitmap.tryAllocPixels(SkImageInfo::MakeA8(profileWidth, 1))) {
208 return bitmap;
209 }
210
211 // Number of x steps at which to apply kernel in y to cover all the profile samples in x.
212 const int numYSteps = numSteps + 2 * halfKernelSize;
213
214 skia_private::AutoTArray<float> bulkAlloc(halfKernelSize + halfKernelSize + numYSteps);
215 float* halfKernel = bulkAlloc.get();
216 float* summedKernel = bulkAlloc.get() + halfKernelSize;
217 float* yEvals = bulkAlloc.get() + 2 * halfKernelSize;
218 make_half_kernel_and_summed_table(halfKernel, summedKernel, halfKernelSize, sigma);
219
220 float firstX = -halfKernelSize + 0.5f;
221 apply_kernel_in_y(yEvals, numYSteps, firstX, radius, halfKernelSize, summedKernel);
222
223 uint8_t* profile = bitmap.getAddr8(0, 0);
224 for (int i = 0; i < numSteps - 1; ++i) {
225 float evalX = i + 0.5f;
226 profile[i] = eval_at(evalX, radius, halfKernel, halfKernelSize, yEvals + i);
227 }
228 // Ensure the tail of the Gaussian goes to zero.
229 profile[numSteps - 1] = 0;
230
231 bitmap.setImmutable();
232 return bitmap;
233 }
234
235 SkBitmap CreateHalfPlaneProfile(int profileWidth) {
236 SkASSERT(!(profileWidth & 0x1));
237
238 SkBitmap bitmap;
239 if (!bitmap.tryAllocPixels(SkImageInfo::MakeA8(profileWidth, 1))) {
240 return bitmap;
241 }
242
243 uint8_t* profile = bitmap.getAddr8(0, 0);
244
245 // The full kernel is 6 sigmas wide.
246 const float sigma = profileWidth / 6.0f;
247 const int halfKernelSize = profileWidth / 2;
248
249 skia_private::AutoTArray<float> halfKernel(halfKernelSize);
250
251 // The half kernel should sum to 0.5.
252 const float tot = 2.0f * make_unnormalized_half_kernel(halfKernel.get(), halfKernelSize, sigma);
253 float sum = 0.0f;
254 // Populate the profile from the right edge to the middle.
255 for (int i = 0; i < halfKernelSize; ++i) {
256 halfKernel[halfKernelSize - i - 1] /= tot;
257 sum += halfKernel[halfKernelSize - i - 1];
258 profile[profileWidth - i - 1] = SkUnitScalarClampToByte(sum);
259 }
260 // Populate the profile from the middle to the left edge (by flipping the half kernel and
261 // continuing the summation).
262 for (int i = 0; i < halfKernelSize; ++i) {
263 sum += halfKernel[i];
264 profile[halfKernelSize - i - 1] = SkUnitScalarClampToByte(sum);
265 }
266 // Ensure the tail of the Gaussian goes to zero.
267 profile[profileWidth - 1] = 0;
268
269 bitmap.setImmutable();
270 return bitmap;
271 }
272
273 ///////////////////////////////////////////////////////////////////////////////
274 // RRect Blur
275 ///////////////////////////////////////////////////////////////////////////////
276
277 // Evaluate the vertical blur at the specified 'y' value given the location of the top of the
278 // rrect.
279 static uint8_t eval_V(float top, int y, const uint8_t* integral, int integralSize, float sixSigma) {
280 if (top < 0) {
281 return 0; // an empty column
282 }
283
284 float fT = (top - y - 0.5f) * (integralSize / sixSigma);
285 if (fT < 0) {
286 return 255;
287 } else if (fT >= integralSize - 1) {
288 return 0;
289 }
290
291 int lower = (int)fT;
292 float frac = fT - lower;
293
294 SkASSERT(lower + 1 < integralSize);
295
296 return integral[lower] * (1.0f - frac) + integral[lower + 1] * frac;
297 }
298
299 // Apply a gaussian 'kernel' horizontally at the specified 'x', 'y' location.
300 static uint8_t eval_H(int x,
301 int y,
302 const std::vector<float>& topVec,
303 const float* kernel,
304 int kernelSize,
305 const uint8_t* integral,
306 int integralSize,
307 float sixSigma) {
308 SkASSERT(0 <= x && x < (int)topVec.size());
309 SkASSERT(kernelSize % 2);
310
311 float accum = 0.0f;
312
313 int xSampleLoc = x - (kernelSize / 2);
314 for (int i = 0; i < kernelSize; ++i, ++xSampleLoc) {
315 if (xSampleLoc < 0 || xSampleLoc >= (int)topVec.size()) {
316 continue;
317 }
318
319 accum += kernel[i] * eval_V(topVec[xSampleLoc], y, integral, integralSize, sixSigma);
320 }
321
322 return accum + 0.5f;
323 }
324
325 SkBitmap CreateRRectBlurMask(const SkRRect& rrectToDraw, const SkISize& dimensions, float sigma) {
326 SkASSERT(!skgpu::BlurIsEffectivelyIdentity(sigma));
327 int radius = skgpu::BlurSigmaRadius(sigma);
328 int kernelSize = skgpu::BlurKernelWidth(radius);
329
330 SkASSERT(kernelSize % 2);
331 SkASSERT(dimensions.width() % 2);
332 SkASSERT(dimensions.height() % 2);
333
334 SkVector radii = rrectToDraw.getSimpleRadii();
335 SkASSERT(SkScalarNearlyEqual(radii.fX, radii.fY));
336
337 const int halfWidthPlus1 = (dimensions.width() / 2) + 1;
338 const int halfHeightPlus1 = (dimensions.height() / 2) + 1;
339
340 std::unique_ptr<float[]> kernel(new float[kernelSize]);
341 skgpu::Compute1DBlurKernel(sigma, radius, SkSpan<float>(kernel.get(), kernelSize));
342
343 const int tableWidth = ComputeIntegralTableWidth(6.0f * sigma);
344 SkBitmap integral = CreateIntegralTable(tableWidth);
345 if (integral.empty()) {
346 return {};
347 }
348
349 SkBitmap result;
350 if (!result.tryAllocPixels(SkImageInfo::MakeA8(dimensions.width(), dimensions.height()))) {
351 return {};
352 }
353
354 std::vector<float> topVec;
355 topVec.reserve(dimensions.width());
356 for (int x = 0; x < dimensions.width(); ++x) {
357 if (x < rrectToDraw.rect().fLeft || x > rrectToDraw.rect().fRight) {
358 topVec.push_back(-1);
359 } else {
360 if (x + 0.5f < rrectToDraw.rect().fLeft + radii.fX) { // in the circular section
361 float xDist = rrectToDraw.rect().fLeft + radii.fX - x - 0.5f;
362 float h = sqrtf(radii.fX * radii.fX - xDist * xDist);
363 SkASSERT(0 <= h && h < radii.fY);
364 topVec.push_back(rrectToDraw.rect().fTop + radii.fX - h + 3 * sigma);
365 } else {
366 topVec.push_back(rrectToDraw.rect().fTop + 3 * sigma);
367 }
368 }
369 }
370
371 for (int y = 0; y < halfHeightPlus1; ++y) {
372 uint8_t* scanline = result.getAddr8(0, y);
373
374 for (int x = 0; x < halfWidthPlus1; ++x) {
375 scanline[x] = eval_H(x,
376 y,
377 topVec,
378 kernel.get(),
379 kernelSize,
380 integral.getAddr8(0, 0),
381 integral.width(),
382 6.0f * sigma);
383 scanline[dimensions.width() - x - 1] = scanline[x];
384 }
385
386 memcpy(result.getAddr8(0, dimensions.height() - y - 1), scanline, result.rowBytes());
387 }
388
389 result.setImmutable();
390 return result;
391 }
392
393 } // namespace skgpu