GrContext.h revision b9e8230b50fc383869ee64208e23e5b6403568a1
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 "GrClipData.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 GrDrawState;
23class GrDrawTarget;
24class GrFontCache;
25class GrFragmentProcessor;
26class GrGpu;
27class GrGpuTraceMarker;
28class GrIndexBuffer;
29class GrIndexBufferAllocPool;
30class GrInOrderDrawBuffer;
31class GrLayerCache;
32class GrOvalRenderer;
33class GrPath;
34class GrPathRenderer;
35class GrResourceEntry;
36class GrResourceCache;
37class GrResourceCache2;
38class GrStencilBuffer;
39class GrTestTarget;
40class GrTextContext;
41class GrTextureParams;
42class GrVertexBuffer;
43class GrVertexBufferAllocPool;
44class GrStrokeInfo;
45class GrSoftwarePathRenderer;
46class SkStrokeRec;
47
48class SK_API GrContext : public SkRefCnt {
49public:
50    SK_DECLARE_INST_COUNT(GrContext)
51
52    struct Options {
53        Options() : fDrawPathToCompressedTexture(false) { }
54
55        // EXPERIMENTAL
56        // May be removed in the future, or may become standard depending
57        // on the outcomes of a variety of internal tests.
58        bool fDrawPathToCompressedTexture;
59    };
60
61    /**
62     * Creates a GrContext for a backend context.
63     */
64    static GrContext* Create(GrBackend, GrBackendContext, const Options* opts = NULL);
65
66    virtual ~GrContext();
67
68    /**
69     * The GrContext normally assumes that no outsider is setting state
70     * within the underlying 3D API's context/device/whatever. This call informs
71     * the context that the state was modified and it should resend. Shouldn't
72     * be called frequently for good performance.
73     * The flag bits, state, is dpendent on which backend is used by the
74     * context, either GL or D3D (possible in future).
75     */
76    void resetContext(uint32_t state = kAll_GrBackendState);
77
78    /**
79     * Callback function to allow classes to cleanup on GrContext destruction.
80     * The 'info' field is filled in with the 'info' passed to addCleanUp.
81     */
82    typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
83
84    /**
85     * Add a function to be called from within GrContext's destructor.
86     * This gives classes a chance to free resources held on a per context basis.
87     * The 'info' parameter will be stored and passed to the callback function.
88     */
89    void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
90        CleanUpData* entry = fCleanUpData.push();
91
92        entry->fFunc = cleanUp;
93        entry->fInfo = info;
94    }
95
96    /**
97     * Abandons all GPU resources and assumes the underlying backend 3D API
98     * context is not longer usable. Call this if you have lost the associated
99     * GPU context, and thus internal texture, buffer, etc. references/IDs are
100     * now invalid. Should be called even when GrContext is no longer going to
101     * be used for two reasons:
102     *  1) ~GrContext will not try to free the objects in the 3D API.
103     *  2) Any GrGpuResources created by this GrContext that outlive
104     *     will be marked as invalid (GrGpuResource::wasDestroyed()) and
105     *     when they're destroyed no 3D API calls will be made.
106     * Content drawn since the last GrContext::flush() may be lost. After this
107     * function is called the only valid action on the GrContext or
108     * GrGpuResources it created is to destroy them.
109     */
110    void abandonContext();
111    void contextDestroyed() { this->abandonContext(); }  //  legacy alias
112
113    ///////////////////////////////////////////////////////////////////////////
114    // Resource Cache
115
116    /**
117     *  Return the current GPU resource cache limits.
118     *
119     *  @param maxResources If non-null, returns maximum number of resources that
120     *                      can be held in the cache.
121     *  @param maxResourceBytes If non-null, returns maximum number of bytes of
122     *                          video memory that can be held in the cache.
123     */
124    void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
125
126    /**
127     *  Gets the current GPU resource cache usage.
128     *
129     *  @param resourceCount If non-null, returns the number of resources that are held in the
130     *                       cache.
131     *  @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
132     *                          in the cache.
133     */
134    void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
135
136    /**
137     *  Specify the GPU resource cache limits. If the current cache exceeds either
138     *  of these, it will be purged (LRU) to keep the cache within these limits.
139     *
140     *  @param maxResources The maximum number of resources that can be held in
141     *                      the cache.
142     *  @param maxResourceBytes The maximum number of bytes of video memory
143     *                          that can be held in the cache.
144     */
145    void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
146
147    /**
148     * Frees GPU created by the context. Can be called to reduce GPU memory
149     * pressure.
150     */
151    void freeGpuResources();
152
153    /**
154     * This method should be called whenever a GrResource is unreffed or
155     * switched from exclusive to non-exclusive. This
156     * gives the resource cache a chance to discard unneeded resources.
157     * Note: this entry point will be removed once totally ref-driven
158     * cache maintenance is implemented.
159     */
160    void purgeCache();
161
162    /**
163     * Purge all the unlocked resources from the cache.
164     * This entry point is mainly meant for timing texture uploads
165     * and is not defined in normal builds of Skia.
166     */
167    void purgeAllUnlockedResources();
168
169    /**
170     * Stores a custom resource in the cache, based on the specified key.
171     */
172    void addResourceToCache(const GrResourceKey&, GrGpuResource*);
173
174    /**
175     * Finds a resource in the cache, based on the specified key. This is intended for use in
176     * conjunction with addResourceToCache(). The return value will be NULL if not found. The
177     * caller must balance with a call to unref().
178     */
179    GrGpuResource* findAndRefCachedResource(const GrResourceKey&);
180
181    /**
182     * Creates a new text rendering context that is optimal for the
183     * render target and the context. Caller assumes the ownership
184     * of the returned object. The returned object must be deleted
185     * before the context is destroyed.
186     */
187    GrTextContext* createTextContext(GrRenderTarget*,
188                                     const SkDeviceProperties&,
189                                     bool enableDistanceFieldFonts);
190
191    ///////////////////////////////////////////////////////////////////////////
192    // Textures
193
194    /**
195     * Creates a new entry, based on the specified key and texture and returns it. The caller owns a
196     * ref on the returned texture which must be balanced by a call to unref.
197     *
198     * @param params    The texture params used to draw a texture may help determine
199     *                  the cache entry used. (e.g. different versions may exist
200     *                  for different wrap modes on GPUs with limited NPOT
201     *                  texture support). NULL implies clamp wrap modes.
202     * @param desc      Description of the texture properties.
203     * @param cacheID   Cache-specific properties (e.g., texture gen ID)
204     * @param srcData   Pointer to the pixel values.
205     * @param rowBytes  The number of bytes between rows of the texture. Zero
206     *                  implies tightly packed rows. For compressed pixel configs, this
207     *                  field is ignored.
208     * @param cacheKey  (optional) If non-NULL, we'll write the cache key we used to cacheKey.
209     */
210    GrTexture* createTexture(const GrTextureParams* params,
211                             const GrSurfaceDesc& desc,
212                             const GrCacheID& cacheID,
213                             const void* srcData,
214                             size_t rowBytes,
215                             GrResourceKey* cacheKey = NULL);
216    /**
217     * Search for an entry based on key and dimensions. If found, ref it and return it. The return
218     * value will be NULL if not found. The caller must balance with a call to unref.
219     *
220     *  @param desc     Description of the texture properties.
221     *  @param cacheID Cache-specific properties (e.g., texture gen ID)
222     *  @param params   The texture params used to draw a texture may help determine
223     *                  the cache entry used. (e.g. different versions may exist
224     *                  for different wrap modes on GPUs with limited NPOT
225     *                  texture support). NULL implies clamp wrap modes.
226     */
227    GrTexture* findAndRefTexture(const GrSurfaceDesc& desc,
228                                 const GrCacheID& cacheID,
229                                 const GrTextureParams* params);
230    /**
231     * Determines whether a texture is in the cache. If the texture is found it
232     * will not be locked or returned. This call does not affect the priority of
233     * the texture for deletion.
234     */
235    bool isTextureInCache(const GrSurfaceDesc& desc,
236                          const GrCacheID& cacheID,
237                          const GrTextureParams* params) const;
238
239    /**
240     * Enum that determines how closely a returned scratch texture must match
241     * a provided GrSurfaceDesc.
242     */
243    enum ScratchTexMatch {
244        /**
245         * Finds a texture that exactly matches the descriptor.
246         */
247        kExact_ScratchTexMatch,
248        /**
249         * Finds a texture that approximately matches the descriptor. Will be
250         * at least as large in width and height as desc specifies. If desc
251         * specifies that texture is a render target then result will be a
252         * render target. If desc specifies a render target and doesn't set the
253         * no stencil flag then result will have a stencil. Format and aa level
254         * will always match.
255         */
256        kApprox_ScratchTexMatch
257    };
258
259    /**
260     * Returns a texture matching the desc. It's contents are unknown. The caller
261     * owns a ref on the returned texture and must balance with a call to unref.
262     * It is guaranteed that the same texture will not be returned in subsequent
263     * calls until all refs to the texture are dropped.
264     *
265     * Textures created by createTexture() hide the complications of
266     * tiling non-power-of-two textures on APIs that don't support this (e.g.
267     * unextended GLES2). NPOT scratch textures are not tilable on such APIs.
268     *
269     * internalFlag is a temporary workaround until changes in the internal
270     * architecture are complete. Use the default value.
271     */
272    GrTexture* refScratchTexture(const GrSurfaceDesc&, ScratchTexMatch match,
273                                 bool internalFlag = false);
274
275    /**
276     * Creates a texture that is outside the cache. Does not count against
277     * cache's budget.
278     *
279     * Textures created by createTexture() hide the complications of
280     * tiling non-power-of-two textures on APIs that don't support this (e.g.
281     * unextended GLES2). NPOT uncached textures are not tilable on such APIs.
282     */
283    GrTexture* createUncachedTexture(const GrSurfaceDesc& desc,
284                                     void* srcData,
285                                     size_t rowBytes);
286
287    /**
288     * Returns true if the specified use of an indexed texture is supported.
289     * Support may depend upon whether the texture params indicate that the
290     * texture will be tiled. Passing NULL for the texture params indicates
291     * clamp mode.
292     */
293    bool supportsIndex8PixelConfig(const GrTextureParams*,
294                                   int width,
295                                   int height) const;
296
297    /**
298     *  Return the max width or height of a texture supported by the current GPU.
299     */
300    int getMaxTextureSize() const;
301
302    /**
303     *  Temporarily override the true max texture size. Note: an override
304     *  larger then the true max texture size will have no effect.
305     *  This entry point is mainly meant for testing texture size dependent
306     *  features and is only available if defined outside of Skia (see
307     *  bleed GM.
308     */
309    void setMaxTextureSizeOverride(int maxTextureSizeOverride);
310
311    ///////////////////////////////////////////////////////////////////////////
312    // Render targets
313
314    /**
315     * Sets the render target.
316     * @param target    the render target to set.
317     */
318    void setRenderTarget(GrRenderTarget* target) {
319        fRenderTarget.reset(SkSafeRef(target));
320    }
321
322    /**
323     * Gets the current render target.
324     * @return the currently bound render target.
325     */
326    const GrRenderTarget* getRenderTarget() const { return fRenderTarget.get(); }
327    GrRenderTarget* getRenderTarget() { return fRenderTarget.get(); }
328
329    /**
330     * Can the provided configuration act as a color render target?
331     */
332    bool isConfigRenderable(GrPixelConfig config, bool withMSAA) const;
333
334    /**
335     * Return the max width or height of a render target supported by the
336     * current GPU.
337     */
338    int getMaxRenderTargetSize() const;
339
340    /**
341     * Returns the max sample count for a render target. It will be 0 if MSAA
342     * is not supported.
343     */
344    int getMaxSampleCount() const;
345
346    /**
347     * Returns the recommended sample count for a render target when using this
348     * context.
349     *
350     * @param  config the configuration of the render target.
351     * @param  dpi the display density in dots per inch.
352     *
353     * @return sample count that should be perform well and have good enough
354     *         rendering quality for the display. Alternatively returns 0 if
355     *         MSAA is not supported or recommended to be used by default.
356     */
357    int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const;
358
359    ///////////////////////////////////////////////////////////////////////////
360    // Backend Surfaces
361
362    /**
363     * Wraps an existing texture with a GrTexture object.
364     *
365     * OpenGL: if the object is a texture Gr may change its GL texture params
366     *         when it is drawn.
367     *
368     * @param  desc     description of the object to create.
369     *
370     * @return GrTexture object or NULL on failure.
371     */
372    GrTexture* wrapBackendTexture(const GrBackendTextureDesc& desc);
373
374    /**
375     * Wraps an existing render target with a GrRenderTarget object. It is
376     * similar to wrapBackendTexture but can be used to draw into surfaces
377     * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
378     * the client will resolve to a texture).
379     *
380     * @param  desc     description of the object to create.
381     *
382     * @return GrTexture object or NULL on failure.
383     */
384     GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc);
385
386    ///////////////////////////////////////////////////////////////////////////
387    // Matrix state
388
389    /**
390     * Gets the current transformation matrix.
391     * @return the current matrix.
392     */
393    const SkMatrix& getMatrix() const { return fViewMatrix; }
394
395    /**
396     * Sets the transformation matrix.
397     * @param m the matrix to set.
398     */
399    void setMatrix(const SkMatrix& m) { fViewMatrix = m; }
400
401    /**
402     * Sets the current transformation matrix to identity.
403     */
404    void setIdentityMatrix() { fViewMatrix.reset(); }
405
406    /**
407     * Concats the current matrix. The passed matrix is applied before the
408     * current matrix.
409     * @param m the matrix to concat.
410     */
411    void concatMatrix(const SkMatrix& m) { fViewMatrix.preConcat(m); }
412
413
414    ///////////////////////////////////////////////////////////////////////////
415    // Clip state
416    /**
417     * Gets the current clip.
418     * @return the current clip.
419     */
420    const GrClipData* getClip() const { return fClip; }
421
422    /**
423     * Sets the clip.
424     * @param clipData  the clip to set.
425     */
426    void setClip(const GrClipData* clipData) { fClip = clipData; }
427
428    ///////////////////////////////////////////////////////////////////////////
429    // Draws
430
431    /**
432     * Clear the entire or rect of the render target, ignoring any clips.
433     * @param rect  the rect to clear or the whole thing if rect is NULL.
434     * @param color the color to clear to.
435     * @param canIgnoreRect allows partial clears to be converted to whole
436     *                      clears on platforms for which that is cheap
437     * @param target if non-NULL, the render target to clear otherwise clear
438     *               the current render target
439     */
440    void clear(const SkIRect* rect, GrColor color, bool canIgnoreRect,
441               GrRenderTarget* target = NULL);
442
443    /**
444     *  Draw everywhere (respecting the clip) with the paint.
445     */
446    void drawPaint(const GrPaint& paint);
447
448    /**
449     *  Draw the rect using a paint.
450     *  @param paint        describes how to color pixels.
451     *  @param strokeInfo   the stroke information (width, join, cap), and.
452     *                      the dash information (intervals, count, phase).
453     *                      If strokeInfo == NULL, then the rect is filled.
454     *                      Otherwise, if stroke width == 0, then the stroke
455     *                      is always a single pixel thick, else the rect is
456     *                      mitered/beveled stroked based on stroke width.
457     *  The rects coords are used to access the paint (through texture matrix)
458     */
459    void drawRect(const GrPaint& paint,
460                  const SkRect&,
461                  const GrStrokeInfo* strokeInfo = NULL);
462
463    /**
464     * Maps a rect of local coordinates onto the a rect of destination
465     * coordinates. The localRect is stretched over the dstRect. The dstRect is
466     * transformed by the context's matrix. An additional optional matrix can be
467     *  provided to transform the local rect.
468     *
469     * @param paint         describes how to color pixels.
470     * @param dstRect       the destination rect to draw.
471     * @param localRect     rect of local coordinates to be mapped onto dstRect
472     * @param localMatrix   Optional matrix to transform localRect.
473     */
474    void drawRectToRect(const GrPaint& paint,
475                        const SkRect& dstRect,
476                        const SkRect& localRect,
477                        const SkMatrix* localMatrix = NULL);
478
479    /**
480     *  Draw a roundrect using a paint.
481     *
482     *  @param paint        describes how to color pixels.
483     *  @param rrect        the roundrect to draw
484     *  @param strokeInfo   the stroke information (width, join, cap) and
485     *                      the dash information (intervals, count, phase).
486     */
487    void drawRRect(const GrPaint& paint, const SkRRect& rrect, const GrStrokeInfo& strokeInfo);
488
489    /**
490     *  Shortcut for drawing an SkPath consisting of nested rrects using a paint.
491     *  Does not support stroking. The result is undefined if outer does not contain
492     *  inner.
493     *
494     *  @param paint        describes how to color pixels.
495     *  @param outer        the outer roundrect
496     *  @param inner        the inner roundrect
497     */
498    void drawDRRect(const GrPaint& paint, const SkRRect& outer, const SkRRect& inner);
499
500
501    /**
502     * Draws a path.
503     *
504     * @param paint         describes how to color pixels.
505     * @param path          the path to draw
506     * @param strokeInfo    the stroke information (width, join, cap) and
507     *                      the dash information (intervals, count, phase).
508     */
509    void drawPath(const GrPaint& paint, const SkPath& path, const GrStrokeInfo& strokeInfo);
510
511    /**
512     * Draws vertices with a paint.
513     *
514     * @param   paint           describes how to color pixels.
515     * @param   primitiveType   primitives type to draw.
516     * @param   vertexCount     number of vertices.
517     * @param   positions       array of vertex positions, required.
518     * @param   texCoords       optional array of texture coordinates used
519     *                          to access the paint.
520     * @param   colors          optional array of per-vertex colors, supercedes
521     *                          the paint's color field.
522     * @param   indices         optional array of indices. If NULL vertices
523     *                          are drawn non-indexed.
524     * @param   indexCount      if indices is non-null then this is the
525     *                          number of indices.
526     */
527    void drawVertices(const GrPaint& paint,
528                      GrPrimitiveType primitiveType,
529                      int vertexCount,
530                      const SkPoint positions[],
531                      const SkPoint texs[],
532                      const GrColor colors[],
533                      const uint16_t indices[],
534                      int indexCount);
535
536    /**
537     * Draws an oval.
538     *
539     * @param paint         describes how to color pixels.
540     * @param oval          the bounding rect of the oval.
541     * @param strokeInfo    the stroke information (width, join, cap) and
542     *                      the dash information (intervals, count, phase).
543     */
544    void drawOval(const GrPaint& paint,
545                  const SkRect& oval,
546                  const GrStrokeInfo& strokeInfo);
547
548    ///////////////////////////////////////////////////////////////////////////
549    // Misc.
550
551    /**
552     * Flags that affect flush() behavior.
553     */
554    enum FlushBits {
555        /**
556         * A client may reach a point where it has partially rendered a frame
557         * through a GrContext that it knows the user will never see. This flag
558         * causes the flush to skip submission of deferred content to the 3D API
559         * during the flush.
560         */
561        kDiscard_FlushBit                    = 0x2,
562    };
563
564    /**
565     * Call to ensure all drawing to the context has been issued to the
566     * underlying 3D API.
567     * @param flagsBitfield     flags that control the flushing behavior. See
568     *                          FlushBits.
569     */
570    void flush(int flagsBitfield = 0);
571
572   /**
573    * These flags can be used with the read/write pixels functions below.
574    */
575    enum PixelOpsFlags {
576        /** The GrContext will not be flushed before the surface read or write. This means that
577            the read or write may occur before previous draws have executed. */
578        kDontFlush_PixelOpsFlag = 0x1,
579        /** Any surface writes should be flushed to the backend 3D API after the surface operation
580            is complete */
581        kFlushWrites_PixelOp = 0x2,
582        /** The src for write or dst read is unpremultiplied. This is only respected if both the
583            config src and dst configs are an RGBA/BGRA 8888 format. */
584        kUnpremul_PixelOpsFlag  = 0x4,
585    };
586
587    /**
588     * Reads a rectangle of pixels from a render target.
589     * @param target        the render target to read from. NULL means the current render target.
590     * @param left          left edge of the rectangle to read (inclusive)
591     * @param top           top edge of the rectangle to read (inclusive)
592     * @param width         width of rectangle to read in pixels.
593     * @param height        height of rectangle to read in pixels.
594     * @param config        the pixel config of the destination buffer
595     * @param buffer        memory to read the rectangle into.
596     * @param rowBytes      number of bytes bewtween consecutive rows. Zero means rows are tightly
597     *                      packed.
598     * @param pixelOpsFlags see PixelOpsFlags enum above.
599     *
600     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
601     *         pixel config or because no render target is currently set and NULL was passed for
602     *         target.
603     */
604    bool readRenderTargetPixels(GrRenderTarget* target,
605                                int left, int top, int width, int height,
606                                GrPixelConfig config, void* buffer,
607                                size_t rowBytes = 0,
608                                uint32_t pixelOpsFlags = 0);
609
610    /**
611     * Writes a rectangle of pixels to a surface.
612     * @param surface       the surface to write to.
613     * @param left          left edge of the rectangle to write (inclusive)
614     * @param top           top edge of the rectangle to write (inclusive)
615     * @param width         width of rectangle to write in pixels.
616     * @param height        height of rectangle to write in pixels.
617     * @param config        the pixel config of the source buffer
618     * @param buffer        memory to read pixels from
619     * @param rowBytes      number of bytes between consecutive rows. Zero
620     *                      means rows are tightly packed.
621     * @param pixelOpsFlags see PixelOpsFlags enum above.
622     * @return true if the write succeeded, false if not. The write can fail because of an
623     *         unsupported combination of surface and src configs.
624     */
625    bool writeSurfacePixels(GrSurface* surface,
626                            int left, int top, int width, int height,
627                            GrPixelConfig config, const void* buffer,
628                            size_t rowBytes,
629                            uint32_t pixelOpsFlags = 0);
630
631    /**
632     * Copies a rectangle of texels from src to dst.
633     * bounds.
634     * @param dst           the surface to copy to.
635     * @param src           the surface to copy from.
636     * @param srcRect       the rectangle of the src that should be copied.
637     * @param dstPoint      the translation applied when writing the srcRect's pixels to the dst.
638     * @param pixelOpsFlags see PixelOpsFlags enum above. (kUnpremul_PixelOpsFlag is not allowed).
639     */
640    void copySurface(GrSurface* dst,
641                     GrSurface* src,
642                     const SkIRect& srcRect,
643                     const SkIPoint& dstPoint,
644                     uint32_t pixelOpsFlags = 0);
645
646    /** Helper that copies the whole surface but fails when the two surfaces are not identically
647        sized. */
648    bool copySurface(GrSurface* dst, GrSurface* src) {
649        if (NULL == dst || NULL == src || dst->width() != src->width() ||
650            dst->height() != src->height()) {
651            return false;
652        }
653        this->copySurface(dst, src, SkIRect::MakeWH(dst->width(), dst->height()),
654                          SkIPoint::Make(0,0));
655        return true;
656    }
657
658    /**
659     * After this returns any pending writes to the surface will have been issued to the backend 3D API.
660     */
661    void flushSurfaceWrites(GrSurface* surface);
662
663    /**
664     * Resolves a render target that has MSAA. The intermediate MSAA buffer is
665     * down-sampled to the associated GrTexture (accessible via
666     * GrRenderTarget::asTexture()). Any pending draws to the render target will
667     * be executed before the resolve.
668     *
669     * This is only necessary when a client wants to access the object directly
670     * using the backend API directly. GrContext will detect when it must
671     * perform a resolve to a GrTexture used as the source of a draw or before
672     * reading pixels back from a GrTexture or GrRenderTarget.
673     */
674    void resolveRenderTarget(GrRenderTarget*);
675
676    /**
677     * Provides a perfomance hint that the render target's contents are allowed
678     * to become undefined.
679     */
680    void discardRenderTarget(GrRenderTarget*);
681
682#ifdef SK_DEVELOPER
683    void dumpFontCache() const;
684#endif
685
686    ///////////////////////////////////////////////////////////////////////////
687    // Helpers
688
689    class AutoRenderTarget : public ::SkNoncopyable {
690    public:
691        AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
692            fPrevTarget = context->getRenderTarget();
693            SkSafeRef(fPrevTarget);
694            context->setRenderTarget(target);
695            fContext = context;
696        }
697        AutoRenderTarget(GrContext* context) {
698            fPrevTarget = context->getRenderTarget();
699            SkSafeRef(fPrevTarget);
700            fContext = context;
701        }
702        ~AutoRenderTarget() {
703            if (fContext) {
704                fContext->setRenderTarget(fPrevTarget);
705            }
706            SkSafeUnref(fPrevTarget);
707        }
708    private:
709        GrContext*      fContext;
710        GrRenderTarget* fPrevTarget;
711    };
712
713    /**
714     * Save/restore the view-matrix in the context. It can optionally adjust a paint to account
715     * for a coordinate system change. Here is an example of how the paint param can be used:
716     *
717     * A GrPaint is setup with GrProcessors. The stages will have access to the pre-matrix source
718     * geometry positions when the draw is executed. Later on a decision is made to transform the
719     * geometry to device space on the CPU. The effects now need to know that the space in which
720     * the geometry will be specified has changed.
721     *
722     * Note that when restore is called (or in the destructor) the context's matrix will be
723     * restored. However, the paint will not be restored. The caller must make a copy of the
724     * paint if necessary. Hint: use SkTCopyOnFirstWrite if the AutoMatrix is conditionally
725     * initialized.
726     */
727    class AutoMatrix : public ::SkNoncopyable {
728    public:
729        AutoMatrix() : fContext(NULL) {}
730
731        ~AutoMatrix() { this->restore(); }
732
733        /**
734         * Initializes by pre-concat'ing the context's current matrix with the preConcat param.
735         */
736        void setPreConcat(GrContext* context, const SkMatrix& preConcat, GrPaint* paint = NULL) {
737            SkASSERT(context);
738
739            this->restore();
740
741            fContext = context;
742            fMatrix = context->getMatrix();
743            this->preConcat(preConcat, paint);
744        }
745
746        /**
747         * Sets the context's matrix to identity. Returns false if the inverse matrix is required to
748         * update a paint but the matrix cannot be inverted.
749         */
750        bool setIdentity(GrContext* context, GrPaint* paint = NULL) {
751            SkASSERT(context);
752
753            this->restore();
754
755            if (paint) {
756                if (!paint->localCoordChangeInverse(context->getMatrix())) {
757                    return false;
758                }
759            }
760            fMatrix = context->getMatrix();
761            fContext = context;
762            context->setIdentityMatrix();
763            return true;
764        }
765
766        /**
767         * Replaces the context's matrix with a new matrix. Returns false if the inverse matrix is
768         * required to update a paint but the matrix cannot be inverted.
769         */
770        bool set(GrContext* context, const SkMatrix& newMatrix, GrPaint* paint = NULL) {
771            if (paint) {
772                if (!this->setIdentity(context, paint)) {
773                    return false;
774                }
775                this->preConcat(newMatrix, paint);
776            } else {
777                this->restore();
778                fContext = context;
779                fMatrix = context->getMatrix();
780                context->setMatrix(newMatrix);
781            }
782            return true;
783        }
784
785        /**
786         * If this has been initialized then the context's matrix will be further updated by
787         * pre-concat'ing the preConcat param. The matrix that will be restored remains unchanged.
788         * The paint is assumed to be relative to the context's matrix at the time this call is
789         * made, not the matrix at the time AutoMatrix was first initialized. In other words, this
790         * performs an incremental update of the paint.
791         */
792        void preConcat(const SkMatrix& preConcat, GrPaint* paint = NULL) {
793            if (paint) {
794                paint->localCoordChange(preConcat);
795            }
796            fContext->concatMatrix(preConcat);
797        }
798
799        /**
800         * Returns false if never initialized or the inverse matrix was required to update a paint
801         * but the matrix could not be inverted.
802         */
803        bool succeeded() const { return SkToBool(fContext); }
804
805        /**
806         * If this has been initialized then the context's original matrix is restored.
807         */
808        void restore() {
809            if (fContext) {
810                fContext->setMatrix(fMatrix);
811                fContext = NULL;
812            }
813        }
814
815    private:
816        GrContext*  fContext;
817        SkMatrix    fMatrix;
818    };
819
820    class AutoClip : public ::SkNoncopyable {
821    public:
822        // This enum exists to require a caller of the constructor to acknowledge that the clip will
823        // initially be wide open. It also could be extended if there are other desirable initial
824        // clip states.
825        enum InitialClip {
826            kWideOpen_InitialClip,
827        };
828
829        AutoClip(GrContext* context, InitialClip initialState)
830        : fContext(context) {
831            SkASSERT(kWideOpen_InitialClip == initialState);
832            fNewClipData.fClipStack = &fNewClipStack;
833
834            fOldClip = context->getClip();
835            context->setClip(&fNewClipData);
836        }
837
838        AutoClip(GrContext* context, const SkRect& newClipRect)
839        : fContext(context)
840        , fNewClipStack(newClipRect) {
841            fNewClipData.fClipStack = &fNewClipStack;
842
843            fOldClip = fContext->getClip();
844            fContext->setClip(&fNewClipData);
845        }
846
847        ~AutoClip() {
848            if (fContext) {
849                fContext->setClip(fOldClip);
850            }
851        }
852    private:
853        GrContext*        fContext;
854        const GrClipData* fOldClip;
855
856        SkClipStack       fNewClipStack;
857        GrClipData        fNewClipData;
858    };
859
860    class AutoWideOpenIdentityDraw {
861    public:
862        AutoWideOpenIdentityDraw(GrContext* ctx, GrRenderTarget* rt)
863            : fAutoClip(ctx, AutoClip::kWideOpen_InitialClip)
864            , fAutoRT(ctx, rt) {
865            fAutoMatrix.setIdentity(ctx);
866            // should never fail with no paint param.
867            SkASSERT(fAutoMatrix.succeeded());
868        }
869
870    private:
871        AutoClip fAutoClip;
872        AutoRenderTarget fAutoRT;
873        AutoMatrix fAutoMatrix;
874    };
875
876    ///////////////////////////////////////////////////////////////////////////
877    // Functions intended for internal use only.
878    GrGpu* getGpu() { return fGpu; }
879    const GrGpu* getGpu() const { return fGpu; }
880    GrFontCache* getFontCache() { return fFontCache; }
881    GrLayerCache* getLayerCache() { return fLayerCache.get(); }
882    GrDrawTarget* getTextTarget();
883    const GrIndexBuffer* getQuadIndexBuffer() const;
884    GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
885    GrResourceCache* getResourceCache() { return fResourceCache; }
886    GrResourceCache2* getResourceCache2() { return fResourceCache2; }
887
888    // Called by tests that draw directly to the context via GrDrawTarget
889    void getTestTarget(GrTestTarget*);
890
891    void addGpuTraceMarker(const GrGpuTraceMarker* marker);
892    void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
893
894    /**
895     * Stencil buffers add themselves to the cache using addStencilBuffer. findStencilBuffer is
896     * called to check the cache for a SB that matches an RT's criteria.
897     */
898    void addStencilBuffer(GrStencilBuffer* sb);
899    GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt);
900
901    GrPathRenderer* getPathRenderer(
902                    const SkPath& path,
903                    const SkStrokeRec& stroke,
904                    const GrDrawTarget* target,
905                    bool allowSW,
906                    GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
907                    GrPathRendererChain::StencilSupport* stencilSupport = NULL);
908
909    /**
910     *  This returns a copy of the the GrContext::Options that was passed to the
911     *  constructor of this class.
912     */
913    const Options& getOptions() const { return fOptions; }
914
915#if GR_CACHE_STATS
916    void printCacheStats() const;
917#endif
918
919    class GPUStats {
920    public:
921#if GR_GPU_STATS
922        GPUStats() { this->reset(); }
923
924        void reset() { fRenderTargetBinds = 0; fShaderCompilations = 0; }
925
926        int renderTargetBinds() const { return fRenderTargetBinds; }
927        void incRenderTargetBinds() { fRenderTargetBinds++; }
928        int shaderCompilations() const { return fShaderCompilations; }
929        void incShaderCompilations() { fShaderCompilations++; }
930    private:
931        int fRenderTargetBinds;
932        int fShaderCompilations;
933#else
934        void incRenderTargetBinds() {}
935        void incShaderCompilations() {}
936#endif
937    };
938
939#if GR_GPU_STATS
940    const GPUStats* gpuStats() const;
941#endif
942
943private:
944    // Used to indicate whether a draw should be performed immediately or queued in fDrawBuffer.
945    enum BufferedDraw {
946        kYes_BufferedDraw,
947        kNo_BufferedDraw,
948    };
949    BufferedDraw fLastDrawWasBuffered;
950
951    GrGpu*                          fGpu;
952    SkMatrix                        fViewMatrix;
953    SkAutoTUnref<GrRenderTarget>    fRenderTarget;
954    const GrClipData*               fClip;  // TODO: make this ref counted
955    GrDrawState*                    fDrawState;
956
957    GrResourceCache*                fResourceCache;
958    GrResourceCache2*               fResourceCache2;
959    GrFontCache*                    fFontCache;
960    SkAutoTDelete<GrLayerCache>     fLayerCache;
961
962    GrPathRendererChain*            fPathRendererChain;
963    GrSoftwarePathRenderer*         fSoftwarePathRenderer;
964
965    GrVertexBufferAllocPool*        fDrawBufferVBAllocPool;
966    GrIndexBufferAllocPool*         fDrawBufferIBAllocPool;
967    GrInOrderDrawBuffer*            fDrawBuffer;
968
969    // Set by OverbudgetCB() to request that GrContext flush before exiting a draw.
970    bool                            fFlushToReduceCacheSize;
971
972    GrAARectRenderer*               fAARectRenderer;
973    GrOvalRenderer*                 fOvalRenderer;
974
975    bool                            fDidTestPMConversions;
976    int                             fPMToUPMConversion;
977    int                             fUPMToPMConversion;
978
979    struct CleanUpData {
980        PFCleanUpFunc fFunc;
981        void*         fInfo;
982    };
983
984    SkTDArray<CleanUpData>          fCleanUpData;
985
986    int                             fMaxTextureSizeOverride;
987
988    const Options                   fOptions;
989
990    GrContext(const Options&); // init must be called after the constructor.
991    bool init(GrBackend, GrBackendContext);
992
993    void setupDrawBuffer();
994
995    class AutoRestoreEffects;
996    class AutoCheckFlush;
997    /// Sets the paint and returns the target to draw into. The paint can be NULL in which case the
998    /// draw state is left unmodified.
999    GrDrawTarget* prepareToDraw(const GrPaint*, BufferedDraw, AutoRestoreEffects*, AutoCheckFlush*);
1000
1001    void internalDrawPath(GrDrawTarget* target, bool useAA, const SkPath& path,
1002                          const GrStrokeInfo& stroke);
1003
1004    GrTexture* createResizedTexture(const GrSurfaceDesc& desc,
1005                                    const GrCacheID& cacheID,
1006                                    const void* srcData,
1007                                    size_t rowBytes,
1008                                    bool filter);
1009
1010    GrTexture* createNewScratchTexture(const GrSurfaceDesc& desc);
1011
1012    /**
1013     * These functions create premul <-> unpremul effects if it is possible to generate a pair
1014     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
1015     * return NULL.
1016     */
1017    const GrFragmentProcessor* createPMToUPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
1018    const GrFragmentProcessor* createUPMToPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
1019
1020    /**
1021     *  This callback allows the resource cache to callback into the GrContext
1022     *  when the cache is still overbudget after a purge.
1023     */
1024    static bool OverbudgetCB(void* data);
1025
1026    typedef SkRefCnt INHERITED;
1027};
1028
1029#endif
1030