Debian Codegraph @

src/gpu/AtlasTypes.h

raw
1 /*
2 * Copyright 2022 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 #ifndef skgpu_AtlasTypes_DEFINED
9 #define skgpu_AtlasTypes_DEFINED
10
11 #include "include/core/SkColor.h"
12 #include "include/core/SkColorType.h"
13 #include "include/core/SkPoint.h"
14 #include "include/core/SkRect.h"
15 #include "include/core/SkRefCnt.h"
16 #include "include/core/SkTypes.h"
17 #include "include/private/base/SkDebug.h"
18 #include "include/private/base/SkTArray.h"
19 #include "include/private/base/SkTo.h"
20 #include "src/base/SkTInternalLList.h"
21 #include "src/core/SkIPoint16.h"
22 #include "src/gpu/RectanizerSkyline.h"
23 #include "src/gpu/Token.h"
24
25 #include <array>
26 #include <cstdint>
27 #include <cstring>
28 #include <utility>
29
30 class SkPixmap;
31 namespace skgpu::graphite { class RecorderPriv; }
32
33 /**
34 * This file includes internal types that are used by all of our gpu backends for atlases.
35 */
36
37 namespace skgpu {
38
39 struct IRect16 {
40 int16_t fLeft, fTop, fRight, fBottom;
41
42 [[nodiscard]] static IRect16 MakeEmpty() {
43 IRect16 r;
44 r.setEmpty();
45 return r;
46 }
47
48 [[nodiscard]] static IRect16 MakeWH(int16_t w, int16_t h) {
49 IRect16 r;
50 r.set(0, 0, w, h);
51 return r;
52 }
53
54 [[nodiscard]] static IRect16 MakeXYWH(int16_t x, int16_t y, int16_t w, int16_t h) {
55 IRect16 r;
56 r.set(x, y, x + w, y + h);
57 return r;
58 }
59
60 [[nodiscard]] static IRect16 Make(const SkIRect& ir) {
61 IRect16 r;
62 r.set(ir);
63 return r;
64 }
65
66 int width() const { return fRight - fLeft; }
67 int height() const { return fBottom - fTop; }
68 int area() const { return this->width() * this->height(); }
69 bool isEmpty() const { return fLeft >= fRight || fTop >= fBottom; }
70
71 void setEmpty() { memset(this, 0, sizeof(*this)); }
72
73 void set(int16_t left, int16_t top, int16_t right, int16_t bottom) {
74 fLeft = left;
75 fTop = top;
76 fRight = right;
77 fBottom = bottom;
78 }
79
80 void set(const SkIRect& r) {
81 fLeft = SkToS16(r.fLeft);
82 fTop = SkToS16(r.fTop);
83 fRight = SkToS16(r.fRight);
84 fBottom = SkToS16(r.fBottom);
85 }
86
87 void offset(int16_t dx, int16_t dy) {
88 fLeft += dx;
89 fTop += dy;
90 fRight += dx;
91 fBottom += dy;
92 }
93 };
94
95 /**
96 * Formats for masks, used by the font cache. Important that these are 0-based.
97 */
98 enum class MaskFormat : int {
99 kA8, //!< 1-byte per pixel
100 kA565, //!< 2-bytes per pixel, RGB represent 3-channel LCD coverage
101 kARGB, //!< 4-bytes per pixel, color format
102
103 kLast = kARGB
104 };
105 static const int kMaskFormatCount = static_cast<int>(MaskFormat::kLast) + 1;
106
107 /**
108 * Return the number of bytes-per-pixel for the specified mask format.
109 */
110 inline constexpr int MaskFormatBytesPerPixel(MaskFormat format) {
111 SkASSERT(static_cast<int>(format) < kMaskFormatCount);
112 // kA8 (0) -> 1
113 // kA565 (1) -> 2
114 // kARGB (2) -> 4
115 static_assert(static_cast<int>(MaskFormat::kA8) == 0, "enum_order_dependency");
116 static_assert(static_cast<int>(MaskFormat::kA565) == 1, "enum_order_dependency");
117 static_assert(static_cast<int>(MaskFormat::kARGB) == 2, "enum_order_dependency");
118
119 return SkTo<int>(1u << static_cast<int>(format));
120 }
121
122 static constexpr SkColorType MaskFormatToColorType(MaskFormat format) {
123 switch (format) {
124 case MaskFormat::kA8:
125 return kAlpha_8_SkColorType;
126 case MaskFormat::kA565:
127 return kRGB_565_SkColorType;
128 case MaskFormat::kARGB:
129 return kRGBA_8888_SkColorType;
130 }
131 SkUNREACHABLE;
132 }
133
134 /**
135 * Keep track of generation number for atlases and Plots.
136 */
137 class AtlasGenerationCounter {
138 public:
139 inline static constexpr uint64_t kInvalidGeneration = 0;
140 uint64_t next() {
141 return fGeneration++;
142 }
143
144 private:
145 uint64_t fGeneration{1};
146 };
147
148 /**
149 * A PlotLocator specifies the plot and is analogous to a directory path:
150 * page/plot/plotGeneration
151 *
152 * In fact PlotLocator is a portion of a glyph image location in the atlas fully specified by:
153 * format/atlasGeneration/page/plot/plotGeneration/rect
154 */
155 class PlotLocator {
156 public:
157 // These are both restricted by the space they occupy in the PlotLocator.
158 // maxPages is also limited by being crammed into the glyph uvs.
159 // maxPlots is also limited by the fPlotAlreadyUpdated bitfield in
160 // GrDrawOpAtlas::BulkUseTokenUpdater.
161 inline static constexpr auto kMaxMultitexturePages = 4;
162 inline static constexpr int kMaxPlots = 32;
163
164 PlotLocator(uint32_t pageIdx, uint32_t plotIdx, uint64_t generation)
165 : fGenID(generation)
166 , fPlotIndex(plotIdx)
167 , fPageIndex(pageIdx) {
168 SkASSERT(pageIdx < kMaxMultitexturePages);
169 SkASSERT(plotIdx < kMaxPlots);
170 SkASSERT(generation < ((uint64_t)1 << 48));
171 }
172
173 PlotLocator()
174 : fGenID(AtlasGenerationCounter::kInvalidGeneration)
175 , fPlotIndex(0)
176 , fPageIndex(0) {}
177
178 bool isValid() const {
179 return fGenID != AtlasGenerationCounter::kInvalidGeneration ||
180 fPlotIndex != 0 || fPageIndex != 0;
181 }
182
183 void makeInvalid() {
184 fGenID = AtlasGenerationCounter::kInvalidGeneration;
185 fPlotIndex = 0;
186 fPageIndex = 0;
187 }
188
189 bool operator==(const PlotLocator& other) const {
190 return fGenID == other.fGenID &&
191 fPlotIndex == other.fPlotIndex &&
192 fPageIndex == other.fPageIndex; }
193
194 uint32_t pageIndex() const { return fPageIndex; }
195 uint32_t plotIndex() const { return fPlotIndex; }
196 uint64_t genID() const { return fGenID; }
197
198 private:
199 uint64_t fGenID:48;
200 uint64_t fPlotIndex:8;
201 uint64_t fPageIndex:8;
202 };
203
204 // AtlasLocator handles atlas position information. It keeps a left-top, right-bottom pair of
205 // encoded UV coordinates. The bits 13 & 14 of the U coordinates hold the atlas page index.
206 // This information is handed directly as is from fUVs. This encoding has the nice property
207 // that width = fUVs[2] - fUVs[0]; the page encoding in the top bits subtracts to zero.
208 class AtlasLocator {
209 public:
210 std::array<uint16_t, 4> getUVs() const {
211 return fUVs;
212 }
213
214 void invalidatePlotLocator() { fPlotLocator.makeInvalid(); }
215
216 // TODO: Remove the small path renderer's use of this for eviction
217 PlotLocator plotLocator() const { return fPlotLocator; }
218
219 uint32_t pageIndex() const { return fPlotLocator.pageIndex(); }
220
221 uint32_t plotIndex() const { return fPlotLocator.plotIndex(); }
222
223 uint64_t genID() const { return fPlotLocator.genID(); }
224
225 SkIPoint topLeft() const {
226 return {fUVs[0] & 0x1FFF, fUVs[1]};
227 }
228
229 SkPoint widthHeight() const {
230 auto width = fUVs[2] - fUVs[0],
231 height = fUVs[3] - fUVs[1];
232 return SkPoint::Make(width, height);
233 }
234
235 uint16_t width() const {
236 return fUVs[2] - fUVs[0];
237 }
238
239 uint16_t height() const {
240 return fUVs[3] - fUVs[1];
241 }
242
243 void insetSrc(int padding) {
244 SkASSERT(2 * padding <= this->width());
245 SkASSERT(2 * padding <= this->height());
246
247 fUVs[0] += padding;
248 fUVs[1] += padding;
249 fUVs[2] -= padding;
250 fUVs[3] -= padding;
251 }
252
253 void updatePlotLocator(PlotLocator p) {
254 fPlotLocator = p;
255 SkASSERT(fPlotLocator.pageIndex() <= 3);
256 uint16_t page = fPlotLocator.pageIndex() << 13;
257 fUVs[0] = (fUVs[0] & 0x1FFF) | page;
258 fUVs[2] = (fUVs[2] & 0x1FFF) | page;
259 }
260
261 void updateRect(skgpu::IRect16 rect) {
262 SkASSERT(rect.fLeft <= rect.fRight);
263 SkASSERT(rect.fRight <= 0x1FFF);
264 fUVs[0] = (fUVs[0] & 0xE000) | rect.fLeft;
265 fUVs[1] = rect.fTop;
266 fUVs[2] = (fUVs[2] & 0xE000) | rect.fRight;
267 fUVs[3] = rect.fBottom;
268 }
269
270 private:
271 PlotLocator fPlotLocator{0, 0, AtlasGenerationCounter::kInvalidGeneration};
272
273 // The inset padded bounds in the atlas in the lower 13 bits, and page index in bits 13 &
274 // 14 of the Us.
275 std::array<uint16_t, 4> fUVs{0, 0, 0, 0};
276 };
277
278 /**
279 * An interface for eviction callbacks. Whenever an atlas evicts a specific PlotLocator,
280 * it will call all of the registered listeners so they can process the eviction.
281 */
282 class PlotEvictionCallback {
283 public:
284 virtual ~PlotEvictionCallback() = default;
285 virtual void evict(PlotLocator) = 0;
286 };
287
288 /**
289 * A class which can be handed back to an atlas for updating plots in bulk. The
290 * current max number of plots per page an atlas can handle is 32. If in the future
291 * this is insufficient then we can move to a 64 bit int.
292 */
293 class BulkUsePlotUpdater {
294 public:
295 BulkUsePlotUpdater() {
296 memset(fPlotAlreadyUpdated, 0, sizeof(fPlotAlreadyUpdated));
297 }
298 BulkUsePlotUpdater(const BulkUsePlotUpdater& that)
299 : fPlotsToUpdate(that.fPlotsToUpdate) {
300 memcpy(fPlotAlreadyUpdated, that.fPlotAlreadyUpdated, sizeof(fPlotAlreadyUpdated));
301 }
302
303 bool add(const skgpu::AtlasLocator& atlasLocator) {
304 int plotIdx = atlasLocator.plotIndex();
305 int pageIdx = atlasLocator.pageIndex();
306 if (this->find(pageIdx, plotIdx)) {
307 return false;
308 }
309 this->set(pageIdx, plotIdx);
310 return true;
311 }
312
313 void reset() {
314 fPlotsToUpdate.clear();
315 memset(fPlotAlreadyUpdated, 0, sizeof(fPlotAlreadyUpdated));
316 }
317
318 struct PlotData {
319 PlotData(int pageIdx, int plotIdx) : fPageIndex(pageIdx), fPlotIndex(plotIdx) {}
320 uint32_t fPageIndex;
321 uint32_t fPlotIndex;
322 };
323
324 int count() const { return fPlotsToUpdate.size(); }
325
326 const PlotData& plotData(int index) const { return fPlotsToUpdate[index]; }
327
328 private:
329 bool find(int pageIdx, int index) const {
330 SkASSERT(index < skgpu::PlotLocator::kMaxPlots);
331 return (fPlotAlreadyUpdated[pageIdx] >> index) & 1;
332 }
333
334 void set(int pageIdx, int index) {
335 SkASSERT(!this->find(pageIdx, index));
336 fPlotAlreadyUpdated[pageIdx] |= (1 << index);
337 fPlotsToUpdate.push_back(PlotData(pageIdx, index));
338 }
339
340 inline static constexpr int kMinItems = 4;
341 skia_private::STArray<kMinItems, PlotData, true> fPlotsToUpdate;
342 // TODO: increase this to uint64_t to allow more plots per page
343 uint32_t fPlotAlreadyUpdated[skgpu::PlotLocator::kMaxMultitexturePages];
344 };
345
346 /**
347 * The backing texture for an atlas is broken into a spatial grid of Plots. The Plots
348 * keep track of subimage placement via their Rectanizer. A Plot may be subclassed if
349 * the atlas class needs to track additional information. Plots are initialized to zero
350 * for all color types.
351 */
352 class Plot : public SkRefCnt {
353 SK_DECLARE_INTERNAL_LLIST_INTERFACE(Plot);
354
355 public:
356 Plot(int pageIndex, int plotIndex, AtlasGenerationCounter* generationCounter,
357 int offX, int offY, int width, int height, SkColorType colorType, size_t bpp);
358
359 uint32_t pageIndex() const { return fPageIndex; }
360
361 /** plotIndex() is a unique id for the plot relative to the owning GrAtlas and page. */
362 uint32_t plotIndex() const { return fPlotIndex; }
363 /**
364 * genID() is incremented when the plot is evicted due to a atlas spill. It is used to
365 * know if a particular subimage is still present in the atlas.
366 */
367 uint64_t genID() const { return fGenID; }
368 PlotLocator plotLocator() const {
369 SkASSERT(fPlotLocator.isValid());
370 return fPlotLocator;
371 }
372 SkDEBUGCODE(size_t bpp() const { return fBytesPerPixel; })
373
374 /**
375 * To add data to the Plot, first call addRect to see if it's possible. If successful,
376 * use the atlasLocator to get a pointer to the location in the atlas via dataAt() and render to
377 * that location, or if you already have data use copySubImage().
378 */
379 bool addRect(int width, int height, AtlasLocator* atlasLocator);
380 void* dataAt(const AtlasLocator& atlasLocator);
381 void copySubImage(const AtlasLocator& atlasLocator, const void* image);
382 // Returns a Pixmap pointing to the backing data for the locator. Optionally, the caller can
383 // provide an inset that is applied to all four sides. This is useful for use cases that need
384 // to leave space between items in the atlas. The pixmap will exclude the padding. The entire
385 // Plot is cleared to zero when allocated. By passing an initialColor here, the caller can
386 // re-clear the entire locator's rect (including any padding) to any color.
387 SkPixmap prepForRender(const AtlasLocator&,
388 int padding = 0,
389 std::optional<SkColor> initialColor = {});
390
391 // TODO: Utility method for Ganesh, consider removing
392 bool addSubImage(int width, int height, const void* image, AtlasLocator* atlasLocator);
393
394 /**
395 * To manage the lifetime of a plot, we use two tokens. We use the last upload token to
396 * know when we can 'piggy back' uploads, i.e. if the last upload hasn't been flushed to
397 * the gpu, we don't need to issue a new upload even if we update the cpu backing store. We
398 * use lastUse to determine when we can evict a plot from the cache, i.e. if the last use
399 * has already flushed through the gpu then we can reuse the plot.
400 */
401 skgpu::Token lastUploadToken() const { return fLastUpload; }
402 skgpu::Token lastUseToken() const { return fLastUse; }
403 void setLastUploadToken(skgpu::Token token) { fLastUpload = token; }
404 void setLastUseToken(skgpu::Token token) { fLastUse = token; }
405
406 int flushesSinceLastUsed() { return fFlushesSinceLastUse; }
407 void resetFlushesSinceLastUsed() { fFlushesSinceLastUse = 0; }
408 void incFlushesSinceLastUsed() { fFlushesSinceLastUse++; }
409
410 bool needsUpload() { return !fDirtyRect.isEmpty(); }
411 std::pair<const void*, SkIRect> prepareForUpload();
412 // Re-initialize Plot. The client should ensure that they process any eviction callbacks
413 // before calling this, otherwise any cached references will point to invalid data.
414 // If freeData is true, this will free the backing data as well. This should only be used
415 // when we know we won't be adding to the Plot immediately afterwards.
416 void resetRects(bool freeData);
417
418 void markFullIfUsed() { fIsFull = !fDirtyRect.isEmpty(); }
419 bool isEmpty() const { return fRectanizer.percentFull() == 0; }
420 bool hasAllocation() const { return fData != nullptr; }
421
422 /**
423 * Create a clone of this plot. The cloned plot will take the place of the current plot in
424 * the atlas
425 */
426 sk_sp<Plot> clone() const {
427 return sk_sp<Plot>(new Plot(
428 fPageIndex, fPlotIndex, fGenerationCounter, fX, fY, fWidth, fHeight, fColorType,
429 fBytesPerPixel));
430 }
431
432 #ifdef SK_DEBUG
433 void resetListPtrs() {
434 fPrev = fNext = nullptr;
435 fList = nullptr;
436 }
437 #endif
438
439 private:
440 ~Plot() override;
441 size_t rowBytes() const { return fWidth * fBytesPerPixel; }
442 void* dataAt(SkIPoint atlasPoint);
443
444 skgpu::Token fLastUpload;
445 skgpu::Token fLastUse;
446 int fFlushesSinceLastUse;
447
448 struct {
449 const uint32_t fPageIndex : 16;
450 const uint32_t fPlotIndex : 16;
451 };
452 AtlasGenerationCounter* const fGenerationCounter;
453 uint64_t fGenID;
454 PlotLocator fPlotLocator;
455 std::byte* fData;
456 const int fWidth;
457 const int fHeight;
458 const int fX;
459 const int fY;
460 skgpu::RectanizerSkyline fRectanizer;
461 const SkIPoint16 fOffset; // the offset of the plot in the backing texture
462 const SkColorType fColorType;
463 const size_t fBytesPerPixel;
464 SkIRect fDirtyRect; // area in the Plot that needs to be uploaded
465 bool fIsFull;
466 SkDEBUGCODE(bool fDirty;)
467 };
468
469 typedef SkTInternalLList<Plot> PlotList;
470
471 } // namespace skgpu
472
473 #endif // skgpu_AtlasTypes_DEFINED