Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / GrDrawTarget.h
1 /*
2  * Copyright 2010 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #ifndef GrDrawTarget_DEFINED
9 #define GrDrawTarget_DEFINED
10
11 #include "GrClipData.h"
12 #include "GrContext.h"
13 #include "GrDrawState.h"
14 #include "GrIndexBuffer.h"
15 #include "GrTraceMarker.h"
16
17 #include "SkClipStack.h"
18 #include "SkMatrix.h"
19 #include "SkPath.h"
20 #include "SkStrokeRec.h"
21 #include "SkTArray.h"
22 #include "SkTLazy.h"
23 #include "SkTypes.h"
24 #include "SkXfermode.h"
25
26 class GrClipData;
27 class GrDrawTargetCaps;
28 class GrPath;
29 class GrVertexBuffer;
30
31 class GrDrawTarget : public SkRefCnt {
32 protected:
33     class DrawInfo;
34
35 public:
36     SK_DECLARE_INST_COUNT(GrDrawTarget)
37
38     ///////////////////////////////////////////////////////////////////////////
39
40     // The context may not be fully constructed and should not be used during GrDrawTarget
41     // construction.
42     GrDrawTarget(GrContext* context);
43     virtual ~GrDrawTarget();
44
45     /**
46      * Gets the capabilities of the draw target.
47      */
48     const GrDrawTargetCaps* caps() const { return fCaps.get(); }
49
50     /**
51      * Sets the current clip to the region specified by clip. All draws will be
52      * clipped against this clip if kClip_StateBit is enabled.
53      *
54      * Setting the clip may (or may not) zero out the client's stencil bits.
55      *
56      * @param description of the clipping region
57      */
58     void setClip(const GrClipData* clip);
59
60     /**
61      * Gets the current clip.
62      *
63      * @return the clip.
64      */
65     const GrClipData* getClip() const;
66
67     /**
68      * Sets the draw state object for the draw target. Note that this does not
69      * make a copy. The GrDrawTarget will take a reference to passed object.
70      * Passing NULL will cause the GrDrawTarget to use its own internal draw
71      * state object rather than an externally provided one.
72      */
73     void setDrawState(GrDrawState*  drawState);
74
75     /**
76      * Read-only access to the GrDrawTarget's current draw state.
77      */
78     const GrDrawState& getDrawState() const { return *fDrawState; }
79
80     /**
81      * Read-write access to the GrDrawTarget's current draw state. Note that
82      * this doesn't ref.
83      */
84     GrDrawState* drawState() { return fDrawState; }
85
86     /**
87      * Color alpha and coverage are two inputs to the drawing pipeline. For some
88      * blend modes it is safe to fold the coverage into constant or per-vertex
89      * color alpha value. For other blend modes they must be handled separately.
90      * Depending on features available in the underlying 3D API this may or may
91      * not be possible.
92      *
93      * This function considers the current draw state and the draw target's
94      * capabilities to determine whether coverage can be handled correctly. The
95      * following assumptions are made:
96      *    1. The caller intends to somehow specify coverage. This can be
97      *       specified either by enabling a coverage stage on the GrDrawState or
98      *       via the vertex layout.
99      *    2. Other than enabling coverage stages or enabling coverage in the
100      *       layout, the current configuration of the target's GrDrawState is as
101      *       it will be at draw time.
102      */
103     bool canApplyCoverage() const;
104
105     /** When we're using coverage AA but the blend is incompatible (given gpu
106      * limitations) we should disable AA. */
107     bool shouldDisableCoverageAAForBlend() {
108         // Enable below if we should draw with AA even when it produces
109         // incorrect blending.
110         // return false;
111         return !this->canApplyCoverage();
112     }
113
114     /**
115      * Given the current draw state and hw support, will HW AA lines be used (if
116      * a line primitive type is drawn)?
117      */
118     bool willUseHWAALines() const;
119
120     /**
121      * There are three types of "sources" of geometry (vertices and indices) for
122      * draw calls made on the target. When performing an indexed draw, the
123      * indices and vertices can use different source types. Once a source is
124      * specified it can be used for multiple draws. However, the time at which
125      * the geometry data is no longer editable depends on the source type.
126      *
127      * Sometimes it is necessary to perform a draw while upstack code has
128      * already specified geometry that it isn't finished with. So there are push
129      * and pop methods. This allows the client to push the sources, draw
130      * something using alternate sources, and then pop to restore the original
131      * sources.
132      *
133      * Aside from pushes and pops, a source remains valid until another source
134      * is set or resetVertexSource / resetIndexSource is called. Drawing from
135      * a reset source is an error.
136      *
137      * The three types of sources are:
138      *
139      * 1. A cpu array (set*SourceToArray). This is useful when the caller
140      *    already provided vertex data in a format compatible with a
141      *    GrVertexLayout. The data in the array is consumed at the time that
142      *    set*SourceToArray is called and subsequent edits to the array will not
143      *    be reflected in draws.
144      *
145      * 2. Reserve. This is most useful when the caller has data it must
146      *    transform before drawing and is not long-lived. The caller requests
147      *    that the draw target make room for some amount of vertex and/or index
148      *    data. The target provides ptrs to hold the vertex and/or index data.
149      *
150      *    The data is writable up until the next drawIndexed, drawNonIndexed,
151      *    drawIndexedInstances, drawRect, copySurface, or pushGeometrySource. At
152      *    this point the data is frozen and the ptrs are no longer valid.
153      *
154      *    Where the space is allocated and how it is uploaded to the GPU is
155      *    subclass-dependent.
156      *
157      * 3. Vertex and Index Buffers. This is most useful for geometry that will
158      *    is long-lived. When the data in the buffer is consumed depends on the
159      *    GrDrawTarget subclass. For deferred subclasses the caller has to
160      *    guarantee that the data is still available in the buffers at playback.
161      *    (TODO: Make this more automatic as we have done for read/write pixels)
162      *
163      * The size of each vertex is determined by querying the current GrDrawState.
164      */
165
166     /**
167      * Reserves space for vertices and/or indices. Zero can be specifed as
168      * either the vertex or index count if the caller desires to only reserve
169      * space for only indices or only vertices. If zero is specifed for
170      * vertexCount then the vertex source will be unmodified and likewise for
171      * indexCount.
172      *
173      * If the function returns true then the reserve suceeded and the vertices
174      * and indices pointers will point to the space created.
175      *
176      * If the target cannot make space for the request then this function will
177      * return false. If vertexCount was non-zero then upon failure the vertex
178      * source is reset and likewise for indexCount.
179      *
180      * The pointers to the space allocated for vertices and indices remain valid
181      * until a drawIndexed, drawNonIndexed, drawIndexedInstances, drawRect,
182      * copySurface, or push/popGeomtrySource is called. At that point logically a
183      * snapshot of the data is made and the pointers are invalid.
184      *
185      * @param vertexCount  the number of vertices to reserve space for. Can be
186      *                     0. Vertex size is queried from the current GrDrawState.
187      * @param indexCount   the number of indices to reserve space for. Can be 0.
188      * @param vertices     will point to reserved vertex space if vertexCount is
189      *                     non-zero. Illegal to pass NULL if vertexCount > 0.
190      * @param indices      will point to reserved index space if indexCount is
191      *                     non-zero. Illegal to pass NULL if indexCount > 0.
192      */
193      bool reserveVertexAndIndexSpace(int vertexCount,
194                                      int indexCount,
195                                      void** vertices,
196                                      void** indices);
197
198     /**
199      * Provides hints to caller about the number of vertices and indices
200      * that can be allocated cheaply. This can be useful if caller is reserving
201      * space but doesn't know exactly how much geometry is needed.
202      *
203      * Also may hint whether the draw target should be flushed first. This is
204      * useful for deferred targets.
205      *
206      * @param vertexCount  in: hint about how many vertices the caller would
207      *                     like to allocate. Vertex size is queried from the
208      *                     current GrDrawState.
209      *                     out: a hint about the number of vertices that can be
210      *                     allocated cheaply. Negative means no hint.
211      *                     Ignored if NULL.
212      * @param indexCount   in: hint about how many indices the caller would
213      *                     like to allocate.
214      *                     out: a hint about the number of indices that can be
215      *                     allocated cheaply. Negative means no hint.
216      *                     Ignored if NULL.
217      *
218      * @return  true if target should be flushed based on the input values.
219      */
220     virtual bool geometryHints(int* vertexCount,
221                                int* indexCount) const;
222
223     /**
224      * Sets source of vertex data for the next draw. Array must contain
225      * the vertex data when this is called.
226      *
227      * @param vertexArray   cpu array containing vertex data.
228      * @param vertexCount   the number of vertices in the array. Vertex size is
229      *                      queried from the current GrDrawState.
230      */
231     void setVertexSourceToArray(const void* vertexArray, int vertexCount);
232
233     /**
234      * Sets source of index data for the next indexed draw. Array must contain
235      * the indices when this is called.
236      *
237      * @param indexArray    cpu array containing index data.
238      * @param indexCount    the number of indices in the array.
239      */
240     void setIndexSourceToArray(const void* indexArray, int indexCount);
241
242     /**
243      * Sets source of vertex data for the next draw. Data does not have to be
244      * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances.
245      *
246      * @param buffer        vertex buffer containing vertex data. Must be
247      *                      unlocked before draw call. Vertex size is queried
248      *                      from current GrDrawState.
249      */
250     void setVertexSourceToBuffer(const GrVertexBuffer* buffer);
251
252     /**
253      * Sets source of index data for the next indexed draw. Data does not have
254      * to be in the buffer until drawIndexed.
255      *
256      * @param buffer index buffer containing indices. Must be unlocked
257      *               before indexed draw call.
258      */
259     void setIndexSourceToBuffer(const GrIndexBuffer* buffer);
260
261     /**
262      * Resets vertex source. Drawing from reset vertices is illegal. Set vertex
263      * source to reserved, array, or buffer before next draw. May be able to free
264      * up temporary storage allocated by setVertexSourceToArray or
265      * reserveVertexSpace.
266      */
267     void resetVertexSource();
268
269     /**
270      * Resets index source. Indexed Drawing from reset indices is illegal. Set
271      * index source to reserved, array, or buffer before next indexed draw. May
272      * be able to free up temporary storage allocated by setIndexSourceToArray
273      * or reserveIndexSpace.
274      */
275     void resetIndexSource();
276
277     /**
278      * Query to find out if the vertex or index source is reserved.
279      */
280     bool hasReservedVerticesOrIndices() const {
281         return kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc ||
282         kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc;
283     }
284
285     /**
286      * Pushes and resets the vertex/index sources. Any reserved vertex / index
287      * data is finalized (i.e. cannot be updated after the matching pop but can
288      * be drawn from). Must be balanced by a pop.
289      */
290     void pushGeometrySource();
291
292     /**
293      * Pops the vertex / index sources from the matching push.
294      */
295     void popGeometrySource();
296
297     /**
298      * Draws indexed geometry using the current state and current vertex / index
299      * sources.
300      *
301      * @param type         The type of primitives to draw.
302      * @param startVertex  the vertex in the vertex array/buffer corresponding
303      *                     to index 0
304      * @param startIndex   first index to read from index src.
305      * @param vertexCount  one greater than the max index.
306      * @param indexCount   the number of index elements to read. The index count
307      *                     is effectively trimmed to the last completely
308      *                     specified primitive.
309      * @param devBounds    optional bounds hint. This is a promise from the caller,
310      *                     not a request for clipping.
311      */
312     void drawIndexed(GrPrimitiveType type,
313                      int startVertex,
314                      int startIndex,
315                      int vertexCount,
316                      int indexCount,
317                      const SkRect* devBounds = NULL);
318
319     /**
320      * Draws non-indexed geometry using the current state and current vertex
321      * sources.
322      *
323      * @param type         The type of primitives to draw.
324      * @param startVertex  the vertex in the vertex array/buffer corresponding
325      *                     to index 0
326      * @param vertexCount  one greater than the max index.
327      * @param devBounds    optional bounds hint. This is a promise from the caller,
328      *                     not a request for clipping.
329      */
330     void drawNonIndexed(GrPrimitiveType type,
331                         int startVertex,
332                         int vertexCount,
333                         const SkRect* devBounds = NULL);
334
335     /**
336      * Draws path into the stencil buffer. The fill must be either even/odd or
337      * winding (not inverse or hairline). It will respect the HW antialias flag
338      * on the draw state (if possible in the 3D API).
339      */
340     void stencilPath(const GrPath*, SkPath::FillType fill);
341
342     /**
343      * Draws a path. Fill must not be a hairline. It will respect the HW
344      * antialias flag on the draw state (if possible in the 3D API).
345      */
346     void drawPath(const GrPath*, SkPath::FillType fill);
347
348     /**
349      * Draws many paths. It will respect the HW
350      * antialias flag on the draw state (if possible in the 3D API).
351      *
352      * @param transforms array of 2d affine transformations, one for each path.
353      * @param fill the fill type for drawing all the paths. Fill must not be a
354      *             hairline.
355      * @param stroke the stroke for drawing all the paths.
356      */
357     void drawPaths(int pathCount, const GrPath** paths,
358                    const SkMatrix* transforms, SkPath::FillType fill,
359                    SkStrokeRec::Style stroke);
360
361     /**
362      * Helper function for drawing rects. It performs a geometry src push and pop
363      * and thus will finalize any reserved geometry.
364      *
365      * @param rect        the rect to draw
366      * @param matrix      optional matrix applied to rect (before viewMatrix)
367      * @param localRect   optional rect that specifies local coords to map onto
368      *                    rect. If NULL then rect serves as the local coords.
369      * @param localMatrix optional matrix applied to localRect. If
370      *                    srcRect is non-NULL and srcMatrix is non-NULL
371      *                    then srcRect will be transformed by srcMatrix.
372      *                    srcMatrix can be NULL when no srcMatrix is desired.
373      */
374     void drawRect(const SkRect& rect,
375                   const SkMatrix* matrix,
376                   const SkRect* localRect,
377                   const SkMatrix* localMatrix) {
378         AutoGeometryPush agp(this);
379         this->onDrawRect(rect, matrix, localRect, localMatrix);
380     }
381
382     /**
383      * Helper for drawRect when the caller doesn't need separate local rects or matrices.
384      */
385     void drawSimpleRect(const SkRect& rect, const SkMatrix* matrix = NULL) {
386         this->drawRect(rect, matrix, NULL, NULL);
387     }
388     void drawSimpleRect(const SkIRect& irect, const SkMatrix* matrix = NULL) {
389         SkRect rect = SkRect::Make(irect);
390         this->drawRect(rect, matrix, NULL, NULL);
391     }
392
393     /**
394      * This call is used to draw multiple instances of some geometry with a
395      * given number of vertices (V) and indices (I) per-instance. The indices in
396      * the index source must have the form i[k+I] == i[k] + V. Also, all indices
397      * i[kI] ... i[(k+1)I-1] must be elements of the range kV ... (k+1)V-1. As a
398      * concrete example, the following index buffer for drawing a series of
399      * quads each as two triangles each satisfies these conditions with V=4 and
400      * I=6:
401      *      (0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, ...)
402      *
403      * The call assumes that the pattern of indices fills the entire index
404      * source. The size of the index buffer limits the number of instances that
405      * can be drawn by the GPU in a single draw. However, the caller may specify
406      * any (positive) number for instanceCount and if necessary multiple GPU
407      * draws will be issued. Moreover, when drawIndexedInstances is called
408      * multiple times it may be possible for GrDrawTarget to group them into a
409      * single GPU draw.
410      *
411      * @param type          the type of primitives to draw
412      * @param instanceCount the number of instances to draw. Each instance
413      *                      consists of verticesPerInstance vertices indexed by
414      *                      indicesPerInstance indices drawn as the primitive
415      *                      type specified by type.
416      * @param verticesPerInstance   The number of vertices in each instance (V
417      *                              in the above description).
418      * @param indicesPerInstance    The number of indices in each instance (I
419      *                              in the above description).
420      * @param devBounds    optional bounds hint. This is a promise from the caller,
421      *                     not a request for clipping.
422      */
423     void drawIndexedInstances(GrPrimitiveType type,
424                               int instanceCount,
425                               int verticesPerInstance,
426                               int indicesPerInstance,
427                               const SkRect* devBounds = NULL);
428
429     /**
430      * Clear the current render target if one isn't passed in. Ignores the
431      * clip and all other draw state (blend mode, stages, etc). Clears the
432      * whole thing if rect is NULL, otherwise just the rect. If canIgnoreRect
433      * is set then the entire render target can be optionally cleared.
434      */
435     virtual void clear(const SkIRect* rect,
436                        GrColor color,
437                        bool canIgnoreRect,
438                        GrRenderTarget* renderTarget = NULL) = 0;
439
440     /**
441      * Discards the contents render target. NULL indicates that the current render target should
442      * be discarded.
443      **/
444     virtual void discard(GrRenderTarget* = NULL) = 0;
445
446     /**
447      * Called at start and end of gpu trace marking
448      * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start
449      * and end of a code block respectively
450      */
451     void addGpuTraceMarker(GrGpuTraceMarker* marker);
452     void removeGpuTraceMarker(GrGpuTraceMarker* marker);
453
454     /**
455      * Copies a pixel rectangle from one surface to another. This call may finalize
456      * reserved vertex/index data (as though a draw call was made). The src pixels
457      * copied are specified by srcRect. They are copied to a rect of the same
458      * size in dst with top left at dstPoint. If the src rect is clipped by the
459      * src bounds then  pixel values in the dst rect corresponding to area clipped
460      * by the src rect are not overwritten. This method can fail and return false
461      * depending on the type of surface, configs, etc, and the backend-specific
462      * limitations. If rect is clipped out entirely by the src or dst bounds then
463      * true is returned since there is no actual copy necessary to succeed.
464      */
465     bool copySurface(GrSurface* dst,
466                      GrSurface* src,
467                      const SkIRect& srcRect,
468                      const SkIPoint& dstPoint);
469     /**
470      * Function that determines whether a copySurface call would succeed without
471      * performing the copy.
472      */
473     bool canCopySurface(GrSurface* dst,
474                         GrSurface* src,
475                         const SkIRect& srcRect,
476                         const SkIPoint& dstPoint);
477
478     /**
479      * This is can be called before allocating a texture to be a dst for copySurface. It will
480      * populate the origin, config, and flags fields of the desc such that copySurface is more
481      * likely to succeed and be efficient.
482      */
483     virtual void initCopySurfaceDstDesc(const GrSurface* src, GrTextureDesc* desc);
484
485
486     /**
487      * Release any resources that are cached but not currently in use. This
488      * is intended to give an application some recourse when resources are low.
489      */
490     virtual void purgeResources() {};
491
492     /**
493      * For subclass internal use to invoke a call to onDraw(). See DrawInfo below.
494      */
495     void executeDraw(const DrawInfo& info) { this->onDraw(info); }
496
497     /**
498      * For subclass internal use to invoke a call to onDrawPath().
499      */
500     void executeDrawPath(const GrPath* path, SkPath::FillType fill,
501                          const GrDeviceCoordTexture* dstCopy) {
502         this->onDrawPath(path, fill, dstCopy);
503     }
504
505     /**
506      * For subclass internal use to invoke a call to onDrawPaths().
507      */
508     void executeDrawPaths(int pathCount, const GrPath** paths,
509                           const SkMatrix* transforms, SkPath::FillType fill,
510                           SkStrokeRec::Style stroke,
511                           const GrDeviceCoordTexture* dstCopy) {
512         this->onDrawPaths(pathCount, paths, transforms, fill, stroke, dstCopy);
513     }
514
515     inline bool isGpuTracingEnabled() const {
516         return this->getContext()->isGpuTracingEnabled();
517     }
518
519     ////////////////////////////////////////////////////////////////////////////
520
521     /**
522      * See AutoStateRestore below.
523      */
524     enum ASRInit {
525         kPreserve_ASRInit,
526         kReset_ASRInit
527     };
528
529     /**
530      * Saves off the current state and restores it in the destructor. It will
531      * install a new GrDrawState object on the target (setDrawState) and restore
532      * the previous one in the destructor. The caller should call drawState() to
533      * get the new draw state after the ASR is installed.
534      *
535      * GrDrawState* state = target->drawState();
536      * AutoStateRestore asr(target, GrDrawTarget::kReset_ASRInit).
537      * state->setRenderTarget(rt); // state refers to the GrDrawState set on
538      *                             // target before asr was initialized.
539      *                             // Therefore, rt is set on the GrDrawState
540      *                             // that will be restored after asr's
541      *                             // destructor rather than target's current
542      *                             // GrDrawState.
543      */
544     class AutoStateRestore : public ::SkNoncopyable {
545     public:
546         /**
547          * Default ASR will have no effect unless set() is subsequently called.
548          */
549         AutoStateRestore();
550
551         /**
552          * Saves the state on target. The state will be restored when the ASR
553          * is destroyed. If this constructor is used do not call set().
554          *
555          * @param init  Should the newly installed GrDrawState be a copy of the
556          *              previous state or a default-initialized GrDrawState.
557          * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
558          *                   matrix will be preconcat'ed with the param. All stages will be
559                              updated to compensate for the matrix change. If init == kReset
560                              then the draw state's matrix will be this matrix.
561          */
562         AutoStateRestore(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
563
564         ~AutoStateRestore();
565
566         /**
567          * Saves the state on target. The state will be restored when the ASR
568          * is destroyed. This should only be called once per ASR object and only
569          * when the default constructor was used. For nested saves use multiple
570          * ASR objects.
571          *
572          * @param init  Should the newly installed GrDrawState be a copy of the
573          *              previous state or a default-initialized GrDrawState.
574          * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
575          *                   matrix will be preconcat'ed with the param. All stages will be
576                              updated to compensate for the matrix change. If init == kReset
577                              then the draw state's matrix will be this matrix.
578          */
579         void set(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
580
581         /**
582          * Like set() but makes the view matrix identity. When init is kReset it is as though
583          * NULL was passed to set's viewMatrix param. When init is kPreserve it is as though
584          * the inverse view matrix was passed. If kPreserve is passed and the draw state's matrix
585          * is not invertible then this may fail.
586          */
587         bool setIdentity(GrDrawTarget* target, ASRInit init);
588
589     private:
590         GrDrawTarget*                       fDrawTarget;
591         SkTLazy<GrDrawState>                fTempState;
592         GrDrawState*                        fSavedState;
593     };
594
595     ////////////////////////////////////////////////////////////////////////////
596
597     class AutoReleaseGeometry : public ::SkNoncopyable {
598     public:
599         AutoReleaseGeometry(GrDrawTarget*  target,
600                             int            vertexCount,
601                             int            indexCount);
602         AutoReleaseGeometry();
603         ~AutoReleaseGeometry();
604         bool set(GrDrawTarget*  target,
605                  int            vertexCount,
606                  int            indexCount);
607         bool succeeded() const { return NULL != fTarget; }
608         void* vertices() const { SkASSERT(this->succeeded()); return fVertices; }
609         void* indices() const { SkASSERT(this->succeeded()); return fIndices; }
610         SkPoint* positions() const {
611             return static_cast<SkPoint*>(this->vertices());
612         }
613
614     private:
615         void reset();
616
617         GrDrawTarget* fTarget;
618         void*         fVertices;
619         void*         fIndices;
620     };
621
622     ////////////////////////////////////////////////////////////////////////////
623
624     class AutoClipRestore : public ::SkNoncopyable {
625     public:
626         AutoClipRestore(GrDrawTarget* target) {
627             fTarget = target;
628             fClip = fTarget->getClip();
629         }
630
631         AutoClipRestore(GrDrawTarget* target, const SkIRect& newClip);
632
633         ~AutoClipRestore() {
634             fTarget->setClip(fClip);
635         }
636     private:
637         GrDrawTarget*           fTarget;
638         const GrClipData*       fClip;
639         SkTLazy<SkClipStack>    fStack;
640         GrClipData              fReplacementClip;
641     };
642
643     ////////////////////////////////////////////////////////////////////////////
644
645     /**
646      * Saves the geometry src state at construction and restores in the destructor. It also saves
647      * and then restores the vertex attrib state.
648      */
649     class AutoGeometryPush : public ::SkNoncopyable {
650     public:
651         AutoGeometryPush(GrDrawTarget* target)
652             : fAttribRestore(target->drawState()) {
653             SkASSERT(NULL != target);
654             fTarget = target;
655             target->pushGeometrySource();
656         }
657
658         ~AutoGeometryPush() { fTarget->popGeometrySource(); }
659
660     private:
661         GrDrawTarget*                           fTarget;
662         GrDrawState::AutoVertexAttribRestore    fAttribRestore;
663     };
664
665     /**
666      * Combination of AutoGeometryPush and AutoStateRestore. The vertex attribs will be in default
667      * state regardless of ASRInit value.
668      */
669     class AutoGeometryAndStatePush : public ::SkNoncopyable {
670     public:
671         AutoGeometryAndStatePush(GrDrawTarget* target,
672                                  ASRInit init,
673                                  const SkMatrix* viewMatrix = NULL)
674             : fState(target, init, viewMatrix) {
675             SkASSERT(NULL != target);
676             fTarget = target;
677             target->pushGeometrySource();
678             if (kPreserve_ASRInit == init) {
679                 target->drawState()->setDefaultVertexAttribs();
680             }
681         }
682
683         ~AutoGeometryAndStatePush() { fTarget->popGeometrySource(); }
684
685     private:
686         AutoStateRestore fState;
687         GrDrawTarget*    fTarget;
688     };
689
690     ///////////////////////////////////////////////////////////////////////////
691     // Draw execution tracking (for font atlases and other resources)
692     class DrawToken {
693     public:
694         DrawToken(GrDrawTarget* drawTarget, uint32_t drawID) :
695                   fDrawTarget(drawTarget), fDrawID(drawID) {}
696
697         bool isIssued() { return NULL != fDrawTarget && fDrawTarget->isIssued(fDrawID); }
698
699     private:
700         GrDrawTarget*  fDrawTarget;
701         uint32_t       fDrawID;   // this may wrap, but we're doing direct comparison
702                                   // so that should be okay
703     };
704
705     virtual DrawToken getCurrentDrawToken() { return DrawToken(this, 0); }
706
707 protected:
708
709     enum GeometrySrcType {
710         kNone_GeometrySrcType,     //<! src has not been specified
711         kReserved_GeometrySrcType, //<! src was set using reserve*Space
712         kArray_GeometrySrcType,    //<! src was set using set*SourceToArray
713         kBuffer_GeometrySrcType    //<! src was set using set*SourceToBuffer
714     };
715
716     struct GeometrySrcState {
717         GeometrySrcType         fVertexSrc;
718         union {
719             // valid if src type is buffer
720             const GrVertexBuffer*   fVertexBuffer;
721             // valid if src type is reserved or array
722             int                     fVertexCount;
723         };
724
725         GeometrySrcType         fIndexSrc;
726         union {
727             // valid if src type is buffer
728             const GrIndexBuffer*    fIndexBuffer;
729             // valid if src type is reserved or array
730             int                     fIndexCount;
731         };
732
733         size_t                  fVertexSize;
734     };
735
736     int indexCountInCurrentSource() const {
737         const GeometrySrcState& src = this->getGeomSrc();
738         switch (src.fIndexSrc) {
739             case kNone_GeometrySrcType:
740                 return 0;
741             case kReserved_GeometrySrcType:
742             case kArray_GeometrySrcType:
743                 return src.fIndexCount;
744             case kBuffer_GeometrySrcType:
745                 return static_cast<int>(src.fIndexBuffer->gpuMemorySize() / sizeof(uint16_t));
746             default:
747                 SkFAIL("Unexpected Index Source.");
748                 return 0;
749         }
750     }
751
752     // This method is called by copySurface  The srcRect is guaranteed to be entirely within the
753     // src bounds. Likewise, the dst rect implied by dstPoint and srcRect's width and height falls
754     // entirely within the dst. The default implementation will draw a rect from the src to the
755     // dst if the src is a texture and the dst is a render target and fail otherwise.
756     virtual bool onCopySurface(GrSurface* dst,
757                                GrSurface* src,
758                                const SkIRect& srcRect,
759                                const SkIPoint& dstPoint);
760
761     // Called to determine whether an onCopySurface call would succeed or not. This is useful for
762     // proxy subclasses to test whether the copy would succeed without executing it yet. Derived
763     // classes must keep this consistent with their implementation of onCopySurface(). The inputs
764     // are the same as onCopySurface(), i.e. srcRect and dstPoint are clipped to be inside the src
765     // and dst bounds.
766     virtual bool onCanCopySurface(GrSurface* dst,
767                                   GrSurface* src,
768                                   const SkIRect& srcRect,
769                                   const SkIPoint& dstPoint);
770
771     GrContext* getContext() { return fContext; }
772     const GrContext* getContext() const { return fContext; }
773
774     // A subclass may override this function if it wishes to be notified when the clip is changed.
775     // The override should call INHERITED::clipWillBeSet().
776     virtual void clipWillBeSet(const GrClipData* clipData);
777
778     // subclasses must call this in their destructors to ensure all vertex
779     // and index sources have been released (including those held by
780     // pushGeometrySource())
781     void releaseGeometry();
782
783     // accessors for derived classes
784     const GeometrySrcState& getGeomSrc() const { return fGeoSrcStateStack.back(); }
785     // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert.
786     size_t getVertexSize() const {
787         // the vertex layout is only valid if a vertex source has been specified.
788         SkASSERT(this->getGeomSrc().fVertexSrc != kNone_GeometrySrcType);
789         return this->getGeomSrc().fVertexSize;
790     }
791
792     // Subclass must initialize this in its constructor.
793     SkAutoTUnref<const GrDrawTargetCaps> fCaps;
794
795     const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; }
796
797     /**
798      * Used to communicate draws to subclass's onDraw function.
799      */
800     class DrawInfo {
801     public:
802         DrawInfo(const DrawInfo& di) { (*this) = di; }
803         DrawInfo& operator =(const DrawInfo& di);
804
805         GrPrimitiveType primitiveType() const { return fPrimitiveType; }
806         int startVertex() const { return fStartVertex; }
807         int startIndex() const { return fStartIndex; }
808         int vertexCount() const { return fVertexCount; }
809         int indexCount() const { return fIndexCount; }
810         int verticesPerInstance() const { return fVerticesPerInstance; }
811         int indicesPerInstance() const { return fIndicesPerInstance; }
812         int instanceCount() const { return fInstanceCount; }
813
814         bool isIndexed() const { return fIndexCount > 0; }
815 #ifdef SK_DEBUG
816         bool isInstanced() const; // this version is longer because of asserts
817 #else
818         bool isInstanced() const { return fInstanceCount > 0; }
819 #endif
820
821         // adds or remove instances
822         void adjustInstanceCount(int instanceOffset);
823         // shifts the start vertex
824         void adjustStartVertex(int vertexOffset);
825         // shifts the start index
826         void adjustStartIndex(int indexOffset);
827
828         void setDevBounds(const SkRect& bounds) {
829             fDevBoundsStorage = bounds;
830             fDevBounds = &fDevBoundsStorage;
831         }
832         const SkRect* getDevBounds() const { return fDevBounds; }
833
834         // NULL if no copy of the dst is needed for the draw.
835         const GrDeviceCoordTexture* getDstCopy() const {
836             if (NULL != fDstCopy.texture()) {
837                 return &fDstCopy;
838             } else {
839                 return NULL;
840             }
841         }
842
843     private:
844         DrawInfo() { fDevBounds = NULL; }
845
846         friend class GrDrawTarget;
847
848         GrPrimitiveType         fPrimitiveType;
849
850         int                     fStartVertex;
851         int                     fStartIndex;
852         int                     fVertexCount;
853         int                     fIndexCount;
854
855         int                     fInstanceCount;
856         int                     fVerticesPerInstance;
857         int                     fIndicesPerInstance;
858
859         SkRect                  fDevBoundsStorage;
860         SkRect*                 fDevBounds;
861
862         GrDeviceCoordTexture    fDstCopy;
863     };
864
865 private:
866     // A subclass can optionally overload this function to be notified before
867     // vertex and index space is reserved.
868     virtual void willReserveVertexAndIndexSpace(int vertexCount, int indexCount) {}
869
870     // implemented by subclass to allocate space for reserved geom
871     virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) = 0;
872     virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
873     // implemented by subclass to handle release of reserved geom space
874     virtual void releaseReservedVertexSpace() = 0;
875     virtual void releaseReservedIndexSpace() = 0;
876     // subclass must consume array contents when set
877     virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) = 0;
878     virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) = 0;
879     // subclass is notified that geom source will be set away from an array
880     virtual void releaseVertexArray() = 0;
881     virtual void releaseIndexArray() = 0;
882     // subclass overrides to be notified just before geo src state is pushed/popped.
883     virtual void geometrySourceWillPush() = 0;
884     virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
885     // subclass called to perform drawing
886     virtual void onDraw(const DrawInfo&) = 0;
887     // Implementation of drawRect. The geometry src and vertex attribs will already
888     // be saved before this is called and restored afterwards. A subclass may override
889     // this to perform more optimal rect rendering. Its draws should be funneled through
890     // one of the public GrDrawTarget draw methods (e.g. drawNonIndexed,
891     // drawIndexedInstances, ...). The base class draws a two triangle fan using
892     // drawNonIndexed from reserved vertex space.
893     virtual void onDrawRect(const SkRect& rect,
894                             const SkMatrix* matrix,
895                             const SkRect* localRect,
896                             const SkMatrix* localMatrix);
897
898     virtual void onStencilPath(const GrPath*, SkPath::FillType) = 0;
899     virtual void onDrawPath(const GrPath*, SkPath::FillType,
900                             const GrDeviceCoordTexture* dstCopy) = 0;
901     virtual void onDrawPaths(int, const GrPath**, const SkMatrix*,
902                              SkPath::FillType, SkStrokeRec::Style,
903                              const GrDeviceCoordTexture* dstCopy) = 0;
904
905     virtual void didAddGpuTraceMarker() = 0;
906     virtual void didRemoveGpuTraceMarker() = 0;
907
908     // helpers for reserving vertex and index space.
909     bool reserveVertexSpace(size_t vertexSize,
910                             int vertexCount,
911                             void** vertices);
912     bool reserveIndexSpace(int indexCount, void** indices);
913
914     // called by drawIndexed and drawNonIndexed. Use a negative indexCount to
915     // indicate non-indexed drawing.
916     bool checkDraw(GrPrimitiveType type, int startVertex,
917                    int startIndex, int vertexCount,
918                    int indexCount) const;
919     // called when setting a new vert/idx source to unref prev vb/ib
920     void releasePreviousVertexSource();
921     void releasePreviousIndexSource();
922
923     // Makes a copy of the dst if it is necessary for the draw. Returns false if a copy is required
924     // but couldn't be made. Otherwise, returns true.
925     bool setupDstReadIfNecessary(DrawInfo* info) {
926         return this->setupDstReadIfNecessary(&info->fDstCopy, info->getDevBounds());
927     }
928     bool setupDstReadIfNecessary(GrDeviceCoordTexture* dstCopy, const SkRect* drawBounds);
929
930     // Check to see if this set of draw commands has been sent out
931     virtual bool       isIssued(uint32_t drawID) { return true; }
932
933     enum {
934         kPreallocGeoSrcStateStackCnt = 4,
935     };
936     SkSTArray<kPreallocGeoSrcStateStackCnt, GeometrySrcState, true> fGeoSrcStateStack;
937     const GrClipData*                                               fClip;
938     GrDrawState*                                                    fDrawState;
939     GrDrawState                                                     fDefaultDrawState;
940     // The context owns us, not vice-versa, so this ptr is not ref'ed by DrawTarget.
941     GrContext*                                                      fContext;
942     // To keep track that we always have at least as many debug marker adds as removes
943     int                                                             fGpuTraceMarkerCount;
944     GrTraceMarkerSet                                                fActiveTraceMarkers;
945
946     typedef SkRefCnt INHERITED;
947 };
948
949 #endif