2 * Copyright 2010 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef GrContext_DEFINED
9 #define GrContext_DEFINED
11 #include "GrClipData.h"
14 #include "GrPathRendererChain.h"
15 #include "GrRenderTarget.h"
16 #include "GrTexture.h"
18 #include "SkPathEffect.h"
21 class GrAARectRenderer;
22 class GrAutoScratchTexture;
29 class GrGpuTraceMarker;
31 class GrIndexBufferAllocPool;
32 class GrInOrderDrawBuffer;
37 class GrResourceEntry;
38 class GrResourceCache;
39 class GrStencilBuffer;
41 class GrTextureParams;
43 class GrVertexBufferAllocPool;
45 class GrSoftwarePathRenderer;
48 class SK_API GrContext : public SkRefCnt {
50 SK_DECLARE_INST_COUNT(GrContext)
53 * Creates a GrContext for a backend context.
55 static GrContext* Create(GrBackend, GrBackendContext);
60 * The GrContext normally assumes that no outsider is setting state
61 * within the underlying 3D API's context/device/whatever. This call informs
62 * the context that the state was modified and it should resend. Shouldn't
63 * be called frequently for good performance.
64 * The flag bits, state, is dpendent on which backend is used by the
65 * context, either GL or D3D (possible in future).
67 void resetContext(uint32_t state = kAll_GrBackendState);
70 * Callback function to allow classes to cleanup on GrContext destruction.
71 * The 'info' field is filled in with the 'info' passed to addCleanUp.
73 typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
76 * Add a function to be called from within GrContext's destructor.
77 * This gives classes a chance to free resources held on a per context basis.
78 * The 'info' parameter will be stored and passed to the callback function.
80 void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
81 CleanUpData* entry = fCleanUpData.push();
83 entry->fFunc = cleanUp;
88 * Abandons all GPU resources, assumes 3D API state is unknown. Call this
89 * if you have lost the associated GPU context, and thus internal texture,
90 * buffer, etc. references/IDs are now invalid. Should be called even when
91 * GrContext is no longer going to be used for two reasons:
92 * 1) ~GrContext will not try to free the objects in the 3D API.
93 * 2) If you've created GrGpuObjects that outlive the GrContext they will
94 * be marked as invalid (GrGpuObjects::isValid()) and won't attempt to
95 * free their underlying resource in the 3D API.
96 * Content drawn since the last GrContext::flush() may be lost.
101 * Similar to contextLost, but makes no attempt to reset state.
102 * Use this method when GrContext destruction is pending, but
103 * the graphics context is destroyed first.
105 void contextDestroyed();
107 ///////////////////////////////////////////////////////////////////////////
111 * Return the current GPU resource cache limits.
113 * @param maxResources If non-null, returns maximum number of resources that
114 * can be held in the cache.
115 * @param maxResourceBytes If non-null, returns maximum number of bytes of
116 * video memory that can be held in the cache.
118 void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
119 SK_ATTR_DEPRECATED("This function has been renamed to getResourceCacheLimits().")
120 void getTextureCacheLimits(int* maxTextures, size_t* maxTextureBytes) const {
121 this->getResourceCacheLimits(maxTextures, maxTextureBytes);
125 * Gets the current GPU resource cache usage.
127 * @param resourceCount If non-null, returns the number of resources that are held in the
129 * @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
132 void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
134 SK_ATTR_DEPRECATED("Use getResourceCacheUsage().")
135 size_t getGpuTextureCacheBytes() const {
137 this->getResourceCacheUsage(NULL, &bytes);
141 SK_ATTR_DEPRECATED("Use getResourceCacheUsage().")
142 int getGpuTextureCacheResourceCount() const {
144 this->getResourceCacheUsage(&count, NULL);
149 * Specify the GPU resource cache limits. If the current cache exceeds either
150 * of these, it will be purged (LRU) to keep the cache within these limits.
152 * @param maxResources The maximum number of resources that can be held in
154 * @param maxResourceBytes The maximum number of bytes of video memory
155 * that can be held in the cache.
157 void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
158 SK_ATTR_DEPRECATED("This function has been renamed to setResourceCacheLimits().")
159 void setTextureCacheLimits(int maxTextures, size_t maxTextureBytes) {
160 this->setResourceCacheLimits(maxTextures, maxTextureBytes);
164 * Frees GPU created by the context. Can be called to reduce GPU memory
167 void freeGpuResources();
170 * This method should be called whenever a GrResource is unreffed or
171 * switched from exclusive to non-exclusive. This
172 * gives the resource cache a chance to discard unneeded resources.
173 * Note: this entry point will be removed once totally ref-driven
174 * cache maintenance is implemented.
179 * Purge all the unlocked resources from the cache.
180 * This entry point is mainly meant for timing texture uploads
181 * and is not defined in normal builds of Skia.
183 void purgeAllUnlockedResources();
186 * Stores a custom resource in the cache, based on the specified key.
188 void addResourceToCache(const GrResourceKey&, GrCacheable*);
191 * Finds a resource in the cache, based on the specified key. This is intended for use in
192 * conjunction with addResourceToCache(). The return value will be NULL if not found. The
193 * caller must balance with a call to unref().
195 GrCacheable* findAndRefCachedResource(const GrResourceKey&);
197 ///////////////////////////////////////////////////////////////////////////
201 * Creates a new entry, based on the specified key and texture and returns it. The caller owns a
202 * ref on the returned texture which must be balanced by a call to unref.
204 * @param params The texture params used to draw a texture may help determine
205 * the cache entry used. (e.g. different versions may exist
206 * for different wrap modes on GPUs with limited NPOT
207 * texture support). NULL implies clamp wrap modes.
208 * @param desc Description of the texture properties.
209 * @param cacheID Cache-specific properties (e.g., texture gen ID)
210 * @param srcData Pointer to the pixel values.
211 * @param rowBytes The number of bytes between rows of the texture. Zero
212 * implies tightly packed rows. For compressed pixel configs, this
214 * @param cacheKey (optional) If non-NULL, we'll write the cache key we used to cacheKey.
216 GrTexture* createTexture(const GrTextureParams* params,
217 const GrTextureDesc& desc,
218 const GrCacheID& cacheID,
221 GrResourceKey* cacheKey = NULL);
223 * Search for an entry based on key and dimensions. If found, ref it and return it. The return
224 * value will be NULL if not found. The caller must balance with a call to unref.
226 * @param desc Description of the texture properties.
227 * @param cacheID Cache-specific properties (e.g., texture gen ID)
228 * @param params The texture params used to draw a texture may help determine
229 * the cache entry used. (e.g. different versions may exist
230 * for different wrap modes on GPUs with limited NPOT
231 * texture support). NULL implies clamp wrap modes.
233 GrTexture* findAndRefTexture(const GrTextureDesc& desc,
234 const GrCacheID& cacheID,
235 const GrTextureParams* params);
237 * Determines whether a texture is in the cache. If the texture is found it
238 * will not be locked or returned. This call does not affect the priority of
239 * the texture for deletion.
241 bool isTextureInCache(const GrTextureDesc& desc,
242 const GrCacheID& cacheID,
243 const GrTextureParams* params) const;
246 * Enum that determines how closely a returned scratch texture must match
247 * a provided GrTextureDesc.
249 enum ScratchTexMatch {
251 * Finds a texture that exactly matches the descriptor.
253 kExact_ScratchTexMatch,
255 * Finds a texture that approximately matches the descriptor. Will be
256 * at least as large in width and height as desc specifies. If desc
257 * specifies that texture is a render target then result will be a
258 * render target. If desc specifies a render target and doesn't set the
259 * no stencil flag then result will have a stencil. Format and aa level
262 kApprox_ScratchTexMatch
266 * Returns a texture matching the desc. It's contents are unknown. Subsequent
267 * requests with the same descriptor are not guaranteed to return the same
268 * texture. The same texture is guaranteed not be returned again until it is
269 * unlocked. Call must be balanced with an unlockTexture() call. The caller
270 * owns a ref on the returned texture and must balance with a call to unref.
272 * Textures created by createAndLockTexture() hide the complications of
273 * tiling non-power-of-two textures on APIs that don't support this (e.g.
274 * unextended GLES2). Tiling a NPOT texture created by lockScratchTexture on
275 * such an API will create gaps in the tiling pattern. This includes clamp
276 * mode. (This may be addressed in a future update.)
278 GrTexture* lockAndRefScratchTexture(const GrTextureDesc&, ScratchTexMatch match);
281 * When done with an entry, call unlockScratchTexture(entry) on it, which returns
282 * it to the cache, where it may be purged. This does not unref the texture.
284 void unlockScratchTexture(GrTexture* texture);
287 * Creates a texture that is outside the cache. Does not count against
290 GrTexture* createUncachedTexture(const GrTextureDesc& desc,
295 * Returns true if the specified use of an indexed texture is supported.
296 * Support may depend upon whether the texture params indicate that the
297 * texture will be tiled. Passing NULL for the texture params indicates
300 bool supportsIndex8PixelConfig(const GrTextureParams*,
305 * Return the max width or height of a texture supported by the current GPU.
307 int getMaxTextureSize() const;
310 * Temporarily override the true max texture size. Note: an override
311 * larger then the true max texture size will have no effect.
312 * This entry point is mainly meant for testing texture size dependent
313 * features and is only available if defined outside of Skia (see
316 void setMaxTextureSizeOverride(int maxTextureSizeOverride);
318 ///////////////////////////////////////////////////////////////////////////
322 * Sets the render target.
323 * @param target the render target to set.
325 void setRenderTarget(GrRenderTarget* target) {
326 fRenderTarget.reset(SkSafeRef(target));
330 * Gets the current render target.
331 * @return the currently bound render target.
333 const GrRenderTarget* getRenderTarget() const { return fRenderTarget.get(); }
334 GrRenderTarget* getRenderTarget() { return fRenderTarget.get(); }
337 * Can the provided configuration act as a color render target?
339 bool isConfigRenderable(GrPixelConfig config, bool withMSAA) const;
342 * Return the max width or height of a render target supported by the
345 int getMaxRenderTargetSize() const;
348 * Returns the max sample count for a render target. It will be 0 if MSAA
351 int getMaxSampleCount() const;
354 * Returns the recommended sample count for a render target when using this
357 * @param config the configuration of the render target.
358 * @param dpi the display density in dots per inch.
360 * @return sample count that should be perform well and have good enough
361 * rendering quality for the display. Alternatively returns 0 if
362 * MSAA is not supported or recommended to be used by default.
364 int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const;
366 ///////////////////////////////////////////////////////////////////////////
370 * Wraps an existing texture with a GrTexture object.
372 * OpenGL: if the object is a texture Gr may change its GL texture params
375 * @param desc description of the object to create.
377 * @return GrTexture object or NULL on failure.
379 GrTexture* wrapBackendTexture(const GrBackendTextureDesc& desc);
382 * Wraps an existing render target with a GrRenderTarget object. It is
383 * similar to wrapBackendTexture but can be used to draw into surfaces
384 * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
385 * the client will resolve to a texture).
387 * @param desc description of the object to create.
389 * @return GrTexture object or NULL on failure.
391 GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc);
393 ///////////////////////////////////////////////////////////////////////////
397 * Gets the current transformation matrix.
398 * @return the current matrix.
400 const SkMatrix& getMatrix() const { return fViewMatrix; }
403 * Sets the transformation matrix.
404 * @param m the matrix to set.
406 void setMatrix(const SkMatrix& m) { fViewMatrix = m; }
409 * Sets the current transformation matrix to identity.
411 void setIdentityMatrix() { fViewMatrix.reset(); }
414 * Concats the current matrix. The passed matrix is applied before the
416 * @param m the matrix to concat.
418 void concatMatrix(const SkMatrix& m) { fViewMatrix.preConcat(m); }
421 ///////////////////////////////////////////////////////////////////////////
424 * Gets the current clip.
425 * @return the current clip.
427 const GrClipData* getClip() const { return fClip; }
431 * @param clipData the clip to set.
433 void setClip(const GrClipData* clipData) { fClip = clipData; }
435 ///////////////////////////////////////////////////////////////////////////
439 * Clear the entire or rect of the render target, ignoring any clips.
440 * @param rect the rect to clear or the whole thing if rect is NULL.
441 * @param color the color to clear to.
442 * @param canIgnoreRect allows partial clears to be converted to whole
443 * clears on platforms for which that is cheap
444 * @param target if non-NULL, the render target to clear otherwise clear
445 * the current render target
447 void clear(const SkIRect* rect, GrColor color, bool canIgnoreRect,
448 GrRenderTarget* target = NULL);
451 * Draw everywhere (respecting the clip) with the paint.
453 void drawPaint(const GrPaint& paint);
456 * Draw the rect using a paint.
457 * @param paint describes how to color pixels.
458 * @param strokeInfo the stroke information (width, join, cap), and.
459 * the dash information (intervals, count, phase).
460 * If strokeInfo == NULL, then the rect is filled.
461 * Otherwise, if stroke width == 0, then the stroke
462 * is always a single pixel thick, else the rect is
463 * mitered/beveled stroked based on stroke width.
464 * If the stroke is dashed the rect is sent to drawPath.
465 * @param matrix Optional matrix applied to the rect. Applied before
466 * context's matrix or the paint's matrix.
467 * The rects coords are used to access the paint (through texture matrix)
469 void drawRect(const GrPaint& paint,
471 const GrStrokeInfo* strokeInfo = NULL,
472 const SkMatrix* matrix = NULL);
475 * Maps a rect of local coordinates onto the a rect of destination
476 * coordinates. Each rect can optionally be transformed. The localRect
477 * is stretched over the dstRect. The dstRect is transformed by the
478 * context's matrix. Additional optional matrices for both rects can be
479 * provided by parameters.
481 * @param paint describes how to color pixels.
482 * @param dstRect the destination rect to draw.
483 * @param localRect rect of local coordinates to be mapped onto dstRect
484 * @param dstMatrix Optional matrix to transform dstRect. Applied before context's matrix.
485 * @param localMatrix Optional matrix to transform localRect.
487 void drawRectToRect(const GrPaint& paint,
488 const SkRect& dstRect,
489 const SkRect& localRect,
490 const SkMatrix* dstMatrix = NULL,
491 const SkMatrix* localMatrix = NULL);
494 * Draw a roundrect using a paint.
496 * @param paint describes how to color pixels.
497 * @param rrect the roundrect to draw
498 * @param strokeInfo the stroke information (width, join, cap) and
499 * the dash information (intervals, count, phase).
501 void drawRRect(const GrPaint& paint, const SkRRect& rrect, const GrStrokeInfo& strokeInfo);
504 * Shortcut for drawing an SkPath consisting of nested rrects using a paint.
505 * Does not support stroking. The result is undefined if outer does not contain
508 * @param paint describes how to color pixels.
509 * @param outer the outer roundrect
510 * @param inner the inner roundrect
512 void drawDRRect(const GrPaint& paint, const SkRRect& outer, const SkRRect& inner);
518 * @param paint describes how to color pixels.
519 * @param path the path to draw
520 * @param strokeInfo the stroke information (width, join, cap) and
521 * the dash information (intervals, count, phase).
523 void drawPath(const GrPaint& paint, const SkPath& path, const GrStrokeInfo& strokeInfo);
526 * Draws vertices with a paint.
528 * @param paint describes how to color pixels.
529 * @param primitiveType primitives type to draw.
530 * @param vertexCount number of vertices.
531 * @param positions array of vertex positions, required.
532 * @param texCoords optional array of texture coordinates used
533 * to access the paint.
534 * @param colors optional array of per-vertex colors, supercedes
535 * the paint's color field.
536 * @param indices optional array of indices. If NULL vertices
537 * are drawn non-indexed.
538 * @param indexCount if indices is non-null then this is the
541 void drawVertices(const GrPaint& paint,
542 GrPrimitiveType primitiveType,
544 const SkPoint positions[],
545 const SkPoint texs[],
546 const GrColor colors[],
547 const uint16_t indices[],
553 * @param paint describes how to color pixels.
554 * @param oval the bounding rect of the oval.
555 * @param strokeInfo the stroke information (width, join, cap) and
556 * the dash information (intervals, count, phase).
558 void drawOval(const GrPaint& paint,
560 const GrStrokeInfo& strokeInfo);
562 ///////////////////////////////////////////////////////////////////////////
566 * Flags that affect flush() behavior.
570 * A client may reach a point where it has partially rendered a frame
571 * through a GrContext that it knows the user will never see. This flag
572 * causes the flush to skip submission of deferred content to the 3D API
575 kDiscard_FlushBit = 0x2,
579 * Call to ensure all drawing to the context has been issued to the
581 * @param flagsBitfield flags that control the flushing behavior. See
584 void flush(int flagsBitfield = 0);
587 * These flags can be used with the read/write pixels functions below.
590 /** The GrContext will not be flushed. This means that the read or write may occur before
591 previous draws have executed. */
592 kDontFlush_PixelOpsFlag = 0x1,
593 /** The src for write or dst read is unpremultiplied. This is only respected if both the
594 config src and dst configs are an RGBA/BGRA 8888 format. */
595 kUnpremul_PixelOpsFlag = 0x2,
599 * Reads a rectangle of pixels from a render target.
600 * @param target the render target to read from. NULL means the current render target.
601 * @param left left edge of the rectangle to read (inclusive)
602 * @param top top edge of the rectangle to read (inclusive)
603 * @param width width of rectangle to read in pixels.
604 * @param height height of rectangle to read in pixels.
605 * @param config the pixel config of the destination buffer
606 * @param buffer memory to read the rectangle into.
607 * @param rowBytes number of bytes bewtween consecutive rows. Zero means rows are tightly
609 * @param pixelOpsFlags see PixelOpsFlags enum above.
611 * @return true if the read succeeded, false if not. The read can fail because of an unsupported
612 * pixel config or because no render target is currently set and NULL was passed for
615 bool readRenderTargetPixels(GrRenderTarget* target,
616 int left, int top, int width, int height,
617 GrPixelConfig config, void* buffer,
619 uint32_t pixelOpsFlags = 0);
622 * Copy the src pixels [buffer, row bytes, pixel config] into a render target at the specified
624 * @param target the render target to write into. NULL means the current render target.
625 * @param left left edge of the rectangle to write (inclusive)
626 * @param top top edge of the rectangle to write (inclusive)
627 * @param width width of rectangle to write in pixels.
628 * @param height height of rectangle to write in pixels.
629 * @param config the pixel config of the source buffer
630 * @param buffer memory to read the rectangle from.
631 * @param rowBytes number of bytes between consecutive rows. Zero means rows are tightly
633 * @param pixelOpsFlags see PixelOpsFlags enum above.
635 * @return true if the write succeeded, false if not. The write can fail because of an
636 * unsupported combination of target and pixel configs.
638 bool writeRenderTargetPixels(GrRenderTarget* target,
639 int left, int top, int width, int height,
640 GrPixelConfig config, const void* buffer,
642 uint32_t pixelOpsFlags = 0);
645 * Reads a rectangle of pixels from a texture.
646 * @param texture the texture to read from.
647 * @param left left edge of the rectangle to read (inclusive)
648 * @param top top edge of the rectangle to read (inclusive)
649 * @param width width of rectangle to read in pixels.
650 * @param height height of rectangle to read in pixels.
651 * @param config the pixel config of the destination buffer
652 * @param buffer memory to read the rectangle into.
653 * @param rowBytes number of bytes between consecutive rows. Zero means rows are tightly
655 * @param pixelOpsFlags see PixelOpsFlags enum above.
657 * @return true if the read succeeded, false if not. The read can fail because of an unsupported
660 bool readTexturePixels(GrTexture* texture,
661 int left, int top, int width, int height,
662 GrPixelConfig config, void* buffer,
664 uint32_t pixelOpsFlags = 0);
667 * Writes a rectangle of pixels to a texture.
668 * @param texture the render target to read from.
669 * @param left left edge of the rectangle to write (inclusive)
670 * @param top top edge of the rectangle to write (inclusive)
671 * @param width width of rectangle to write in pixels.
672 * @param height height of rectangle to write in pixels.
673 * @param config the pixel config of the source buffer
674 * @param buffer memory to read pixels from
675 * @param rowBytes number of bytes between consecutive rows. Zero
676 * means rows are tightly packed.
677 * @param pixelOpsFlags see PixelOpsFlags enum above.
678 * @return true if the write succeeded, false if not. The write can fail because of an
679 * unsupported combination of texture and pixel configs.
681 bool writeTexturePixels(GrTexture* texture,
682 int left, int top, int width, int height,
683 GrPixelConfig config, const void* buffer,
685 uint32_t pixelOpsFlags = 0);
688 * Copies a rectangle of texels from src to dst. The size of dst is the size of the rectangle
689 * copied and topLeft is the position of the rect in src. The rectangle is clipped to src's
691 * @param src the texture to copy from.
692 * @param dst the render target to copy to.
693 * @param topLeft the point in src that will be copied to the top-left of dst. If NULL,
694 * (0, 0) will be used.
696 void copyTexture(GrTexture* src, GrRenderTarget* dst, const SkIPoint* topLeft = NULL);
699 * Resolves a render target that has MSAA. The intermediate MSAA buffer is
700 * down-sampled to the associated GrTexture (accessible via
701 * GrRenderTarget::asTexture()). Any pending draws to the render target will
702 * be executed before the resolve.
704 * This is only necessary when a client wants to access the object directly
705 * using the backend API directly. GrContext will detect when it must
706 * perform a resolve to a GrTexture used as the source of a draw or before
707 * reading pixels back from a GrTexture or GrRenderTarget.
709 void resolveRenderTarget(GrRenderTarget*);
712 * Provides a perfomance hint that the render target's contents are allowed
713 * to become undefined.
715 void discardRenderTarget(GrRenderTarget*);
718 void dumpFontCache() const;
721 ///////////////////////////////////////////////////////////////////////////
724 class AutoRenderTarget : public ::SkNoncopyable {
726 AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
727 fPrevTarget = context->getRenderTarget();
728 SkSafeRef(fPrevTarget);
729 context->setRenderTarget(target);
732 AutoRenderTarget(GrContext* context) {
733 fPrevTarget = context->getRenderTarget();
734 SkSafeRef(fPrevTarget);
737 ~AutoRenderTarget() {
738 if (NULL != fContext) {
739 fContext->setRenderTarget(fPrevTarget);
741 SkSafeUnref(fPrevTarget);
745 GrRenderTarget* fPrevTarget;
749 * Save/restore the view-matrix in the context. It can optionally adjust a paint to account
750 * for a coordinate system change. Here is an example of how the paint param can be used:
752 * A GrPaint is setup with GrEffects. The stages will have access to the pre-matrix source
753 * geometry positions when the draw is executed. Later on a decision is made to transform the
754 * geometry to device space on the CPU. The effects now need to know that the space in which
755 * the geometry will be specified has changed.
757 * Note that when restore is called (or in the destructor) the context's matrix will be
758 * restored. However, the paint will not be restored. The caller must make a copy of the
759 * paint if necessary. Hint: use SkTCopyOnFirstWrite if the AutoMatrix is conditionally
762 class AutoMatrix : public ::SkNoncopyable {
764 AutoMatrix() : fContext(NULL) {}
766 ~AutoMatrix() { this->restore(); }
769 * Initializes by pre-concat'ing the context's current matrix with the preConcat param.
771 void setPreConcat(GrContext* context, const SkMatrix& preConcat, GrPaint* paint = NULL) {
772 SkASSERT(NULL != context);
777 fMatrix = context->getMatrix();
778 this->preConcat(preConcat, paint);
782 * Sets the context's matrix to identity. Returns false if the inverse matrix is required to
783 * update a paint but the matrix cannot be inverted.
785 bool setIdentity(GrContext* context, GrPaint* paint = NULL) {
786 SkASSERT(NULL != context);
791 if (!paint->localCoordChangeInverse(context->getMatrix())) {
795 fMatrix = context->getMatrix();
797 context->setIdentityMatrix();
802 * Replaces the context's matrix with a new matrix. Returns false if the inverse matrix is
803 * required to update a paint but the matrix cannot be inverted.
805 bool set(GrContext* context, const SkMatrix& newMatrix, GrPaint* paint = NULL) {
807 if (!this->setIdentity(context, paint)) {
810 this->preConcat(newMatrix, paint);
814 fMatrix = context->getMatrix();
815 context->setMatrix(newMatrix);
821 * If this has been initialized then the context's matrix will be further updated by
822 * pre-concat'ing the preConcat param. The matrix that will be restored remains unchanged.
823 * The paint is assumed to be relative to the context's matrix at the time this call is
824 * made, not the matrix at the time AutoMatrix was first initialized. In other words, this
825 * performs an incremental update of the paint.
827 void preConcat(const SkMatrix& preConcat, GrPaint* paint = NULL) {
829 paint->localCoordChange(preConcat);
831 fContext->concatMatrix(preConcat);
835 * Returns false if never initialized or the inverse matrix was required to update a paint
836 * but the matrix could not be inverted.
838 bool succeeded() const { return NULL != fContext; }
841 * If this has been initialized then the context's original matrix is restored.
844 if (NULL != fContext) {
845 fContext->setMatrix(fMatrix);
855 class AutoClip : public ::SkNoncopyable {
857 // This enum exists to require a caller of the constructor to acknowledge that the clip will
858 // initially be wide open. It also could be extended if there are other desirable initial
861 kWideOpen_InitialClip,
864 AutoClip(GrContext* context, InitialClip initialState)
865 : fContext(context) {
866 SkASSERT(kWideOpen_InitialClip == initialState);
867 fNewClipData.fClipStack = &fNewClipStack;
869 fOldClip = context->getClip();
870 context->setClip(&fNewClipData);
873 AutoClip(GrContext* context, const SkRect& newClipRect)
875 , fNewClipStack(newClipRect) {
876 fNewClipData.fClipStack = &fNewClipStack;
878 fOldClip = fContext->getClip();
879 fContext->setClip(&fNewClipData);
883 if (NULL != fContext) {
884 fContext->setClip(fOldClip);
889 const GrClipData* fOldClip;
891 SkClipStack fNewClipStack;
892 GrClipData fNewClipData;
895 class AutoWideOpenIdentityDraw {
897 AutoWideOpenIdentityDraw(GrContext* ctx, GrRenderTarget* rt)
898 : fAutoClip(ctx, AutoClip::kWideOpen_InitialClip)
900 fAutoMatrix.setIdentity(ctx);
901 // should never fail with no paint param.
902 SkASSERT(fAutoMatrix.succeeded());
907 AutoRenderTarget fAutoRT;
908 AutoMatrix fAutoMatrix;
911 ///////////////////////////////////////////////////////////////////////////
912 // Functions intended for internal use only.
913 GrGpu* getGpu() { return fGpu; }
914 const GrGpu* getGpu() const { return fGpu; }
915 GrFontCache* getFontCache() { return fFontCache; }
916 GrLayerCache* getLayerCache() { return fLayerCache.get(); }
917 GrDrawTarget* getTextTarget();
918 const GrIndexBuffer* getQuadIndexBuffer() const;
919 GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
921 // Called by tests that draw directly to the context via GrDrawTarget
922 void getTestTarget(GrTestTarget*);
924 // Functions for managing gpu trace markers
925 bool isGpuTracingEnabled() const { return fGpuTracingEnabled; }
926 void enableGpuTracing() { fGpuTracingEnabled = true; }
927 void disableGpuTracing() { fGpuTracingEnabled = false; }
929 void addGpuTraceMarker(const GrGpuTraceMarker* marker);
930 void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
933 * Stencil buffers add themselves to the cache using addStencilBuffer. findStencilBuffer is
934 * called to check the cache for a SB that matches an RT's criteria.
936 void addStencilBuffer(GrStencilBuffer* sb);
937 GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt);
939 GrPathRenderer* getPathRenderer(
941 const SkStrokeRec& stroke,
942 const GrDrawTarget* target,
944 GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
945 GrPathRendererChain::StencilSupport* stencilSupport = NULL);
948 void printCacheStats() const;
952 // Used to indicate whether a draw should be performed immediately or queued in fDrawBuffer.
957 BufferedDraw fLastDrawWasBuffered;
960 SkMatrix fViewMatrix;
961 SkAutoTUnref<GrRenderTarget> fRenderTarget;
962 const GrClipData* fClip; // TODO: make this ref counted
963 GrDrawState* fDrawState;
965 GrResourceCache* fResourceCache;
966 GrFontCache* fFontCache;
967 SkAutoTDelete<GrLayerCache> fLayerCache;
969 GrPathRendererChain* fPathRendererChain;
970 GrSoftwarePathRenderer* fSoftwarePathRenderer;
972 GrVertexBufferAllocPool* fDrawBufferVBAllocPool;
973 GrIndexBufferAllocPool* fDrawBufferIBAllocPool;
974 GrInOrderDrawBuffer* fDrawBuffer;
976 // Set by OverbudgetCB() to request that GrContext flush before exiting a draw.
977 bool fFlushToReduceCacheSize;
979 GrAARectRenderer* fAARectRenderer;
980 GrOvalRenderer* fOvalRenderer;
982 bool fDidTestPMConversions;
983 int fPMToUPMConversion;
984 int fUPMToPMConversion;
991 SkTDArray<CleanUpData> fCleanUpData;
993 int fMaxTextureSizeOverride;
995 bool fGpuTracingEnabled;
997 GrContext(); // init must be called after the constructor.
998 bool init(GrBackend, GrBackendContext);
1000 void setupDrawBuffer();
1002 class AutoRestoreEffects;
1003 class AutoCheckFlush;
1004 /// Sets the paint and returns the target to draw into. The paint can be NULL in which case the
1005 /// draw state is left unmodified.
1006 GrDrawTarget* prepareToDraw(const GrPaint*, BufferedDraw, AutoRestoreEffects*, AutoCheckFlush*);
1008 void internalDrawPath(GrDrawTarget* target, bool useAA, const SkPath& path,
1009 const GrStrokeInfo& stroke);
1011 GrTexture* createResizedTexture(const GrTextureDesc& desc,
1012 const GrCacheID& cacheID,
1013 const void* srcData,
1017 // Needed so GrTexture's returnToCache helper function can call
1018 // addExistingTextureToCache
1019 friend class GrTexture;
1020 friend class GrStencilAndCoverPathRenderer;
1022 // Add an existing texture to the texture cache. This is intended solely
1023 // for use with textures released from an GrAutoScratchTexture.
1024 void addExistingTextureToCache(GrTexture* texture);
1027 * These functions create premul <-> unpremul effects if it is possible to generate a pair
1028 * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
1031 const GrEffectRef* createPMToUPMEffect(GrTexture* texture,
1033 const SkMatrix& matrix);
1034 const GrEffectRef* createUPMToPMEffect(GrTexture* texture,
1036 const SkMatrix& matrix);
1039 * This callback allows the resource cache to callback into the GrContext
1040 * when the cache is still overbudget after a purge.
1042 static bool OverbudgetCB(void* data);
1044 /** Creates a new gpu path, based on the specified path and stroke and returns it.
1045 * The caller owns a ref on the returned path which must be balanced by a call to unref.
1047 * @param skPath the path geometry.
1048 * @param stroke the path stroke.
1049 * @return a new path or NULL if the operation is not supported by the backend.
1051 GrPath* createPath(const SkPath& skPath, const SkStrokeRec& stroke);
1053 typedef SkRefCnt INHERITED;
1057 * Gets and locks a scratch texture from a descriptor using either exact or approximate criteria.
1058 * Unlocks texture in the destructor.
1060 class GrAutoScratchTexture : public ::SkNoncopyable {
1062 GrAutoScratchTexture()
1067 GrAutoScratchTexture(GrContext* context,
1068 const GrTextureDesc& desc,
1069 GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch)
1072 this->set(context, desc, match);
1075 ~GrAutoScratchTexture() {
1080 if (NULL != fContext && NULL != fTexture) {
1081 fContext->unlockScratchTexture(fTexture);
1088 * When detaching a texture we do not unlock it in the texture cache but
1089 * we do set the returnToCache flag. In this way the texture remains
1090 * "locked" in the texture cache until it is freed and recycled in
1091 * GrTexture::internal_dispose. In reality, the texture has been removed
1092 * from the cache (because this is in AutoScratchTexture) and by not
1093 * calling unlockScratchTexture we simply don't re-add it. It will be
1094 * reattached in GrTexture::internal_dispose.
1096 * Note that the caller is assumed to accept and manage the ref to the
1099 GrTexture* detach() {
1100 if (NULL == fTexture) {
1103 GrTexture* texture = fTexture;
1106 // This GrAutoScratchTexture has a ref from lockAndRefScratchTexture, which we give up now.
1107 // The cache also has a ref which we are lending to the caller of detach(). When the caller
1108 // lets go of the ref and the ref count goes to 0 internal_dispose will see this flag is
1109 // set and re-ref the texture, thereby restoring the cache's ref.
1110 SkASSERT(texture->getRefCnt() > 1);
1111 texture->impl()->setFlag((GrTextureFlags) GrTextureImpl::kReturnToCache_FlagBit);
1113 SkASSERT(NULL != texture->getCacheEntry());
1118 GrTexture* set(GrContext* context,
1119 const GrTextureDesc& desc,
1120 GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch) {
1124 if (NULL != fContext) {
1125 fTexture = fContext->lockAndRefScratchTexture(desc, match);
1126 if (NULL == fTexture) {
1135 GrTexture* texture() { return fTexture; }
1138 GrContext* fContext;
1139 GrTexture* fTexture;