xref: /aosp_15_r20/external/skia/src/gpu/ganesh/GrDrawOpAtlas.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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                                                skgpu::PlotEvictionCallback* evictor,
92                                                std::string_view label);
93 
94     /**
95      * Adds a width x height subimage to the atlas. Upon success it returns 'kSucceeded' and returns
96      * the ID and the subimage's coordinates in the backing texture. 'kTryAgain' is returned if
97      * the subimage cannot fit in the atlas without overwriting texels that will be read in the
98      * current draw. This indicates that the op should end its current draw and begin another
99      * before adding more data. Upon success, an upload of the provided image data will have
100      * been added to the GrDrawOp::Target, in "asap" mode if possible, otherwise in "inline" mode.
101      * Successive uploads in either mode may be consolidated.
102      * 'kError' will be returned when some unrecoverable error was encountered while trying to
103      * add the subimage. In this case the op being created should be discarded.
104      *
105      * NOTE: When the GrDrawOp prepares a draw that reads from the atlas, it must immediately call
106      * 'setLastUseToken' with the currentToken from the GrDrawOp::Target, otherwise the next call to
107      * addToAtlas might cause the previous data to be overwritten before it has been read.
108      */
109 
110     enum class ErrorCode {
111         kError,
112         kSucceeded,
113         kTryAgain
114     };
115 
116     ErrorCode addToAtlas(GrResourceProvider*, GrDeferredUploadTarget*,
117                          int width, int height, const void* image, skgpu::AtlasLocator*);
118 
getViews()119     const GrSurfaceProxyView* getViews() const { return fViews; }
120 
atlasGeneration()121     uint64_t atlasGeneration() const { return fAtlasGeneration; }
122 
hasID(const skgpu::PlotLocator & plotLocator)123     bool hasID(const skgpu::PlotLocator& plotLocator) {
124         if (!plotLocator.isValid()) {
125             return false;
126         }
127 
128         uint32_t plot = plotLocator.plotIndex();
129         uint32_t page = plotLocator.pageIndex();
130         uint64_t plotGeneration = fPages[page].fPlotArray[plot]->genID();
131         uint64_t locatorGeneration = plotLocator.genID();
132         return plot < fNumPlots && page < fNumActivePages && plotGeneration == locatorGeneration;
133     }
134 
135     /** 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)136     void setLastUseToken(const skgpu::AtlasLocator& atlasLocator, skgpu::AtlasToken token) {
137         SkASSERT(this->hasID(atlasLocator.plotLocator()));
138         uint32_t plotIdx = atlasLocator.plotIndex();
139         SkASSERT(plotIdx < fNumPlots);
140         uint32_t pageIdx = atlasLocator.pageIndex();
141         SkASSERT(pageIdx < fNumActivePages);
142         skgpu::Plot* plot = fPages[pageIdx].fPlotArray[plotIdx].get();
143         this->makeMRU(plot, pageIdx);
144         plot->setLastUseToken(token);
145     }
146 
numActivePages()147     uint32_t numActivePages() { return fNumActivePages; }
148 
setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater & updater,skgpu::AtlasToken token)149     void setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater& updater,
150                              skgpu::AtlasToken token) {
151         int count = updater.count();
152         for (int i = 0; i < count; i++) {
153             const skgpu::BulkUsePlotUpdater::PlotData& pd = updater.plotData(i);
154             // it's possible we've added a plot to the updater and subsequently the plot's page
155             // was deleted -- so we check to prevent a crash
156             if (pd.fPageIndex < fNumActivePages) {
157                 skgpu::Plot* plot = fPages[pd.fPageIndex].fPlotArray[pd.fPlotIndex].get();
158                 this->makeMRU(plot, pd.fPageIndex);
159                 plot->setLastUseToken(token);
160             }
161         }
162     }
163 
164     void compact(skgpu::AtlasToken startTokenForNextFlush);
165 
166     void instantiate(GrOnFlushResourceProvider*);
167 
maxPages()168     uint32_t maxPages() const {
169         return fMaxPages;
170     }
171 
172 private:
173     friend class GrDrawOpAtlasTools;
174 
175     GrDrawOpAtlas(GrProxyProvider*, const GrBackendFormat& format, SkColorType, size_t bpp,
176                   int width, int height, int plotWidth, int plotHeight,
177                   skgpu::AtlasGenerationCounter* generationCounter,
178                   AllowMultitexturing allowMultitexturing, std::string_view label);
179 
180     inline bool updatePlot(GrDeferredUploadTarget*, skgpu::AtlasLocator*, skgpu::Plot*);
181 
makeMRU(skgpu::Plot * plot,uint32_t pageIdx)182     inline void makeMRU(skgpu::Plot* plot, uint32_t pageIdx) {
183         if (fPages[pageIdx].fPlotList.head() == plot) {
184             return;
185         }
186 
187         fPages[pageIdx].fPlotList.remove(plot);
188         fPages[pageIdx].fPlotList.addToHead(plot);
189 
190         // No MRU update for pages -- since we will always try to add from
191         // the front and remove from the back there is no need for MRU.
192     }
193 
194     bool uploadToPage(unsigned int pageIdx, GrDeferredUploadTarget*, int width, int height,
195                       const void* image, skgpu::AtlasLocator*);
196 
197     void uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels,
198                              GrTextureProxy* proxy,
199                              skgpu::Plot* plot);
200 
201     bool createPages(GrProxyProvider*, skgpu::AtlasGenerationCounter*);
202     bool activateNewPage(GrResourceProvider*);
203     void deactivateLastPage();
204 
205     void processEviction(skgpu::PlotLocator);
processEvictionAndResetRects(skgpu::Plot * plot)206     inline void processEvictionAndResetRects(skgpu::Plot* plot) {
207         this->processEviction(plot->plotLocator());
208         plot->resetRects();
209     }
210 
211     GrBackendFormat       fFormat;
212     SkColorType           fColorType;
213     size_t                fBytesPerPixel;
214     int                   fTextureWidth;
215     int                   fTextureHeight;
216     int                   fPlotWidth;
217     int                   fPlotHeight;
218     unsigned int          fNumPlots;
219     const std::string     fLabel;
220 
221     // A counter to track the atlas eviction state for Glyphs. Each Glyph has a PlotLocator
222     // which contains its current generation. When the atlas evicts a plot, it increases
223     // the generation counter. If a Glyph's generation is less than the atlas's
224     // generation, then it knows it's been evicted and is either free to be deleted or
225     // re-added to the atlas if necessary.
226     skgpu::AtlasGenerationCounter* const fGenerationCounter;
227     uint64_t                      fAtlasGeneration;
228 
229     // nextFlushToken() value at the end of the previous flush
230     skgpu::AtlasToken fPrevFlushToken;
231 
232     // the number of flushes since this atlas has been last used
233     int                   fFlushesSinceLastUse;
234 
235     std::vector<skgpu::PlotEvictionCallback*> fEvictionCallbacks;
236 
237     struct Page {
238         // allocated array of Plots
239         std::unique_ptr<sk_sp<skgpu::Plot>[]> fPlotArray;
240         // LRU list of Plots (MRU at head - LRU at tail)
241         skgpu::PlotList fPlotList;
242     };
243     // proxies kept separate to make it easier to pass them up to client
244     GrSurfaceProxyView fViews[skgpu::PlotLocator::kMaxMultitexturePages];
245     Page fPages[skgpu::PlotLocator::kMaxMultitexturePages];
246     uint32_t fMaxPages;
247 
248     uint32_t fNumActivePages;
249 
250     SkDEBUGCODE(void validate(const skgpu::AtlasLocator& atlasLocator) const;)
251 };
252 
253 // There are three atlases (A8, 565, ARGB) that are kept in relation with one another. In
254 // general, because A8 is the most frequently used mask format its dimensions are 2x the 565 and
255 // ARGB dimensions, with the constraint that an atlas size will always contain at least one plot.
256 // Since the ARGB atlas takes the most space, its dimensions are used to size the other two atlases.
257 class GrDrawOpAtlasConfig {
258 public:
259     // The capabilities of the GPU define maxTextureSize. The client provides maxBytes, and this
260     // represents the largest they want a single atlas texture to be. Due to multitexturing, we
261     // may expand temporarily to use more space as needed.
262     GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes);
263 
264     // For testing only - make minimum sized atlases -- a single plot for ARGB, four for A8
GrDrawOpAtlasConfig()265     GrDrawOpAtlasConfig() : GrDrawOpAtlasConfig(kMaxAtlasDim, 0) {}
266 
267     SkISize atlasDimensions(skgpu::MaskFormat type) const;
268     SkISize plotDimensions(skgpu::MaskFormat type) const;
269 
270 private:
271     // On some systems texture coordinates are represented using half-precision floating point
272     // with 11 significant bits, which limits the largest atlas dimensions to 2048x2048.
273     // For simplicity we'll use this constraint for all of our atlas textures.
274     // This can be revisited later if we need larger atlases.
275     inline static constexpr int kMaxAtlasDim = 2048;
276 
277     SkISize fARGBDimensions;
278     int     fMaxTextureSize;
279 };
280 
281 #endif
282