GrContext.h revision c82a8b7aa4ec19fba508c394920a9e88d3e5bd12
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 "GrClip.h"
14#include "GrPaint.h"
15#include "GrAARectRenderer.h"
16// not strictly needed but requires WK change in LayerTextureUpdaterCanvas to
17// remove.
18#include "GrRenderTarget.h"
19
20class GrAutoScratchTexture;
21class GrDrawState;
22class GrDrawTarget;
23class GrFontCache;
24class GrGpu;
25class GrIndexBuffer;
26class GrIndexBufferAllocPool;
27class GrInOrderDrawBuffer;
28class GrPathRenderer;
29class GrPathRendererChain;
30class GrResourceEntry;
31class GrResourceCache;
32class GrStencilBuffer;
33class GrVertexBuffer;
34class GrVertexBufferAllocPool;
35class GrSoftwarePathRenderer;
36
37class GR_API GrContext : public GrRefCnt {
38public:
39    /**
40     * Creates a GrContext from within a 3D context.
41     */
42    static GrContext* Create(GrEngine engine,
43                             GrPlatform3DContext context3D);
44
45    /**
46     * Returns the number of GrContext instances for the current thread.
47     */
48    static int GetThreadInstanceCount();
49
50    virtual ~GrContext();
51
52    /**
53     * The GrContext normally assumes that no outsider is setting state
54     * within the underlying 3D API's context/device/whatever. This call informs
55     * the context that the state was modified and it should resend. Shouldn't
56     * be called frequently for good performance.
57     */
58    void resetContext();
59
60    /**
61     * Abandons all gpu resources, assumes 3D API state is unknown. Call this
62     * if you have lost the associated GPU context, and thus internal texture,
63     * buffer, etc. references/IDs are now invalid. Should be called even when
64     * GrContext is no longer going to be used for two reasons:
65     *  1) ~GrContext will not try to free the objects in the 3D API.
66     *  2) If you've created GrResources that outlive the GrContext they will
67     *     be marked as invalid (GrResource::isValid()) and won't attempt to
68     *     free their underlying resource in the 3D API.
69     * Content drawn since the last GrContext::flush() may be lost.
70     */
71    void contextLost();
72
73    /**
74     * Similar to contextLost, but makes no attempt to reset state.
75     * Use this method when GrContext destruction is pending, but
76     * the graphics context is destroyed first.
77     */
78    void contextDestroyed();
79
80    /**
81     * Frees gpu created by the context. Can be called to reduce GPU memory
82     * pressure.
83     */
84    void freeGpuResources();
85
86    ///////////////////////////////////////////////////////////////////////////
87    // Textures
88
89    /**
90     * Token that refers to an entry in the texture cache. Returned by
91     * functions that lock textures. Passed to unlockTexture.
92     */
93    class SK_API TextureCacheEntry {
94    public:
95        TextureCacheEntry() : fEntry(NULL) {}
96        TextureCacheEntry(const TextureCacheEntry& e) : fEntry(e.fEntry) {}
97        TextureCacheEntry& operator= (const TextureCacheEntry& e) {
98            fEntry = e.fEntry;
99            return *this;
100        }
101        GrTexture* texture() const;
102        void reset() { fEntry = NULL; }
103    private:
104        explicit TextureCacheEntry(GrResourceEntry* entry) { fEntry = entry; }
105        void set(GrResourceEntry* entry) { fEntry = entry; }
106        GrResourceEntry* cacheEntry() { return fEntry; }
107        GrResourceEntry* fEntry;
108        friend class GrContext;
109    };
110
111    /**
112     *  Create a new entry, based on the specified key and texture, and return
113     *  its "locked" entry. Must call be balanced with an unlockTexture() call.
114     *
115     *  @param sampler  The sampler state used to draw a texture may be used
116     *                  to determine how to store the pixel data in the texture
117     *                  cache. (e.g. different versions may exist for different
118     *                  wrap modes on GPUs with limited or no NPOT texture
119     *                  support). Only the wrap and filter fields are used. NULL
120     *                  implies clamp wrap modes and nearest filtering.
121     * @param desc      Description of the texture properties.
122     * @param srcData   Pointer to the pixel values.
123     * @param rowBytes  The number of bytes between rows of the texture. Zero
124     *                  implies tightly packed rows.
125     */
126    TextureCacheEntry createAndLockTexture(const GrSamplerState* sampler,
127                                           const GrTextureDesc& desc,
128                                           void* srcData, size_t rowBytes);
129
130    /**
131     *  Search for an entry based on key and dimensions. If found, "lock" it and
132     *  return it. The entry's texture() function will return NULL if not found.
133     *  Must be balanced with an unlockTexture() call.
134     *
135     *  @param desc      Description of the texture properties.
136     *  @param sampler  The sampler state used to draw a texture may be used
137     *                  to determine the cache entry used. (e.g. different
138     *                  versions may exist for different wrap modes on GPUs with
139     *                  limited or no NPOT texture support). Only the wrap and
140     *                  filter fields are used. NULL implies clamp wrap modes
141     *                  and nearest filtering.
142     */
143    TextureCacheEntry findAndLockTexture(const GrTextureDesc& desc,
144                                         const GrSamplerState* sampler);
145    /**
146     * Determines whether a texture is in the cache. If the texture is found it
147     * will not be locked or returned. This call does not affect the priority of
148     * the texture for deletion.
149     */
150    bool isTextureInCache(const GrTextureDesc& desc,
151                          const GrSamplerState* sampler) const;
152
153    /**
154     * Enum that determines how closely a returned scratch texture must match
155     * a provided GrTextureDesc.
156     */
157    enum ScratchTexMatch {
158        /**
159         * Finds a texture that exactly matches the descriptor.
160         */
161        kExact_ScratchTexMatch,
162        /**
163         * Finds a texture that approximately matches the descriptor. Will be
164         * at least as large in width and height as desc specifies. If desc
165         * specifies that texture is a render target then result will be a
166         * render target. If desc specifies a render target and doesn't set the
167         * no stencil flag then result will have a stencil. Format and aa level
168         * will always match.
169         */
170        kApprox_ScratchTexMatch
171    };
172
173    /**
174     * Returns a texture matching the desc. It's contents are unknown. Subsequent
175     * requests with the same descriptor are not guaranteed to return the same
176     * texture. The same texture is guaranteed not be returned again until it is
177     * unlocked. Must call be balanced with an unlockTexture() call.
178     *
179     * Textures created by createAndLockTexture() hide the complications of
180     * tiling non-power-of-two textures on APIs that don't support this (e.g.
181     * unextended GLES2). Tiling a npot texture created by lockScratchTexture on
182     * such an API will create gaps in the tiling pattern. This includes clamp
183     * mode. (This may be addressed in a future update.)
184     */
185    TextureCacheEntry lockScratchTexture(const GrTextureDesc& desc,
186                                         ScratchTexMatch match);
187
188    /**
189     *  When done with an entry, call unlockTexture(entry) on it, which returns
190     *  it to the cache, where it may be purged.
191     */
192    void unlockTexture(TextureCacheEntry entry);
193
194    /**
195     * Creates a texture that is outside the cache. Does not count against
196     * cache's budget.
197     */
198    GrTexture* createUncachedTexture(const GrTextureDesc& desc,
199                                     void* srcData,
200                                     size_t rowBytes);
201
202    /**
203     *  Returns true if the specified use of an indexed texture is supported.
204     */
205    bool supportsIndex8PixelConfig(const GrSamplerState* sampler,
206                                   int width,
207                                   int height) const;
208
209    /**
210     *  Return the current texture cache budget in bytes.
211     */
212    size_t getTextureCacheBudget() const;
213
214    /**
215     *  Specify the texture cache budget. If the current cache size exceeds the
216     *  budget it will immediately be purged to be within the budget.
217     *
218     *  @param maxTextureBytes The maximum number of bytes of texture memory
219     *                         that can be held in the cache.
220     */
221    void setTextureCacheBudget(size_t maxTextureBytes);
222    // DEPRECATED, this will be deleted soon.
223    void setTextureCacheLimits(int ignored, size_t maxTextureBytes) {
224        this->setTextureCacheBudget(maxTextureBytes);
225    }
226
227    /**
228     * Returns the current number of bytes of GPU memory hosted by the texture
229     * cache.
230     */
231    size_t getGpuTextureCacheBytes() const;
232
233    /**
234     *  Return the max width or height of a texture supported by the current gpu
235     */
236    int getMaxTextureSize() const;
237
238    /**
239     * Return the max width or height of a render target supported by the
240     * current gpu
241     */
242    int getMaxRenderTargetSize() const;
243
244    ///////////////////////////////////////////////////////////////////////////
245    // Render targets
246
247    /**
248     * Sets the render target.
249     * @param target    the render target to set. (should not be NULL.)
250     */
251    void setRenderTarget(GrRenderTarget* target);
252
253    /**
254     * Gets the current render target.
255     * @return the currently bound render target. Should never be NULL.
256     */
257    const GrRenderTarget* getRenderTarget() const;
258    GrRenderTarget* getRenderTarget();
259
260    GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
261
262    /**
263     * Can the provided configuration act as a color render target?
264     */
265    bool isConfigRenderable(GrPixelConfig config) const;
266
267    ///////////////////////////////////////////////////////////////////////////
268    // Platform Surfaces
269
270    /**
271     * Wraps an existing texture with a GrTexture object.
272     *
273     * OpenGL: if the object is a texture Gr may change its GL texture params
274     *         when it is drawn.
275     *
276     * @param  desc     description of the object to create.
277     *
278     * @return GrTexture object or NULL on failure.
279     */
280    GrTexture* createPlatformTexture(const GrPlatformTextureDesc& desc);
281
282    /**
283     * Wraps an existing render target with a GrRenderTarget object. It is
284     * similar to createPlatformTexture but can be used to draw into surfaces
285     * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
286     * the client will resolve to a texture).
287     *
288     * @param  desc     description of the object to create.
289     *
290     * @return GrTexture object or NULL on failure.
291     */
292     GrRenderTarget* createPlatformRenderTarget(
293                                    const GrPlatformRenderTargetDesc& desc);
294
295    ///////////////////////////////////////////////////////////////////////////
296    // Matrix state
297
298    /**
299     * Gets the current transformation matrix.
300     * @return the current matrix.
301     */
302    const GrMatrix& getMatrix() const;
303
304    /**
305     * Sets the transformation matrix.
306     * @param m the matrix to set.
307     */
308    void setMatrix(const GrMatrix& m);
309
310    /**
311     * Concats the current matrix. The passed matrix is applied before the
312     * current matrix.
313     * @param m the matrix to concat.
314     */
315    void concatMatrix(const GrMatrix& m) const;
316
317
318    ///////////////////////////////////////////////////////////////////////////
319    // Clip state
320    /**
321     * Gets the current clip.
322     * @return the current clip.
323     */
324    const GrClip& getClip() const;
325
326    /**
327     * Sets the clip.
328     * @param clip  the clip to set.
329     */
330    void setClip(const GrClip& clip);
331
332    /**
333     * Convenience method for setting the clip to a rect.
334     * @param rect  the rect to set as the new clip.
335     */
336    void setClip(const GrIRect& rect);
337
338    ///////////////////////////////////////////////////////////////////////////
339    // Draws
340
341    /**
342     * Clear the entire or rect of the render target, ignoring any clips.
343     * @param rect  the rect to clear or the whole thing if rect is NULL.
344     * @param color the color to clear to.
345     * @param target if non-NULL, the render target to clear otherwise clear
346     *               the current render target
347     */
348    void clear(const GrIRect* rect, GrColor color,
349               GrRenderTarget* target = NULL);
350
351    /**
352     *  Draw everywhere (respecting the clip) with the paint.
353     */
354    void drawPaint(const GrPaint& paint);
355
356    /**
357     *  Draw the rect using a paint.
358     *  @param paint        describes how to color pixels.
359     *  @param strokeWidth  If strokeWidth < 0, then the rect is filled, else
360     *                      the rect is mitered stroked based on strokeWidth. If
361     *                      strokeWidth == 0, then the stroke is always a single
362     *                      pixel thick.
363     *  @param matrix       Optional matrix applied to the rect. Applied before
364     *                      context's matrix or the paint's matrix.
365     *  The rects coords are used to access the paint (through texture matrix)
366     */
367    void drawRect(const GrPaint& paint,
368                  const GrRect&,
369                  GrScalar strokeWidth = -1,
370                  const GrMatrix* matrix = NULL);
371
372    /**
373     * Maps a rect of paint coordinates onto the a rect of destination
374     * coordinates. Each rect can optionally be transformed. The srcRect
375     * is stretched over the dstRect. The dstRect is transformed by the
376     * context's matrix and the srcRect is transformed by the paint's matrix.
377     * Additional optional matrices can be provided by parameters.
378     *
379     * @param paint     describes how to color pixels.
380     * @param dstRect   the destination rect to draw.
381     * @param srcRect   rect of paint coordinates to be mapped onto dstRect
382     * @param dstMatrix Optional matrix to transform dstRect. Applied before
383     *                  context's matrix.
384     * @param srcMatrix Optional matrix to transform srcRect Applied before
385     *                  paint's matrix.
386     */
387    void drawRectToRect(const GrPaint& paint,
388                        const GrRect& dstRect,
389                        const GrRect& srcRect,
390                        const GrMatrix* dstMatrix = NULL,
391                        const GrMatrix* srcMatrix = NULL);
392
393    /**
394     * Draws a path.
395     *
396     * @param paint         describes how to color pixels.
397     * @param path          the path to draw
398     * @param fill          the path filling rule to use.
399     * @param translate     optional additional translation applied to the
400     *                      path.
401     */
402    void drawPath(const GrPaint& paint, const SkPath& path, GrPathFill fill,
403                  const GrPoint* translate = NULL);
404
405    /**
406     * Draws vertices with a paint.
407     *
408     * @param   paint           describes how to color pixels.
409     * @param   primitiveType   primitives type to draw.
410     * @param   vertexCount     number of vertices.
411     * @param   positions       array of vertex positions, required.
412     * @param   texCoords       optional array of texture coordinates used
413     *                          to access the paint.
414     * @param   colors          optional array of per-vertex colors, supercedes
415     *                          the paint's color field.
416     * @param   indices         optional array of indices. If NULL vertices
417     *                          are drawn non-indexed.
418     * @param   indexCount      if indices is non-null then this is the
419     *                          number of indices.
420     */
421    void drawVertices(const GrPaint& paint,
422                      GrPrimitiveType primitiveType,
423                      int vertexCount,
424                      const GrPoint positions[],
425                      const GrPoint texs[],
426                      const GrColor colors[],
427                      const uint16_t indices[],
428                      int indexCount);
429
430    /**
431     * Draws an oval.
432     *
433     * @param paint         describes how to color pixels.
434     * @param rect          the bounding rect of the oval.
435     * @param strokeWidth   if strokeWidth < 0, then the oval is filled, else
436     *                      the rect is stroked based on strokeWidth. If
437     *                      strokeWidth == 0, then the stroke is always a single
438     *                      pixel thick.
439     */
440    void drawOval(const GrPaint& paint,
441                  const GrRect& rect,
442                  SkScalar strokeWidth);
443
444    ///////////////////////////////////////////////////////////////////////////
445    // Misc.
446
447    /**
448     * Flags that affect flush() behavior.
449     */
450    enum FlushBits {
451        /**
452         * A client may want Gr to bind a GrRenderTarget in the 3D API so that
453         * it can be rendered to directly. However, Gr lazily sets state. Simply
454         * calling setRenderTarget() followed by flush() without flags may not
455         * bind the render target. This flag forces the context to bind the last
456         * set render target in the 3D API.
457         */
458        kForceCurrentRenderTarget_FlushBit   = 0x1,
459        /**
460         * A client may reach a point where it has partially rendered a frame
461         * through a GrContext that it knows the user will never see. This flag
462         * causes the flush to skip submission of deferred content to the 3D API
463         * during the flush.
464         */
465        kDiscard_FlushBit                    = 0x2,
466    };
467
468    /**
469     * Call to ensure all drawing to the context has been issued to the
470     * underlying 3D API.
471     * @param flagsBitfield     flags that control the flushing behavior. See
472     *                          FlushBits.
473     */
474    void flush(int flagsBitfield = 0);
475
476    /**
477     * Reads a rectangle of pixels from a render target.
478     * @param target        the render target to read from. NULL means the
479     *                      current render target.
480     * @param left          left edge of the rectangle to read (inclusive)
481     * @param top           top edge of the rectangle to read (inclusive)
482     * @param width         width of rectangle to read in pixels.
483     * @param height        height of rectangle to read in pixels.
484     * @param config        the pixel config of the destination buffer
485     * @param buffer        memory to read the rectangle into.
486     * @param rowBytes      number of bytes bewtween consecutive rows. Zero
487     *                      means rows are tightly packed.
488     *
489     * @return true if the read succeeded, false if not. The read can fail
490     *              because of an unsupported pixel config or because no render
491     *              target is currently set.
492     */
493    bool readRenderTargetPixels(GrRenderTarget* target,
494                                int left, int top, int width, int height,
495                                GrPixelConfig config, void* buffer,
496                                size_t rowBytes) {
497        return this->internalReadRenderTargetPixels(target, left, top,
498                                                    width, height,
499                                                    config, buffer,
500                                                    rowBytes, 0);
501    }
502
503    /**
504     * Copy the src pixels [buffer, rowbytes, pixelconfig] into a render target
505     * at the specified rectangle.
506     * @param target        the render target to write into. NULL means the
507     *                      current render target.
508     * @param left          left edge of the rectangle to write (inclusive)
509     * @param top           top edge of the rectangle to write (inclusive)
510     * @param width         width of rectangle to write in pixels.
511     * @param height        height of rectangle to write in pixels.
512     * @param config        the pixel config of the source buffer
513     * @param buffer        memory to read the rectangle from.
514     * @param rowBytes      number of bytes bewtween consecutive rows. Zero
515     *                      means rows are tightly packed.
516     */
517    void writeRenderTargetPixels(GrRenderTarget* target,
518                                 int left, int top, int width, int height,
519                                 GrPixelConfig config, const void* buffer,
520                                 size_t rowBytes) {
521        this->internalWriteRenderTargetPixels(target, left, top, width, height,
522                                              config, buffer, rowBytes, 0);
523    }
524
525    /**
526     * Reads a rectangle of pixels from a texture.
527     * @param texture       the texture to read from.
528     * @param left          left edge of the rectangle to read (inclusive)
529     * @param top           top edge of the rectangle to read (inclusive)
530     * @param width         width of rectangle to read in pixels.
531     * @param height        height of rectangle to read in pixels.
532     * @param config        the pixel config of the destination buffer
533     * @param buffer        memory to read the rectangle into.
534     * @param rowBytes      number of bytes bewtween consecutive rows. Zero
535     *                      means rows are tightly packed.
536     *
537     * @return true if the read succeeded, false if not. The read can fail
538     *              because of an unsupported pixel config.
539     */
540    bool readTexturePixels(GrTexture* texture,
541                           int left, int top, int width, int height,
542                           GrPixelConfig config, void* buffer,
543                           size_t rowBytes) {
544        return this->internalReadTexturePixels(texture, left, top,
545                                               width, height,
546                                               config, buffer, rowBytes, 0);
547    }
548
549    /**
550     * Writes a rectangle of pixels to a texture.
551     * @param texture       the render target to read from.
552     * @param left          left edge of the rectangle to write (inclusive)
553     * @param top           top edge of the rectangle to write (inclusive)
554     * @param width         width of rectangle to write in pixels.
555     * @param height        height of rectangle to write in pixels.
556     * @param config        the pixel config of the source buffer
557     * @param buffer        memory to read pixels from
558     * @param rowBytes      number of bytes bewtween consecutive rows. Zero
559     *                      means rows are tightly packed.
560     */
561    void writeTexturePixels(GrTexture* texture,
562                            int left, int top, int width, int height,
563                            GrPixelConfig config, const void* buffer,
564                            size_t rowBytes) {
565        this->internalWriteTexturePixels(texture, left, top, width, height,
566                                         config, buffer, rowBytes, 0);
567    }
568    /**
569     * Copies all texels from one texture to another.
570     * @param src           the texture to copy from.
571     * @param dst           the render target to copy to.
572     */
573    void copyTexture(GrTexture* src, GrRenderTarget* dst);
574
575    /**
576     * Resolves a render target that has MSAA. The intermediate MSAA buffer is
577     * downsampled to the associated GrTexture (accessible via
578     * GrRenderTarget::asTexture()). Any pending draws to the render target will
579     * be executed before the resolve.
580     *
581     * This is only necessary when a client wants to access the object directly
582     * using the underlying graphics API. GrContext will detect when it must
583     * perform a resolve to a GrTexture used as the source of a draw or before
584     * reading pixels back from a GrTexture or GrRenderTarget.
585     */
586    void resolveRenderTarget(GrRenderTarget* target);
587
588    /**
589     * Applies a 2D Gaussian blur to a given texture.
590     * @param srcTexture      The source texture to be blurred.
591     * @param temp1           A scratch texture.  Must not be NULL.
592     * @param temp2           A scratch texture.  May be NULL, in which case
593     *                        srcTexture is overwritten with intermediate
594     *                        results.
595     * @param rect            The destination rectangle.
596     * @param sigmaX          The blur's standard deviation in X.
597     * @param sigmaY          The blur's standard deviation in Y.
598     * @return the blurred texture, which may be temp1, temp2 or srcTexture.
599     */
600     GrTexture* gaussianBlur(GrTexture* srcTexture,
601                             GrAutoScratchTexture* temp1,
602                             GrAutoScratchTexture* temp2,
603                             const SkRect& rect,
604                             float sigmaX, float sigmaY);
605
606    /**
607     * This enum is used with the function below, applyMorphology.
608     */
609    enum MorphologyType {
610        kErode_MorphologyType,
611        kDilate_MorphologyType,
612    };
613
614    /**
615     * Applies a 2D morphology to a given texture.
616     * @param srcTexture      The source texture to be blurred.
617     * @param rect            The destination rectangle.
618     * @param temp1           A scratch texture.  Must not be NULL.
619     * @param temp2           A scratch texture.  Must not be NULL.
620     * @param filter          The morphology filter.  Must be kDilate_Filter or
621     *                        kErode_Filter.
622     * @param radius          The morphology radius in X and Y.  The filter is
623     *                        applied to a fWidth by fHeight rectangle of
624     *                        pixels.
625     * @return the morphed texture, which may be temp1, temp2 or srcTexture.
626     */
627    GrTexture* applyMorphology(GrTexture* srcTexture,
628                               const GrRect& rect,
629                               GrTexture* temp1, GrTexture* temp2,
630                               MorphologyType type,
631                               SkISize radius);
632
633    ///////////////////////////////////////////////////////////////////////////
634    // Helpers
635
636    class AutoRenderTarget : ::GrNoncopyable {
637    public:
638        AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
639            fContext = NULL;
640            fPrevTarget = context->getRenderTarget();
641            if (fPrevTarget != target) {
642                context->setRenderTarget(target);
643                fContext = context;
644            }
645        }
646        ~AutoRenderTarget() {
647            if (fContext) {
648                fContext->setRenderTarget(fPrevTarget);
649            }
650        }
651    private:
652        GrContext*      fContext;
653        GrRenderTarget* fPrevTarget;
654    };
655
656
657    ///////////////////////////////////////////////////////////////////////////
658    // Functions intended for internal use only.
659    GrGpu* getGpu() { return fGpu; }
660    const GrGpu* getGpu() const { return fGpu; }
661    GrFontCache* getFontCache() { return fFontCache; }
662    GrDrawTarget* getTextTarget(const GrPaint& paint);
663    const GrIndexBuffer* getQuadIndexBuffer() const;
664
665    /**
666     * Stencil buffers add themselves to the cache using
667     * addAndLockStencilBuffer. When a SB's RT-attachment count
668     * reaches zero the SB unlocks itself using unlockStencilBuffer and is
669     * eligible for purging. findStencilBuffer is called to check the cache for
670     * a SB that matching an RT's criteria. If a match is found that has been
671     * unlocked (its attachment count has reached 0) then it will be relocked.
672     */
673    GrResourceEntry* addAndLockStencilBuffer(GrStencilBuffer* sb);
674    void unlockStencilBuffer(GrResourceEntry* sbEntry);
675    GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt);
676
677    /*
678     * postClipPush acts as a hint to this and lower-level classes (e.g.,
679     * GrGpu) that the clip stack has changed.
680     */
681    virtual void postClipPush();
682
683    /*
684     * preClipPop acts as a hint that the clip stack has been restored to an
685     * earlier state.
686     */
687    virtual void preClipPop();
688
689    GrPathRenderer* getPathRenderer(const SkPath& path,
690                                    GrPathFill fill,
691                                    const GrDrawTarget* target,
692                                    bool antiAlias,
693                                    bool allowSW);
694
695private:
696    // used to keep track of when we need to flush the draw buffer
697    enum DrawCategory {
698        kBuffered_DrawCategory,      // last draw was inserted in draw buffer
699        kUnbuffered_DrawCategory,    // last draw was not inserted in the draw buffer
700    };
701    DrawCategory fLastDrawCategory;
702
703    GrGpu*              fGpu;
704    GrDrawState*        fDrawState;
705
706    GrResourceCache*    fTextureCache;
707    GrFontCache*        fFontCache;
708
709    GrPathRendererChain*        fPathRendererChain;
710    GrSoftwarePathRenderer*     fSoftwarePathRenderer;
711
712    GrVertexBufferAllocPool*    fDrawBufferVBAllocPool;
713    GrIndexBufferAllocPool*     fDrawBufferIBAllocPool;
714    GrInOrderDrawBuffer*        fDrawBuffer;
715
716    GrAARectRenderer*           fAARectRenderer;
717
718    GrContext(GrGpu* gpu);
719
720    void setupDrawBuffer();
721
722    void flushDrawBuffer();
723
724    void setPaint(const GrPaint& paint);
725
726    GrDrawTarget* prepareToDraw(const GrPaint& paint, DrawCategory drawType);
727
728    void internalDrawPath(const GrPaint& paint, const SkPath& path,
729                          GrPathFill fill, const GrPoint* translate);
730
731    /**
732     * Flags to the internal read/write pixels funcs
733     */
734    enum PixelOpsFlags {
735        kDontFlush_PixelOpsFlag = 0x1,
736    };
737
738    bool internalReadRenderTargetPixels(GrRenderTarget* target,
739                                        int left, int top,
740                                        int width, int height,
741                                        GrPixelConfig config, void* buffer,
742                                        size_t rowBytes, uint32_t flags);
743
744    void internalWriteRenderTargetPixels(GrRenderTarget* target,
745                                        int left, int top,
746                                        int width, int height,
747                                        GrPixelConfig, const void* buffer,
748                                        size_t rowBytes, uint32_t flags);
749
750    bool internalReadTexturePixels(GrTexture* texture,
751                                   int left, int top,
752                                   int width, int height,
753                                   GrPixelConfig config, void* buffer,
754                                   size_t rowBytes, uint32_t flags);
755
756    void internalWriteTexturePixels(GrTexture* texture,
757                                    int left, int top,
758                                    int width, int height,
759                                    GrPixelConfig config, const void* buffer,
760                                    size_t rowBytes, uint32_t flags);
761    // needed for access to internalWriteTexturePixels. TODO: make GrContext
762    // be a facade for an internal class. Then functions that are public on the
763    // internal class would have only be callable in src/gpu. The facade would
764    // only have to functions necessary for clients.
765    friend class GrAtlas;
766
767    // computes vertex layout bits based on the paint. If paint expresses
768    // a texture for a stage, the stage coords will be bound to postitions
769    // unless hasTexCoords[s]==true in which case stage s's input coords
770    // are bound to tex coord index s. hasTexCoords == NULL is a shortcut
771    // for an array where all the values are false.
772    static int PaintStageVertexLayoutBits(
773                                    const GrPaint& paint,
774                                    const bool hasTexCoords[GrPaint::kTotalStages]);
775
776};
777
778/**
779 *  Save/restore the view-matrix in the context.
780 */
781class GrAutoMatrix : GrNoncopyable {
782public:
783    GrAutoMatrix() : fContext(NULL) {}
784    GrAutoMatrix(GrContext* ctx) : fContext(ctx) {
785        fMatrix = ctx->getMatrix();
786    }
787    GrAutoMatrix(GrContext* ctx, const GrMatrix& matrix) : fContext(ctx) {
788        fMatrix = ctx->getMatrix();
789        ctx->setMatrix(matrix);
790    }
791    void set(GrContext* ctx) {
792        if (NULL != fContext) {
793            fContext->setMatrix(fMatrix);
794        }
795        fMatrix = ctx->getMatrix();
796        fContext = ctx;
797    }
798    void set(GrContext* ctx, const GrMatrix& matrix) {
799        if (NULL != fContext) {
800            fContext->setMatrix(fMatrix);
801        }
802        fMatrix = ctx->getMatrix();
803        ctx->setMatrix(matrix);
804        fContext = ctx;
805    }
806    ~GrAutoMatrix() {
807        if (NULL != fContext) {
808            fContext->setMatrix(fMatrix);
809        }
810    }
811
812private:
813    GrContext*  fContext;
814    GrMatrix    fMatrix;
815};
816
817/**
818 * Gets and locks a scratch texture from a descriptor using
819 * either exact or approximate criteria. Unlocks texture in
820 * the destructor.
821 */
822class GrAutoScratchTexture : ::GrNoncopyable {
823public:
824    GrAutoScratchTexture()
825        : fContext(NULL) {
826    }
827
828    GrAutoScratchTexture(GrContext* context,
829                         const GrTextureDesc& desc,
830                         GrContext::ScratchTexMatch match =
831                            GrContext::kApprox_ScratchTexMatch)
832      : fContext(NULL) {
833      this->set(context, desc, match);
834    }
835
836    ~GrAutoScratchTexture() {
837        if (NULL != fContext) {
838            fContext->unlockTexture(fEntry);
839        }
840    }
841
842    GrTexture* set(GrContext* context,
843                   const GrTextureDesc& desc,
844                   GrContext::ScratchTexMatch match =
845                        GrContext::kApprox_ScratchTexMatch) {
846        if (NULL != fContext) {
847            fContext->unlockTexture(fEntry);
848            fEntry.reset();
849        }
850        fContext = context;
851        if (NULL != fContext) {
852            fEntry = fContext->lockScratchTexture(desc, match);
853            GrTexture* ret = fEntry.texture();
854            if (NULL == ret) {
855                fContext = NULL;
856            }
857            return ret;
858        } else {
859            return NULL;
860        }
861    }
862
863    GrTexture* texture() { return fEntry.texture(); }
864private:
865    GrContext*                    fContext;
866    GrContext::TextureCacheEntry  fEntry;
867};
868
869#endif
870