GrGpu.h revision 235ef3d0e253200af43bb69139df09744f5ddbef
1
2/*
3 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef GrGpu_DEFINED
11#define GrGpu_DEFINED
12
13#include "GrDrawTarget.h"
14#include "GrRect.h"
15#include "GrRefCnt.h"
16#include "GrClipMaskManager.h"
17
18#include "SkPath.h"
19
20class GrContext;
21class GrIndexBufferAllocPool;
22class GrPath;
23class GrPathRenderer;
24class GrPathRendererChain;
25class GrResource;
26class GrStencilBuffer;
27class GrVertexBufferAllocPool;
28
29class GrGpu : public GrDrawTarget {
30
31public:
32
33    /**
34     * Additional blend coefficients for dual source blending, not exposed
35     * through GrPaint/GrContext.
36     */
37    enum ExtendedBlendCoeffs {
38        // source 2 refers to second output color when
39        // using dual source blending.
40        kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount,
41        kIS2C_GrBlendCoeff,
42        kS2A_GrBlendCoeff,
43        kIS2A_GrBlendCoeff,
44
45        kTotalGrBlendCoeffCount
46    };
47
48    /**
49     * Create an instance of GrGpu that matches the specified backend. If the requested backend is
50     * not supported (at compile-time or run-time) this returns NULL. The context will not be
51     * fully constructed and should not be used by GrGpu until after this function returns.
52     */
53    static GrGpu* Create(GrBackend, GrBackendContext, GrContext* context);
54
55    ////////////////////////////////////////////////////////////////////////////
56
57    GrGpu(GrContext* context);
58    virtual ~GrGpu();
59
60    GrContext* getContext() { return this->INHERITED::getContext(); }
61    const GrContext* getContext() const { return this->INHERITED::getContext(); }
62
63    /**
64     * The GrGpu object normally assumes that no outsider is setting state
65     * within the underlying 3D API's context/device/whatever. This call informs
66     * the GrGpu that the state was modified and it shouldn't make assumptions
67     * about the state.
68     */
69    void markContextDirty() { fContextIsDirty = true; }
70
71    void unimpl(const char[]);
72
73    /**
74     * Creates a texture object. If desc width or height is not a power of
75     * two but underlying API requires a power of two texture then srcData
76     * will be embedded in a power of two texture. The extra width and height
77     * is filled as though srcData were rendered clamped into the texture.
78     *
79     * If kRenderTarget_TextureFlag is specified the GrRenderTarget is
80     * accessible via GrTexture::asRenderTarget(). The texture will hold a ref
81     * on the render target until the texture is destroyed.
82     *
83     * @param desc        describes the texture to be created.
84     * @param srcData     texel data to load texture. Begins with full-size
85     *                    palette data for paletted textures. Contains width*
86     *                    height texels. If NULL texture data is uninitialized.
87     *
88     * @return    The texture object if successful, otherwise NULL.
89     */
90    GrTexture* createTexture(const GrTextureDesc& desc,
91                             const void* srcData, size_t rowBytes);
92
93    /**
94     * Implements GrContext::wrapBackendTexture
95     */
96    GrTexture* wrapBackendTexture(const GrBackendTextureDesc&);
97
98    /**
99     * Implements GrContext::wrapBackendTexture
100     */
101    GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&);
102
103    /**
104     * Creates a vertex buffer.
105     *
106     * @param size    size in bytes of the vertex buffer
107     * @param dynamic hints whether the data will be frequently changed
108     *                by either GrVertexBuffer::lock or
109     *                GrVertexBuffer::updateData.
110     *
111     * @return    The vertex buffer if successful, otherwise NULL.
112     */
113    GrVertexBuffer* createVertexBuffer(uint32_t size, bool dynamic);
114
115    /**
116     * Creates an index buffer.
117     *
118     * @param size    size in bytes of the index buffer
119     * @param dynamic hints whether the data will be frequently changed
120     *                by either GrIndexBuffer::lock or
121     *                GrIndexBuffer::updateData.
122     *
123     * @return The index buffer if successful, otherwise NULL.
124     */
125    GrIndexBuffer* createIndexBuffer(uint32_t size, bool dynamic);
126
127    /**
128     * Creates a path object that can be stenciled using stencilPath(). It is
129     * only legal to call this if the caps report support for path stenciling.
130     */
131    GrPath* createPath(const SkPath& path);
132
133    /**
134     * Returns an index buffer that can be used to render quads.
135     * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
136     * The max number of quads can be queried using GrIndexBuffer::maxQuads().
137     * Draw with kTriangles_GrPrimitiveType
138     * @ return the quad index buffer
139     */
140    const GrIndexBuffer* getQuadIndexBuffer() const;
141
142    /**
143     * Resolves MSAA.
144     */
145    void resolveRenderTarget(GrRenderTarget* target);
146
147    /**
148     * Ensures that the current render target is actually set in the
149     * underlying 3D API. Used when client wants to use 3D API to directly
150     * render to the RT.
151     */
152    void forceRenderTargetFlush();
153
154    /**
155     * Gets a preferred 8888 config to use for writing / reading pixel data. The returned config
156     * must have at least as many bits per channel as the config param.
157     */
158    virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig config) const { return config; }
159    virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig config) const { return config; }
160
161    /**
162     * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't
163     * match the texture's config.
164     */
165    virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0;
166
167    /**
168     * OpenGL's readPixels returns the result bottom-to-top while the skia
169     * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious
170     * solution is to have the subclass do the flip using either the CPU or GPU.
171     * However, the caller (GrContext) may have transformations to apply and can
172     * simply fold in the y-flip for free. On the other hand, the subclass may
173     * be able to do it for free itself. For example, the subclass may have to
174     * do memcpys to handle rowBytes that aren't tight. It could do the y-flip
175     * concurrently.
176     *
177     * This function returns true if a y-flip is required to put the pixels in
178     * top-to-bottom order and the subclass cannot do it for free.
179     *
180     * See read pixels for the params
181     * @return true if calling readPixels with the same set of params will
182     *              produce bottom-to-top data
183     */
184     virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
185                                            int left, int top,
186                                            int width, int height,
187                                            GrPixelConfig config,
188                                            size_t rowBytes) const = 0;
189     /**
190      * This should return true if reading a NxM rectangle of pixels from a
191      * render target is faster if the target has dimensons N and M and the read
192      * rectangle has its top-left at 0,0.
193      */
194     virtual bool fullReadPixelsIsFasterThanPartial() const { return false; };
195
196    /**
197     * Reads a rectangle of pixels from a render target.
198     *
199     * @param renderTarget  the render target to read from. NULL means the
200     *                      current render target.
201     * @param left          left edge of the rectangle to read (inclusive)
202     * @param top           top edge of the rectangle to read (inclusive)
203     * @param width         width of rectangle to read in pixels.
204     * @param height        height of rectangle to read in pixels.
205     * @param config        the pixel config of the destination buffer
206     * @param buffer        memory to read the rectangle into.
207     * @param rowBytes      the number of bytes between consecutive rows. Zero
208     *                      means rows are tightly packed.
209     * @param invertY       buffer should be populated bottom-to-top as opposed
210     *                      to top-to-bottom (skia's usual order)
211     *
212     * @return true if the read succeeded, false if not. The read can fail
213     *              because of a unsupported pixel config or because no render
214     *              target is currently set.
215     */
216    bool readPixels(GrRenderTarget* renderTarget,
217                    int left, int top, int width, int height,
218                    GrPixelConfig config, void* buffer, size_t rowBytes);
219
220    /**
221     * Updates the pixels in a rectangle of a texture.
222     *
223     * @param left          left edge of the rectangle to write (inclusive)
224     * @param top           top edge of the rectangle to write (inclusive)
225     * @param width         width of rectangle to write in pixels.
226     * @param height        height of rectangle to write in pixels.
227     * @param config        the pixel config of the source buffer
228     * @param buffer        memory to read pixels from
229     * @param rowBytes      number of bytes between consecutive rows. Zero
230     *                      means rows are tightly packed.
231     */
232    bool writeTexturePixels(GrTexture* texture,
233                            int left, int top, int width, int height,
234                            GrPixelConfig config, const void* buffer,
235                            size_t rowBytes);
236
237    /**
238     * Called to tell Gpu object that all GrResources have been lost and should
239     * be abandoned. Overrides must call INHERITED::abandonResources().
240     */
241    virtual void abandonResources();
242
243    /**
244     * Called to tell Gpu object to release all GrResources. Overrides must call
245     * INHERITED::releaseResources().
246     */
247    void releaseResources();
248
249    /**
250     * Add resource to list of resources. Should only be called by GrResource.
251     * @param resource  the resource to add.
252     */
253    void insertResource(GrResource* resource);
254
255    /**
256     * Remove resource from list of resources. Should only be called by
257     * GrResource.
258     * @param resource  the resource to remove.
259     */
260    void removeResource(GrResource* resource);
261
262    // GrDrawTarget overrides
263    virtual void clear(const GrIRect* rect,
264                       GrColor color,
265                       GrRenderTarget* renderTarget = NULL) SK_OVERRIDE;
266
267    virtual void purgeResources() SK_OVERRIDE {
268        // The clip mask manager can rebuild all its clip masks so just
269        // get rid of them all.
270        fClipMaskManager.releaseResources();
271    }
272
273    // After the client interacts directly with the 3D context state the GrGpu
274    // must resync its internal state and assumptions about 3D context state.
275    // Each time this occurs the GrGpu bumps a timestamp.
276    // state of the 3D context
277    // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
278    // a billion years.
279    typedef uint64_t ResetTimestamp;
280
281    // This timestamp is always older than the current timestamp
282    static const ResetTimestamp kExpiredTimestamp = 0;
283    // Returns a timestamp based on the number of times the context was reset.
284    // This timestamp can be used to lazily detect when cached 3D context state
285    // is dirty.
286    ResetTimestamp getResetTimestamp() const {
287        return fResetTimestamp;
288    }
289
290    /**
291     * Can the provided configuration act as a color render target?
292     */
293    bool isConfigRenderable(GrPixelConfig config) const {
294        GrAssert(kGrPixelConfigCnt > config);
295        return fConfigRenderSupport[config];
296    }
297
298    /**
299     * These methods are called by the clip manager's setupClipping function
300     * which (called as part of GrGpu's implementation of onDraw and
301     * onStencilPath member functions.) The GrGpu subclass should flush the
302     * stencil state to the 3D API in its implementation of flushGraphicsState.
303     */
304    void enableScissor(const GrIRect& rect) {
305        fScissorState.fEnabled = true;
306        fScissorState.fRect = rect;
307    }
308    void disableScissor() { fScissorState.fEnabled = false; }
309
310    /**
311     * Like the scissor methods above this is called by setupClipping and
312     * should be flushed by the GrGpu subclass in flushGraphicsState. These
313     * stencil settings should be used in place of those on the GrDrawState.
314     * They have been adjusted to account for any interactions between the
315     * GrDrawState's stencil settings and stencil clipping.
316     */
317    void setStencilSettings(const GrStencilSettings& settings) {
318        fStencilSettings = settings;
319    }
320    void disableStencil() { fStencilSettings.setDisabled(); }
321
322    // GrGpu subclass sets clip bit in the stencil buffer. The subclass is
323    // free to clear the remaining bits to zero if masked clears are more
324    // expensive than clearing all bits.
325    virtual void clearStencilClip(const GrIRect& rect, bool insideClip) = 0;
326
327    enum PrivateDrawStateStateBits {
328        kFirstBit = (GrDrawState::kLastPublicStateBit << 1),
329
330        kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify
331                                                 // stencil bits used for
332                                                 // clipping.
333    };
334
335protected:
336    enum DrawType {
337        kDrawPoints_DrawType,
338        kDrawLines_DrawType,
339        kDrawTriangles_DrawType,
340        kStencilPath_DrawType,
341    };
342
343    DrawType PrimTypeToDrawType(GrPrimitiveType type) {
344        switch (type) {
345            case kTriangles_GrPrimitiveType:
346            case kTriangleStrip_GrPrimitiveType:
347            case kTriangleFan_GrPrimitiveType:
348                return kDrawTriangles_DrawType;
349            case kPoints_GrPrimitiveType:
350                return kDrawPoints_DrawType;
351            case kLines_GrPrimitiveType:
352            case kLineStrip_GrPrimitiveType:
353                return kDrawLines_DrawType;
354            default:
355                GrCrash("Unexpected primitive type");
356                return kDrawTriangles_DrawType;
357        }
358    }
359
360    // prepares clip flushes gpu state before a draw
361    bool setupClipAndFlushState(DrawType, const GrDeviceCoordTexture* dstCopy);
362
363    // Functions used to map clip-respecting stencil tests into normal
364    // stencil funcs supported by GPUs.
365    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
366                                            GrStencilFunc func);
367    static void ConvertStencilFuncAndMask(GrStencilFunc func,
368                                          bool clipInStencil,
369                                          unsigned int clipBit,
370                                          unsigned int userBits,
371                                          unsigned int* ref,
372                                          unsigned int* mask);
373
374    GrClipMaskManager           fClipMaskManager;
375
376    struct GeometryPoolState {
377        const GrVertexBuffer* fPoolVertexBuffer;
378        int                   fPoolStartVertex;
379
380        const GrIndexBuffer*  fPoolIndexBuffer;
381        int                   fPoolStartIndex;
382    };
383    const GeometryPoolState& getGeomPoolState() {
384        return fGeomPoolStateStack.back();
385    }
386
387    // The state of the scissor is controlled by the clip manager
388    struct ScissorState {
389        bool    fEnabled;
390        GrIRect fRect;
391    } fScissorState;
392
393    // The final stencil settings to use as determined by the clip manager.
394    GrStencilSettings fStencilSettings;
395
396    // Derived classes need access to this so they can fill it out in their
397    // constructors
398    bool    fConfigRenderSupport[kGrPixelConfigCnt];
399
400    // Helpers for setting up geometry state
401    void finalizeReservedVertices();
402    void finalizeReservedIndices();
403
404private:
405    // GrDrawTarget overrides
406    virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) SK_OVERRIDE;
407    virtual bool onReserveIndexSpace(int indexCount, void** indices) SK_OVERRIDE;
408    virtual void releaseReservedVertexSpace() SK_OVERRIDE;
409    virtual void releaseReservedIndexSpace() SK_OVERRIDE;
410    virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) SK_OVERRIDE;
411    virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) SK_OVERRIDE;
412    virtual void releaseVertexArray() SK_OVERRIDE;
413    virtual void releaseIndexArray() SK_OVERRIDE;
414    virtual void geometrySourceWillPush() SK_OVERRIDE;
415    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) SK_OVERRIDE;
416
417
418    // called when the 3D context state is unknown. Subclass should emit any
419    // assumed 3D context state and dirty any state cache.
420    virtual void onResetContext() = 0;
421
422    // overridden by backend-specific derived class to create objects.
423    virtual GrTexture* onCreateTexture(const GrTextureDesc& desc,
424                                       const void* srcData,
425                                       size_t rowBytes) = 0;
426    virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0;
427    virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0;
428    virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size, bool dynamic) = 0;
429    virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size, bool dynamic) = 0;
430    virtual GrPath* onCreatePath(const SkPath& path) = 0;
431
432    // overridden by backend-specific derived class to perform the clear and
433    // clearRect. NULL rect means clear whole target.
434    virtual void onClear(const GrIRect* rect, GrColor color) = 0;
435
436    // overridden by backend-specific derived class to perform the draw call.
437    virtual void onGpuDraw(const DrawInfo&) = 0;
438    // when GrDrawTarget::stencilPath is called the draw state's current stencil
439    // settings are ignored. Instead the GrGpu decides the stencil rules
440    // necessary to stencil the path. These are still subject to filtering by
441    // the clip mask manager.
442    virtual void setStencilPathSettings(const GrPath&,
443                                        SkPath::FillType,
444                                        GrStencilSettings* settings) = 0;
445    // overridden by backend-specific derived class to perform the path stenciling.
446    virtual void onGpuStencilPath(const GrPath*, SkPath::FillType) = 0;
447
448    // overridden by backend-specific derived class to perform flush
449    virtual void onForceRenderTargetFlush() = 0;
450
451    // overridden by backend-specific derived class to perform the read pixels.
452    virtual bool onReadPixels(GrRenderTarget* target,
453                              int left, int top, int width, int height,
454                              GrPixelConfig,
455                              void* buffer,
456                              size_t rowBytes) = 0;
457
458    // overridden by backend-specific derived class to perform the texture update
459    virtual bool onWriteTexturePixels(GrTexture* texture,
460                                      int left, int top, int width, int height,
461                                      GrPixelConfig config, const void* buffer,
462                                      size_t rowBytes) = 0;
463
464    // overridden by backend-specific derived class to perform the resolve
465    virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
466
467    // width and height may be larger than rt (if underlying API allows it).
468    // Should attach the SB to the RT. Returns false if compatible sb could
469    // not be created.
470    virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0;
471
472    // attaches an existing SB to an existing RT.
473    virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0;
474
475    // The GrGpu typically records the clients requested state and then flushes
476    // deltas from previous state at draw time. This function does the
477    // backend-specific flush of the state.
478    // returns false if current state is unsupported.
479    virtual bool flushGraphicsState(DrawType, const GrDeviceCoordTexture* dstCopy) = 0;
480
481    // clears the entire stencil buffer to 0
482    virtual void clearStencil() = 0;
483
484    // Given a rt, find or create a stencil buffer and attach it
485    bool attachStencilBufferToRenderTarget(GrRenderTarget* target);
486
487    // GrDrawTarget overrides
488    virtual void onDraw(const DrawInfo&) SK_OVERRIDE;
489    virtual void onStencilPath(const GrPath* path, const SkStrokeRec& stroke,
490                               SkPath::FillType) SK_OVERRIDE;
491
492    // readies the pools to provide vertex/index data.
493    void prepareVertexPool();
494    void prepareIndexPool();
495
496    void resetContext() {
497        // We call this because the client may have messed with the
498        // stencil buffer. Perhaps we should detect whether it is a
499        // internally created stencil buffer and if so skip the invalidate.
500        fClipMaskManager.invalidateStencilMask();
501        this->onResetContext();
502        ++fResetTimestamp;
503    }
504
505    void handleDirtyContext() {
506        if (fContextIsDirty) {
507            this->resetContext();
508            fContextIsDirty = false;
509        }
510    }
511
512    enum {
513        kPreallocGeomPoolStateStackCnt = 4,
514    };
515    typedef SkTInternalLList<GrResource> ResourceList;
516    SkSTArray<kPreallocGeomPoolStateStackCnt, GeometryPoolState, true>  fGeomPoolStateStack;
517    ResetTimestamp                                                      fResetTimestamp;
518    GrVertexBufferAllocPool*                                            fVertexPool;
519    GrIndexBufferAllocPool*                                             fIndexPool;
520    // counts number of uses of vertex/index pool in the geometry stack
521    int                                                                 fVertexPoolUseCnt;
522    int                                                                 fIndexPoolUseCnt;
523    // these are mutable so they can be created on-demand
524    mutable GrIndexBuffer*                                              fQuadIndexBuffer;
525    bool                                                                fContextIsDirty;
526    ResourceList                                                        fResourceList;
527
528    typedef GrDrawTarget INHERITED;
529};
530
531#endif
532