1 /*
2 * Copyright 2015 Google Inc.
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/ganesh/GrDrawOpAtlas.h"
9
10 #include "include/core/SkRect.h"
11 #include "include/gpu/GpuTypes.h"
12 #include "include/gpu/ganesh/GrTypes.h"
13 #include "include/private/base/SkMath.h"
14 #include "include/private/base/SkPoint_impl.h"
15 #include "include/private/base/SkTArray.h"
16 #include "include/private/base/SkTPin.h"
17 #include "include/private/gpu/ganesh/GrTypesPriv.h"
18 #include "src/base/SkMathPriv.h"
19 #include "src/core/SkTraceEvent.h"
20 #include "src/gpu/SkBackingFit.h"
21 #include "src/gpu/Swizzle.h"
22 #include "src/gpu/ganesh/GrBackendUtils.h"
23 #include "src/gpu/ganesh/GrCaps.h"
24 #include "src/gpu/ganesh/GrProxyProvider.h"
25 #include "src/gpu/ganesh/GrSurfaceProxy.h"
26 #include "src/gpu/ganesh/GrTextureProxy.h"
27
28 #include <algorithm>
29 #include <functional>
30 #include <memory>
31 #include <tuple>
32 #include <utility>
33
34 using namespace skia_private;
35
36 using AtlasLocator = skgpu::AtlasLocator;
37 using AtlasToken = skgpu::AtlasToken;
38 using EvictionCallback = skgpu::PlotEvictionCallback;
39 using GenerationCounter = skgpu::AtlasGenerationCounter;
40 using MaskFormat = skgpu::MaskFormat;
41 using Plot = skgpu::Plot;
42 using PlotList = skgpu::PlotList;
43 using PlotLocator = skgpu::PlotLocator;
44
45 #if defined(DUMP_ATLAS_DATA)
46 static const constexpr bool kDumpAtlasData = true;
47 #else
48 static const constexpr bool kDumpAtlasData = false;
49 #endif
50
51 #ifdef SK_DEBUG
validate(const AtlasLocator & atlasLocator) const52 void GrDrawOpAtlas::validate(const AtlasLocator& atlasLocator) const {
53 // Verify that the plotIndex stored in the PlotLocator is consistent with the glyph rectangle
54 int numPlotsX = fTextureWidth / fPlotWidth;
55 int numPlotsY = fTextureHeight / fPlotHeight;
56
57 int plotIndex = atlasLocator.plotIndex();
58 auto topLeft = atlasLocator.topLeft();
59 int plotX = topLeft.x() / fPlotWidth;
60 int plotY = topLeft.y() / fPlotHeight;
61 SkASSERT(plotIndex == (numPlotsY - plotY - 1) * numPlotsX + (numPlotsX - plotX - 1));
62 }
63 #endif
64
65 // When proxy allocation is deferred until flush time the proxies acting as atlases require
66 // special handling. This is because the usage that can be determined from the ops themselves
67 // isn't sufficient. Independent of the ops there will be ASAP and inline uploads to the
68 // atlases. Extending the usage interval of any op that uses an atlas to the start of the
69 // flush (as is done for proxies that are used for sw-generated masks) also won't work because
70 // the atlas persists even beyond the last use in an op - for a given flush. Given this, atlases
71 // must explicitly manage the lifetime of their backing proxies via the onFlushCallback system
72 // (which calls this method).
instantiate(GrOnFlushResourceProvider * onFlushResourceProvider)73 void GrDrawOpAtlas::instantiate(GrOnFlushResourceProvider* onFlushResourceProvider) {
74 for (uint32_t i = 0; i < fNumActivePages; ++i) {
75 // All the atlas pages are now instantiated at flush time in the activeNewPage method.
76 SkASSERT(fViews[i].proxy() && fViews[i].proxy()->isInstantiated());
77 }
78 }
79
Make(GrProxyProvider * proxyProvider,const GrBackendFormat & format,SkColorType colorType,size_t bpp,int width,int height,int plotWidth,int plotHeight,GenerationCounter * generationCounter,AllowMultitexturing allowMultitexturing,int atlasPageNum,EvictionCallback * evictor,std::string_view label)80 std::unique_ptr<GrDrawOpAtlas> GrDrawOpAtlas::Make(GrProxyProvider* proxyProvider,
81 const GrBackendFormat& format,
82 SkColorType colorType, size_t bpp, int width,
83 int height, int plotWidth, int plotHeight,
84 GenerationCounter* generationCounter,
85 AllowMultitexturing allowMultitexturing,
86 #ifdef SK_ENABLE_SMALL_PAGE
87 int atlasPageNum,
88 #endif
89 EvictionCallback* evictor,
90 std::string_view label) {
91 if (!format.isValid()) {
92 return nullptr;
93 }
94
95 std::unique_ptr<GrDrawOpAtlas> atlas(new GrDrawOpAtlas(proxyProvider, format, colorType, bpp,
96 width, height, plotWidth, plotHeight,
97 generationCounter,
98 #ifdef SK_ENABLE_SMALL_PAGE
99 allowMultitexturing, atlasPageNum, label));
100 #else
101 allowMultitexturing, label));
102 #endif
103 if (!atlas->createPages(proxyProvider, generationCounter) || !atlas->getViews()[0].proxy()) {
104 return nullptr;
105 }
106
107 if (evictor != nullptr) {
108 atlas->fEvictionCallbacks.emplace_back(evictor);
109 }
110 return atlas;
111 }
112
113 ///////////////////////////////////////////////////////////////////////////////
114
GrDrawOpAtlas(GrProxyProvider * proxyProvider,const GrBackendFormat & format,SkColorType colorType,size_t bpp,int width,int height,int plotWidth,int plotHeight,GenerationCounter * generationCounter,AllowMultitexturing allowMultitexturing,int atlasPageNum,std::string_view label)115 GrDrawOpAtlas::GrDrawOpAtlas(GrProxyProvider* proxyProvider, const GrBackendFormat& format,
116 SkColorType colorType, size_t bpp, int width, int height,
117 int plotWidth, int plotHeight, GenerationCounter* generationCounter,
118 #ifdef SK_ENABLE_SMALL_PAGE
119 AllowMultitexturing allowMultitexturing, int atlasPageNum, std::string_view label)
120 #else
121 AllowMultitexturing allowMultitexturing, std::string_view label)
122 #endif
123 : fFormat(format)
124 , fColorType(colorType)
125 , fBytesPerPixel(bpp)
126 , fTextureWidth(width)
127 , fTextureHeight(height)
128 , fPlotWidth(plotWidth)
129 , fPlotHeight(plotHeight)
130 , fLabel(label)
131 , fGenerationCounter(generationCounter)
132 , fAtlasGeneration(fGenerationCounter->next())
133 , fPrevFlushToken(AtlasToken::InvalidToken())
134 , fFlushesSinceLastUse(0)
135 #ifdef SK_ENABLE_SMALL_PAGE
136 , fMaxPages(AllowMultitexturing::kYes == allowMultitexturing ? ((atlasPageNum > 16) ? 16 : atlasPageNum) : 1)
137 #else
138 , fMaxPages(AllowMultitexturing::kYes == allowMultitexturing ?
139 PlotLocator::kMaxMultitexturePages : 1)
140 #endif
141 , fNumActivePages(0) {
142 int numPlotsX = width/plotWidth;
143 int numPlotsY = height/plotHeight;
144 SkASSERT(numPlotsX * numPlotsY <= PlotLocator::kMaxPlots);
145 SkASSERT(fPlotWidth * numPlotsX == fTextureWidth);
146 SkASSERT(fPlotHeight * numPlotsY == fTextureHeight);
147
148 fNumPlots = numPlotsX * numPlotsY;
149 SkDebugf(
150 "Texture[Width:%{public}d, Height:%{public}d, MaxPage:%{public}d], "
151 "Plot[Width:%{public}d, Height:%{public}d].",
152 fTextureWidth, fTextureHeight, fMaxPages, fPlotWidth, fPlotHeight
153 );
154 }
155
processEviction(PlotLocator plotLocator)156 inline void GrDrawOpAtlas::processEviction(PlotLocator plotLocator) {
157 for (EvictionCallback* evictor : fEvictionCallbacks) {
158 evictor->evict(plotLocator);
159 }
160
161 fAtlasGeneration = fGenerationCounter->next();
162 }
163
uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn & writePixels,GrTextureProxy * proxy,Plot * plot)164 void GrDrawOpAtlas::uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels,
165 GrTextureProxy* proxy,
166 Plot* plot) {
167 SkASSERT(proxy && proxy->peekTexture());
168 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
169
170 const void* dataPtr;
171 SkIRect rect;
172 std::tie(dataPtr, rect) = plot->prepareForUpload();
173
174 writePixels(proxy,
175 rect,
176 SkColorTypeToGrColorType(fColorType),
177 dataPtr,
178 fBytesPerPixel*fPlotWidth);
179 }
180
updatePlot(GrDeferredUploadTarget * target,AtlasLocator * atlasLocator,Plot * plot)181 inline bool GrDrawOpAtlas::updatePlot(GrDeferredUploadTarget* target,
182 AtlasLocator* atlasLocator, Plot* plot) {
183 uint32_t pageIdx = plot->pageIndex();
184 if (pageIdx >= fNumActivePages) {
185 return false;
186 }
187 this->makeMRU(plot, pageIdx);
188
189 // If our most recent upload has already occurred then we have to insert a new
190 // upload. Otherwise, we already have a scheduled upload that hasn't yet ocurred.
191 // This new update will piggy back on that previously scheduled update.
192 if (plot->lastUploadToken() < target->tokenTracker()->nextFlushToken()) {
193 // With c+14 we could move sk_sp into lamba to only ref once.
194 sk_sp<Plot> plotsp(SkRef(plot));
195
196 GrTextureProxy* proxy = fViews[pageIdx].asTextureProxy();
197 SkASSERT(proxy && proxy->isInstantiated()); // This is occurring at flush time
198
199 AtlasToken lastUploadToken = target->addASAPUpload(
200 [this, plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
201 this->uploadPlotToTexture(writePixels, proxy, plotsp.get());
202 });
203 plot->setLastUploadToken(lastUploadToken);
204 }
205 atlasLocator->updatePlotLocator(plot->plotLocator());
206 SkDEBUGCODE(this->validate(*atlasLocator);)
207 return true;
208 }
209
uploadToPage(unsigned int pageIdx,GrDeferredUploadTarget * target,int width,int height,const void * image,AtlasLocator * atlasLocator)210 bool GrDrawOpAtlas::uploadToPage(unsigned int pageIdx, GrDeferredUploadTarget* target, int width,
211 int height, const void* image, AtlasLocator* atlasLocator) {
212 SkASSERT(fViews[pageIdx].proxy() && fViews[pageIdx].proxy()->isInstantiated());
213
214 // look through all allocated plots for one we can share, in Most Recently Refed order
215 PlotList::Iter plotIter;
216 plotIter.init(fPages[pageIdx].fPlotList, PlotList::Iter::kHead_IterStart);
217
218 for (Plot* plot = plotIter.get(); plot; plot = plotIter.next()) {
219 SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
220 plot->bpp());
221
222 if (plot->addSubImage(width, height, image, atlasLocator)) {
223 return this->updatePlot(target, atlasLocator, plot);
224 }
225 }
226
227 return false;
228 }
229
230 // Number of atlas-related flushes beyond which we consider a plot to no longer be in use.
231 //
232 // This value is somewhat arbitrary -- the idea is to keep it low enough that
233 // a page with unused plots will get removed reasonably quickly, but allow it
234 // to hang around for a bit in case it's needed. The assumption is that flushes
235 // are rare; i.e., we are not continually refreshing the frame.
236 static constexpr auto kPlotRecentlyUsedCount = 32;
237 static constexpr auto kAtlasRecentlyUsedCount = 128;
238
addToAtlas(GrResourceProvider * resourceProvider,GrDeferredUploadTarget * target,int width,int height,const void * image,AtlasLocator * atlasLocator)239 GrDrawOpAtlas::ErrorCode GrDrawOpAtlas::addToAtlas(GrResourceProvider* resourceProvider,
240 GrDeferredUploadTarget* target,
241 int width, int height, const void* image,
242 AtlasLocator* atlasLocator) {
243 if (width > fPlotWidth || height > fPlotHeight) {
244 return ErrorCode::kError;
245 }
246
247 // Look through each page to see if we can upload without having to flush
248 // We prioritize this upload to the first pages, not the most recently used, to make it easier
249 // to remove unused pages in reverse page order.
250 for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
251 if (this->uploadToPage(pageIdx, target, width, height, image, atlasLocator)) {
252 return ErrorCode::kSucceeded;
253 }
254 }
255
256 // If the above fails, then see if the least recently used plot per page has already been
257 // flushed to the gpu if we're at max page allocation, or if the plot has aged out otherwise.
258 // We wait until we've grown to the full number of pages to begin evicting already flushed
259 // plots so that we can maximize the opportunity for reuse.
260 // As before we prioritize this upload to the first pages, not the most recently used.
261 if (fNumActivePages == this->maxPages()) {
262 for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
263 Plot* plot = fPages[pageIdx].fPlotList.tail();
264 SkASSERT(plot);
265 if (plot->lastUseToken() < target->tokenTracker()->nextFlushToken()) {
266 this->processEvictionAndResetRects(plot);
267 SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
268 plot->bpp());
269 SkDEBUGCODE(bool verify = )plot->addSubImage(width, height, image, atlasLocator);
270 SkASSERT(verify);
271 if (!this->updatePlot(target, atlasLocator, plot)) {
272 return ErrorCode::kError;
273 }
274 return ErrorCode::kSucceeded;
275 }
276 }
277 } else {
278 // If we haven't activated all the available pages, try to create a new one and add to it
279 if (!this->activateNewPage(resourceProvider)) {
280 return ErrorCode::kError;
281 }
282
283 if (this->uploadToPage(fNumActivePages-1, target, width, height, image, atlasLocator)) {
284 return ErrorCode::kSucceeded;
285 } else {
286 // If we fail to upload to a newly activated page then something has gone terribly
287 // wrong - return an error
288 return ErrorCode::kError;
289 }
290 }
291
292 if (!fNumActivePages) {
293 return ErrorCode::kError;
294 }
295
296 // Try to find a plot that we can perform an inline upload to.
297 // We prioritize this upload in reverse order of pages to counterbalance the order above.
298 Plot* plot = nullptr;
299 for (int pageIdx = ((int)fNumActivePages)-1; pageIdx >= 0; --pageIdx) {
300 Plot* currentPlot = fPages[pageIdx].fPlotList.tail();
301 if (currentPlot->lastUseToken() != target->tokenTracker()->nextDrawToken()) {
302 plot = currentPlot;
303 break;
304 }
305 }
306
307 // If we can't find a plot that is not used in a draw currently being prepared by an op, then
308 // we have to fail. This gives the op a chance to enqueue the draw, and call back into this
309 // function. When that draw is enqueued, the draw token advances, and the subsequent call will
310 // continue past this branch and prepare an inline upload that will occur after the enqueued
311 // draw which references the plot's pre-upload content.
312 if (!plot) {
313 return ErrorCode::kTryAgain;
314 }
315
316 this->processEviction(plot->plotLocator());
317 int pageIdx = plot->pageIndex();
318 fPages[pageIdx].fPlotList.remove(plot);
319 sk_sp<Plot>& newPlot = fPages[pageIdx].fPlotArray[plot->plotIndex()];
320 newPlot = plot->clone();
321
322 fPages[pageIdx].fPlotList.addToHead(newPlot.get());
323 SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
324 newPlot->bpp());
325 SkDEBUGCODE(bool verify = )newPlot->addSubImage(width, height, image, atlasLocator);
326 SkASSERT(verify);
327
328 // Note that this plot will be uploaded inline with the draws whereas the
329 // one it displaced most likely was uploaded ASAP.
330 // With c++14 we could move sk_sp into lambda to only ref once.
331 sk_sp<Plot> plotsp(SkRef(newPlot.get()));
332
333 GrTextureProxy* proxy = fViews[pageIdx].asTextureProxy();
334 SkASSERT(proxy && proxy->isInstantiated());
335
336 AtlasToken lastUploadToken = target->addInlineUpload(
337 [this, plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
338 this->uploadPlotToTexture(writePixels, proxy, plotsp.get());
339 });
340 newPlot->setLastUploadToken(lastUploadToken);
341
342 atlasLocator->updatePlotLocator(newPlot->plotLocator());
343 SkDEBUGCODE(this->validate(*atlasLocator);)
344
345 return ErrorCode::kSucceeded;
346 }
347
348 #ifdef SK_ENABLE_SMALL_PAGE
compactRadicals(skgpu::AtlasToken startTokenForNextFlush)349 void GrDrawOpAtlas::compactRadicals(skgpu::AtlasToken startTokenForNextFlush) {
350 if (fNumActivePages <= 1) {
351 return;
352 }
353 PlotList::Iter plotIter;
354 unsigned short usedAtlasLastFlush = 0;
355 for (uint32_t pageIndex = 0; pageIndex < fNumActivePages; ++pageIndex) {
356 plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
357 while (Plot* plot = plotIter.get()) {
358 if (plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
359 usedAtlasLastFlush |= (1 << pageIndex);
360 break;
361 } else if (plot->lastUploadToken() != skgpu::AtlasToken::InvalidToken()) {
362 this->processEvictionAndResetRects(plot);
363 }
364 plotIter.next();
365 }
366 }
367 int lastPageIndex = fNumActivePages - 1;
368 while (lastPageIndex > 0 && !(usedAtlasLastFlush & (1 << lastPageIndex))) {
369 deactivateLastPage();
370 lastPageIndex--;
371 }
372 }
373 #endif
374
compact(AtlasToken startTokenForNextFlush)375 void GrDrawOpAtlas::compact(AtlasToken startTokenForNextFlush) {
376 #ifdef SK_ENABLE_SMALL_PAGE
377 int threshold;
378 if (this->fUseRadicalsCompact) {
379 threshold = 1;
380 compactRadicals(startTokenForNextFlush);
381 } else {
382 threshold = kPlotRecentlyUsedCount;
383 }
384 #else
385 int threshold = kPlotRecentlyUsedCount;
386 #endif
387 if (fNumActivePages < 1) {
388 fPrevFlushToken = startTokenForNextFlush;
389 return;
390 }
391
392 // For all plots, reset number of flushes since used if used this frame.
393 PlotList::Iter plotIter;
394 bool atlasUsedThisFlush = false;
395 for (uint32_t pageIndex = 0; pageIndex < fNumActivePages; ++pageIndex) {
396 plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
397 while (Plot* plot = plotIter.get()) {
398 // Reset number of flushes since used
399 if (plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
400 plot->resetFlushesSinceLastUsed();
401 atlasUsedThisFlush = true;
402 }
403
404 plotIter.next();
405 }
406 }
407
408 if (atlasUsedThisFlush) {
409 fFlushesSinceLastUse = 0;
410 } else {
411 ++fFlushesSinceLastUse;
412 }
413
414 // We only try to compact if the atlas was used in the recently completed flush or
415 // hasn't been used in a long time.
416 // This is to handle the case where a lot of text or path rendering has occurred but then just
417 // a blinking cursor is drawn.
418 if (atlasUsedThisFlush || fFlushesSinceLastUse > kAtlasRecentlyUsedCount) {
419 TArray<Plot*> availablePlots;
420 uint32_t lastPageIndex = fNumActivePages - 1;
421
422 // For all plots but the last one, update number of flushes since used, and check to see
423 // if there are any in the first pages that the last page can safely upload to.
424 for (uint32_t pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex) {
425 if constexpr (kDumpAtlasData) {
426 SkDebugf("page %u: ", pageIndex);
427 }
428
429 plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
430 while (Plot* plot = plotIter.get()) {
431 // Update number of flushes since plot was last used
432 // We only increment the 'sinceLastUsed' count for flushes where the atlas was used
433 // to avoid deleting everything when we return to text drawing in the blinking
434 // cursor case
435 if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
436 plot->incFlushesSinceLastUsed();
437 }
438
439 if constexpr (kDumpAtlasData) {
440 SkDebugf("%d ", plot->flushesSinceLastUsed());
441 }
442
443 // Count plots we can potentially upload to in all pages except the last one
444 // (the potential compactee).
445 if (plot->flushesSinceLastUsed() > threshold) {
446 availablePlots.push_back() = plot;
447 }
448
449 plotIter.next();
450 }
451
452 if constexpr (kDumpAtlasData) {
453 SkDebugf("\n");
454 }
455 }
456
457 // Count recently used plots in the last page and evict any that are no longer in use.
458 // Since we prioritize uploading to the first pages, this will eventually
459 // clear out usage of this page unless we have a large need.
460 plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
461 unsigned int usedPlots = 0;
462 if constexpr (kDumpAtlasData) {
463 SkDebugf("page %u: ", lastPageIndex);
464 }
465
466 while (Plot* plot = plotIter.get()) {
467 // Update number of flushes since plot was last used
468 if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
469 plot->incFlushesSinceLastUsed();
470 }
471
472 if constexpr (kDumpAtlasData) {
473 SkDebugf("%d ", plot->flushesSinceLastUsed());
474 }
475
476 // If this plot was used recently
477 if (plot->flushesSinceLastUsed() <= threshold) {
478 usedPlots++;
479 } else if (plot->lastUseToken() != AtlasToken::InvalidToken()) {
480 // otherwise if aged out just evict it.
481 this->processEvictionAndResetRects(plot);
482 }
483 plotIter.next();
484 }
485
486 if constexpr (kDumpAtlasData) {
487 SkDebugf("\n");
488 }
489
490 // If recently used plots in the last page are using less than a quarter of the page, try
491 // to evict them if there's available space in earlier pages. Since we prioritize uploading
492 // to the first pages, this will eventually clear out usage of this page unless we have a
493 // large need.
494 if (!availablePlots.empty() && usedPlots && usedPlots <= fNumPlots / 4) {
495 plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
496 while (Plot* plot = plotIter.get()) {
497 // If this plot was used recently
498 if (plot->flushesSinceLastUsed() <= threshold) {
499 // See if there's room in an earlier page and if so evict.
500 // We need to be somewhat harsh here so that a handful of plots that are
501 // consistently in use don't end up locking the page in memory.
502 if (!availablePlots.empty()) {
503 this->processEvictionAndResetRects(plot);
504 this->processEvictionAndResetRects(availablePlots.back());
505 availablePlots.pop_back();
506 --usedPlots;
507 }
508 if (!usedPlots || availablePlots.empty()) {
509 break;
510 }
511 }
512 plotIter.next();
513 }
514 }
515
516 // If none of the plots in the last page have been used recently, delete it.
517 if (!usedPlots) {
518 if constexpr (kDumpAtlasData) {
519 SkDebugf("delete %u\n", fNumActivePages - 1);
520 }
521
522 this->deactivateLastPage();
523 fFlushesSinceLastUse = 0;
524 }
525 }
526
527 fPrevFlushToken = startTokenForNextFlush;
528 }
529
createPages(GrProxyProvider * proxyProvider,GenerationCounter * generationCounter)530 bool GrDrawOpAtlas::createPages(
531 GrProxyProvider* proxyProvider, GenerationCounter* generationCounter) {
532 SkASSERT(SkIsPow2(fTextureWidth) && SkIsPow2(fTextureHeight));
533
534 SkISize dims = {fTextureWidth, fTextureHeight};
535
536 int numPlotsX = fTextureWidth/fPlotWidth;
537 int numPlotsY = fTextureHeight/fPlotHeight;
538
539 GrColorType grColorType = SkColorTypeToGrColorType(fColorType);
540
541 for (uint32_t i = 0; i < this->maxPages(); ++i) {
542 skgpu::Swizzle swizzle = proxyProvider->caps()->getReadSwizzle(fFormat, grColorType);
543 if (GrColorTypeIsAlphaOnly(grColorType)) {
544 swizzle = skgpu::Swizzle::Concat(swizzle, skgpu::Swizzle("aaaa"));
545 }
546 sk_sp<GrSurfaceProxy> proxy = proxyProvider->createProxy(fFormat,
547 dims,
548 GrRenderable::kNo,
549 1,
550 skgpu::Mipmapped::kNo,
551 SkBackingFit::kExact,
552 skgpu::Budgeted::kYes,
553 GrProtected::kNo,
554 fLabel,
555 GrInternalSurfaceFlags::kNone,
556 GrSurfaceProxy::UseAllocator::kNo);
557 if (!proxy) {
558 return false;
559 }
560 fViews[i] = GrSurfaceProxyView(std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle);
561
562 // set up allocated plots
563 fPages[i].fPlotArray = std::make_unique<sk_sp<Plot>[]>(numPlotsX * numPlotsY);
564
565 sk_sp<Plot>* currPlot = fPages[i].fPlotArray.get();
566 for (int y = numPlotsY - 1, r = 0; y >= 0; --y, ++r) {
567 for (int x = numPlotsX - 1, c = 0; x >= 0; --x, ++c) {
568 uint32_t plotIndex = r * numPlotsX + c;
569 currPlot->reset(new Plot(
570 i, plotIndex, generationCounter, x, y, fPlotWidth, fPlotHeight, fColorType,
571 fBytesPerPixel));
572
573 // build LRU list
574 fPages[i].fPlotList.addToHead(currPlot->get());
575 ++currPlot;
576 }
577 }
578
579 }
580
581 return true;
582 }
583
activateNewPage(GrResourceProvider * resourceProvider)584 bool GrDrawOpAtlas::activateNewPage(GrResourceProvider* resourceProvider) {
585 SkASSERT(fNumActivePages < this->maxPages());
586
587 if (!fViews[fNumActivePages].proxy()->instantiate(resourceProvider)) {
588 return false;
589 }
590
591 if constexpr (kDumpAtlasData) {
592 SkDebugf("activated page#: %u\n", fNumActivePages);
593 }
594
595 ++fNumActivePages;
596 return true;
597 }
598
deactivateLastPage()599 inline void GrDrawOpAtlas::deactivateLastPage() {
600 SkASSERT(fNumActivePages);
601
602 uint32_t lastPageIndex = fNumActivePages - 1;
603
604 int numPlotsX = fTextureWidth/fPlotWidth;
605 int numPlotsY = fTextureHeight/fPlotHeight;
606
607 fPages[lastPageIndex].fPlotList.reset();
608 for (int r = 0; r < numPlotsY; ++r) {
609 for (int c = 0; c < numPlotsX; ++c) {
610 uint32_t plotIndex = r * numPlotsX + c;
611
612 Plot* currPlot = fPages[lastPageIndex].fPlotArray[plotIndex].get();
613 currPlot->resetRects();
614 currPlot->resetFlushesSinceLastUsed();
615
616 // rebuild the LRU list
617 SkDEBUGCODE(currPlot->resetListPtrs());
618 fPages[lastPageIndex].fPlotList.addToHead(currPlot);
619 }
620 }
621
622 // remove ref to the backing texture
623 fViews[lastPageIndex].proxy()->deinstantiate();
624 --fNumActivePages;
625 }
626
GrDrawOpAtlasConfig(int maxTextureSize,size_t maxBytes)627 GrDrawOpAtlasConfig::GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes) {
628 static const SkISize kARGBDimensions[] = {
629 {256, 256}, // maxBytes < 2^19
630 {512, 256}, // 2^19 <= maxBytes < 2^20
631 {512, 512}, // 2^20 <= maxBytes < 2^21
632 {1024, 512}, // 2^21 <= maxBytes < 2^22
633 {1024, 1024}, // 2^22 <= maxBytes < 2^23
634 {2048, 1024}, // 2^23 <= maxBytes
635 };
636
637 // Index 0 corresponds to maxBytes of 2^18, so start by dividing it by that
638 maxBytes >>= 18;
639 // Take the floor of the log to get the index
640 int index = maxBytes > 0
641 ? SkTPin<int>(SkPrevLog2(maxBytes), 0, std::size(kARGBDimensions) - 1)
642 : 0;
643
644 SkASSERT(kARGBDimensions[index].width() <= kMaxAtlasDim);
645 SkASSERT(kARGBDimensions[index].height() <= kMaxAtlasDim);
646 fARGBDimensions.set(std::min<int>(kARGBDimensions[index].width(), maxTextureSize),
647 std::min<int>(kARGBDimensions[index].height(), maxTextureSize));
648 fMaxTextureSize = std::min<int>(maxTextureSize, kMaxAtlasDim);
649 }
650
651 #ifdef SK_ENABLE_SMALL_PAGE
resetAsSmallPage()652 int GrDrawOpAtlasConfig::resetAsSmallPage() {
653 size_t maxBytes = fARGBDimensions.width() * fARGBDimensions.height() * 4;
654 fARGBDimensions.set(512, 512);
655 int calculatedNums = static_cast<int>(maxBytes / (fARGBDimensions.width() * fARGBDimensions.height()));
656 fPageNums = calculatedNums;
657 return calculatedNums;
658 }
659 #endif
660
atlasDimensions(MaskFormat type) const661 SkISize GrDrawOpAtlasConfig::atlasDimensions(MaskFormat type) const {
662 if (MaskFormat::kA8 == type) {
663 // A8 is always 2x the ARGB dimensions, clamped to the max allowed texture size
664 return { std::min<int>(2 * fARGBDimensions.width(), fMaxTextureSize),
665 std::min<int>(2 * fARGBDimensions.height(), fMaxTextureSize) };
666 } else {
667 return fARGBDimensions;
668 }
669 }
670
plotDimensions(MaskFormat type) const671 SkISize GrDrawOpAtlasConfig::plotDimensions(MaskFormat type) const {
672 if (MaskFormat::kA8 == type) {
673 SkISize atlasDimensions = this->atlasDimensions(type);
674 // For A8 we want to grow the plots at larger texture sizes to accept more of the
675 // larger SDF glyphs. Since the largest SDF glyph can be 170x170 with padding, this
676 // allows us to pack 3 in a 512x256 plot, or 9 in a 512x512 plot.
677
678 #ifdef SK_ENABLE_SMALL_PAGE
679 // This will give us 515×512 plots for 1024x1024, 256x256 plots otherwise.
680 int plotWidth = atlasDimensions.width() >= 1024 ? 512 : 256;
681 int plotHeight = atlasDimensions.height() >= 1024 ? 512 : 256;
682 #else
683 // This will give us 512x256 plots for 2048x1024, 512x512 plots for 2048x2048,
684 // and 256x256 plots otherwise.
685 int plotWidth = atlasDimensions.width() >= 2048 ? 512 : 256;
686 int plotHeight = atlasDimensions.height() >= 2048 ? 512 : 256;
687 #endif
688
689 return { plotWidth, plotHeight };
690 } else {
691 // ARGB and LCD always use 256x256 plots -- this has been shown to be faster
692 return { 256, 256 };
693 }
694 }
695