GrGpu.h revision 17aa047066eaaa56637c4c2b93c8c4c374127dbf
1/*
2 * Copyright 2011 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 GrGpu_DEFINED
9#define GrGpu_DEFINED
10
11#include "GrPipelineBuilder.h"
12#include "GrProgramDesc.h"
13#include "GrStencil.h"
14#include "GrTextureParamsAdjuster.h"
15#include "GrXferProcessor.h"
16#include "SkPath.h"
17
18class GrBatchTracker;
19class GrContext;
20class GrGLContext;
21class GrIndexBuffer;
22class GrNonInstancedVertices;
23class GrPath;
24class GrPathRange;
25class GrPathRenderer;
26class GrPathRendererChain;
27class GrPathRendering;
28class GrPipeline;
29class GrPrimitiveProcessor;
30class GrRenderTarget;
31class GrStencilAttachment;
32class GrSurface;
33class GrTexture;
34class GrTransferBuffer;
35class GrVertexBuffer;
36class GrVertices;
37
38class GrGpu : public SkRefCnt {
39public:
40    /**
41     * Create an instance of GrGpu that matches the specified backend. If the requested backend is
42     * not supported (at compile-time or run-time) this returns nullptr. The context will not be
43     * fully constructed and should not be used by GrGpu until after this function returns.
44     */
45    static GrGpu* Create(GrBackend, GrBackendContext, const GrContextOptions&, GrContext* context);
46
47    ////////////////////////////////////////////////////////////////////////////
48
49    GrGpu(GrContext* context);
50    ~GrGpu() override;
51
52    GrContext* getContext() { return fContext; }
53    const GrContext* getContext() const { return fContext; }
54
55    /**
56     * Gets the capabilities of the draw target.
57     */
58    const GrCaps* caps() const { return fCaps.get(); }
59
60    GrPathRendering* pathRendering() { return fPathRendering.get();  }
61
62    // Called by GrContext when the underlying backend context has been destroyed.
63    // GrGpu should use this to ensure that no backend API calls will be made from
64    // here onward, including in its destructor. Subclasses should call
65    // INHERITED::contextAbandoned() if they override this.
66    virtual void contextAbandoned();
67
68    /**
69     * The GrGpu object normally assumes that no outsider is setting state
70     * within the underlying 3D API's context/device/whatever. This call informs
71     * the GrGpu that the state was modified and it shouldn't make assumptions
72     * about the state.
73     */
74    void markContextDirty(uint32_t state = kAll_GrBackendState) { fResetBits |= state; }
75
76    /**
77     * Creates a texture object. If kRenderTarget_GrSurfaceFlag the texture can
78     * be used as a render target by calling GrTexture::asRenderTarget(). Not all
79     * pixel configs can be used as render targets. Support for configs as textures
80     * or render targets can be checked using GrCaps.
81     *
82     * @param desc        describes the texture to be created.
83     * @param budgeted    does this texture count against the resource cache budget?
84     * @param srcData     texel data to load texture. Begins with full-size
85     *                    palette data for paletted textures. For compressed
86     *                    formats it contains the compressed pixel data. Otherwise,
87     *                    it contains width*height texels. If nullptr texture data
88     *                    is uninitialized.
89     * @param rowBytes    the number of bytes between consecutive rows. Zero
90     *                    means rows are tightly packed. This field is ignored
91     *                    for compressed formats.
92     *
93     * @return    The texture object if successful, otherwise nullptr.
94     */
95    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted,
96                             const void* srcData, size_t rowBytes);
97
98    /**
99     * Implements GrContext::wrapBackendTexture
100     */
101    GrTexture* wrapBackendTexture(const GrBackendTextureDesc&, GrWrapOwnership);
102
103    /**
104     * Implements GrContext::wrapBackendTexture
105     */
106    GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&, GrWrapOwnership);
107
108    /**
109     * Creates a vertex buffer.
110     *
111     * @param size    size in bytes of the vertex buffer
112     * @param dynamic hints whether the data will be frequently changed
113     *                by either GrVertexBuffer::map() or
114     *                GrVertexBuffer::updateData().
115     *
116     * @return    The vertex buffer if successful, otherwise nullptr.
117     */
118    GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic);
119
120    /**
121     * Creates an index buffer.
122     *
123     * @param size    size in bytes of the index buffer
124     * @param dynamic hints whether the data will be frequently changed
125     *                by either GrIndexBuffer::map() or
126     *                GrIndexBuffer::updateData().
127     *
128     * @return The index buffer if successful, otherwise nullptr.
129     */
130    GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic);
131
132    /**
133     * Creates a transfer buffer.
134     *
135     * @param size      size in bytes of the index buffer
136     * @param toGpu     true if used to transfer from the cpu to the gpu
137     *                  otherwise to be used to transfer from the gpu to the cpu
138     *
139     * @return The transfer buffer if successful, otherwise nullptr.
140     */
141    GrTransferBuffer* createTransferBuffer(size_t size, TransferType type);
142
143    /**
144     * Resolves MSAA.
145     */
146    void resolveRenderTarget(GrRenderTarget* target);
147
148    /** Info struct returned by getReadPixelsInfo about performing intermediate draws before
149        reading pixels for performance or correctness. */
150    struct ReadPixelTempDrawInfo {
151        /** If the GrGpu is requesting that the caller do a draw to an intermediate surface then
152            this is descriptor for the temp surface. The draw should always be a rect with
153            dst 0,0,w,h. */
154        GrSurfaceDesc   fTempSurfaceDesc;
155        /** Indicates whether there is a performance advantage to using an exact match texture
156            (in terms of width and height) for the intermediate texture instead of approximate. */
157        bool            fUseExactScratch;
158        /** The caller should swap the R and B channel in the temp draw and then instead of reading
159            the desired config back it should read GrPixelConfigSwapRAndB(readConfig). The swap
160            during the draw and the swap at readback time cancel and the client gets the correct
161            data. The swapped read back is either faster for or required by the underlying backend
162            3D API. */
163        bool            fSwapRAndB;
164    };
165    /** Describes why an intermediate draw must/should be performed before readPixels. */
166    enum DrawPreference {
167        /** On input means that the caller would proceed without draw if the GrGpu doesn't request
168            one.
169            On output means that the GrGpu is not requesting a draw. */
170        kNoDraw_DrawPreference,
171        /** Means that the client would prefer a draw for performance of the readback but
172            can satisfy a straight readPixels call on the inputs without an intermediate draw.
173            getReadPixelsInfo will never set the draw preference to this value but may leave
174            it set. */
175        kCallerPrefersDraw_DrawPreference,
176        /** On output means that GrGpu would prefer a draw for performance of the readback but
177            can satisfy a straight readPixels call on the inputs without an intermediate draw. The
178            caller of getReadPixelsInfo should never specify this on intput. */
179        kGpuPrefersDraw_DrawPreference,
180        /** On input means that the caller requires a draw to do a transformation and there is no
181            CPU fallback.
182            On output means that GrGpu can only satisfy the readPixels request if the intermediate
183            draw is performed.
184          */
185        kRequireDraw_DrawPreference
186    };
187
188    /**
189     * Used to negotiate whether and how an intermediate draw should or must be performed before
190     * a readPixels call. If this returns false then GrGpu could not deduce an intermediate draw
191     * that would allow a successful readPixels call. The passed width, height, and rowBytes,
192     * must be non-zero and already reflect clipping to the src bounds.
193     */
194    bool getReadPixelsInfo(GrSurface* srcSurface, int readWidth, int readHeight, size_t rowBytes,
195                           GrPixelConfig readConfig, DrawPreference*, ReadPixelTempDrawInfo*);
196
197    /** Info struct returned by getWritePixelsInfo about performing an intermediate draw in order
198        to write pixels to a GrSurface for either performance or correctness reasons. */
199    struct WritePixelTempDrawInfo {
200        /** If the GrGpu is requesting that the caller upload to an intermediate surface and draw
201            that to the dst then this is the descriptor for the intermediate surface. The caller
202            should upload the pixels such that the upper left pixel of the upload rect is at 0,0 in
203            the intermediate surface.*/
204        GrSurfaceDesc   fTempSurfaceDesc;
205        /** If set, fTempSurfaceDesc's config will be a R/B swap of the src pixel config. The caller
206            should upload the pixels as is such that R and B will be swapped in the intermediate
207            surface. When the intermediate is drawn to the dst the shader should swap R/B again
208            such that the correct swizzle results in the dst. This is done to work around either
209            performance or API restrictions in the backend 3D API implementation. */
210        bool            fSwapRAndB;
211    };
212
213    /**
214     * Used to negotiate whether and how an intermediate surface should be used to write pixels to
215     * a GrSurface. If this returns false then GrGpu could not deduce an intermediate draw
216     * that would allow a successful transfer of the src pixels to the dst. The passed width,
217     * height, and rowBytes, must be non-zero and already reflect clipping to the dst bounds.
218     */
219    bool getWritePixelsInfo(GrSurface* dstSurface, int width, int height, size_t rowBytes,
220                            GrPixelConfig srcConfig, DrawPreference*, WritePixelTempDrawInfo*);
221
222    /**
223     * Reads a rectangle of pixels from a render target.
224     *
225     * @param surface       The surface to read from
226     * @param left          left edge of the rectangle to read (inclusive)
227     * @param top           top edge of the rectangle to read (inclusive)
228     * @param width         width of rectangle to read in pixels.
229     * @param height        height of rectangle to read in pixels.
230     * @param config        the pixel config of the destination buffer
231     * @param buffer        memory to read the rectangle into.
232     * @param rowBytes      the number of bytes between consecutive rows. Zero
233     *                      means rows are tightly packed.
234     * @param invertY       buffer should be populated bottom-to-top as opposed
235     *                      to top-to-bottom (skia's usual order)
236     *
237     * @return true if the read succeeded, false if not. The read can fail
238     *              because of a unsupported pixel config or because no render
239     *              target is currently set.
240     */
241    bool readPixels(GrSurface* surface,
242                    int left, int top, int width, int height,
243                    GrPixelConfig config, void* buffer, size_t rowBytes);
244
245    /**
246     * Updates the pixels in a rectangle of a surface.
247     *
248     * @param surface       The surface to write to.
249     * @param left          left edge of the rectangle to write (inclusive)
250     * @param top           top edge of the rectangle to write (inclusive)
251     * @param width         width of rectangle to write in pixels.
252     * @param height        height of rectangle to write in pixels.
253     * @param config        the pixel config of the source buffer
254     * @param buffer        memory to read pixels from
255     * @param rowBytes      number of bytes between consecutive rows. Zero
256     *                      means rows are tightly packed.
257     */
258    bool writePixels(GrSurface* surface,
259                     int left, int top, int width, int height,
260                     GrPixelConfig config, const void* buffer,
261                     size_t rowBytes);
262
263    /**
264     * Updates the pixels in a rectangle of a surface using a GrTransferBuffer
265     *
266     * @param surface       The surface to write to.
267     * @param left          left edge of the rectangle to write (inclusive)
268     * @param top           top edge of the rectangle to write (inclusive)
269     * @param width         width of rectangle to write in pixels.
270     * @param height        height of rectangle to write in pixels.
271     * @param config        the pixel config of the source buffer
272     * @param buffer        GrTransferBuffer to read pixels from
273     * @param offset        offset from the start of the buffer
274     * @param rowBytes      number of bytes between consecutive rows. Zero
275     *                      means rows are tightly packed.
276     */
277    bool transferPixels(GrSurface* surface,
278                        int left, int top, int width, int height,
279                        GrPixelConfig config, GrTransferBuffer* buffer,
280                        size_t offset, size_t rowBytes);
281
282    /**
283     * Clear the passed in render target. Ignores the draw state and clip.
284     */
285    void clear(const SkIRect& rect, GrColor color, GrRenderTarget* renderTarget);
286
287
288    void clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* renderTarget);
289
290    /**
291     * Discards the contents render target. nullptr indicates that the current render target should
292     * be discarded.
293     **/
294    virtual void discard(GrRenderTarget* = nullptr) = 0;
295
296    /**
297     * This is can be called before allocating a texture to be a dst for copySurface. It will
298     * populate the origin, config, and flags fields of the desc such that copySurface can
299     * efficiently succeed. It should only succeed if it can allow copySurface to perform a copy
300     * that would be more effecient than drawing the src to a dst render target.
301     */
302    virtual bool initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc) const = 0;
303
304    // After the client interacts directly with the 3D context state the GrGpu
305    // must resync its internal state and assumptions about 3D context state.
306    // Each time this occurs the GrGpu bumps a timestamp.
307    // state of the 3D context
308    // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
309    // a billion years.
310    typedef uint64_t ResetTimestamp;
311
312    // This timestamp is always older than the current timestamp
313    static const ResetTimestamp kExpiredTimestamp = 0;
314    // Returns a timestamp based on the number of times the context was reset.
315    // This timestamp can be used to lazily detect when cached 3D context state
316    // is dirty.
317    ResetTimestamp getResetTimestamp() const { return fResetTimestamp; }
318
319    virtual void buildProgramDesc(GrProgramDesc*,
320                                  const GrPrimitiveProcessor&,
321                                  const GrPipeline&) const = 0;
322
323    // Called to perform a surface to surface copy. Fallbacks to issuing a draw from the src to dst
324    // take place at the GrDrawTarget level and this function implement faster copy paths. The rect
325    // and point are pre-clipped. The src rect and implied dst rect are guaranteed to be within the
326    // src/dst bounds and non-empty.
327    bool copySurface(GrSurface* dst,
328                     GrSurface* src,
329                     const SkIRect& srcRect,
330                     const SkIPoint& dstPoint);
331
332    struct DrawArgs {
333        DrawArgs(const GrPrimitiveProcessor* primProc,
334                 const GrPipeline* pipeline,
335                 const GrProgramDesc* desc)
336            : fPrimitiveProcessor(primProc)
337            , fPipeline(pipeline)
338            , fDesc(desc) {
339            SkASSERT(primProc && pipeline && desc);
340        }
341        const GrPrimitiveProcessor* fPrimitiveProcessor;
342        const GrPipeline* fPipeline;
343        const GrProgramDesc* fDesc;
344    };
345
346    void draw(const DrawArgs&, const GrVertices&);
347
348    ///////////////////////////////////////////////////////////////////////////
349    // Debugging and Stats
350
351    class Stats {
352    public:
353#if GR_GPU_STATS
354        Stats() { this->reset(); }
355
356        void reset() {
357            fRenderTargetBinds = 0;
358            fShaderCompilations = 0;
359            fTextureCreates = 0;
360            fTextureUploads = 0;
361            fTransfersToTexture = 0;
362            fStencilAttachmentCreates = 0;
363            fNumDraws = 0;
364        }
365
366        int renderTargetBinds() const { return fRenderTargetBinds; }
367        void incRenderTargetBinds() { fRenderTargetBinds++; }
368        int shaderCompilations() const { return fShaderCompilations; }
369        void incShaderCompilations() { fShaderCompilations++; }
370        int textureCreates() const { return fTextureCreates; }
371        void incTextureCreates() { fTextureCreates++; }
372        int textureUploads() const { return fTextureUploads; }
373        void incTextureUploads() { fTextureUploads++; }
374        int transfersToTexture() const { return fTransfersToTexture; }
375        void incTransfersToTexture() { fTransfersToTexture++; }
376        void incStencilAttachmentCreates() { fStencilAttachmentCreates++; }
377        void incNumDraws() { fNumDraws++; }
378        void dump(SkString*);
379        void dumpKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values);
380
381    private:
382        int fRenderTargetBinds;
383        int fShaderCompilations;
384        int fTextureCreates;
385        int fTextureUploads;
386        int fTransfersToTexture;
387        int fStencilAttachmentCreates;
388        int fNumDraws;
389#else
390        void dump(SkString*) {}
391        void dumpKeyValuePairs(SkTArray<SkString>*, SkTArray<double>*) {}
392        void incRenderTargetBinds() {}
393        void incShaderCompilations() {}
394        void incTextureCreates() {}
395        void incTextureUploads() {}
396        void incTransfersToTexture() {}
397        void incStencilAttachmentCreates() {}
398        void incNumDraws() {}
399#endif
400    };
401
402    Stats* stats() { return &fStats; }
403
404    /** Creates a texture directly in the backend API without wrapping it in a GrTexture. This is
405        only to be used for testing (particularly for testing the methods that import an externally
406        created texture into Skia. Must be matched with a call to deleteTestingOnlyTexture(). */
407    virtual GrBackendObject createTestingOnlyBackendTexture(void* pixels, int w, int h,
408                                                            GrPixelConfig config) const = 0;
409    /** Check a handle represents an actual texture in the backend API that has not been freed. */
410    virtual bool isTestingOnlyBackendTexture(GrBackendObject) const = 0;
411    /** If ownership of the backend texture has been transferred pass true for abandonTexture. This
412        will do any necessary cleanup of the handle without freeing the texture in the backend
413        API. */
414    virtual void deleteTestingOnlyBackendTexture(GrBackendObject,
415                                                 bool abandonTexture = false) const = 0;
416
417    // width and height may be larger than rt (if underlying API allows it).
418    // Returns nullptr if compatible sb could not be created, otherwise the caller owns the ref on
419    // the GrStencilAttachment.
420    virtual GrStencilAttachment* createStencilAttachmentForRenderTarget(const GrRenderTarget*,
421                                                                        int width,
422                                                                        int height) = 0;
423    // clears target's entire stencil buffer to 0
424    virtual void clearStencil(GrRenderTarget* target) = 0;
425
426    // draws an outline rectangle for debugging/visualization purposes.
427    virtual void drawDebugWireRect(GrRenderTarget*, const SkIRect&, GrColor) = 0;
428
429    // Determines whether a copy of a texture must be made in order to be compatible with
430    // a given GrTextureParams. If so, the width, height and filter used for the copy are
431    // output via the CopyParams.
432    bool makeCopyForTextureParams(int width, int height, const GrTextureParams&,
433                                  GrTextureProducer::CopyParams*) const;
434
435    // This is only to be used in GL-specific tests.
436    virtual const GrGLContext* glContextForTesting() const { return nullptr; }
437
438    // This is only to be used by testing code
439    virtual void resetShaderCacheForTesting() const {}
440
441protected:
442    // Functions used to map clip-respecting stencil tests into normal
443    // stencil funcs supported by GPUs.
444    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
445                                            GrStencilFunc func);
446    static void ConvertStencilFuncAndMask(GrStencilFunc func,
447                                          bool clipInStencil,
448                                          unsigned int clipBit,
449                                          unsigned int userBits,
450                                          unsigned int* ref,
451                                          unsigned int* mask);
452
453    static void ElevateDrawPreference(GrGpu::DrawPreference* preference,
454                                      GrGpu::DrawPreference elevation) {
455        GR_STATIC_ASSERT(GrGpu::kCallerPrefersDraw_DrawPreference > GrGpu::kNoDraw_DrawPreference);
456        GR_STATIC_ASSERT(GrGpu::kGpuPrefersDraw_DrawPreference >
457                         GrGpu::kCallerPrefersDraw_DrawPreference);
458        GR_STATIC_ASSERT(GrGpu::kRequireDraw_DrawPreference >
459                         GrGpu::kGpuPrefersDraw_DrawPreference);
460        *preference = SkTMax(*preference, elevation);
461    }
462
463    void handleDirtyContext() {
464        if (fResetBits) {
465            this->resetContext();
466        }
467    }
468
469    Stats                                   fStats;
470    SkAutoTDelete<GrPathRendering>          fPathRendering;
471    // Subclass must initialize this in its constructor.
472    SkAutoTUnref<const GrCaps>    fCaps;
473
474private:
475    // called when the 3D context state is unknown. Subclass should emit any
476    // assumed 3D context state and dirty any state cache.
477    virtual void onResetContext(uint32_t resetBits) = 0;
478
479    // Called before certain draws in order to guarantee coherent results from dst reads.
480    virtual void xferBarrier(GrRenderTarget*, GrXferBarrierType) = 0;
481
482    // overridden by backend-specific derived class to create objects.
483    // Texture size and sample size will have already been validated in base class before
484    // onCreateTexture/CompressedTexture are called.
485    virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc,
486                                       GrGpuResource::LifeCycle lifeCycle,
487                                       const void* srcData, size_t rowBytes) = 0;
488    virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc,
489                                                 GrGpuResource::LifeCycle lifeCycle,
490                                                 const void* srcData) = 0;
491    virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&, GrWrapOwnership) = 0;
492    virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&,
493                                                      GrWrapOwnership) = 0;
494    virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0;
495    virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0;
496    virtual GrTransferBuffer* onCreateTransferBuffer(size_t size, TransferType type) = 0;
497
498    // overridden by backend-specific derived class to perform the clear.
499    virtual void onClear(GrRenderTarget*, const SkIRect& rect, GrColor color) = 0;
500
501
502    // Overridden by backend specific classes to perform a clear of the stencil clip bits.  This is
503    // ONLY used by the the clip target
504    virtual void onClearStencilClip(GrRenderTarget*, const SkIRect& rect, bool insideClip) = 0;
505
506    // overridden by backend-specific derived class to perform the draw call.
507    virtual void onDraw(const DrawArgs&, const GrNonInstancedVertices&) = 0;
508
509    virtual bool onGetReadPixelsInfo(GrSurface* srcSurface, int readWidth, int readHeight,
510                                     size_t rowBytes, GrPixelConfig readConfig, DrawPreference*,
511                                     ReadPixelTempDrawInfo*) = 0;
512    virtual bool onGetWritePixelsInfo(GrSurface* dstSurface, int width, int height, size_t rowBytes,
513                                      GrPixelConfig srcConfig, DrawPreference*,
514                                      WritePixelTempDrawInfo*) = 0;
515
516    // overridden by backend-specific derived class to perform the surface read
517    virtual bool onReadPixels(GrSurface*,
518                              int left, int top,
519                              int width, int height,
520                              GrPixelConfig,
521                              void* buffer,
522                              size_t rowBytes) = 0;
523
524    // overridden by backend-specific derived class to perform the surface write
525    virtual bool onWritePixels(GrSurface*,
526                               int left, int top, int width, int height,
527                               GrPixelConfig config, const void* buffer,
528                               size_t rowBytes) = 0;
529
530    // overridden by backend-specific derived class to perform the surface write
531    virtual bool onTransferPixels(GrSurface*,
532                                  int left, int top, int width, int height,
533                                  GrPixelConfig config, GrTransferBuffer* buffer,
534                                  size_t offset, size_t rowBytes) = 0;
535
536    // overridden by backend-specific derived class to perform the resolve
537    virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
538
539    // overridden by backend specific derived class to perform the copy surface
540    virtual bool onCopySurface(GrSurface* dst,
541                               GrSurface* src,
542                               const SkIRect& srcRect,
543                               const SkIPoint& dstPoint) = 0;
544
545    void resetContext() {
546        this->onResetContext(fResetBits);
547        fResetBits = 0;
548        ++fResetTimestamp;
549    }
550
551    ResetTimestamp                                                      fResetTimestamp;
552    uint32_t                                                            fResetBits;
553    // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu.
554    GrContext*                                                          fContext;
555
556    friend class GrPathRendering;
557    typedef SkRefCnt INHERITED;
558};
559
560#endif
561