• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 GrResourceProvider_DEFINED
9 #define GrResourceProvider_DEFINED
10 
11 #include "GrBuffer.h"
12 #include "GrPathRange.h"
13 #include "GrResourceCache.h"
14 #include "SkImageInfo.h"
15 #include "SkScalerContext.h"
16 
17 class GrBackendRenderTarget;
18 class GrBackendSemaphore;
19 class GrBackendTexture;
20 class GrGpu;
21 class GrPath;
22 class GrRenderTarget;
23 class GrResourceProviderPriv;
24 class GrSemaphore;
25 class GrSingleOwner;
26 class GrStencilAttachment;
27 class GrTexture;
28 
29 class GrStyle;
30 class SkDescriptor;
31 class SkPath;
32 class SkTypeface;
33 
34 /**
35  * A factory for arbitrary resource types. This class is intended for use within the Gr code base.
36  *
37  * Some members force callers to make a flags (pendingIO) decision. This can be relaxed once
38  * https://bug.skia.org/4156 is fixed.
39  */
40 class GrResourceProvider {
41 public:
42     GrResourceProvider(GrGpu* gpu, GrResourceCache* cache, GrSingleOwner* owner);
43 
44     /**
45      * Finds a resource in the cache, based on the specified key. Prior to calling this, the caller
46      * must be sure that if a resource of exists in the cache with the given unique key then it is
47      * of type T.
48      */
49     template <typename T>
findByUniqueKey(const GrUniqueKey & key)50     sk_sp<T> findByUniqueKey(const GrUniqueKey& key) {
51         return sk_sp<T>(static_cast<T*>(this->findResourceByUniqueKey(key).release()));
52     }
53 
54     ///////////////////////////////////////////////////////////////////////////
55     // Textures
56 
57     /**
58      * Finds a texture that approximately matches the descriptor. Will be at least as large in width
59      * and height as desc specifies. If desc specifies that the texture should be a render target
60      * then result will be a render target. Format and sample count will always match the request.
61      * The contents of the texture are undefined.
62      */
63     sk_sp<GrTexture> createApproxTexture(const GrSurfaceDesc&, uint32_t flags);
64 
65     /** Create an exact fit texture with no initial data to upload.
66      */
67     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted, uint32_t flags = 0);
68 
69     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted,
70                                    const GrMipLevel texels[], int mipLevelCount,
71                                    SkDestinationSurfaceColorMode mipColorMode);
72 
73     // Create a potentially loose fit texture with the provided data
74     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted, const GrMipLevel&);
75 
76     ///////////////////////////////////////////////////////////////////////////
77     // Wrapped Backend Surfaces
78 
79     /**
80      * Wraps an existing texture with a GrTexture object.
81      *
82      * OpenGL: if the object is a texture Gr may change its GL texture params
83      *         when it is drawn.
84      *
85      * @return GrTexture object or NULL on failure.
86      */
87     sk_sp<GrTexture> wrapBackendTexture(const GrBackendTexture& tex,
88                                         GrWrapOwnership = kBorrow_GrWrapOwnership);
89 
90     /**
91      * This makes the backend texture be renderable. If sampleCnt is > 1 and the underlying API
92      * uses separate MSAA render buffers then a MSAA render buffer is created that resolves
93      * to the texture.
94      */
95     sk_sp<GrTexture> wrapRenderableBackendTexture(const GrBackendTexture& tex,
96                                                   int sampleCnt,
97                                                   GrWrapOwnership = kBorrow_GrWrapOwnership);
98 
99     /**
100      * Wraps an existing render target with a GrRenderTarget object. It is
101      * similar to wrapBackendTexture but can be used to draw into surfaces
102      * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
103      * the client will resolve to a texture). Currently wrapped render targets
104      * always use the kBorrow_GrWrapOwnership semantics.
105      *
106      * @return GrRenderTarget object or NULL on failure.
107      */
108     sk_sp<GrRenderTarget> wrapBackendRenderTarget(const GrBackendRenderTarget&);
109 
110     static const uint32_t kMinScratchTextureSize;
111 
112     /**
113      * Either finds and refs, or creates a static buffer with the given parameters and contents.
114      *
115      * @param intendedType    hint to the graphics subsystem about what the buffer will be used for.
116      * @param size            minimum size of buffer to return.
117      * @param data            optional data with which to initialize the buffer.
118      * @param key             Key to be assigned to the buffer.
119      *
120      * @return The buffer if successful, otherwise nullptr.
121      */
122     sk_sp<const GrBuffer> findOrMakeStaticBuffer(GrBufferType intendedType, size_t size,
123                                                  const void* data, const GrUniqueKey& key);
124 
125     /**
126      * Either finds and refs, or creates an index buffer with a repeating pattern for drawing
127      * contiguous vertices of a repeated mesh. If the return is non-null, the caller owns a ref on
128      * the returned GrBuffer.
129      *
130      * @param pattern     the pattern of indices to repeat
131      * @param patternSize size in bytes of the pattern
132      * @param reps        number of times to repeat the pattern
133      * @param vertCount   number of vertices the pattern references
134      * @param key         Key to be assigned to the index buffer.
135      *
136      * @return The index buffer if successful, otherwise nullptr.
137      */
findOrCreatePatternedIndexBuffer(const uint16_t * pattern,int patternSize,int reps,int vertCount,const GrUniqueKey & key)138     sk_sp<const GrBuffer> findOrCreatePatternedIndexBuffer(const uint16_t* pattern,
139                                                            int patternSize,
140                                                            int reps,
141                                                            int vertCount,
142                                                            const GrUniqueKey& key) {
143         if (auto buffer = this->findByUniqueKey<GrBuffer>(key)) {
144             return buffer;
145         }
146         return this->createPatternedIndexBuffer(pattern, patternSize, reps, vertCount, key);
147     }
148 
149     /**
150      * Returns an index buffer that can be used to render quads.
151      * Six indices per quad: 0, 1, 2, 2, 1, 3, etc.
152      * The max number of quads is the buffer's index capacity divided by 6.
153      * Draw with GrPrimitiveType::kTriangles
154      * @ return the quad index buffer
155      */
refQuadIndexBuffer()156     sk_sp<const GrBuffer> refQuadIndexBuffer() {
157         if (auto buffer = this->findByUniqueKey<const GrBuffer>(fQuadIndexBufferKey)) {
158             return buffer;
159         }
160         return this->createQuadIndexBuffer();
161     }
162 
163     static int QuadCountOfQuadBuffer();
164 
165     /**
166      * Factories for GrPath and GrPathRange objects. It's an error to call these if path rendering
167      * is not supported.
168      */
169     sk_sp<GrPath> createPath(const SkPath&, const GrStyle&);
170     sk_sp<GrPathRange> createPathRange(GrPathRange::PathGenerator*, const GrStyle&);
171     sk_sp<GrPathRange> createGlyphs(const SkTypeface*, const SkScalerContextEffects&,
172                                     const SkDescriptor*, const GrStyle&);
173 
174     /** These flags govern which scratch resources we are allowed to return */
175     enum Flags {
176         /** If the caller intends to do direct reads/writes to/from the CPU then this flag must be
177          *  set when accessing resources during a GrOpList flush. This includes the execution of
178          *  GrOp objects. The reason is that these memory operations are done immediately and
179          *  will occur out of order WRT the operations being flushed.
180          *  Make this automatic: https://bug.skia.org/4156
181          */
182         kNoPendingIO_Flag     = 0x1,
183 
184         /** Normally the caps may indicate a preference for client-side buffers. Set this flag when
185          *  creating a buffer to guarantee it resides in GPU memory.
186          */
187         kRequireGpuMemory_Flag = 0x2,
188     };
189 
190     /**
191      * Returns a buffer.
192      *
193      * @param size            minimum size of buffer to return.
194      * @param intendedType    hint to the graphics subsystem about what the buffer will be used for.
195      * @param GrAccessPattern hint to the graphics subsystem about how the data will be accessed.
196      * @param flags           see Flags enum.
197      * @param data            optional data with which to initialize the buffer.
198      *
199      * @return the buffer if successful, otherwise nullptr.
200      */
201     GrBuffer* createBuffer(size_t size, GrBufferType intendedType, GrAccessPattern, uint32_t flags,
202                            const void* data = nullptr);
203 
204 
205     /**
206      * If passed in render target already has a stencil buffer, return true. Otherwise attempt to
207      * attach one and return true on success.
208      */
209     bool attachStencilAttachment(GrRenderTarget* rt);
210 
211      /**
212       * Wraps an existing texture with a GrRenderTarget object. This is useful when the provided
213       * texture has a format that cannot be textured from by Skia, but we want to raster to it.
214       *
215       * The texture is wrapped as borrowed. The texture object will not be freed once the
216       * render target is destroyed.
217       *
218       * @return GrRenderTarget object or NULL on failure.
219       */
220      sk_sp<GrRenderTarget> wrapBackendTextureAsRenderTarget(const GrBackendTexture&,
221                                                             int sampleCnt);
222 
223     /**
224      * Assigns a unique key to a resource. If the key is associated with another resource that
225      * association is removed and replaced by this resource.
226      */
227     void assignUniqueKeyToResource(const GrUniqueKey&, GrGpuResource*);
228 
229     sk_sp<GrSemaphore> SK_WARN_UNUSED_RESULT makeSemaphore(bool isOwned = true);
230 
231     enum class SemaphoreWrapType {
232         kWillSignal,
233         kWillWait,
234     };
235 
236     sk_sp<GrSemaphore> wrapBackendSemaphore(const GrBackendSemaphore&,
237                                             SemaphoreWrapType wrapType,
238                                             GrWrapOwnership = kBorrow_GrWrapOwnership);
239 
240     // Takes the GrSemaphore and sets the ownership of the semaphore to the GrGpu object used by
241     // this class. This call is only used when passing a GrSemaphore from one context to another.
242     void takeOwnershipOfSemaphore(sk_sp<GrSemaphore>);
243     // Takes the GrSemaphore and resets the ownership of the semaphore so that it is not owned by
244     // any GrGpu. A follow up call to takeOwnershipofSemaphore must be made so that the underlying
245     // semaphore can be deleted. This call is only used when passing a GrSemaphore from one context
246     // to another.
247     void releaseOwnershipOfSemaphore(sk_sp<GrSemaphore>);
248 
abandon()249     void abandon() {
250         fCache = nullptr;
251         fGpu = nullptr;
252     }
253 
caps()254     const GrCaps* caps() const { return fCaps.get(); }
overBudget()255     bool overBudget() const { return fCache->overBudget(); }
256 
257     inline GrResourceProviderPriv priv();
258     inline const GrResourceProviderPriv priv() const;
259 
260 private:
261     sk_sp<GrGpuResource> findResourceByUniqueKey(const GrUniqueKey&);
262 
263     // Attempts to find a resource in the cache that exactly matches the GrSurfaceDesc. Failing that
264     // it returns null. If non-null, the resulting texture is always budgeted.
265     sk_sp<GrTexture> refScratchTexture(const GrSurfaceDesc&, uint32_t scratchTextureFlags);
266 
267     /*
268      * Try to find an existing scratch texture that exactly matches 'desc'. If successful
269      * update the budgeting accordingly.
270      */
271     sk_sp<GrTexture> getExactScratch(const GrSurfaceDesc&, SkBudgeted, uint32_t flags);
272 
cache()273     GrResourceCache* cache() { return fCache; }
cache()274     const GrResourceCache* cache() const { return fCache; }
275 
276     friend class GrResourceProviderPriv;
277 
278     // Method made available via GrResourceProviderPriv
gpu()279     GrGpu* gpu() { return fGpu; }
gpu()280     const GrGpu* gpu() const { return fGpu; }
281 
isAbandoned()282     bool isAbandoned() const {
283         SkASSERT(SkToBool(fGpu) == SkToBool(fCache));
284         return !SkToBool(fCache);
285     }
286 
287     sk_sp<const GrBuffer> createPatternedIndexBuffer(const uint16_t* pattern,
288                                                      int patternSize,
289                                                      int reps,
290                                                      int vertCount,
291                                                      const GrUniqueKey& key);
292 
293     sk_sp<const GrBuffer> createQuadIndexBuffer();
294 
295     GrResourceCache*    fCache;
296     GrGpu*              fGpu;
297     sk_sp<const GrCaps> fCaps;
298     GrUniqueKey         fQuadIndexBufferKey;
299 
300     // In debug builds we guard against improper thread handling
301     SkDEBUGCODE(mutable GrSingleOwner* fSingleOwner;)
302 };
303 
304 #endif
305