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