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 #ifndef GrDrawOpAtlas_DEFINED 9 #define GrDrawOpAtlas_DEFINED 10 11 #include "include/core/SkRefCnt.h" 12 #include "include/core/SkSize.h" 13 #include "include/gpu/ganesh/GrBackendSurface.h" 14 #include "include/private/base/SkAssert.h" 15 #include "include/private/base/SkDebug.h" 16 #include "src/gpu/AtlasTypes.h" 17 #include "src/gpu/ganesh/GrDeferredUpload.h" 18 #include "src/gpu/ganesh/GrSurfaceProxyView.h" 19 20 #include <cstddef> 21 #include <cstdint> 22 #include <memory> 23 #include <string> 24 #include <string_view> 25 #include <vector> 26 27 class GrOnFlushResourceProvider; 28 class GrProxyProvider; 29 class GrResourceProvider; 30 class GrTextureProxy; 31 enum SkColorType : int; 32 33 /** 34 * This class manages one or more atlas textures on behalf of GrDrawOps. The draw ops that use the 35 * atlas perform texture uploads when preparing their draws during flush. The class provides 36 * facilities for using GrDrawOpUploadToken to detect data hazards. Op's uploads are performed in 37 * "ASAP" mode until it is impossible to add data without overwriting texels read by draws that 38 * have not yet executed on the gpu. At that point, the atlas will attempt to allocate a new 39 * atlas texture (or "page") of the same size, up to a maximum number of textures, and upload 40 * to that texture. If that's not possible, the uploads are performed "inline" between draws. If a 41 * single draw would use enough subimage space to overflow the atlas texture then the atlas will 42 * fail to add a subimage. This gives the op the chance to end the draw and begin a new one. 43 * Additional uploads will then succeed in inline mode. 44 * 45 * When the atlas has multiple pages, new uploads are prioritized to the lower index pages, i.e., 46 * it will try to upload to page 0 before page 1 or 2. To keep the atlas from continually using 47 * excess space, periodic garbage collection is needed to shift data from the higher index pages to 48 * the lower ones, and then eventually remove any pages that are no longer in use. "In use" is 49 * determined by using the GrDrawUploadToken system: After a flush each subarea of the page 50 * is checked to see whether it was used in that flush. If less than a quarter of the plots have 51 * been used recently (within kPlotRecentlyUsedCount iterations) and there are available 52 * plots in lower index pages, the higher index page will be deactivated, and its glyphs will 53 * gradually migrate to other pages via the usual upload system. 54 * 55 * Garbage collection is initiated by the GrDrawOpAtlas's client via the compact() method. One 56 * solution is to make the client a subclass of GrOnFlushCallbackObject, register it with the 57 * GrContext via addOnFlushCallbackObject(), and the client's postFlush() method calls compact() 58 * and passes in the given GrDrawUploadToken. 59 */ 60 class GrDrawOpAtlas { 61 public: 62 /** Is the atlas allowed to use more than one texture? */ 63 enum class AllowMultitexturing : bool { kNo, kYes }; 64 65 /** 66 * Returns a GrDrawOpAtlas. This function can be called anywhere, but the returned atlas 67 * should only be used inside of GrMeshDrawOp::onPrepareDraws. 68 * @param proxyProvider Used to create the atlas's texture proxies. 69 * @param format Backend format for the atlas's textures. 70 * Should be compatible with ct. 71 * @param ct The colorType which this atlas will store. 72 * @param bpp Size in bytes of each pixel. 73 * @param width Width in pixels of the atlas. 74 * @param height Height in pixels of the atlas. 75 * @param plotWidth The width of each plot. width/plotWidth should be an integer. 76 * @param plotWidth The height of each plot. height/plotHeight should be an integer. 77 * @param generationCounter A pointer to the context's generation counter. 78 * @param allowMultitexturing Can the atlas use more than one texture. 79 * @param evictor A pointer to an eviction callback class. 80 * @param label A label for the atlas texture. 81 * 82 * @return An initialized DrawAtlas, or nullptr if creation fails. 83 */ 84 static std::unique_ptr<GrDrawOpAtlas> Make(GrProxyProvider* proxyProvider, 85 const GrBackendFormat& format, 86 SkColorType ct, size_t bpp, 87 int width, int height, 88 int plotWidth, int plotHeight, 89 skgpu::AtlasGenerationCounter* generationCounter, 90 AllowMultitexturing allowMultitexturing, 91 #ifdef SK_ENABLE_SMALL_PAGE 92 int atlasPageNum, 93 #endif 94 skgpu::PlotEvictionCallback* evictor, 95 std::string_view label); 96 97 /** 98 * Adds a width x height subimage to the atlas. Upon success it returns 'kSucceeded' and returns 99 * the ID and the subimage's coordinates in the backing texture. 'kTryAgain' is returned if 100 * the subimage cannot fit in the atlas without overwriting texels that will be read in the 101 * current draw. This indicates that the op should end its current draw and begin another 102 * before adding more data. Upon success, an upload of the provided image data will have 103 * been added to the GrDrawOp::Target, in "asap" mode if possible, otherwise in "inline" mode. 104 * Successive uploads in either mode may be consolidated. 105 * 'kError' will be returned when some unrecoverable error was encountered while trying to 106 * add the subimage. In this case the op being created should be discarded. 107 * 108 * NOTE: When the GrDrawOp prepares a draw that reads from the atlas, it must immediately call 109 * 'setLastUseToken' with the currentToken from the GrDrawOp::Target, otherwise the next call to 110 * addToAtlas might cause the previous data to be overwritten before it has been read. 111 */ 112 113 enum class ErrorCode { 114 kError, 115 kSucceeded, 116 kTryAgain 117 }; 118 119 ErrorCode addToAtlas(GrResourceProvider*, GrDeferredUploadTarget*, 120 int width, int height, const void* image, skgpu::AtlasLocator*); 121 getViews()122 const GrSurfaceProxyView* getViews() const { return fViews; } 123 atlasGeneration()124 uint64_t atlasGeneration() const { return fAtlasGeneration; } 125 hasID(const skgpu::PlotLocator & plotLocator)126 bool hasID(const skgpu::PlotLocator& plotLocator) { 127 if (!plotLocator.isValid()) { 128 return false; 129 } 130 131 uint32_t plot = plotLocator.plotIndex(); 132 uint32_t page = plotLocator.pageIndex(); 133 uint64_t plotGeneration = fPages[page].fPlotArray[plot]->genID(); 134 uint64_t locatorGeneration = plotLocator.genID(); 135 return plot < fNumPlots && page < fNumActivePages && plotGeneration == locatorGeneration; 136 } 137 138 /** To ensure the atlas does not evict a given entry, the client must set the last use token. */ setLastUseToken(const skgpu::AtlasLocator & atlasLocator,skgpu::AtlasToken token)139 void setLastUseToken(const skgpu::AtlasLocator& atlasLocator, skgpu::AtlasToken token) { 140 SkASSERT(this->hasID(atlasLocator.plotLocator())); 141 uint32_t plotIdx = atlasLocator.plotIndex(); 142 SkASSERT(plotIdx < fNumPlots); 143 uint32_t pageIdx = atlasLocator.pageIndex(); 144 SkASSERT(pageIdx < fNumActivePages); 145 skgpu::Plot* plot = fPages[pageIdx].fPlotArray[plotIdx].get(); 146 this->makeMRU(plot, pageIdx); 147 plot->setLastUseToken(token); 148 } 149 numActivePages()150 uint32_t numActivePages() { return fNumActivePages; } 151 setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater & updater,skgpu::AtlasToken token)152 void setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater& updater, 153 skgpu::AtlasToken token) { 154 int count = updater.count(); 155 for (int i = 0; i < count; i++) { 156 const skgpu::BulkUsePlotUpdater::PlotData& pd = updater.plotData(i); 157 // it's possible we've added a plot to the updater and subsequently the plot's page 158 // was deleted -- so we check to prevent a crash 159 if (pd.fPageIndex < fNumActivePages) { 160 skgpu::Plot* plot = fPages[pd.fPageIndex].fPlotArray[pd.fPlotIndex].get(); 161 this->makeMRU(plot, pd.fPageIndex); 162 plot->setLastUseToken(token); 163 } 164 } 165 } 166 167 #ifdef SK_ENABLE_SMALL_PAGE setRadicalsCompactFlag(bool isRadicals)168 void setRadicalsCompactFlag(bool isRadicals) { fUseRadicalsCompact = isRadicals; } 169 #endif 170 void compact(skgpu::AtlasToken startTokenForNextFlush); 171 172 void instantiate(GrOnFlushResourceProvider*); 173 maxPages()174 uint32_t maxPages() const { 175 return fMaxPages; 176 } 177 178 private: 179 friend class GrDrawOpAtlasTools; 180 181 GrDrawOpAtlas(GrProxyProvider*, const GrBackendFormat& format, SkColorType, size_t bpp, 182 int width, int height, int plotWidth, int plotHeight, 183 skgpu::AtlasGenerationCounter* generationCounter, 184 #ifdef SK_ENABLE_SMALL_PAGE 185 AllowMultitexturing allowMultitexturing, int atlasPageNum, std::string_view label); 186 #else 187 AllowMultitexturing allowMultitexturing, std::string_view label); 188 #endif 189 190 inline bool updatePlot(GrDeferredUploadTarget*, skgpu::AtlasLocator*, skgpu::Plot*); 191 makeMRU(skgpu::Plot * plot,uint32_t pageIdx)192 inline void makeMRU(skgpu::Plot* plot, uint32_t pageIdx) { 193 if (fPages[pageIdx].fPlotList.head() == plot) { 194 return; 195 } 196 197 fPages[pageIdx].fPlotList.remove(plot); 198 fPages[pageIdx].fPlotList.addToHead(plot); 199 200 // No MRU update for pages -- since we will always try to add from 201 // the front and remove from the back there is no need for MRU. 202 } 203 204 bool uploadToPage(unsigned int pageIdx, GrDeferredUploadTarget*, int width, int height, 205 const void* image, skgpu::AtlasLocator*); 206 207 void uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels, 208 GrTextureProxy* proxy, 209 skgpu::Plot* plot); 210 211 bool createPages(GrProxyProvider*, skgpu::AtlasGenerationCounter*); 212 bool activateNewPage(GrResourceProvider*); 213 void deactivateLastPage(); 214 #ifdef SK_ENABLE_SMALL_PAGE 215 void compactRadicals(skgpu::AtlasToken startTokenForNextFlush); 216 #endif 217 218 void processEviction(skgpu::PlotLocator); processEvictionAndResetRects(skgpu::Plot * plot)219 inline void processEvictionAndResetRects(skgpu::Plot* plot) { 220 this->processEviction(plot->plotLocator()); 221 plot->resetRects(); 222 } 223 224 GrBackendFormat fFormat; 225 SkColorType fColorType; 226 size_t fBytesPerPixel; 227 int fTextureWidth; 228 int fTextureHeight; 229 int fPlotWidth; 230 int fPlotHeight; 231 unsigned int fNumPlots; 232 const std::string fLabel; 233 234 // A counter to track the atlas eviction state for Glyphs. Each Glyph has a PlotLocator 235 // which contains its current generation. When the atlas evicts a plot, it increases 236 // the generation counter. If a Glyph's generation is less than the atlas's 237 // generation, then it knows it's been evicted and is either free to be deleted or 238 // re-added to the atlas if necessary. 239 skgpu::AtlasGenerationCounter* const fGenerationCounter; 240 uint64_t fAtlasGeneration; 241 242 // nextFlushToken() value at the end of the previous flush 243 skgpu::AtlasToken fPrevFlushToken; 244 245 // the number of flushes since this atlas has been last used 246 int fFlushesSinceLastUse; 247 248 std::vector<skgpu::PlotEvictionCallback*> fEvictionCallbacks; 249 250 struct Page { 251 // allocated array of Plots 252 std::unique_ptr<sk_sp<skgpu::Plot>[]> fPlotArray; 253 // LRU list of Plots (MRU at head - LRU at tail) 254 skgpu::PlotList fPlotList; 255 }; 256 // proxies kept separate to make it easier to pass them up to client 257 GrSurfaceProxyView fViews[skgpu::PlotLocator::kMaxMultitexturePages]; 258 Page fPages[skgpu::PlotLocator::kMaxMultitexturePages]; 259 uint32_t fMaxPages; 260 261 uint32_t fNumActivePages; 262 263 #ifdef SK_ENABLE_SMALL_PAGE 264 bool fUseRadicalsCompact = false; 265 #endif 266 267 SkDEBUGCODE(void validate(const skgpu::AtlasLocator& atlasLocator) const;) 268 }; 269 270 // There are three atlases (A8, 565, ARGB) that are kept in relation with one another. In 271 // general, because A8 is the most frequently used mask format its dimensions are 2x the 565 and 272 // ARGB dimensions, with the constraint that an atlas size will always contain at least one plot. 273 // Since the ARGB atlas takes the most space, its dimensions are used to size the other two atlases. 274 class GrDrawOpAtlasConfig { 275 public: 276 // The capabilities of the GPU define maxTextureSize. The client provides maxBytes, and this 277 // represents the largest they want a single atlas texture to be. Due to multitexturing, we 278 // may expand temporarily to use more space as needed. 279 GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes); 280 281 // For testing only - make minimum sized atlases -- a single plot for ARGB, four for A8 GrDrawOpAtlasConfig()282 GrDrawOpAtlasConfig() : GrDrawOpAtlasConfig(kMaxAtlasDim, 0) {} 283 284 SkISize atlasDimensions(skgpu::MaskFormat type) const; 285 SkISize plotDimensions(skgpu::MaskFormat type) const; 286 #ifdef SK_ENABLE_SMALL_PAGE getARGBDimensions()287 SkISize getARGBDimensions(){ return fARGBDimensions; } 288 int resetAsSmallPage(); getPageNums()289 int getPageNums() { return fPageNums; }; 290 #endif 291 292 private: 293 // On some systems texture coordinates are represented using half-precision floating point 294 // with 11 significant bits, which limits the largest atlas dimensions to 2048x2048. 295 // For simplicity we'll use this constraint for all of our atlas textures. 296 // This can be revisited later if we need larger atlases. 297 inline static constexpr int kMaxAtlasDim = 2048; 298 299 SkISize fARGBDimensions; 300 int fMaxTextureSize; 301 #ifdef SK_ENABLE_SMALL_PAGE 302 int fPageNums = 4; // The maximum number of texture pages in the original skia code is 4 303 #endif 304 }; 305 306 #endif 307