• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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      */
caps()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      */
getDrawState()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      */
drawState()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. */
shouldDisableCoverageAAForBlend()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      */
hasReservedVerticesOrIndices()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      */
drawRect(const SkRect & rect,const SkMatrix * matrix,const SkRect * localRect,const SkMatrix * localMatrix)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(const GrGpuTraceMarker* marker);
452     void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
453 
454     /**
455      * Takes the current active set of markers and stores them for later use. Any current marker
456      * in the active set is removed from the active set and the targets remove function is called.
457      * These functions do not work as a stack so you cannot call save a second time before calling
458      * restore. Also, it is assumed that when restore is called the current active set of markers
459      * is empty. When the stored markers are added back into the active set, the targets add marker
460      * is called.
461      */
462     void saveActiveTraceMarkers();
463     void restoreActiveTraceMarkers();
464 
465     /**
466      * Copies a pixel rectangle from one surface to another. This call may finalize
467      * reserved vertex/index data (as though a draw call was made). The src pixels
468      * copied are specified by srcRect. They are copied to a rect of the same
469      * size in dst with top left at dstPoint. If the src rect is clipped by the
470      * src bounds then  pixel values in the dst rect corresponding to area clipped
471      * by the src rect are not overwritten. This method can fail and return false
472      * depending on the type of surface, configs, etc, and the backend-specific
473      * limitations. If rect is clipped out entirely by the src or dst bounds then
474      * true is returned since there is no actual copy necessary to succeed.
475      */
476     bool copySurface(GrSurface* dst,
477                      GrSurface* src,
478                      const SkIRect& srcRect,
479                      const SkIPoint& dstPoint);
480     /**
481      * Function that determines whether a copySurface call would succeed without
482      * performing the copy.
483      */
484     bool canCopySurface(GrSurface* dst,
485                         GrSurface* src,
486                         const SkIRect& srcRect,
487                         const SkIPoint& dstPoint);
488 
489     /**
490      * This is can be called before allocating a texture to be a dst for copySurface. It will
491      * populate the origin, config, and flags fields of the desc such that copySurface is more
492      * likely to succeed and be efficient.
493      */
494     virtual void initCopySurfaceDstDesc(const GrSurface* src, GrTextureDesc* desc);
495 
496 
497     /**
498      * Release any resources that are cached but not currently in use. This
499      * is intended to give an application some recourse when resources are low.
500      */
purgeResources()501     virtual void purgeResources() {};
502 
503     /**
504      * For subclass internal use to invoke a call to onDraw(). See DrawInfo below.
505      */
executeDraw(const DrawInfo & info)506     void executeDraw(const DrawInfo& info) { this->onDraw(info); }
507 
508     /**
509      * For subclass internal use to invoke a call to onDrawPath().
510      */
executeDrawPath(const GrPath * path,SkPath::FillType fill,const GrDeviceCoordTexture * dstCopy)511     void executeDrawPath(const GrPath* path, SkPath::FillType fill,
512                          const GrDeviceCoordTexture* dstCopy) {
513         this->onDrawPath(path, fill, dstCopy);
514     }
515 
516     /**
517      * For subclass internal use to invoke a call to onDrawPaths().
518      */
executeDrawPaths(int pathCount,const GrPath ** paths,const SkMatrix * transforms,SkPath::FillType fill,SkStrokeRec::Style stroke,const GrDeviceCoordTexture * dstCopy)519     void executeDrawPaths(int pathCount, const GrPath** paths,
520                           const SkMatrix* transforms, SkPath::FillType fill,
521                           SkStrokeRec::Style stroke,
522                           const GrDeviceCoordTexture* dstCopy) {
523         this->onDrawPaths(pathCount, paths, transforms, fill, stroke, dstCopy);
524     }
525 
isGpuTracingEnabled()526     inline bool isGpuTracingEnabled() const {
527         return this->getContext()->isGpuTracingEnabled();
528     }
529 
530     ////////////////////////////////////////////////////////////////////////////
531 
532     /**
533      * See AutoStateRestore below.
534      */
535     enum ASRInit {
536         kPreserve_ASRInit,
537         kReset_ASRInit
538     };
539 
540     /**
541      * Saves off the current state and restores it in the destructor. It will
542      * install a new GrDrawState object on the target (setDrawState) and restore
543      * the previous one in the destructor. The caller should call drawState() to
544      * get the new draw state after the ASR is installed.
545      *
546      * GrDrawState* state = target->drawState();
547      * AutoStateRestore asr(target, GrDrawTarget::kReset_ASRInit).
548      * state->setRenderTarget(rt); // state refers to the GrDrawState set on
549      *                             // target before asr was initialized.
550      *                             // Therefore, rt is set on the GrDrawState
551      *                             // that will be restored after asr's
552      *                             // destructor rather than target's current
553      *                             // GrDrawState.
554      */
555     class AutoStateRestore : public ::SkNoncopyable {
556     public:
557         /**
558          * Default ASR will have no effect unless set() is subsequently called.
559          */
560         AutoStateRestore();
561 
562         /**
563          * Saves the state on target. The state will be restored when the ASR
564          * is destroyed. If this constructor is used do not call set().
565          *
566          * @param init  Should the newly installed GrDrawState be a copy of the
567          *              previous state or a default-initialized GrDrawState.
568          * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
569          *                   matrix will be preconcat'ed with the param. All stages will be
570                              updated to compensate for the matrix change. If init == kReset
571                              then the draw state's matrix will be this matrix.
572          */
573         AutoStateRestore(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
574 
575         ~AutoStateRestore();
576 
577         /**
578          * Saves the state on target. The state will be restored when the ASR
579          * is destroyed. This should only be called once per ASR object and only
580          * when the default constructor was used. For nested saves use multiple
581          * ASR objects.
582          *
583          * @param init  Should the newly installed GrDrawState be a copy of the
584          *              previous state or a default-initialized GrDrawState.
585          * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
586          *                   matrix will be preconcat'ed with the param. All stages will be
587                              updated to compensate for the matrix change. If init == kReset
588                              then the draw state's matrix will be this matrix.
589          */
590         void set(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
591 
592         /**
593          * Like set() but makes the view matrix identity. When init is kReset it is as though
594          * NULL was passed to set's viewMatrix param. When init is kPreserve it is as though
595          * the inverse view matrix was passed. If kPreserve is passed and the draw state's matrix
596          * is not invertible then this may fail.
597          */
598         bool setIdentity(GrDrawTarget* target, ASRInit init);
599 
600     private:
601         GrDrawTarget*                       fDrawTarget;
602         SkTLazy<GrDrawState>                fTempState;
603         GrDrawState*                        fSavedState;
604     };
605 
606     ////////////////////////////////////////////////////////////////////////////
607 
608     class AutoReleaseGeometry : public ::SkNoncopyable {
609     public:
610         AutoReleaseGeometry(GrDrawTarget*  target,
611                             int            vertexCount,
612                             int            indexCount);
613         AutoReleaseGeometry();
614         ~AutoReleaseGeometry();
615         bool set(GrDrawTarget*  target,
616                  int            vertexCount,
617                  int            indexCount);
succeeded()618         bool succeeded() const { return NULL != fTarget; }
vertices()619         void* vertices() const { SkASSERT(this->succeeded()); return fVertices; }
indices()620         void* indices() const { SkASSERT(this->succeeded()); return fIndices; }
positions()621         SkPoint* positions() const {
622             return static_cast<SkPoint*>(this->vertices());
623         }
624 
625     private:
626         void reset();
627 
628         GrDrawTarget* fTarget;
629         void*         fVertices;
630         void*         fIndices;
631     };
632 
633     ////////////////////////////////////////////////////////////////////////////
634 
635     class AutoClipRestore : public ::SkNoncopyable {
636     public:
AutoClipRestore(GrDrawTarget * target)637         AutoClipRestore(GrDrawTarget* target) {
638             fTarget = target;
639             fClip = fTarget->getClip();
640         }
641 
642         AutoClipRestore(GrDrawTarget* target, const SkIRect& newClip);
643 
~AutoClipRestore()644         ~AutoClipRestore() {
645             fTarget->setClip(fClip);
646         }
647     private:
648         GrDrawTarget*           fTarget;
649         const GrClipData*       fClip;
650         SkTLazy<SkClipStack>    fStack;
651         GrClipData              fReplacementClip;
652     };
653 
654     ////////////////////////////////////////////////////////////////////////////
655 
656     /**
657      * Saves the geometry src state at construction and restores in the destructor. It also saves
658      * and then restores the vertex attrib state.
659      */
660     class AutoGeometryPush : public ::SkNoncopyable {
661     public:
AutoGeometryPush(GrDrawTarget * target)662         AutoGeometryPush(GrDrawTarget* target)
663             : fAttribRestore(target->drawState()) {
664             SkASSERT(NULL != target);
665             fTarget = target;
666             target->pushGeometrySource();
667         }
668 
~AutoGeometryPush()669         ~AutoGeometryPush() { fTarget->popGeometrySource(); }
670 
671     private:
672         GrDrawTarget*                           fTarget;
673         GrDrawState::AutoVertexAttribRestore    fAttribRestore;
674     };
675 
676     /**
677      * Combination of AutoGeometryPush and AutoStateRestore. The vertex attribs will be in default
678      * state regardless of ASRInit value.
679      */
680     class AutoGeometryAndStatePush : public ::SkNoncopyable {
681     public:
682         AutoGeometryAndStatePush(GrDrawTarget* target,
683                                  ASRInit init,
684                                  const SkMatrix* viewMatrix = NULL)
fState(target,init,viewMatrix)685             : fState(target, init, viewMatrix) {
686             SkASSERT(NULL != target);
687             fTarget = target;
688             target->pushGeometrySource();
689             if (kPreserve_ASRInit == init) {
690                 target->drawState()->setDefaultVertexAttribs();
691             }
692         }
693 
~AutoGeometryAndStatePush()694         ~AutoGeometryAndStatePush() { fTarget->popGeometrySource(); }
695 
696     private:
697         AutoStateRestore fState;
698         GrDrawTarget*    fTarget;
699     };
700 
701     ///////////////////////////////////////////////////////////////////////////
702     // Draw execution tracking (for font atlases and other resources)
703     class DrawToken {
704     public:
DrawToken(GrDrawTarget * drawTarget,uint32_t drawID)705         DrawToken(GrDrawTarget* drawTarget, uint32_t drawID) :
706                   fDrawTarget(drawTarget), fDrawID(drawID) {}
707 
isIssued()708         bool isIssued() { return NULL != fDrawTarget && fDrawTarget->isIssued(fDrawID); }
709 
710     private:
711         GrDrawTarget*  fDrawTarget;
712         uint32_t       fDrawID;   // this may wrap, but we're doing direct comparison
713                                   // so that should be okay
714     };
715 
getCurrentDrawToken()716     virtual DrawToken getCurrentDrawToken() { return DrawToken(this, 0); }
717 
718 protected:
719 
720     enum GeometrySrcType {
721         kNone_GeometrySrcType,     //<! src has not been specified
722         kReserved_GeometrySrcType, //<! src was set using reserve*Space
723         kArray_GeometrySrcType,    //<! src was set using set*SourceToArray
724         kBuffer_GeometrySrcType    //<! src was set using set*SourceToBuffer
725     };
726 
727     struct GeometrySrcState {
728         GeometrySrcType         fVertexSrc;
729         union {
730             // valid if src type is buffer
731             const GrVertexBuffer*   fVertexBuffer;
732             // valid if src type is reserved or array
733             int                     fVertexCount;
734         };
735 
736         GeometrySrcType         fIndexSrc;
737         union {
738             // valid if src type is buffer
739             const GrIndexBuffer*    fIndexBuffer;
740             // valid if src type is reserved or array
741             int                     fIndexCount;
742         };
743 
744         size_t                  fVertexSize;
745     };
746 
indexCountInCurrentSource()747     int indexCountInCurrentSource() const {
748         const GeometrySrcState& src = this->getGeomSrc();
749         switch (src.fIndexSrc) {
750             case kNone_GeometrySrcType:
751                 return 0;
752             case kReserved_GeometrySrcType:
753             case kArray_GeometrySrcType:
754                 return src.fIndexCount;
755             case kBuffer_GeometrySrcType:
756                 return static_cast<int>(src.fIndexBuffer->gpuMemorySize() / sizeof(uint16_t));
757             default:
758                 SkFAIL("Unexpected Index Source.");
759                 return 0;
760         }
761     }
762 
763     // This method is called by copySurface  The srcRect is guaranteed to be entirely within the
764     // src bounds. Likewise, the dst rect implied by dstPoint and srcRect's width and height falls
765     // entirely within the dst. The default implementation will draw a rect from the src to the
766     // dst if the src is a texture and the dst is a render target and fail otherwise.
767     virtual bool onCopySurface(GrSurface* dst,
768                                GrSurface* src,
769                                const SkIRect& srcRect,
770                                const SkIPoint& dstPoint);
771 
772     // Called to determine whether an onCopySurface call would succeed or not. This is useful for
773     // proxy subclasses to test whether the copy would succeed without executing it yet. Derived
774     // classes must keep this consistent with their implementation of onCopySurface(). The inputs
775     // are the same as onCopySurface(), i.e. srcRect and dstPoint are clipped to be inside the src
776     // and dst bounds.
777     virtual bool onCanCopySurface(GrSurface* dst,
778                                   GrSurface* src,
779                                   const SkIRect& srcRect,
780                                   const SkIPoint& dstPoint);
781 
getContext()782     GrContext* getContext() { return fContext; }
getContext()783     const GrContext* getContext() const { return fContext; }
784 
785     // A subclass may override this function if it wishes to be notified when the clip is changed.
786     // The override should call INHERITED::clipWillBeSet().
787     virtual void clipWillBeSet(const GrClipData* clipData);
788 
789     // subclasses must call this in their destructors to ensure all vertex
790     // and index sources have been released (including those held by
791     // pushGeometrySource())
792     void releaseGeometry();
793 
794     // accessors for derived classes
getGeomSrc()795     const GeometrySrcState& getGeomSrc() const { return fGeoSrcStateStack.back(); }
796     // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert.
getVertexSize()797     size_t getVertexSize() const {
798         // the vertex layout is only valid if a vertex source has been specified.
799         SkASSERT(this->getGeomSrc().fVertexSrc != kNone_GeometrySrcType);
800         return this->getGeomSrc().fVertexSize;
801     }
802 
803     // Subclass must initialize this in its constructor.
804     SkAutoTUnref<const GrDrawTargetCaps> fCaps;
805 
getActiveTraceMarkers()806     const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; }
807 
808     /**
809      * Used to communicate draws to subclass's onDraw function.
810      */
811     class DrawInfo {
812     public:
DrawInfo(const DrawInfo & di)813         DrawInfo(const DrawInfo& di) { (*this) = di; }
814         DrawInfo& operator =(const DrawInfo& di);
815 
primitiveType()816         GrPrimitiveType primitiveType() const { return fPrimitiveType; }
startVertex()817         int startVertex() const { return fStartVertex; }
startIndex()818         int startIndex() const { return fStartIndex; }
vertexCount()819         int vertexCount() const { return fVertexCount; }
indexCount()820         int indexCount() const { return fIndexCount; }
verticesPerInstance()821         int verticesPerInstance() const { return fVerticesPerInstance; }
indicesPerInstance()822         int indicesPerInstance() const { return fIndicesPerInstance; }
instanceCount()823         int instanceCount() const { return fInstanceCount; }
824 
isIndexed()825         bool isIndexed() const { return fIndexCount > 0; }
826 #ifdef SK_DEBUG
827         bool isInstanced() const; // this version is longer because of asserts
828 #else
isInstanced()829         bool isInstanced() const { return fInstanceCount > 0; }
830 #endif
831 
832         // adds or remove instances
833         void adjustInstanceCount(int instanceOffset);
834         // shifts the start vertex
835         void adjustStartVertex(int vertexOffset);
836         // shifts the start index
837         void adjustStartIndex(int indexOffset);
838 
setDevBounds(const SkRect & bounds)839         void setDevBounds(const SkRect& bounds) {
840             fDevBoundsStorage = bounds;
841             fDevBounds = &fDevBoundsStorage;
842         }
getDevBounds()843         const SkRect* getDevBounds() const { return fDevBounds; }
844 
845         // NULL if no copy of the dst is needed for the draw.
getDstCopy()846         const GrDeviceCoordTexture* getDstCopy() const {
847             if (NULL != fDstCopy.texture()) {
848                 return &fDstCopy;
849             } else {
850                 return NULL;
851             }
852         }
853 
854     private:
DrawInfo()855         DrawInfo() { fDevBounds = NULL; }
856 
857         friend class GrDrawTarget;
858 
859         GrPrimitiveType         fPrimitiveType;
860 
861         int                     fStartVertex;
862         int                     fStartIndex;
863         int                     fVertexCount;
864         int                     fIndexCount;
865 
866         int                     fInstanceCount;
867         int                     fVerticesPerInstance;
868         int                     fIndicesPerInstance;
869 
870         SkRect                  fDevBoundsStorage;
871         SkRect*                 fDevBounds;
872 
873         GrDeviceCoordTexture    fDstCopy;
874     };
875 
876 private:
877     // A subclass can optionally overload this function to be notified before
878     // vertex and index space is reserved.
willReserveVertexAndIndexSpace(int vertexCount,int indexCount)879     virtual void willReserveVertexAndIndexSpace(int vertexCount, int indexCount) {}
880 
881     // implemented by subclass to allocate space for reserved geom
882     virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) = 0;
883     virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
884     // implemented by subclass to handle release of reserved geom space
885     virtual void releaseReservedVertexSpace() = 0;
886     virtual void releaseReservedIndexSpace() = 0;
887     // subclass must consume array contents when set
888     virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) = 0;
889     virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) = 0;
890     // subclass is notified that geom source will be set away from an array
891     virtual void releaseVertexArray() = 0;
892     virtual void releaseIndexArray() = 0;
893     // subclass overrides to be notified just before geo src state is pushed/popped.
894     virtual void geometrySourceWillPush() = 0;
895     virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
896     // subclass called to perform drawing
897     virtual void onDraw(const DrawInfo&) = 0;
898     // Implementation of drawRect. The geometry src and vertex attribs will already
899     // be saved before this is called and restored afterwards. A subclass may override
900     // this to perform more optimal rect rendering. Its draws should be funneled through
901     // one of the public GrDrawTarget draw methods (e.g. drawNonIndexed,
902     // drawIndexedInstances, ...). The base class draws a two triangle fan using
903     // drawNonIndexed from reserved vertex space.
904     virtual void onDrawRect(const SkRect& rect,
905                             const SkMatrix* matrix,
906                             const SkRect* localRect,
907                             const SkMatrix* localMatrix);
908 
909     virtual void onStencilPath(const GrPath*, SkPath::FillType) = 0;
910     virtual void onDrawPath(const GrPath*, SkPath::FillType,
911                             const GrDeviceCoordTexture* dstCopy) = 0;
912     virtual void onDrawPaths(int, const GrPath**, const SkMatrix*,
913                              SkPath::FillType, SkStrokeRec::Style,
914                              const GrDeviceCoordTexture* dstCopy) = 0;
915 
916     virtual void didAddGpuTraceMarker() = 0;
917     virtual void didRemoveGpuTraceMarker() = 0;
918 
919     // helpers for reserving vertex and index space.
920     bool reserveVertexSpace(size_t vertexSize,
921                             int vertexCount,
922                             void** vertices);
923     bool reserveIndexSpace(int indexCount, void** indices);
924 
925     // called by drawIndexed and drawNonIndexed. Use a negative indexCount to
926     // indicate non-indexed drawing.
927     bool checkDraw(GrPrimitiveType type, int startVertex,
928                    int startIndex, int vertexCount,
929                    int indexCount) const;
930     // called when setting a new vert/idx source to unref prev vb/ib
931     void releasePreviousVertexSource();
932     void releasePreviousIndexSource();
933 
934     // Makes a copy of the dst if it is necessary for the draw. Returns false if a copy is required
935     // but couldn't be made. Otherwise, returns true.
setupDstReadIfNecessary(DrawInfo * info)936     bool setupDstReadIfNecessary(DrawInfo* info) {
937         return this->setupDstReadIfNecessary(&info->fDstCopy, info->getDevBounds());
938     }
939     bool setupDstReadIfNecessary(GrDeviceCoordTexture* dstCopy, const SkRect* drawBounds);
940 
941     // Check to see if this set of draw commands has been sent out
isIssued(uint32_t drawID)942     virtual bool       isIssued(uint32_t drawID) { return true; }
943 
944     enum {
945         kPreallocGeoSrcStateStackCnt = 4,
946     };
947     SkSTArray<kPreallocGeoSrcStateStackCnt, GeometrySrcState, true> fGeoSrcStateStack;
948     const GrClipData*                                               fClip;
949     GrDrawState*                                                    fDrawState;
950     GrDrawState                                                     fDefaultDrawState;
951     // The context owns us, not vice-versa, so this ptr is not ref'ed by DrawTarget.
952     GrContext*                                                      fContext;
953     // To keep track that we always have at least as many debug marker adds as removes
954     int                                                             fGpuTraceMarkerCount;
955     GrTraceMarkerSet                                                fActiveTraceMarkers;
956     GrTraceMarkerSet                                                fStoredTraceMarkers;
957 
958     typedef SkRefCnt INHERITED;
959 };
960 
961 #endif
962