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_graphite_DrawAtlas_DEFINED 9 #define skgpu_graphite_DrawAtlas_DEFINED 10 11 #include <cmath> 12 #include <string> 13 #include <string_view> 14 #include <vector> 15 16 #include "src/core/SkTHash.h" 17 #include "src/gpu/AtlasTypes.h" 18 19 class SkAutoPixmapStorage; 20 21 namespace skgpu::graphite { 22 23 class DrawContext; 24 class Recorder; 25 class TextureProxy; 26 27 /** 28 * TODO: the process described here is tentative, and this comment revised once locked down. 29 * 30 * This class manages one or more atlas textures on behalf of primitive draws in Device. The 31 * drawing processes that use the atlas add preceding UploadTasks when generating RenderPassTasks. 32 * The class provides facilities for using DrawTokens to detect data hazards. Plots that need 33 * uploads are tracked until it is impossible to add data without overwriting texels read by draws 34 * that have not yet been snapped to a RenderPassTask. At that point, the atlas will attempt to 35 * allocate a new atlas texture (or "page") of the same size, up to a maximum number of textures, 36 * and upload to that texture. If that's not possible, then the atlas will fail to add a subimage. 37 * This gives the Device the chance to end the current draw, snap a RenderpassTask, and begin a new 38 * one. Additional uploads will then succeed. 39 * 40 * When the atlas has multiple pages, new uploads are prioritized to the lower index pages, i.e., 41 * it will try to upload to page 0 before page 1 or 2. To keep the atlas from continually using 42 * excess space, periodic garbage collection is needed to shift data from the higher index pages to 43 * the lower ones, and then eventually remove any pages that are no longer in use. "In use" is 44 * determined by using the AtlasToken system: After a DrawPass is snapped a subarea of the page, or 45 * "plot" is checked to see whether it was used in that DrawPass. If less than a quarter of the 46 * plots have been used recently (within kPlotRecentlyUsedCount iterations) and there are available 47 * plots in lower index pages, the higher index page will be deactivated, and its glyphs will 48 * gradually migrate to other pages via the usual upload system. 49 * 50 * Garbage collection is initiated by the DrawAtlas's client via the compact() method. 51 */ 52 class DrawAtlas { 53 public: 54 /** Is the atlas allowed to use more than one texture? */ 55 enum class AllowMultitexturing : bool { kNo, kYes }; 56 57 /** Should the atlas use storage textures? */ 58 enum class UseStorageTextures : bool { kNo, kYes }; 59 60 /** 61 * Returns a DrawAtlas. 62 * @param ct The colorType which this atlas will store. 63 * @param bpp Size in bytes of each pixel. 64 * @param width Width in pixels of the atlas. 65 * @param height Height in pixels of the atlas. 66 * @param plotWidth The width of each plot. width/plotWidth should be an integer. 67 * @param plotWidth The height of each plot. height/plotHeight should be an integer. 68 * @param atlasGeneration A pointer to the context's generation counter. 69 * @param allowMultitexturing Can the atlas use more than one texture. 70 * @param useStorageTextures Should the atlas use storage textures. 71 * @param evictor A pointer to an eviction callback class. 72 * @param label Label for texture resources. 73 * 74 * @return An initialized DrawAtlas, or nullptr if creation fails. 75 */ 76 static std::unique_ptr<DrawAtlas> Make(SkColorType ct, size_t bpp, 77 int width, int height, 78 int plotWidth, int plotHeight, 79 AtlasGenerationCounter* generationCounter, 80 AllowMultitexturing allowMultitexturing, 81 UseStorageTextures useStorageTextures, 82 PlotEvictionCallback* evictor, 83 std::string_view label); 84 85 /** 86 * Adds a width x height subimage to the atlas. Upon success it returns 'kSucceeded' and returns 87 * the ID and the subimage's coordinates in the backing texture. 'kTryAgain' is returned if 88 * the subimage cannot fit in the atlas without overwriting texels that will be read in the 89 * current list of draws. This indicates that the Device should end its current draw, snap a 90 * DrawPass, and begin another before adding more data. 'kError' will be returned when some 91 * unrecoverable error was encountered while trying to add the subimage. In this case the draw 92 * being created should be discarded. 93 * 94 * This tracking does not generate UploadTasks per se. Instead, when the RenderPassTask is 95 * ready to be snapped, recordUploads() will be called by the Device and that will generate the 96 * necessary UploadTasks. If the useCachedUploads argument in recordUploads() is true, this 97 * will generate uploads for the entire area of each Plot that has changed since the last 98 * eviction. Otherwise it will only generate uploads for newly added changes. 99 * 100 * NOTE: When a draw that reads from the atlas is added to the DrawList, the client using this 101 * DrawAtlas must immediately call 'setLastUseToken' with the currentToken from the Recorder, 102 * otherwise the next call to addToAtlas might cause the previous data to be overwritten before 103 * it has been read. 104 */ 105 106 enum class ErrorCode { 107 kError, 108 kSucceeded, 109 kTryAgain 110 }; 111 112 ErrorCode addToAtlas(Recorder*, int width, int height, const void* image, AtlasLocator*); 113 ErrorCode addRect(Recorder*, int width, int height, AtlasLocator*); 114 // Reset Pixmap to point to backing data for the AtlasLocator's Plot. 115 // Return relative location within the Plot, as indicated by the AtlasLocator. 116 SkIPoint prepForRender(const AtlasLocator&, SkAutoPixmapStorage*); 117 bool recordUploads(DrawContext*, Recorder*); 118 getProxies()119 const sk_sp<TextureProxy>* getProxies() const { return fProxies; } 120 atlasID()121 uint32_t atlasID() const { return fAtlasID; } atlasGeneration()122 uint64_t atlasGeneration() const { return fAtlasGeneration; } numActivePages()123 uint32_t numActivePages() const { return fNumActivePages; } numPlots()124 unsigned int numPlots() const { return fNumPlots; } plotSize()125 SkISize plotSize() const { return {fPlotWidth, fPlotHeight}; } getListIndex(const PlotLocator & locator)126 uint32_t getListIndex(const PlotLocator& locator) { 127 return locator.pageIndex() * fNumPlots + locator.plotIndex(); 128 } 129 hasID(const PlotLocator & plotLocator)130 bool hasID(const PlotLocator& plotLocator) { 131 if (!plotLocator.isValid()) { 132 return false; 133 } 134 135 uint32_t plot = plotLocator.plotIndex(); 136 uint32_t page = plotLocator.pageIndex(); 137 uint64_t plotGeneration = fPages[page].fPlotArray[plot]->genID(); 138 uint64_t locatorGeneration = plotLocator.genID(); 139 return plot < fNumPlots && page < fNumActivePages && plotGeneration == locatorGeneration; 140 } 141 142 /** To ensure the atlas does not evict a given entry, the client must set the last use token. */ setLastUseToken(const AtlasLocator & atlasLocator,AtlasToken token)143 void setLastUseToken(const AtlasLocator& atlasLocator, AtlasToken token) { 144 Plot* plot = this->findPlot(atlasLocator); 145 this->internalSetLastUseToken(plot, atlasLocator.pageIndex(), token); 146 } 147 setLastUseTokenBulk(const BulkUsePlotUpdater & updater,AtlasToken token)148 void setLastUseTokenBulk(const BulkUsePlotUpdater& updater, 149 AtlasToken token) { 150 int count = updater.count(); 151 for (int i = 0; i < count; i++) { 152 const BulkUsePlotUpdater::PlotData& pd = updater.plotData(i); 153 // it's possible we've added a plot to the updater and subsequently the plot's page 154 // was deleted -- so we check to prevent a crash 155 if (pd.fPageIndex < fNumActivePages) { 156 Plot* plot = fPages[pd.fPageIndex].fPlotArray[pd.fPlotIndex].get(); 157 this->internalSetLastUseToken(plot, pd.fPageIndex, token); 158 } 159 } 160 } 161 162 void compact(AtlasToken startTokenForNextFlush); 163 164 // Mark all plots with any content as full. Used only with Vello because it can't do 165 // new renders to a texture without a clear. 166 void markUsedPlotsAsFull(); 167 168 // Will try to clear out any GPU resources that aren't needed for any pending uploads or draws. 169 // TODO: Delete backing data for Plots that don't have pending uploads. 170 void freeGpuResources(AtlasToken token); 171 172 void evictAllPlots(); 173 maxPages()174 uint32_t maxPages() const { 175 return fMaxPages; 176 } 177 178 int numAllocated_TestingOnly() const; 179 void setMaxPages_TestingOnly(uint32_t maxPages); 180 181 private: 182 DrawAtlas(SkColorType, size_t bpp, 183 int width, int height, int plotWidth, int plotHeight, 184 AtlasGenerationCounter* generationCounter, 185 AllowMultitexturing allowMultitexturing, 186 UseStorageTextures useStorageTextures, 187 std::string_view label); 188 189 bool addRectToPage(unsigned int pageIdx, int width, int height, AtlasLocator*); 190 191 void updatePlot(Plot* plot, AtlasLocator*); 192 makeMRU(Plot * plot,int pageIdx)193 inline void makeMRU(Plot* plot, int pageIdx) { 194 if (fPages[pageIdx].fPlotList.head() == plot) { 195 return; 196 } 197 198 fPages[pageIdx].fPlotList.remove(plot); 199 fPages[pageIdx].fPlotList.addToHead(plot); 200 201 // No MRU update for pages -- since we will always try to add from 202 // the front and remove from the back there is no need for MRU. 203 } 204 findPlot(const AtlasLocator & atlasLocator)205 Plot* findPlot(const AtlasLocator& atlasLocator) { 206 SkASSERT(this->hasID(atlasLocator.plotLocator())); 207 uint32_t pageIdx = atlasLocator.pageIndex(); 208 uint32_t plotIdx = atlasLocator.plotIndex(); 209 return fPages[pageIdx].fPlotArray[plotIdx].get(); 210 } 211 internalSetLastUseToken(Plot * plot,uint32_t pageIdx,AtlasToken token)212 void internalSetLastUseToken(Plot* plot, uint32_t pageIdx, AtlasToken token) { 213 this->makeMRU(plot, pageIdx); 214 plot->setLastUseToken(token); 215 } 216 217 bool createPages(AtlasGenerationCounter*); 218 bool activateNewPage(Recorder*); 219 void deactivateLastPage(); 220 221 void processEvictionAndResetRects(Plot* plot); 222 223 SkColorType fColorType; 224 size_t fBytesPerPixel; 225 int fTextureWidth; 226 int fTextureHeight; 227 int fPlotWidth; 228 int fPlotHeight; 229 unsigned int fNumPlots; 230 UseStorageTextures fUseStorageTextures; 231 const std::string fLabel; 232 uint32_t fAtlasID; // unique identifier for this atlas 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 AtlasGenerationCounter* const fGenerationCounter; 240 uint64_t fAtlasGeneration; 241 242 // nextFlushToken() value at the end of the previous DrawPass 243 // TODO: rename 244 AtlasToken fPrevFlushToken; 245 246 // the number of flushes since this atlas has been last used 247 // TODO: rename 248 int fFlushesSinceLastUse; 249 250 std::vector<PlotEvictionCallback*> fEvictionCallbacks; 251 252 struct Page { 253 // allocated array of Plots 254 std::unique_ptr<sk_sp<Plot>[]> fPlotArray; 255 // LRU list of Plots (MRU at head - LRU at tail) 256 PlotList fPlotList; 257 }; 258 // proxies kept separate to make it easier to pass them up to client 259 sk_sp<TextureProxy> fProxies[PlotLocator::kMaxMultitexturePages]; 260 Page fPages[PlotLocator::kMaxMultitexturePages]; 261 uint32_t fMaxPages; 262 263 uint32_t fNumActivePages; 264 265 SkDEBUGCODE(void validate(const AtlasLocator& atlasLocator) const;) 266 }; 267 268 // For text there are three atlases (A8, 565, ARGB) that are kept in relation with one another. In 269 // general, because A8 is the most frequently used mask format its dimensions are 2x the 565 and 270 // ARGB dimensions, with the constraint that an atlas size will always contain at least one plot. 271 // Since the ARGB atlas takes the most space, its dimensions are used to size the other two atlases. 272 class DrawAtlasConfig { 273 public: 274 // The capabilities of the GPU define maxTextureSize. The client provides maxBytes, and this 275 // represents the largest they want a single atlas texture to be. Due to multitexturing, we 276 // may expand temporarily to use more space as needed. 277 DrawAtlasConfig(int maxTextureSize, size_t maxBytes); 278 279 SkISize atlasDimensions(MaskFormat type) const; 280 SkISize plotDimensions(MaskFormat type) const; 281 282 private: 283 // On some systems texture coordinates are represented using half-precision floating point 284 // with 11 significant bits, which limits the largest atlas dimensions to 2048x2048. 285 // For simplicity we'll use this constraint for all of our atlas textures. 286 // This can be revisited later if we need larger atlases. 287 inline static constexpr int kMaxAtlasDim = 2048; 288 289 SkISize fARGBDimensions; 290 int fMaxTextureSize; 291 }; 292 293 } // namespace skgpu::graphite 294 295 #endif 296