GrContext.h revision cae27fed5e45e8899e56ece22b27e8958ffc0162
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     * Applies a 2D Gaussian blur to a given texture.
624     * @param srcTexture      The source texture to be blurred.
625     * @param canClobberSrc   If true, srcTexture may be overwritten, and
626     *                        may be returned as the result.
627     * @param rect            The destination rectangle.
628     * @param sigmaX          The blur's standard deviation in X.
629     * @param sigmaY          The blur's standard deviation in Y.
630     * @return the blurred texture, which may be srcTexture reffed, or a
631     * new texture.  It is the caller's responsibility to unref this texture.
632     */
633     GrTexture* gaussianBlur(GrTexture* srcTexture,
634                             bool canClobberSrc,
635                             const SkRect& rect,
636                             float sigmaX, float sigmaY);
637
638    ///////////////////////////////////////////////////////////////////////////
639    // Helpers
640
641    class AutoRenderTarget : public ::GrNoncopyable {
642    public:
643        AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
644            fPrevTarget = context->getRenderTarget();
645            GrSafeRef(fPrevTarget);
646            context->setRenderTarget(target);
647            fContext = context;
648        }
649        AutoRenderTarget(GrContext* context) {
650            fPrevTarget = context->getRenderTarget();
651            GrSafeRef(fPrevTarget);
652            fContext = context;
653        }
654        ~AutoRenderTarget() {
655            if (NULL != fContext) {
656                fContext->setRenderTarget(fPrevTarget);
657            }
658            GrSafeUnref(fPrevTarget);
659        }
660    private:
661        GrContext*      fContext;
662        GrRenderTarget* fPrevTarget;
663    };
664
665    /**
666     * Save/restore the view-matrix in the context. It can optionally adjust a paint to account
667     * for a coordinate system change. Here is an example of how the paint param can be used:
668     *
669     * A GrPaint is setup with GrEffects. The stages will have access to the pre-matrix source
670     * geometry positions when the draw is executed. Later on a decision is made to transform the
671     * geometry to device space on the CPU. The effects now need to know that the space in which
672     * the geometry will be specified has changed.
673     *
674     * Note that when restore is called (or in the destructor) the context's matrix will be
675     * restored. However, the paint will not be restored. The caller must make a copy of the
676     * paint if necessary. Hint: use SkTCopyOnFirstWrite if the AutoMatrix is conditionally
677     * initialized.
678     */
679    class AutoMatrix : GrNoncopyable {
680    public:
681        AutoMatrix() : fContext(NULL) {}
682
683        ~AutoMatrix() { this->restore(); }
684
685        /**
686         * Initializes by pre-concat'ing the context's current matrix with the preConcat param.
687         */
688        void setPreConcat(GrContext* context, const SkMatrix& preConcat, GrPaint* paint = NULL) {
689            GrAssert(NULL != context);
690
691            this->restore();
692
693            fContext = context;
694            fMatrix = context->getMatrix();
695            this->preConcat(preConcat, paint);
696        }
697
698        /**
699         * Sets the context's matrix to identity. Returns false if the inverse matrix is required to
700         * update a paint but the matrix cannot be inverted.
701         */
702        bool setIdentity(GrContext* context, GrPaint* paint = NULL) {
703            GrAssert(NULL != context);
704
705            this->restore();
706
707            if (NULL != paint) {
708                if (!paint->localCoordChangeInverse(context->getMatrix())) {
709                    return false;
710                }
711            }
712            fMatrix = context->getMatrix();
713            fContext = context;
714            context->setIdentityMatrix();
715            return true;
716        }
717
718        /**
719         * Replaces the context's matrix with a new matrix. Returns false if the inverse matrix is
720         * required to update a paint but the matrix cannot be inverted.
721         */
722        bool set(GrContext* context, const SkMatrix& newMatrix, GrPaint* paint = NULL) {
723            if (NULL != paint) {
724                if (!this->setIdentity(context, paint)) {
725                    return false;
726                }
727                this->preConcat(newMatrix, paint);
728            } else {
729                this->restore();
730                fContext = context;
731                fMatrix = context->getMatrix();
732                context->setMatrix(newMatrix);
733            }
734            return true;
735        }
736
737        /**
738         * If this has been initialized then the context's matrix will be further updated by
739         * pre-concat'ing the preConcat param. The matrix that will be restored remains unchanged.
740         * The paint is assumed to be relative to the context's matrix at the time this call is
741         * made, not the matrix at the time AutoMatrix was first initialized. In other words, this
742         * performs an incremental update of the paint.
743         */
744        void preConcat(const SkMatrix& preConcat, GrPaint* paint = NULL) {
745            if (NULL != paint) {
746                paint->localCoordChange(preConcat);
747            }
748            fContext->concatMatrix(preConcat);
749        }
750
751        /**
752         * Returns false if never initialized or the inverse matrix was required to update a paint
753         * but the matrix could not be inverted.
754         */
755        bool succeeded() const { return NULL != fContext; }
756
757        /**
758         * If this has been initialized then the context's original matrix is restored.
759         */
760        void restore() {
761            if (NULL != fContext) {
762                fContext->setMatrix(fMatrix);
763                fContext = NULL;
764            }
765        }
766
767    private:
768        GrContext*  fContext;
769        SkMatrix    fMatrix;
770    };
771
772    class AutoClip : GrNoncopyable {
773    public:
774        // This enum exists to require a caller of the constructor to acknowledge that the clip will
775        // initially be wide open. It also could be extended if there are other desirable initial
776        // clip states.
777        enum InitialClip {
778            kWideOpen_InitialClip,
779        };
780
781        AutoClip(GrContext* context, InitialClip initialState)
782        : fContext(context) {
783            GrAssert(kWideOpen_InitialClip == initialState);
784            fNewClipData.fClipStack = &fNewClipStack;
785
786            fOldClip = context->getClip();
787            context->setClip(&fNewClipData);
788        }
789
790        AutoClip(GrContext* context, const GrRect& newClipRect)
791        : fContext(context)
792        , fNewClipStack(newClipRect) {
793            fNewClipData.fClipStack = &fNewClipStack;
794
795            fOldClip = fContext->getClip();
796            fContext->setClip(&fNewClipData);
797        }
798
799        ~AutoClip() {
800            if (NULL != fContext) {
801                fContext->setClip(fOldClip);
802            }
803        }
804    private:
805        GrContext*        fContext;
806        const GrClipData* fOldClip;
807
808        SkClipStack       fNewClipStack;
809        GrClipData        fNewClipData;
810    };
811
812    class AutoWideOpenIdentityDraw {
813    public:
814        AutoWideOpenIdentityDraw(GrContext* ctx, GrRenderTarget* rt)
815            : fAutoClip(ctx, AutoClip::kWideOpen_InitialClip)
816            , fAutoRT(ctx, rt) {
817            fAutoMatrix.setIdentity(ctx);
818            // should never fail with no paint param.
819            GrAssert(fAutoMatrix.succeeded());
820        }
821
822    private:
823        AutoClip fAutoClip;
824        AutoRenderTarget fAutoRT;
825        AutoMatrix fAutoMatrix;
826    };
827
828    ///////////////////////////////////////////////////////////////////////////
829    // Functions intended for internal use only.
830    GrGpu* getGpu() { return fGpu; }
831    const GrGpu* getGpu() const { return fGpu; }
832    GrFontCache* getFontCache() { return fFontCache; }
833    GrDrawTarget* getTextTarget();
834    const GrIndexBuffer* getQuadIndexBuffer() const;
835
836    /**
837     * Stencil buffers add themselves to the cache using addStencilBuffer. findStencilBuffer is
838     * called to check the cache for a SB that matches an RT's criteria.
839     */
840    void addStencilBuffer(GrStencilBuffer* sb);
841    GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt);
842
843    GrPathRenderer* getPathRenderer(
844                    const SkPath& path,
845                    const SkStrokeRec& stroke,
846                    const GrDrawTarget* target,
847                    bool allowSW,
848                    GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
849                    GrPathRendererChain::StencilSupport* stencilSupport = NULL);
850
851#if GR_CACHE_STATS
852    void printCacheStats() const;
853#endif
854
855private:
856    // Used to indicate whether a draw should be performed immediately or queued in fDrawBuffer.
857    enum BufferedDraw {
858        kYes_BufferedDraw,
859        kNo_BufferedDraw,
860    };
861    BufferedDraw fLastDrawWasBuffered;
862
863    GrGpu*                          fGpu;
864    SkMatrix                        fViewMatrix;
865    SkAutoTUnref<GrRenderTarget>    fRenderTarget;
866    const GrClipData*               fClip;  // TODO: make this ref counted
867    GrDrawState*                    fDrawState;
868
869    GrResourceCache*                fTextureCache;
870    GrFontCache*                    fFontCache;
871
872    GrPathRendererChain*            fPathRendererChain;
873    GrSoftwarePathRenderer*         fSoftwarePathRenderer;
874
875    GrVertexBufferAllocPool*        fDrawBufferVBAllocPool;
876    GrIndexBufferAllocPool*         fDrawBufferIBAllocPool;
877    GrInOrderDrawBuffer*            fDrawBuffer;
878
879    GrAARectRenderer*               fAARectRenderer;
880    GrOvalRenderer*                 fOvalRenderer;
881
882    bool                            fDidTestPMConversions;
883    int                             fPMToUPMConversion;
884    int                             fUPMToPMConversion;
885
886    struct CleanUpData {
887        PFCleanUpFunc fFunc;
888        void*         fInfo;
889    };
890
891    SkTDArray<CleanUpData>      fCleanUpData;
892
893    GrContext(); // init must be called after the constructor.
894    bool init(GrBackend, GrBackendContext);
895
896    void setupDrawBuffer();
897
898    class AutoRestoreEffects;
899    /// Sets the paint and returns the target to draw into. The paint can be NULL in which case the
900    /// draw state is left unmodified.
901    GrDrawTarget* prepareToDraw(const GrPaint*, BufferedDraw, AutoRestoreEffects*);
902
903    void internalDrawPath(GrDrawTarget* target, bool useAA, const SkPath& path,
904                          const SkStrokeRec& stroke);
905
906    GrTexture* createResizedTexture(const GrTextureDesc& desc,
907                                    const GrCacheID& cacheID,
908                                    void* srcData,
909                                    size_t rowBytes,
910                                    bool needsFiltering);
911
912    // Needed so GrTexture's returnToCache helper function can call
913    // addExistingTextureToCache
914    friend class GrTexture;
915
916    // Add an existing texture to the texture cache. This is intended solely
917    // for use with textures released from an GrAutoScratchTexture.
918    void addExistingTextureToCache(GrTexture* texture);
919
920    /**
921     * These functions create premul <-> unpremul effects if it is possible to generate a pair
922     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
923     * return NULL.
924     */
925    const GrEffectRef* createPMToUPMEffect(GrTexture* texture,
926                                           bool swapRAndB,
927                                           const SkMatrix& matrix);
928    const GrEffectRef* createUPMToPMEffect(GrTexture* texture,
929                                           bool swapRAndB,
930                                           const SkMatrix& matrix);
931
932    /**
933     *  This callback allows the resource cache to callback into the GrContext
934     *  when the cache is still overbudget after a purge.
935     */
936    static bool OverbudgetCB(void* data);
937
938    typedef GrRefCnt INHERITED;
939};
940
941/**
942 * Gets and locks a scratch texture from a descriptor using either exact or approximate criteria.
943 * Unlocks texture in the destructor.
944 */
945class GrAutoScratchTexture : ::GrNoncopyable {
946public:
947    GrAutoScratchTexture()
948        : fContext(NULL)
949        , fTexture(NULL) {
950    }
951
952    GrAutoScratchTexture(GrContext* context,
953                         const GrTextureDesc& desc,
954                         GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch)
955      : fContext(NULL)
956      , fTexture(NULL) {
957      this->set(context, desc, match);
958    }
959
960    ~GrAutoScratchTexture() {
961        this->reset();
962    }
963
964    void reset() {
965        if (NULL != fContext && NULL != fTexture) {
966            fContext->unlockScratchTexture(fTexture);
967            fTexture->unref();
968            fTexture = NULL;
969        }
970    }
971
972    /*
973     * When detaching a texture we do not unlock it in the texture cache but
974     * we do set the returnToCache flag. In this way the texture remains
975     * "locked" in the texture cache until it is freed and recycled in
976     * GrTexture::internal_dispose. In reality, the texture has been removed
977     * from the cache (because this is in AutoScratchTexture) and by not
978     * calling unlockScratchTexture we simply don't re-add it. It will be
979     * reattached in GrTexture::internal_dispose.
980     *
981     * Note that the caller is assumed to accept and manage the ref to the
982     * returned texture.
983     */
984    GrTexture* detach() {
985        if (NULL == fTexture) {
986            return NULL;
987        }
988        GrTexture* texture = fTexture;
989        fTexture = NULL;
990
991        // This GrAutoScratchTexture has a ref from lockAndRefScratchTexture, which we give up now.
992        // The cache also has a ref which we are lending to the caller of detach(). When the caller
993        // lets go of the ref and the ref count goes to 0 internal_dispose will see this flag is
994        // set and re-ref the texture, thereby restoring the cache's ref.
995        GrAssert(texture->getRefCnt() > 1);
996        texture->setFlag((GrTextureFlags) GrTexture::kReturnToCache_FlagBit);
997        texture->unref();
998        GrAssert(NULL != texture->getCacheEntry());
999
1000        return texture;
1001    }
1002
1003    GrTexture* set(GrContext* context,
1004                   const GrTextureDesc& desc,
1005                   GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch) {
1006        this->reset();
1007
1008        fContext = context;
1009        if (NULL != fContext) {
1010            fTexture = fContext->lockAndRefScratchTexture(desc, match);
1011            if (NULL == fTexture) {
1012                fContext = NULL;
1013            }
1014            return fTexture;
1015        } else {
1016            return NULL;
1017        }
1018    }
1019
1020    GrTexture* texture() { return fTexture; }
1021
1022private:
1023    GrContext*                    fContext;
1024    GrTexture*                    fTexture;
1025};
1026
1027#endif
1028