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