2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
11 #include "GrDrawTarget.h"
12 #include "GrPathRendering.h"
13 #include "GrProgramDesc.h"
17 class GrIndexBufferAllocPool;
21 class GrPathRendererChain;
22 class GrStencilBuffer;
23 class GrVertexBufferAllocPool;
25 class GrGpu : public GrClipTarget {
29 * Additional blend coefficients for dual source blending, not exposed
30 * through GrPaint/GrContext.
32 enum ExtendedBlendCoeffs {
33 // source 2 refers to second output color when
34 // using dual source blending.
35 kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount,
40 kTotalGrBlendCoeffCount
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.
48 static GrGpu* Create(GrBackend, GrBackendContext, GrContext* context);
50 ////////////////////////////////////////////////////////////////////////////
52 GrGpu(GrContext* context);
55 GrContext* getContext() { return this->INHERITED::getContext(); }
56 const GrContext* getContext() const { return this->INHERITED::getContext(); }
58 GrPathRendering* pathRendering() {
59 return fPathRendering.get();
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();
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
74 void markContextDirty(uint32_t state = kAll_GrBackendState) {
78 void unimpl(const char[]);
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.
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.
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
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.
106 * @return The texture object if successful, otherwise NULL.
108 GrTexture* createTexture(const GrSurfaceDesc& desc,
109 const void* srcData, size_t rowBytes);
112 * Implements GrContext::wrapBackendTexture
114 GrTexture* wrapBackendTexture(const GrBackendTextureDesc&);
117 * Implements GrContext::wrapBackendTexture
119 GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&);
122 * Creates a vertex buffer.
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().
129 * @return The vertex buffer if successful, otherwise NULL.
131 GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic);
134 * Creates an index buffer.
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().
141 * @return The index buffer if successful, otherwise NULL.
143 GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic);
146 * Creates an index buffer for instance drawing with a specific pattern.
148 * @param pattern the pattern to repeat
149 * @param patternSize size in bytes of the pattern
150 * @param reps number of times to repeat the pattern
151 * @param vertCount number of vertices the pattern references
152 * @param dynamic hints whether the data will be frequently changed
153 * by either GrIndexBuffer::map() or
154 * GrIndexBuffer::updateData().
156 * @return The index buffer if successful, otherwise NULL.
158 GrIndexBuffer* createInstancedIndexBuffer(const uint16_t* pattern,
162 bool isDynamic = false);
165 * Returns an index buffer that can be used to render quads.
166 * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
167 * The max number of quads can be queried using GrIndexBuffer::maxQuads().
168 * Draw with kTriangles_GrPrimitiveType
169 * @ return the quad index buffer
171 const GrIndexBuffer* getQuadIndexBuffer() const;
176 void resolveRenderTarget(GrRenderTarget* target);
179 * Gets a preferred 8888 config to use for writing/reading pixel data to/from a surface with
180 * config surfaceConfig. The returned config must have at least as many bits per channel as the
181 * readConfig or writeConfig param.
183 virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig readConfig,
184 GrPixelConfig surfaceConfig) const {
187 virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig writeConfig,
188 GrPixelConfig surfaceConfig) const {
193 * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't
194 * match the texture's config.
196 virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0;
199 * OpenGL's readPixels returns the result bottom-to-top while the skia
200 * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious
201 * solution is to have the subclass do the flip using either the CPU or GPU.
202 * However, the caller (GrContext) may have transformations to apply and can
203 * simply fold in the y-flip for free. On the other hand, the subclass may
204 * be able to do it for free itself. For example, the subclass may have to
205 * do memcpys to handle rowBytes that aren't tight. It could do the y-flip
208 * This function returns true if a y-flip is required to put the pixels in
209 * top-to-bottom order and the subclass cannot do it for free.
211 * See read pixels for the params
212 * @return true if calling readPixels with the same set of params will
213 * produce bottom-to-top data
215 virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
217 int width, int height,
218 GrPixelConfig config,
219 size_t rowBytes) const = 0;
221 * This should return true if reading a NxM rectangle of pixels from a
222 * render target is faster if the target has dimensons N and M and the read
223 * rectangle has its top-left at 0,0.
225 virtual bool fullReadPixelsIsFasterThanPartial() const { return false; };
228 * Reads a rectangle of pixels from a render target.
230 * @param renderTarget the render target to read from. NULL means the
231 * current render target.
232 * @param left left edge of the rectangle to read (inclusive)
233 * @param top top edge of the rectangle to read (inclusive)
234 * @param width width of rectangle to read in pixels.
235 * @param height height of rectangle to read in pixels.
236 * @param config the pixel config of the destination buffer
237 * @param buffer memory to read the rectangle into.
238 * @param rowBytes the number of bytes between consecutive rows. Zero
239 * means rows are tightly packed.
240 * @param invertY buffer should be populated bottom-to-top as opposed
241 * to top-to-bottom (skia's usual order)
243 * @return true if the read succeeded, false if not. The read can fail
244 * because of a unsupported pixel config or because no render
245 * target is currently set.
247 bool readPixels(GrRenderTarget* renderTarget,
248 int left, int top, int width, int height,
249 GrPixelConfig config, void* buffer, size_t rowBytes);
252 * Updates the pixels in a rectangle of a texture.
254 * @param left left edge of the rectangle to write (inclusive)
255 * @param top top edge of the rectangle to write (inclusive)
256 * @param width width of rectangle to write in pixels.
257 * @param height height of rectangle to write in pixels.
258 * @param config the pixel config of the source buffer
259 * @param buffer memory to read pixels from
260 * @param rowBytes number of bytes between consecutive rows. Zero
261 * means rows are tightly packed.
263 bool writeTexturePixels(GrTexture* texture,
264 int left, int top, int width, int height,
265 GrPixelConfig config, const void* buffer,
268 // GrDrawTarget overrides
269 virtual void clearStencilClip(const SkIRect& rect,
271 GrRenderTarget* renderTarget = NULL) SK_OVERRIDE;
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
279 typedef uint64_t ResetTimestamp;
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
286 ResetTimestamp getResetTimestamp() const {
287 return fResetTimestamp;
291 kDrawPoints_DrawType,
293 kDrawTriangles_DrawType,
294 kStencilPath_DrawType,
299 static bool IsPathRenderingDrawType(DrawType type) {
300 return kDrawPath_DrawType == type || kDrawPaths_DrawType == type;
303 GrContext::GPUStats* gpuStats() { return &fGPUStats; }
305 virtual void buildProgramDesc(const GrOptDrawState&,
306 const GrProgramDesc::DescInfo&,
308 const GrDeviceCoordTexture* dstCopy,
312 DrawType PrimTypeToDrawType(GrPrimitiveType type) {
314 case kTriangles_GrPrimitiveType:
315 case kTriangleStrip_GrPrimitiveType:
316 case kTriangleFan_GrPrimitiveType:
317 return kDrawTriangles_DrawType;
318 case kPoints_GrPrimitiveType:
319 return kDrawPoints_DrawType;
320 case kLines_GrPrimitiveType:
321 case kLineStrip_GrPrimitiveType:
322 return kDrawLines_DrawType;
324 SkFAIL("Unexpected primitive type");
325 return kDrawTriangles_DrawType;
329 // prepares clip flushes gpu state before a draw
330 bool setupClipAndFlushState(DrawType,
331 const GrDeviceCoordTexture* dstCopy,
332 const SkRect* devBounds,
333 GrDrawState::AutoRestoreEffects*,
334 GrDrawState::AutoRestoreStencil*);
336 // Functions used to map clip-respecting stencil tests into normal
337 // stencil funcs supported by GPUs.
338 static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
340 static void ConvertStencilFuncAndMask(GrStencilFunc func,
342 unsigned int clipBit,
343 unsigned int userBits,
347 GrContext::GPUStats fGPUStats;
349 struct GeometryPoolState {
350 const GrVertexBuffer* fPoolVertexBuffer;
351 int fPoolStartVertex;
353 const GrIndexBuffer* fPoolIndexBuffer;
356 const GeometryPoolState& getGeomPoolState() {
357 return fGeomPoolStateStack.back();
360 // Helpers for setting up geometry state
361 void finalizeReservedVertices();
362 void finalizeReservedIndices();
364 SkAutoTDelete<GrPathRendering> fPathRendering;
367 // GrDrawTarget overrides
368 virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) SK_OVERRIDE;
369 virtual bool onReserveIndexSpace(int indexCount, void** indices) SK_OVERRIDE;
370 virtual void releaseReservedVertexSpace() SK_OVERRIDE;
371 virtual void releaseReservedIndexSpace() SK_OVERRIDE;
372 virtual void geometrySourceWillPush() SK_OVERRIDE;
373 virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) SK_OVERRIDE;
374 virtual void onClear(const SkIRect* rect, GrColor color, bool canIgnoreRect,
375 GrRenderTarget* renderTarget) SK_OVERRIDE;
377 // called when the 3D context state is unknown. Subclass should emit any
378 // assumed 3D context state and dirty any state cache.
379 virtual void onResetContext(uint32_t resetBits) = 0;
381 // overridden by backend-specific derived class to create objects.
382 virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc,
384 size_t rowBytes) = 0;
385 virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc,
386 const void* srcData) = 0;
387 virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0;
388 virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0;
389 virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0;
390 virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0;
392 // overridden by backend-specific derived class to perform the clear.
393 virtual void onGpuClear(GrRenderTarget*, const SkIRect* rect, GrColor color,
394 bool canIgnoreRect) = 0;
397 // Overridden by backend specific classes to perform a clear of the stencil clip bits. This is
398 // ONLY used by the the clip target
399 virtual void onClearStencilClip(GrRenderTarget*,
401 bool insideClip) = 0;
403 // overridden by backend-specific derived class to perform the draw call.
404 virtual void onGpuDraw(const DrawInfo&) = 0;
406 // overridden by backend-specific derived class to perform the read pixels.
407 virtual bool onReadPixels(GrRenderTarget* target,
408 int left, int top, int width, int height,
411 size_t rowBytes) = 0;
413 // overridden by backend-specific derived class to perform the texture update
414 virtual bool onWriteTexturePixels(GrTexture* texture,
415 int left, int top, int width, int height,
416 GrPixelConfig config, const void* buffer,
417 size_t rowBytes) = 0;
419 // overridden by backend-specific derived class to perform the resolve
420 virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
422 // width and height may be larger than rt (if underlying API allows it).
423 // Should attach the SB to the RT. Returns false if compatible sb could
425 virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0;
427 // attaches an existing SB to an existing RT.
428 virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0;
430 // The GrGpu typically records the clients requested state and then flushes
431 // deltas from previous state at draw time. This function does the
432 // backend-specific flush of the state.
433 // returns false if current state is unsupported.
434 virtual bool flushGraphicsState(DrawType,
435 const GrClipMaskManager::ScissorState&,
436 const GrDeviceCoordTexture* dstCopy) = 0;
438 // clears target's entire stencil buffer to 0
439 virtual void clearStencil(GrRenderTarget* target) = 0;
441 // Given a rt, find or create a stencil buffer and attach it
442 bool attachStencilBufferToRenderTarget(GrRenderTarget* target);
444 // GrDrawTarget overrides
445 virtual void onDraw(const DrawInfo&) SK_OVERRIDE;
446 virtual void onStencilPath(const GrPath*, GrPathRendering::FillType) SK_OVERRIDE;
447 virtual void onDrawPath(const GrPath*, GrPathRendering::FillType,
448 const GrDeviceCoordTexture* dstCopy) SK_OVERRIDE;
449 virtual void onDrawPaths(const GrPathRange*,
450 const uint32_t indices[], int count,
451 const float transforms[], PathTransformType,
452 GrPathRendering::FillType, const GrDeviceCoordTexture*) SK_OVERRIDE;
454 // readies the pools to provide vertex/index data.
455 void prepareVertexPool();
456 void prepareIndexPool();
458 void resetContext() {
459 this->onResetContext(fResetBits);
464 void handleDirtyContext() {
466 this->resetContext();
471 kPreallocGeomPoolStateStackCnt = 4,
473 SkSTArray<kPreallocGeomPoolStateStackCnt, GeometryPoolState, true> fGeomPoolStateStack;
474 ResetTimestamp fResetTimestamp;
476 GrVertexBufferAllocPool* fVertexPool;
477 GrIndexBufferAllocPool* fIndexPool;
478 // counts number of uses of vertex/index pool in the geometry stack
479 int fVertexPoolUseCnt;
480 int fIndexPoolUseCnt;
481 // these are mutable so they can be created on-demand
482 mutable GrIndexBuffer* fQuadIndexBuffer;
484 typedef GrClipTarget INHERITED;