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