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