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