GrContext.h revision a73239a0096370221d3dfababf339dd6d3fed84f
1/*
2 * Copyright 2010 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 GrContext_DEFINED
9#define GrContext_DEFINED
10
11#include "GrClip.h"
12#include "GrColor.h"
13#include "GrPaint.h"
14#include "GrPathRendererChain.h"
15#include "GrRenderTarget.h"
16#include "GrTexture.h"
17#include "SkMatrix.h"
18#include "SkPathEffect.h"
19#include "SkTypes.h"
20
21class GrAARectRenderer;
22class GrBatchFontCache;
23class GrDrawTarget;
24class GrFragmentProcessor;
25class GrGpu;
26class GrGpuTraceMarker;
27class GrIndexBuffer;
28class GrIndexBufferAllocPool;
29class GrLayerCache;
30class GrOvalRenderer;
31class GrPath;
32class GrPathRenderer;
33class GrPipelineBuilder;
34class GrResourceEntry;
35class GrResourceCache;
36class GrTestTarget;
37class GrTextBlobCache;
38class GrTextContext;
39class GrTextureParams;
40class GrVertexBuffer;
41class GrVertexBufferAllocPool;
42class GrStrokeInfo;
43class GrSoftwarePathRenderer;
44class SkGpuDevice;
45
46class SK_API GrContext : public SkRefCnt {
47public:
48    SK_DECLARE_INST_COUNT(GrContext)
49
50    struct Options {
51        Options() : fDrawPathToCompressedTexture(false) { }
52
53        // EXPERIMENTAL
54        // May be removed in the future, or may become standard depending
55        // on the outcomes of a variety of internal tests.
56        bool fDrawPathToCompressedTexture;
57    };
58
59    /**
60     * Creates a GrContext for a backend context.
61     */
62    static GrContext* Create(GrBackend, GrBackendContext, const Options* opts = NULL);
63
64    /**
65     * Only defined in test apps.
66     */
67    static GrContext* CreateMockContext();
68
69    virtual ~GrContext();
70
71    /**
72     * The GrContext normally assumes that no outsider is setting state
73     * within the underlying 3D API's context/device/whatever. This call informs
74     * the context that the state was modified and it should resend. Shouldn't
75     * be called frequently for good performance.
76     * The flag bits, state, is dpendent on which backend is used by the
77     * context, either GL or D3D (possible in future).
78     */
79    void resetContext(uint32_t state = kAll_GrBackendState);
80
81    /**
82     * Callback function to allow classes to cleanup on GrContext destruction.
83     * The 'info' field is filled in with the 'info' passed to addCleanUp.
84     */
85    typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
86
87    /**
88     * Add a function to be called from within GrContext's destructor.
89     * This gives classes a chance to free resources held on a per context basis.
90     * The 'info' parameter will be stored and passed to the callback function.
91     */
92    void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
93        CleanUpData* entry = fCleanUpData.push();
94
95        entry->fFunc = cleanUp;
96        entry->fInfo = info;
97    }
98
99    /**
100     * Abandons all GPU resources and assumes the underlying backend 3D API
101     * context is not longer usable. Call this if you have lost the associated
102     * GPU context, and thus internal texture, buffer, etc. references/IDs are
103     * now invalid. Should be called even when GrContext is no longer going to
104     * be used for two reasons:
105     *  1) ~GrContext will not try to free the objects in the 3D API.
106     *  2) Any GrGpuResources created by this GrContext that outlive
107     *     will be marked as invalid (GrGpuResource::wasDestroyed()) and
108     *     when they're destroyed no 3D API calls will be made.
109     * Content drawn since the last GrContext::flush() may be lost. After this
110     * function is called the only valid action on the GrContext or
111     * GrGpuResources it created is to destroy them.
112     */
113    void abandonContext();
114    void contextDestroyed() { this->abandonContext(); }  //  legacy alias
115
116    ///////////////////////////////////////////////////////////////////////////
117    // Resource Cache
118
119    /**
120     *  Return the current GPU resource cache limits.
121     *
122     *  @param maxResources If non-null, returns maximum number of resources that
123     *                      can be held in the cache.
124     *  @param maxResourceBytes If non-null, returns maximum number of bytes of
125     *                          video memory that can be held in the cache.
126     */
127    void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
128
129    /**
130     *  Gets the current GPU resource cache usage.
131     *
132     *  @param resourceCount If non-null, returns the number of resources that are held in the
133     *                       cache.
134     *  @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
135     *                          in the cache.
136     */
137    void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
138
139    /**
140     *  Specify the GPU resource cache limits. If the current cache exceeds either
141     *  of these, it will be purged (LRU) to keep the cache within these limits.
142     *
143     *  @param maxResources The maximum number of resources that can be held in
144     *                      the cache.
145     *  @param maxResourceBytes The maximum number of bytes of video memory
146     *                          that can be held in the cache.
147     */
148    void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
149
150    /**
151     * Frees GPU created by the context. Can be called to reduce GPU memory
152     * pressure.
153     */
154    void freeGpuResources();
155
156    /**
157     * This method should be called whenever a GrResource is unreffed or
158     * switched from exclusive to non-exclusive. This
159     * gives the resource cache a chance to discard unneeded resources.
160     * Note: this entry point will be removed once totally ref-driven
161     * cache maintenance is implemented.
162     */
163    void purgeCache();
164
165    /**
166     * Purge all the unlocked resources from the cache.
167     * This entry point is mainly meant for timing texture uploads
168     * and is not defined in normal builds of Skia.
169     */
170    void purgeAllUnlockedResources();
171
172    /**
173     * Sets a unique key on the resource. Upon key collision this resource takes the place of the
174     * previous resource that had the key.
175     */
176    void addResourceToCache(const GrUniqueKey&, GrGpuResource*);
177
178    /**
179     * Finds a resource in the cache, based on the specified key. This is intended for use in
180     * conjunction with addResourceToCache(). The return value will be NULL if not found. The
181     * caller must balance with a call to unref().
182     */
183    GrGpuResource* findAndRefCachedResource(const GrUniqueKey&);
184
185    /** Helper for casting resource to a texture. Caller must be sure that the resource cached
186        with the key is either NULL or a texture and not another resource type. */
187    GrTexture* findAndRefCachedTexture(const GrUniqueKey& key) {
188        GrGpuResource* resource = this->findAndRefCachedResource(key);
189        if (resource) {
190            GrTexture* texture = static_cast<GrSurface*>(resource)->asTexture();
191            SkASSERT(texture);
192            return texture;
193        }
194        return NULL;
195    }
196
197    /**
198     * Determines whether a resource is in the cache. If the resource is found it
199     * will not be locked or returned. This call does not affect the priority of
200     * the resource for deletion.
201     */
202    bool isResourceInCache(const GrUniqueKey& key) const;
203
204    ///////////////////////////////////////////////////////////////////////////
205    // Textures
206
207    /**
208     * Creates a new texture in the resource cache and returns it. The caller owns a
209     * ref on the returned texture which must be balanced by a call to unref.
210     *
211     * @param desc      Description of the texture properties.
212     * @param budgeted  Does the texture count against the resource cache budget?
213     * @param srcData   Pointer to the pixel values (optional).
214     * @param rowBytes  The number of bytes between rows of the texture. Zero
215     *                  implies tightly packed rows. For compressed pixel configs, this
216     *                  field is ignored.
217     */
218    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted, const void* srcData,
219                             size_t rowBytes);
220
221    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted) {
222        return this->createTexture(desc, budgeted, NULL, 0);
223    }
224
225    /**
226     * DEPRECATED: use createTexture().
227     */
228    GrTexture* createUncachedTexture(const GrSurfaceDesc& desc, void* srcData, size_t rowBytes) {
229        return this->createTexture(desc, false, srcData, rowBytes);
230    }
231
232    /**
233     * Enum that determines how closely a returned scratch texture must match
234     * a provided GrSurfaceDesc. TODO: Remove this. createTexture() should be used
235     * for exact match and refScratchTexture() should be replaced with createApproxTexture().
236     */
237    enum ScratchTexMatch {
238        /**
239         * Finds a texture that exactly matches the descriptor.
240         */
241        kExact_ScratchTexMatch,
242        /**
243         * Finds a texture that approximately matches the descriptor. Will be
244         * at least as large in width and height as desc specifies. If desc
245         * specifies that texture is a render target then result will be a
246         * render target. If desc specifies a render target and doesn't set the
247         * no stencil flag then result will have a stencil. Format and aa level
248         * will always match.
249         */
250        kApprox_ScratchTexMatch
251    };
252
253    /**
254     * Returns a texture matching the desc. It's contents are unknown. The caller
255     * owns a ref on the returned texture and must balance with a call to unref.
256     * It is guaranteed that the same texture will not be returned in subsequent
257     * calls until all refs to the texture are dropped.
258     *
259     * Textures created by createTexture() hide the complications of
260     * tiling non-power-of-two textures on APIs that don't support this (e.g.
261     * unextended GLES2). NPOT scratch textures are not tilable on such APIs.
262     *
263     * internalFlag is a temporary workaround until changes in the internal
264     * architecture are complete. Use the default value.
265     *
266     * TODO: Once internal flag can be removed, this should be replaced with
267     * createApproxTexture() and exact textures should be created with
268     * createTexture().
269     */
270    GrTexture* refScratchTexture(const GrSurfaceDesc&, ScratchTexMatch match,
271                                 bool internalFlag = false);
272
273    /**
274     * Can the provided configuration act as a texture?
275     */
276    bool isConfigTexturable(GrPixelConfig) const;
277
278    /**
279     * Can non-power-of-two textures be used with tile modes other than clamp?
280     */
281    bool npotTextureTileSupport() const;
282
283    /**
284     *  Return the max width or height of a texture supported by the current GPU.
285     */
286    int getMaxTextureSize() const;
287
288    /**
289     *  Temporarily override the true max texture size. Note: an override
290     *  larger then the true max texture size will have no effect.
291     *  This entry point is mainly meant for testing texture size dependent
292     *  features and is only available if defined outside of Skia (see
293     *  bleed GM.
294     */
295    void setMaxTextureSizeOverride(int maxTextureSizeOverride);
296
297    /**
298     * Can the provided configuration act as a color render target?
299     */
300    bool isConfigRenderable(GrPixelConfig config, bool withMSAA) const;
301
302    /**
303     * Return the max width or height of a render target supported by the
304     * current GPU.
305     */
306    int getMaxRenderTargetSize() const;
307
308    /**
309     * Returns the max sample count for a render target. It will be 0 if MSAA
310     * is not supported.
311     */
312    int getMaxSampleCount() const;
313
314    /**
315     * Returns the recommended sample count for a render target when using this
316     * context.
317     *
318     * @param  config the configuration of the render target.
319     * @param  dpi the display density in dots per inch.
320     *
321     * @return sample count that should be perform well and have good enough
322     *         rendering quality for the display. Alternatively returns 0 if
323     *         MSAA is not supported or recommended to be used by default.
324     */
325    int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const;
326
327    ///////////////////////////////////////////////////////////////////////////
328    // Backend Surfaces
329
330    /**
331     * Wraps an existing texture with a GrTexture object.
332     *
333     * OpenGL: if the object is a texture Gr may change its GL texture params
334     *         when it is drawn.
335     *
336     * @param  desc     description of the object to create.
337     *
338     * @return GrTexture object or NULL on failure.
339     */
340    GrTexture* wrapBackendTexture(const GrBackendTextureDesc& desc);
341
342    /**
343     * Wraps an existing render target with a GrRenderTarget object. It is
344     * similar to wrapBackendTexture but can be used to draw into surfaces
345     * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
346     * the client will resolve to a texture).
347     *
348     * @param  desc     description of the object to create.
349     *
350     * @return GrTexture object or NULL on failure.
351     */
352     GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc);
353
354    ///////////////////////////////////////////////////////////////////////////
355    // Draws
356
357    /**
358     * Clear the entire or rect of the render target, ignoring any clips.
359     * @param rect  the rect to clear or the whole thing if rect is NULL.
360     * @param color the color to clear to.
361     * @param canIgnoreRect allows partial clears to be converted to whole
362     *                      clears on platforms for which that is cheap
363     * @param target The render target to clear.
364     */
365    void clear(const SkIRect* rect, GrColor color, bool canIgnoreRect, GrRenderTarget* target);
366
367    /**
368     *  Draw everywhere (respecting the clip) with the paint.
369     */
370    void drawPaint(GrRenderTarget*, const GrClip&, const GrPaint&, const SkMatrix& viewMatrix);
371
372    /**
373     *  Draw the rect using a paint.
374     *  @param paint        describes how to color pixels.
375     *  @param viewMatrix   transformation matrix
376     *  @param strokeInfo   the stroke information (width, join, cap), and.
377     *                      the dash information (intervals, count, phase).
378     *                      If strokeInfo == NULL, then the rect is filled.
379     *                      Otherwise, if stroke width == 0, then the stroke
380     *                      is always a single pixel thick, else the rect is
381     *                      mitered/beveled stroked based on stroke width.
382     *  The rects coords are used to access the paint (through texture matrix)
383     */
384    void drawRect(GrRenderTarget*,
385                  const GrClip&,
386                  const GrPaint& paint,
387                  const SkMatrix& viewMatrix,
388                  const SkRect&,
389                  const GrStrokeInfo* strokeInfo = NULL);
390
391    /**
392     * Maps a rectangle of shader coordinates to a rectangle and draws that rectangle
393     *
394     * @param paint         describes how to color pixels.
395     * @param viewMatrix    transformation matrix which applies to rectToDraw
396     * @param rectToDraw    the rectangle to draw
397     * @param localRect     the rectangle of shader coordinates applied to rectToDraw
398     * @param localMatrix   an optional matrix to transform the shader coordinates before applying
399     *                      to rectToDraw
400     */
401    void drawNonAARectToRect(GrRenderTarget*,
402                             const GrClip&,
403                             const GrPaint& paint,
404                             const SkMatrix& viewMatrix,
405                             const SkRect& rectToDraw,
406                             const SkRect& localRect,
407                             const SkMatrix* localMatrix = NULL);
408
409    /**
410     * Draws a non-AA rect with paint and a localMatrix
411     */
412    void drawNonAARectWithLocalMatrix(GrRenderTarget* rt,
413                                      const GrClip& clip,
414                                      const GrPaint& paint,
415                                      const SkMatrix& viewMatrix,
416                                      const SkRect& rect,
417                                      const SkMatrix& localMatrix) {
418        this->drawNonAARectToRect(rt, clip, paint, viewMatrix, rect, rect, &localMatrix);
419    }
420
421    /**
422     *  Draw a roundrect using a paint.
423     *
424     *  @param paint        describes how to color pixels.
425     *  @param viewMatrix   transformation matrix
426     *  @param rrect        the roundrect to draw
427     *  @param strokeInfo   the stroke information (width, join, cap) and
428     *                      the dash information (intervals, count, phase).
429     */
430    void drawRRect(GrRenderTarget*,
431                   const GrClip&,
432                   const GrPaint&,
433                   const SkMatrix& viewMatrix,
434                   const SkRRect& rrect,
435                   const GrStrokeInfo&);
436
437    /**
438     *  Shortcut for drawing an SkPath consisting of nested rrects using a paint.
439     *  Does not support stroking. The result is undefined if outer does not contain
440     *  inner.
441     *
442     *  @param paint        describes how to color pixels.
443     *  @param viewMatrix   transformation matrix
444     *  @param outer        the outer roundrect
445     *  @param inner        the inner roundrect
446     */
447    void drawDRRect(GrRenderTarget*,
448                    const GrClip&,
449                    const GrPaint&,
450                    const SkMatrix& viewMatrix,
451                    const SkRRect& outer,
452                    const SkRRect& inner);
453
454
455    /**
456     * Draws a path.
457     *
458     * @param paint         describes how to color pixels.
459     * @param viewMatrix    transformation matrix
460     * @param path          the path to draw
461     * @param strokeInfo    the stroke information (width, join, cap) and
462     *                      the dash information (intervals, count, phase).
463     */
464    void drawPath(GrRenderTarget*,
465                  const GrClip&,
466                  const GrPaint&,
467                  const SkMatrix& viewMatrix,
468                  const SkPath&,
469                  const GrStrokeInfo&);
470
471    /**
472     * Draws vertices with a paint.
473     *
474     * @param   paint           describes how to color pixels.
475     * @param   viewMatrix      transformation matrix
476     * @param   primitiveType   primitives type to draw.
477     * @param   vertexCount     number of vertices.
478     * @param   positions       array of vertex positions, required.
479     * @param   texCoords       optional array of texture coordinates used
480     *                          to access the paint.
481     * @param   colors          optional array of per-vertex colors, supercedes
482     *                          the paint's color field.
483     * @param   indices         optional array of indices. If NULL vertices
484     *                          are drawn non-indexed.
485     * @param   indexCount      if indices is non-null then this is the
486     *                          number of indices.
487     */
488    void drawVertices(GrRenderTarget*,
489                      const GrClip&,
490                      const GrPaint& paint,
491                      const SkMatrix& viewMatrix,
492                      GrPrimitiveType primitiveType,
493                      int vertexCount,
494                      const SkPoint positions[],
495                      const SkPoint texs[],
496                      const GrColor colors[],
497                      const uint16_t indices[],
498                      int indexCount);
499
500    /**
501     * Draws an oval.
502     *
503     * @param paint         describes how to color pixels.
504     * @param viewMatrix    transformation matrix
505     * @param oval          the bounding rect of the oval.
506     * @param strokeInfo    the stroke information (width, join, cap) and
507     *                      the dash information (intervals, count, phase).
508     */
509    void drawOval(GrRenderTarget*,
510                  const GrClip&,
511                  const GrPaint& paint,
512                  const SkMatrix& viewMatrix,
513                  const SkRect& oval,
514                  const GrStrokeInfo& strokeInfo);
515
516    ///////////////////////////////////////////////////////////////////////////
517    // Misc.
518
519    /**
520     * Flags that affect flush() behavior.
521     */
522    enum FlushBits {
523        /**
524         * A client may reach a point where it has partially rendered a frame
525         * through a GrContext that it knows the user will never see. This flag
526         * causes the flush to skip submission of deferred content to the 3D API
527         * during the flush.
528         */
529        kDiscard_FlushBit                    = 0x2,
530    };
531
532    /**
533     * Call to ensure all drawing to the context has been issued to the
534     * underlying 3D API.
535     * @param flagsBitfield     flags that control the flushing behavior. See
536     *                          FlushBits.
537     */
538    void flush(int flagsBitfield = 0);
539
540   /**
541    * These flags can be used with the read/write pixels functions below.
542    */
543    enum PixelOpsFlags {
544        /** The GrContext will not be flushed before the surface read or write. This means that
545            the read or write may occur before previous draws have executed. */
546        kDontFlush_PixelOpsFlag = 0x1,
547        /** Any surface writes should be flushed to the backend 3D API after the surface operation
548            is complete */
549        kFlushWrites_PixelOp = 0x2,
550        /** The src for write or dst read is unpremultiplied. This is only respected if both the
551            config src and dst configs are an RGBA/BGRA 8888 format. */
552        kUnpremul_PixelOpsFlag  = 0x4,
553    };
554
555    /**
556     * Reads a rectangle of pixels from a render target.
557     * @param target        the render target to read from.
558     * @param left          left edge of the rectangle to read (inclusive)
559     * @param top           top edge of the rectangle to read (inclusive)
560     * @param width         width of rectangle to read in pixels.
561     * @param height        height of rectangle to read in pixels.
562     * @param config        the pixel config of the destination buffer
563     * @param buffer        memory to read the rectangle into.
564     * @param rowBytes      number of bytes bewtween consecutive rows. Zero means rows are tightly
565     *                      packed.
566     * @param pixelOpsFlags see PixelOpsFlags enum above.
567     *
568     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
569     *         pixel config or because no render target is currently set and NULL was passed for
570     *         target.
571     */
572    bool readRenderTargetPixels(GrRenderTarget* target,
573                                int left, int top, int width, int height,
574                                GrPixelConfig config, void* buffer,
575                                size_t rowBytes = 0,
576                                uint32_t pixelOpsFlags = 0);
577
578    /**
579     * Writes a rectangle of pixels to a surface.
580     * @param surface       the surface to write to.
581     * @param left          left edge of the rectangle to write (inclusive)
582     * @param top           top edge of the rectangle to write (inclusive)
583     * @param width         width of rectangle to write in pixels.
584     * @param height        height of rectangle to write in pixels.
585     * @param config        the pixel config of the source buffer
586     * @param buffer        memory to read pixels from
587     * @param rowBytes      number of bytes between consecutive rows. Zero
588     *                      means rows are tightly packed.
589     * @param pixelOpsFlags see PixelOpsFlags enum above.
590     * @return true if the write succeeded, false if not. The write can fail because of an
591     *         unsupported combination of surface and src configs.
592     */
593    bool writeSurfacePixels(GrSurface* surface,
594                            int left, int top, int width, int height,
595                            GrPixelConfig config, const void* buffer,
596                            size_t rowBytes,
597                            uint32_t pixelOpsFlags = 0);
598
599    /**
600     * Copies a rectangle of texels from src to dst.
601     * bounds.
602     * @param dst           the surface to copy to.
603     * @param src           the surface to copy from.
604     * @param srcRect       the rectangle of the src that should be copied.
605     * @param dstPoint      the translation applied when writing the srcRect's pixels to the dst.
606     * @param pixelOpsFlags see PixelOpsFlags enum above. (kUnpremul_PixelOpsFlag is not allowed).
607     */
608    void copySurface(GrSurface* dst,
609                     GrSurface* src,
610                     const SkIRect& srcRect,
611                     const SkIPoint& dstPoint,
612                     uint32_t pixelOpsFlags = 0);
613
614    /** Helper that copies the whole surface but fails when the two surfaces are not identically
615        sized. */
616    bool copySurface(GrSurface* dst, GrSurface* src) {
617        if (NULL == dst || NULL == src || dst->width() != src->width() ||
618            dst->height() != src->height()) {
619            return false;
620        }
621        this->copySurface(dst, src, SkIRect::MakeWH(dst->width(), dst->height()),
622                          SkIPoint::Make(0,0));
623        return true;
624    }
625
626    /**
627     * After this returns any pending writes to the surface will have been issued to the backend 3D API.
628     */
629    void flushSurfaceWrites(GrSurface* surface);
630
631    /**
632     * Equivalent to flushSurfaceWrites but also performs MSAA resolve if necessary. This call is
633     * used to make the surface contents available to be read in the backend 3D API, usually for a
634     * compositing step external to Skia.
635     *
636     * It is not necessary to call this before reading the render target via Skia/GrContext.
637     * GrContext will detect when it must perform a resolve before reading pixels back from the
638     * surface or using it as a texture.
639     */
640    void prepareSurfaceForExternalRead(GrSurface*);
641
642    /**
643     * Provides a perfomance hint that the render target's contents are allowed
644     * to become undefined.
645     */
646    void discardRenderTarget(GrRenderTarget*);
647
648    ///////////////////////////////////////////////////////////////////////////
649    // Functions intended for internal use only.
650    GrGpu* getGpu() { return fGpu; }
651    const GrGpu* getGpu() const { return fGpu; }
652    GrBatchFontCache* getBatchFontCache() { return fBatchFontCache; }
653    GrLayerCache* getLayerCache() { return fLayerCache.get(); }
654    GrTextBlobCache* getTextBlobCache() { return fTextBlobCache; }
655    GrDrawTarget* getTextTarget();
656    const GrIndexBuffer* getQuadIndexBuffer() const;
657    GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
658    GrResourceCache* getResourceCache() { return fResourceCache; }
659
660    // Called by tests that draw directly to the context via GrDrawTarget
661    void getTestTarget(GrTestTarget*);
662
663    void addGpuTraceMarker(const GrGpuTraceMarker* marker);
664    void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
665
666    GrPathRenderer* getPathRenderer(
667                    const GrDrawTarget* target,
668                    const GrPipelineBuilder*,
669                    const SkMatrix& viewMatrix,
670                    const SkPath& path,
671                    const GrStrokeInfo& stroke,
672                    bool allowSW,
673                    GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
674                    GrPathRendererChain::StencilSupport* stencilSupport = NULL);
675
676    /**
677     *  This returns a copy of the the GrContext::Options that was passed to the
678     *  constructor of this class.
679     */
680    const Options& getOptions() const { return fOptions; }
681
682    /** Prints cache stats to the string if GR_CACHE_STATS == 1. */
683    void dumpCacheStats(SkString*) const;
684    void printCacheStats() const;
685
686    /** Prints GPU stats to the string if GR_GPU_STATS == 1. */
687    void dumpGpuStats(SkString*) const;
688    void printGpuStats() const;
689
690private:
691    GrGpu*                          fGpu;
692
693    GrResourceCache*                fResourceCache;
694    GrBatchFontCache*               fBatchFontCache;
695    SkAutoTDelete<GrLayerCache>     fLayerCache;
696    SkAutoTDelete<GrTextBlobCache>  fTextBlobCache;
697
698    GrPathRendererChain*            fPathRendererChain;
699    GrSoftwarePathRenderer*         fSoftwarePathRenderer;
700
701    GrVertexBufferAllocPool*        fDrawBufferVBAllocPool;
702    GrIndexBufferAllocPool*         fDrawBufferIBAllocPool;
703    GrDrawTarget*                   fDrawBuffer;
704
705    // Set by OverbudgetCB() to request that GrContext flush before exiting a draw.
706    bool                            fFlushToReduceCacheSize;
707    GrAARectRenderer*               fAARectRenderer;
708    GrOvalRenderer*                 fOvalRenderer;
709
710    bool                            fDidTestPMConversions;
711    int                             fPMToUPMConversion;
712    int                             fUPMToPMConversion;
713
714    struct CleanUpData {
715        PFCleanUpFunc fFunc;
716        void*         fInfo;
717    };
718
719    SkTDArray<CleanUpData>          fCleanUpData;
720
721    int                             fMaxTextureSizeOverride;
722
723    const Options                   fOptions;
724
725    GrContext(const Options&); // init must be called after the constructor.
726    bool init(GrBackend, GrBackendContext);
727    void initMockContext();
728    void initCommon();
729
730    void setupDrawBuffer();
731
732    class AutoCheckFlush;
733    // Sets the paint and returns the target to draw into.
734    GrDrawTarget* prepareToDraw(GrPipelineBuilder*,
735                                GrRenderTarget* rt,
736                                const GrClip&,
737                                const GrPaint* paint,
738                                const AutoCheckFlush*);
739
740    // A simpler version of the above which just returns the draw target.  Clip is *NOT* set
741    GrDrawTarget* prepareToDraw();
742
743    void internalDrawPath(GrDrawTarget*,
744                          GrPipelineBuilder*,
745                          const SkMatrix& viewMatrix,
746                          GrColor,
747                          bool useAA,
748                          const SkPath&,
749                          const GrStrokeInfo&);
750
751    GrTexture* internalRefScratchTexture(const GrSurfaceDesc&, uint32_t flags);
752
753    /**
754     * Creates a new text rendering context that is optimal for the
755     * render target and the context. Caller assumes the ownership
756     * of the returned object. The returned object must be deleted
757     * before the context is destroyed.
758     * TODO we can possibly bury this behind context, but we need to be able to use the
759     * drawText_asPaths logic on SkGpuDevice
760     */
761    GrTextContext* createTextContext(GrRenderTarget*,
762                                     SkGpuDevice*,
763                                     const SkDeviceProperties&,
764                                     bool enableDistanceFieldFonts);
765
766
767    /**
768     * These functions create premul <-> unpremul effects if it is possible to generate a pair
769     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
770     * return NULL.
771     */
772    const GrFragmentProcessor* createPMToUPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
773    const GrFragmentProcessor* createUPMToPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
774
775    /**
776     *  This callback allows the resource cache to callback into the GrContext
777     *  when the cache is still over budget after a purge.
778     */
779    static void OverBudgetCB(void* data);
780
781    /**
782     * A callback similar to the above for use by the TextBlobCache
783     * TODO move textblob draw calls below context so we can use the call above.
784     */
785    static void TextBlobCacheOverBudgetCB(void* data);
786
787    // TODO see note on createTextContext
788    friend class SkGpuDevice;
789
790    typedef SkRefCnt INHERITED;
791};
792
793#endif
794