Debian Codegraph @

src/gpu/TiledTextureUtils.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
8 #include "src/gpu/TiledTextureUtils.h"
9
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkMatrix.h"
13 #include "include/core/SkRect.h"
14 #include "include/core/SkSamplingOptions.h"
15 #include "include/core/SkSize.h"
16 #include "src/base/SkSafeMath.h"
17 #include "src/core/SkCanvasPriv.h"
18 #include "src/core/SkDevice.h"
19 #include "src/core/SkSamplingPriv.h"
20 #include "src/image/SkImage_Base.h"
21 #include "src/image/SkImage_Picture.h"
22 #include "src/image/SkImage_Raster.h"
23
24 #include <functional>
25
26 //////////////////////////////////////////////////////////////////////////////
27 // Helper functions for tiling a large SkBitmap
28
29 namespace {
30
31 static const int kBmpSmallTileSize = 1 << 10;
32
33 size_t get_tile_count(const SkIRect& srcRect, int tileSize) {
34 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
35 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
36 // We calculate expected tile count before we read the bitmap's pixels, so hypothetically we can
37 // have lazy images with excessive dimensions that would cause (tilesX*tilesY) to overflow int.
38 // In these situations we also later fail to allocate a bitmap to store the lazy image, so there
39 // isn't really a performance concern around one image turning into millions of tiles.
40 return SkSafeMath::Mul(tilesX, tilesY);
41 }
42
43 int determine_tile_size(const SkIRect& src, int maxTileSize) {
44 if (maxTileSize <= kBmpSmallTileSize) {
45 return maxTileSize;
46 }
47
48 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
49 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
50
51 maxTileTotalTileSize *= maxTileSize * maxTileSize;
52 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
53
54 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
55 return kBmpSmallTileSize;
56 } else {
57 return maxTileSize;
58 }
59 }
60
61 // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
62 // pixels from the bitmap are necessary.
63 SkIRect determine_clipped_src_rect(SkIRect clippedSrcIRect,
64 const SkMatrix& viewMatrix,
65 const SkMatrix& srcToDstRect,
66 const SkISize& imageDimensions,
67 const SkRect* srcRectPtr) {
68 SkMatrix inv = SkMatrix::Concat(viewMatrix, srcToDstRect);
69 if (auto inverse = inv.invert()) {
70 inv = *inverse;
71 } else {
72 return SkIRect::MakeEmpty();
73 }
74 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
75 inv.mapRect(&clippedSrcRect);
76 if (srcRectPtr) {
77 if (!clippedSrcRect.intersect(*srcRectPtr)) {
78 return SkIRect::MakeEmpty();
79 }
80 }
81 clippedSrcRect.roundOut(&clippedSrcIRect);
82 SkIRect bmpBounds = SkIRect::MakeSize(imageDimensions);
83 if (!clippedSrcIRect.intersect(bmpBounds)) {
84 return SkIRect::MakeEmpty();
85 }
86
87 return clippedSrcIRect;
88 }
89
90 int draw_tiled_image(SkCanvas* canvas,
91 std::function<sk_sp<SkImage>(SkIRect)> imageProc,
92 SkISize originalSize,
93 int tileSize,
94 const SkMatrix& srcToDst,
95 const SkRect& srcRect,
96 const SkIRect& clippedSrcIRect,
97 const SkPaint* paint,
98 SkCanvas::QuadAAFlags origAAFlags,
99 SkCanvas::SrcRectConstraint constraint,
100 SkSamplingOptions sampling) {
101 if (sampling.isAniso()) {
102 sampling = SkSamplingPriv::AnisoFallback(/* imageIsMipped= */ false);
103 }
104 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
105
106 int nx = originalSize.width() / tileSize;
107 int ny = originalSize.height() / tileSize;
108
109 int numTilesDrawn = 0;
110
111 skia_private::TArray<SkCanvas::ImageSetEntry> imgSet(nx * ny);
112
113 for (int x = 0; x <= nx; x++) {
114 for (int y = 0; y <= ny; y++) {
115 SkRect tileR;
116 // TODO: this will prevent int overflow, however at sizes > 2^24 the float can't
117 // represent all the bits in the int
118 int tileRight = (x == nx) ? originalSize.width() : (x + 1) * tileSize;
119 int tileBottom = (y == ny) ? originalSize.height() : (y + 1) * tileSize;
120 tileR.setLTRB(SkIntToScalar(x * tileSize), SkIntToScalar(y * tileSize),
121 SkIntToScalar(tileRight), SkIntToScalar(tileBottom));
122
123 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
124 continue;
125 }
126
127 if (!tileR.intersect(srcRect)) {
128 continue;
129 }
130
131 SkIRect iTileR;
132 tileR.roundOut(&iTileR);
133 SkVector offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
134 SkIntToScalar(iTileR.fTop));
135 SkRect rectToDraw = tileR;
136 if (!srcToDst.mapRect(&rectToDraw)) {
137 continue;
138 }
139
140 if (sampling.filter != SkFilterMode::kNearest || sampling.useCubic) {
141 SkIRect iClampRect;
142
143 if (SkCanvas::kFast_SrcRectConstraint == constraint) {
144 // In bleed mode we want to always expand the tile on all edges
145 // but stay within the bitmap bounds
146 iClampRect = SkIRect::MakeWH(originalSize.width(), originalSize.height());
147 } else {
148 // In texture-domain/clamp mode we only want to expand the
149 // tile on edges interior to "srcRect" (i.e., we want to
150 // not bleed across the original clamped edges)
151 srcRect.roundOut(&iClampRect);
152 }
153 int outset = sampling.useCubic ? kBicubicFilterTexelPad : 1;
154 skgpu::TiledTextureUtils::ClampedOutsetWithOffset(&iTileR, outset, &offset,
155 iClampRect);
156 }
157
158 sk_sp<SkImage> image = imageProc(iTileR);
159 if (!image) {
160 continue;
161 }
162
163 unsigned aaFlags = SkCanvas::kNone_QuadAAFlags;
164 // Preserve the original edge AA flags for the exterior tile edges.
165 if (tileR.fLeft <= srcRect.fLeft && (origAAFlags & SkCanvas::kLeft_QuadAAFlag)) {
166 aaFlags |= SkCanvas::kLeft_QuadAAFlag;
167 }
168 if (tileR.fRight >= srcRect.fRight && (origAAFlags & SkCanvas::kRight_QuadAAFlag)) {
169 aaFlags |= SkCanvas::kRight_QuadAAFlag;
170 }
171 if (tileR.fTop <= srcRect.fTop && (origAAFlags & SkCanvas::kTop_QuadAAFlag)) {
172 aaFlags |= SkCanvas::kTop_QuadAAFlag;
173 }
174 if (tileR.fBottom >= srcRect.fBottom &&
175 (origAAFlags & SkCanvas::kBottom_QuadAAFlag)) {
176 aaFlags |= SkCanvas::kBottom_QuadAAFlag;
177 }
178
179 // Offset the source rect to make it "local" to our tmp bitmap
180 tileR.offset(-offset.fX, -offset.fY);
181
182 imgSet.push_back(SkCanvas::ImageSetEntry(std::move(image),
183 tileR,
184 rectToDraw,
185 /* matrixIndex= */ -1,
186 /* alpha= */ 1.0f,
187 aaFlags,
188 /* hasClip= */ false));
189
190 numTilesDrawn += 1;
191 }
192 }
193
194 canvas->experimental_DrawEdgeAAImageSet(imgSet.data(),
195 imgSet.size(),
196 /* dstClips= */ nullptr,
197 /* preViewMatrices= */ nullptr,
198 sampling,
199 paint,
200 constraint);
201 return numTilesDrawn;
202 }
203
204 } // anonymous namespace
205
206 namespace skgpu {
207
208 // tileSize and clippedSubset are valid if true is returned
209 bool TiledTextureUtils::ShouldTileImage(SkIRect conservativeClipBounds,
210 const SkISize& imageSize,
211 const SkMatrix& ctm,
212 const SkMatrix& srcToDst,
213 const SkRect* src,
214 int maxTileSize,
215 size_t cacheSize,
216 int* tileSize,
217 SkIRect* clippedSubset) {
218 // if it's larger than the max tile size, then we have no choice but tiling.
219 if (imageSize.width() > maxTileSize || imageSize.height() > maxTileSize) {
220 *clippedSubset = determine_clipped_src_rect(conservativeClipBounds, ctm,
221 srcToDst, imageSize, src);
222 *tileSize = determine_tile_size(*clippedSubset, maxTileSize);
223 return true;
224 }
225
226 // If the image would only produce 4 tiles of the smaller size, don't bother tiling it.
227 const size_t area = imageSize.width() * imageSize.height();
228 if (area < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
229 return false;
230 }
231
232 // At this point we know we could do the draw by uploading the entire bitmap as a texture.
233 // However, if the texture would be large compared to the cache size and we don't require most
234 // of it for this draw then tile to reduce the amount of upload and cache spill.
235 if (!cacheSize) {
236 // We don't have access to the cacheSize so we will just upload the entire image
237 // to be on the safe side and not tile.
238 return false;
239 }
240
241 // An assumption here is that sw bitmap size is a good proxy for its size as a texture
242 size_t bmpSize = area * sizeof(SkPMColor); // assume 32bit pixels
243 if (bmpSize < cacheSize / 2) {
244 return false;
245 }
246
247 // Figure out how much of the src we will need based on the src rect and clipping. Reject if
248 // tiling memory savings would be < 50%.
249 *clippedSubset = determine_clipped_src_rect(conservativeClipBounds, ctm,
250 srcToDst, imageSize, src);
251 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
252 size_t usedTileBytes = get_tile_count(*clippedSubset, kBmpSmallTileSize) *
253 kBmpSmallTileSize * kBmpSmallTileSize *
254 sizeof(SkPMColor); // assume 32bit pixels;
255
256 return usedTileBytes * 2 < bmpSize;
257 }
258
259 /**
260 * Optimize the src rect sampling area within an image (sized 'width' x 'height') such that
261 * 'outSrcRect' will be completely contained in the image's bounds. The corresponding rect
262 * to draw will be output to 'outDstRect'. The mapping between src and dst will be cached in
263 * 'outSrcToDst'. Outputs are not always updated when kSkip is returned.
264 *
265 * 'dstClip' should be null when there is no additional clipping.
266 */
267 TiledTextureUtils::ImageDrawMode TiledTextureUtils::OptimizeSampleArea(const SkISize& imageSize,
268 const SkRect& origSrcRect,
269 const SkRect& origDstRect,
270 const SkPoint dstClip[4],
271 SkRect* outSrcRect,
272 SkRect* outDstRect,
273 SkMatrix* outSrcToDst) {
274 if (origSrcRect.isEmpty() || origDstRect.isEmpty()) {
275 return ImageDrawMode::kSkip;
276 }
277
278 *outSrcToDst = SkMatrix::RectToRectOrIdentity(origSrcRect, origDstRect);
279
280 SkRect src = origSrcRect;
281 SkRect dst = origDstRect;
282
283 const SkRect srcBounds = SkRect::Make(imageSize);
284
285 if (!srcBounds.contains(src)) {
286 if (!src.intersect(srcBounds)) {
287 return ImageDrawMode::kSkip;
288 }
289 outSrcToDst->mapRect(&dst, src);
290
291 // Both src and dst have gotten smaller. If dstClip is provided, confirm it is still
292 // contained in dst, otherwise cannot optimize the sample area and must use a decal instead
293 if (dstClip) {
294 for (int i = 0; i < 4; ++i) {
295 if (!dst.contains(dstClip[i].fX, dstClip[i].fY)) {
296 // Must resort to using a decal mode restricted to the clipped 'src', and
297 // use the original dst rect (filling in src bounds as needed)
298 *outSrcRect = src;
299 *outDstRect = origDstRect;
300 return ImageDrawMode::kDecal;
301 }
302 }
303 }
304 }
305
306 // The original src and dst were fully contained in the image, or there was no dst clip to
307 // worry about, or the clip was still contained in the restricted dst rect.
308 *outSrcRect = src;
309 *outDstRect = dst;
310 return ImageDrawMode::kOptimized;
311 }
312
313 bool TiledTextureUtils::CanDisableMipmap(const SkMatrix& viewM,
314 const SkMatrix& localM,
315 bool sharpenMipmappedTextures) {
316 SkMatrix matrix;
317 matrix.setConcat(viewM, localM);
318 // With sharp mips, we bias mipmap lookups by -0.5. That means our final LOD is >= 0 until
319 // the computed LOD is >= 0.5. At what scale factor does a texture get an LOD of
320 // 0.5?
321 //
322 // Want: 0 = log2(1/s) - 0.5
323 // 0.5 = log2(1/s)
324 // 2^0.5 = 1/s
325 // 1/2^0.5 = s
326 // 2^0.5/2 = s
327 SkScalar mipScale = sharpenMipmappedTextures ? SK_ScalarRoot2Over2 : SK_Scalar1;
328 return matrix.getMinScale() >= mipScale;
329 }
330
331
332 // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
333 // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
334 // of 'iRect' for all possible outsets/clamps.
335 void TiledTextureUtils::ClampedOutsetWithOffset(SkIRect* iRect, int outset, SkPoint* offset,
336 const SkIRect& clamp) {
337 iRect->outset(outset, outset);
338
339 int leftClampDelta = clamp.fLeft - iRect->fLeft;
340 if (leftClampDelta > 0) {
341 offset->fX -= outset - leftClampDelta;
342 iRect->fLeft = clamp.fLeft;
343 } else {
344 offset->fX -= outset;
345 }
346
347 int topClampDelta = clamp.fTop - iRect->fTop;
348 if (topClampDelta > 0) {
349 offset->fY -= outset - topClampDelta;
350 iRect->fTop = clamp.fTop;
351 } else {
352 offset->fY -= outset;
353 }
354
355 if (iRect->fRight > clamp.fRight) {
356 iRect->fRight = clamp.fRight;
357 }
358 if (iRect->fBottom > clamp.fBottom) {
359 iRect->fBottom = clamp.fBottom;
360 }
361 }
362
363 std::tuple<bool, size_t> TiledTextureUtils::DrawAsTiledImageRect(
364 SkCanvas* canvas,
365 const SkImage* image,
366 const SkRect& srcRect,
367 const SkRect& dstRect,
368 SkCanvas::QuadAAFlags aaFlags,
369 const SkSamplingOptions& origSampling,
370 const SkPaint* paint,
371 SkCanvas::SrcRectConstraint constraint,
372 bool sharpenMM,
373 size_t cacheSize,
374 size_t maxTextureSize,
375 bool renderLazyPictureTilesOnGPU) {
376 if (canvas->isClipEmpty()) {
377 return {true, 0};
378 }
379
380 if (!image->isTextureBacked()) {
381 SkRect src;
382 SkRect dst;
383 SkMatrix srcToDst;
384 ImageDrawMode mode = OptimizeSampleArea(SkISize::Make(image->width(), image->height()),
385 srcRect, dstRect, /* dstClip= */ nullptr,
386 &src, &dst, &srcToDst);
387 if (mode == ImageDrawMode::kSkip) {
388 return {true, 0};
389 }
390
391 SkASSERT(mode != ImageDrawMode::kDecal); // only happens if there is a 'dstClip'
392
393 if (src.contains(image->bounds())) {
394 constraint = SkCanvas::kFast_SrcRectConstraint;
395 }
396
397 SkDevice* device = SkCanvasPriv::TopDevice(canvas);
398 const SkMatrix& localToDevice = device->localToDevice();
399
400 SkSamplingOptions sampling = origSampling;
401 if (sampling.mipmap != SkMipmapMode::kNone &&
402 CanDisableMipmap(localToDevice, srcToDst, sharpenMM)) {
403 sampling = SkSamplingOptions(sampling.filter);
404 }
405
406 SkIRect clipRect = device->devClipBounds();
407
408 int tileFilterPad;
409 if (sampling.useCubic) {
410 tileFilterPad = kBicubicFilterTexelPad;
411 } else if (sampling.filter == SkFilterMode::kLinear || sampling.isAniso()) {
412 // Aniso will fallback to linear filtering in the tiling case.
413 tileFilterPad = 1;
414 } else {
415 tileFilterPad = 0;
416 }
417
418 int maxTileSize = maxTextureSize - 2 * tileFilterPad;
419 int tileSize;
420 SkIRect clippedSubset;
421 if (ShouldTileImage(clipRect,
422 image->dimensions(),
423 localToDevice,
424 srcToDst,
425 &src,
426 maxTileSize,
427 cacheSize,
428 &tileSize,
429 &clippedSubset)) {
430 // If it's a Picture-backed image we should subset the SkPicture directly rather than
431 // converting to a Bitmap and then subsetting. Rendering to a bitmap will use a Raster
432 // surface, and the SkPicture could have GPU data.
433 //
434 // If we render a subset of a very large SkPicture into a GPU texture "tile", it'll
435 // require intermediate coordinates that need high precision. If we don't have that,
436 // bite the bullet and render the lazy picture tiles on the CPU and upload the data
437 // instead.
438 if (renderLazyPictureTilesOnGPU &&
439 as_IB(image)->type() == SkImage_Base::Type::kLazyPicture) {
440 auto imageProc = [&](SkIRect iTileR) {
441 return image->makeSubset(nullptr, iTileR, {});
442 };
443
444 size_t tiles = draw_tiled_image(canvas,
445 imageProc,
446 image->dimensions(),
447 tileSize,
448 srcToDst,
449 src,
450 clippedSubset,
451 paint,
452 aaFlags,
453 constraint,
454 sampling);
455 return {true, tiles};
456 }
457
458 // Extract pixels on the CPU, since we have to split into separate textures before
459 // sending to the GPU if tiling.
460 if (SkBitmap bm; as_IB(image)->getROPixels(nullptr, &bm)) {
461 auto imageProc = [&](SkIRect iTileR) -> sk_sp<SkImage> {
462 // We must subset as a bitmap and then turn it into an SkImage if we want
463 // caching to work. Image subsets always make a copy of the pixels and lose
464 // the association with the original's SkPixelRef.
465 if (SkBitmap subsetBmp; bm.extractSubset(&subsetBmp, iTileR)) {
466 return SkImage_Raster::MakeFromBitmap(subsetBmp, SkCopyPixelsMode::kNever);
467 }
468 return nullptr;
469 };
470
471 size_t tiles = draw_tiled_image(canvas,
472 imageProc,
473 bm.dimensions(),
474 tileSize,
475 srcToDst,
476 src,
477 clippedSubset,
478 paint,
479 aaFlags,
480 constraint,
481 sampling);
482 return {true, tiles};
483 }
484 }
485 }
486
487 return {false, 0};
488 }
489
490 } // namespace skgpu