GrDrawTarget.h revision 8dc7c3a839b38b73af34cc2674a06f49eb1ce527
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 "GrClip.h"
12#include "GrClipMaskManager.h"
13#include "GrContext.h"
14#include "GrPathProcessor.h"
15#include "GrPrimitiveProcessor.h"
16#include "GrIndexBuffer.h"
17#include "GrPathRendering.h"
18#include "GrPipelineBuilder.h"
19#include "GrTraceMarker.h"
20#include "GrVertexBuffer.h"
21
22#include "SkClipStack.h"
23#include "SkMatrix.h"
24#include "SkPath.h"
25#include "SkStrokeRec.h"
26#include "SkTArray.h"
27#include "SkTLazy.h"
28#include "SkTypes.h"
29#include "SkXfermode.h"
30
31class GrBatch;
32class GrClip;
33class GrDrawTargetCaps;
34class GrGeometryProcessor;
35class GrPath;
36class GrPathRange;
37class GrPipeline;
38
39class GrDrawTarget : public SkRefCnt {
40public:
41    SK_DECLARE_INST_COUNT(GrDrawTarget)
42
43    typedef GrPathRange::PathIndexType PathIndexType;
44    typedef GrPathRendering::PathTransformType PathTransformType;
45
46    ///////////////////////////////////////////////////////////////////////////
47
48    // The context may not be fully constructed and should not be used during GrDrawTarget
49    // construction.
50    GrDrawTarget(GrContext* context);
51    virtual ~GrDrawTarget();
52
53    /**
54     * Gets the capabilities of the draw target.
55     */
56    const GrDrawTargetCaps* caps() const { return fCaps.get(); }
57
58    /**
59     * There are two types of "sources" of geometry (vertices and indices) for
60     * draw calls made on the target. When performing an indexed draw, the
61     * indices and vertices can use different source types. Once a source is
62     * specified it can be used for multiple draws. However, the time at which
63     * the geometry data is no longer editable depends on the source type.
64     *
65     * Sometimes it is necessary to perform a draw while upstack code has
66     * already specified geometry that it isn't finished with. So there are push
67     * and pop methods. This allows the client to push the sources, draw
68     * something using alternate sources, and then pop to restore the original
69     * sources.
70     *
71     * Aside from pushes and pops, a source remains valid until another source
72     * is set or resetVertexSource / resetIndexSource is called. Drawing from
73     * a reset source is an error.
74     *
75     * The two types of sources are:
76     *
77     * 1. Reserve. This is most useful when the caller has data it must
78     *    transform before drawing and is not long-lived. The caller requests
79     *    that the draw target make room for some amount of vertex and/or index
80     *    data. The target provides ptrs to hold the vertex and/or index data.
81     *
82     *    The data is writable up until the next drawIndexed, drawNonIndexed,
83     *    drawIndexedInstances, drawRect, copySurface, or pushGeometrySource. At
84     *    this point the data is frozen and the ptrs are no longer valid.
85     *
86     *    Where the space is allocated and how it is uploaded to the GPU is
87     *    subclass-dependent.
88     *
89     * 2. Vertex and Index Buffers. This is most useful for geometry that will
90     *    is long-lived. When the data in the buffer is consumed depends on the
91     *    GrDrawTarget subclass. For deferred subclasses the caller has to
92     *    guarantee that the data is still available in the buffers at playback.
93     *    (TODO: Make this more automatic as we have done for read/write pixels)
94     */
95
96    /**
97     * Reserves space for vertices and/or indices. Zero can be specifed as
98     * either the vertex or index count if the caller desires to only reserve
99     * space for only indices or only vertices. If zero is specifed for
100     * vertexCount then the vertex source will be unmodified and likewise for
101     * indexCount.
102     *
103     * If the function returns true then the reserve suceeded and the vertices
104     * and indices pointers will point to the space created.
105     *
106     * If the target cannot make space for the request then this function will
107     * return false. If vertexCount was non-zero then upon failure the vertex
108     * source is reset and likewise for indexCount.
109     *
110     * The pointers to the space allocated for vertices and indices remain valid
111     * until a drawIndexed, drawNonIndexed, drawIndexedInstances, drawRect,
112     * copySurface, or push/popGeomtrySource is called. At that point logically a
113     * snapshot of the data is made and the pointers are invalid.
114     *
115     * @param vertexCount  the number of vertices to reserve space for. Can be
116     *                     0. Vertex size is queried from the current GrPipelineBuilder.
117     * @param indexCount   the number of indices to reserve space for. Can be 0.
118     * @param vertices     will point to reserved vertex space if vertexCount is
119     *                     non-zero. Illegal to pass NULL if vertexCount > 0.
120     * @param indices      will point to reserved index space if indexCount is
121     *                     non-zero. Illegal to pass NULL if indexCount > 0.
122     */
123     bool reserveVertexAndIndexSpace(int vertexCount,
124                                     size_t vertexStride,
125                                     int indexCount,
126                                     void** vertices,
127                                     void** indices);
128
129    /**
130     * Provides hints to caller about the number of vertices and indices
131     * that can be allocated cheaply. This can be useful if caller is reserving
132     * space but doesn't know exactly how much geometry is needed.
133     *
134     * Also may hint whether the draw target should be flushed first. This is
135     * useful for deferred targets.
136     *
137     * @param vertexCount  in: hint about how many vertices the caller would
138     *                     like to allocate. Vertex size is queried from the
139     *                     current GrPipelineBuilder.
140     *                     out: a hint about the number of vertices that can be
141     *                     allocated cheaply. Negative means no hint.
142     *                     Ignored if NULL.
143     * @param indexCount   in: hint about how many indices the caller would
144     *                     like to allocate.
145     *                     out: a hint about the number of indices that can be
146     *                     allocated cheaply. Negative means no hint.
147     *                     Ignored if NULL.
148     *
149     * @return  true if target should be flushed based on the input values.
150     */
151    virtual bool geometryHints(size_t vertexStride, int* vertexCount, int* indexCount) const;
152
153    /**
154     * Sets source of vertex data for the next draw. Data does not have to be
155     * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances.
156     *
157     * @param buffer        vertex buffer containing vertex data. Must be
158     *                      unlocked before draw call. Vertex size is queried
159     *                      from current GrPipelineBuilder.
160     */
161    void setVertexSourceToBuffer(const GrVertexBuffer* buffer, size_t vertexStride);
162
163    /**
164     * Sets source of index data for the next indexed draw. Data does not have
165     * to be in the buffer until drawIndexed.
166     *
167     * @param buffer index buffer containing indices. Must be unlocked
168     *               before indexed draw call.
169     */
170    void setIndexSourceToBuffer(const GrIndexBuffer* buffer);
171
172    /**
173     * Resets vertex source. Drawing from reset vertices is illegal. Set vertex
174     * source to reserved, array, or buffer before next draw. May be able to free
175     * up temporary storage allocated by setVertexSourceToArray or
176     * reserveVertexSpace.
177     */
178    void resetVertexSource();
179
180    /**
181     * Resets index source. Indexed Drawing from reset indices is illegal. Set
182     * index source to reserved, array, or buffer before next indexed draw. May
183     * be able to free up temporary storage allocated by setIndexSourceToArray
184     * or reserveIndexSpace.
185     */
186    void resetIndexSource();
187
188    /**
189     * Query to find out if the vertex or index source is reserved.
190     */
191    bool hasReservedVerticesOrIndices() const {
192        return kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc ||
193        kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc;
194    }
195
196    /**
197     * Pushes and resets the vertex/index sources. Any reserved vertex / index
198     * data is finalized (i.e. cannot be updated after the matching pop but can
199     * be drawn from). Must be balanced by a pop.
200     */
201    void pushGeometrySource();
202
203    /**
204     * Pops the vertex / index sources from the matching push.
205     */
206    void popGeometrySource();
207
208    /**
209     * Draws indexed geometry using the current state and current vertex / index
210     * sources.
211     *
212     * @param type         The type of primitives to draw.
213     * @param startVertex  the vertex in the vertex array/buffer corresponding
214     *                     to index 0
215     * @param startIndex   first index to read from index src.
216     * @param vertexCount  one greater than the max index.
217     * @param indexCount   the number of index elements to read. The index count
218     *                     is effectively trimmed to the last completely
219     *                     specified primitive.
220     * @param devBounds    optional bounds hint. This is a promise from the caller,
221     *                     not a request for clipping.
222     */
223    void drawIndexed(GrPipelineBuilder*,
224                     const GrGeometryProcessor*,
225                     GrPrimitiveType type,
226                     int startVertex,
227                     int startIndex,
228                     int vertexCount,
229                     int indexCount,
230                     const SkRect* devBounds = NULL);
231
232    /**
233     * Draws non-indexed geometry using the current state and current vertex
234     * sources.
235     *
236     * @param type         The type of primitives to draw.
237     * @param startVertex  the vertex in the vertex array/buffer corresponding
238     *                     to index 0
239     * @param vertexCount  one greater than the max index.
240     * @param devBounds    optional bounds hint. This is a promise from the caller,
241     *                     not a request for clipping.
242     */
243    void drawNonIndexed(GrPipelineBuilder*,
244                        const GrGeometryProcessor*,
245                        GrPrimitiveType type,
246                        int startVertex,
247                        int vertexCount,
248                        const SkRect* devBounds = NULL);
249
250    // TODO devbounds should live on the batch
251    void drawBatch(GrPipelineBuilder*, GrBatch*, const SkRect* devBounds = NULL);
252
253    /**
254     * Draws path into the stencil buffer. The fill must be either even/odd or
255     * winding (not inverse or hairline). It will respect the HW antialias flag
256     * on the GrPipelineBuilder (if possible in the 3D API).  Note, we will never have an inverse
257     * fill with stencil path
258     */
259    void stencilPath(GrPipelineBuilder*, const GrPathProcessor*, const GrPath*,
260                     GrPathRendering::FillType);
261
262    /**
263     * Draws a path. Fill must not be a hairline. It will respect the HW
264     * antialias flag on the GrPipelineBuilder (if possible in the 3D API).
265     */
266    void drawPath(GrPipelineBuilder*, const GrPathProcessor*, const GrPath*,
267                  GrPathRendering::FillType);
268
269    /**
270     * Draws the aggregate path from combining multiple. Note that this will not
271     * always be equivalent to back-to-back calls to drawPath(). It will respect
272     * the HW antialias flag on the GrPipelineBuilder (if possible in the 3D API).
273     *
274     * @param pathRange       Source paths to draw from
275     * @param indices         Array of path indices to draw
276     * @param indexType       Data type of the array elements in indexBuffer
277     * @param transformValues Array of transforms for the individual paths
278     * @param transformType   Type of transforms in transformBuffer
279     * @param count           Number of paths to draw
280     * @param fill            Fill type for drawing all the paths
281     */
282    void drawPaths(GrPipelineBuilder*,
283                   const GrPathProcessor*,
284                   const GrPathRange* pathRange,
285                   const void* indices,
286                   PathIndexType indexType,
287                   const float transformValues[],
288                   PathTransformType transformType,
289                   int count,
290                   GrPathRendering::FillType fill);
291
292    /**
293     * Helper function for drawing rects. It performs a geometry src push and pop
294     * and thus will finalize any reserved geometry.
295     *
296     * @param rect        the rect to draw
297     * @param localRect   optional rect that specifies local coords to map onto
298     *                    rect. If NULL then rect serves as the local coords.
299     * @param localMatrix Optional local matrix. The local coordinates are specified by localRect,
300     *                    or if it is NULL by rect. This matrix applies to the coordinate implied by
301     *                    that rectangle before it is input to GrCoordTransforms that read local
302     *                    coordinates
303     */
304    void drawRect(GrPipelineBuilder* pipelineBuilder,
305                  GrColor color,
306                  const SkMatrix& viewMatrix,
307                  const SkRect& rect,
308                  const SkRect* localRect,
309                  const SkMatrix* localMatrix) {
310        this->onDrawRect(pipelineBuilder, color, viewMatrix, rect, localRect, localMatrix);
311    }
312
313    /**
314     * Helper for drawRect when the caller doesn't need separate local rects or matrices.
315     */
316    void drawSimpleRect(GrPipelineBuilder* ds, GrColor color, const SkMatrix& viewM,
317                        const SkRect& rect) {
318        this->drawRect(ds, color, viewM, rect, NULL, NULL);
319    }
320    void drawSimpleRect(GrPipelineBuilder* ds, GrColor color, const SkMatrix& viewM,
321                        const SkIRect& irect) {
322        SkRect rect = SkRect::Make(irect);
323        this->drawRect(ds, color, viewM, rect, NULL, NULL);
324    }
325
326    /**
327     * This call is used to draw multiple instances of some geometry with a
328     * given number of vertices (V) and indices (I) per-instance. The indices in
329     * the index source must have the form i[k+I] == i[k] + V. Also, all indices
330     * i[kI] ... i[(k+1)I-1] must be elements of the range kV ... (k+1)V-1. As a
331     * concrete example, the following index buffer for drawing a series of
332     * quads each as two triangles each satisfies these conditions with V=4 and
333     * I=6:
334     *      (0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, ...)
335     *
336     * The call assumes that the pattern of indices fills the entire index
337     * source. The size of the index buffer limits the number of instances that
338     * can be drawn by the GPU in a single draw. However, the caller may specify
339     * any (positive) number for instanceCount and if necessary multiple GPU
340     * draws will be issued. Moreover, when drawIndexedInstances is called
341     * multiple times it may be possible for GrDrawTarget to group them into a
342     * single GPU draw.
343     *
344     * @param type          the type of primitives to draw
345     * @param instanceCount the number of instances to draw. Each instance
346     *                      consists of verticesPerInstance vertices indexed by
347     *                      indicesPerInstance indices drawn as the primitive
348     *                      type specified by type.
349     * @param verticesPerInstance   The number of vertices in each instance (V
350     *                              in the above description).
351     * @param indicesPerInstance    The number of indices in each instance (I
352     *                              in the above description).
353     * @param devBounds    optional bounds hint. This is a promise from the caller,
354     *                     not a request for clipping.
355     */
356    void drawIndexedInstances(GrPipelineBuilder*,
357                              const GrGeometryProcessor*,
358                              GrPrimitiveType type,
359                              int instanceCount,
360                              int verticesPerInstance,
361                              int indicesPerInstance,
362                              const SkRect* devBounds = NULL);
363
364    /**
365     * Clear the passed in render target. Ignores the GrPipelineBuilder and clip. Clears the whole
366     * thing if rect is NULL, otherwise just the rect. If canIgnoreRect is set then the entire
367     * render target can be optionally cleared.
368     */
369    void clear(const SkIRect* rect,
370               GrColor color,
371               bool canIgnoreRect,
372               GrRenderTarget* renderTarget);
373
374    /**
375     * Discards the contents render target.
376     **/
377    virtual void discard(GrRenderTarget*) = 0;
378
379    /**
380     * Called at start and end of gpu trace marking
381     * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start
382     * and end of a code block respectively
383     */
384    void addGpuTraceMarker(const GrGpuTraceMarker* marker);
385    void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
386
387    /**
388     * Takes the current active set of markers and stores them for later use. Any current marker
389     * in the active set is removed from the active set and the targets remove function is called.
390     * These functions do not work as a stack so you cannot call save a second time before calling
391     * restore. Also, it is assumed that when restore is called the current active set of markers
392     * is empty. When the stored markers are added back into the active set, the targets add marker
393     * is called.
394     */
395    void saveActiveTraceMarkers();
396    void restoreActiveTraceMarkers();
397
398    /**
399     * Copies a pixel rectangle from one surface to another. This call may finalize
400     * reserved vertex/index data (as though a draw call was made). The src pixels
401     * copied are specified by srcRect. They are copied to a rect of the same
402     * size in dst with top left at dstPoint. If the src rect is clipped by the
403     * src bounds then  pixel values in the dst rect corresponding to area clipped
404     * by the src rect are not overwritten. This method can fail and return false
405     * depending on the type of surface, configs, etc, and the backend-specific
406     * limitations. If rect is clipped out entirely by the src or dst bounds then
407     * true is returned since there is no actual copy necessary to succeed.
408     */
409    bool copySurface(GrSurface* dst,
410                     GrSurface* src,
411                     const SkIRect& srcRect,
412                     const SkIPoint& dstPoint);
413    /**
414     * Function that determines whether a copySurface call would succeed without actually
415     * performing the copy.
416     */
417    bool canCopySurface(const GrSurface* dst,
418                        const GrSurface* src,
419                        const SkIRect& srcRect,
420                        const SkIPoint& dstPoint);
421
422    /**
423     * Release any resources that are cached but not currently in use. This
424     * is intended to give an application some recourse when resources are low.
425     */
426    virtual void purgeResources() {};
427
428    ////////////////////////////////////////////////////////////////////////////
429
430    class AutoReleaseGeometry : public ::SkNoncopyable {
431    public:
432        AutoReleaseGeometry(GrDrawTarget*  target,
433                            int            vertexCount,
434                            size_t         vertexStride,
435                            int            indexCount);
436        AutoReleaseGeometry();
437        ~AutoReleaseGeometry();
438        bool set(GrDrawTarget*  target,
439                 int            vertexCount,
440                 size_t         vertexStride,
441                 int            indexCount);
442        bool succeeded() const { return SkToBool(fTarget); }
443        void* vertices() const { SkASSERT(this->succeeded()); return fVertices; }
444        void* indices() const { SkASSERT(this->succeeded()); return fIndices; }
445        SkPoint* positions() const {
446            return static_cast<SkPoint*>(this->vertices());
447        }
448
449    private:
450        void reset();
451
452        GrDrawTarget* fTarget;
453        void*         fVertices;
454        void*         fIndices;
455    };
456
457    ////////////////////////////////////////////////////////////////////////////
458
459    /**
460     * Saves the geometry src state at construction and restores in the destructor. It also saves
461     * and then restores the vertex attrib state.
462     */
463    class AutoGeometryPush : public ::SkNoncopyable {
464    public:
465        AutoGeometryPush(GrDrawTarget* target) {
466            SkASSERT(target);
467            fTarget = target;
468            target->pushGeometrySource();
469        }
470
471        ~AutoGeometryPush() { fTarget->popGeometrySource(); }
472
473    private:
474        GrDrawTarget*                           fTarget;
475    };
476
477    ///////////////////////////////////////////////////////////////////////////
478    // Draw execution tracking (for font atlases and other resources)
479    class DrawToken {
480    public:
481        DrawToken(GrDrawTarget* drawTarget, uint32_t drawID) :
482                  fDrawTarget(drawTarget), fDrawID(drawID) {}
483
484        bool isIssued() { return fDrawTarget && fDrawTarget->isIssued(fDrawID); }
485
486    private:
487        GrDrawTarget*  fDrawTarget;
488        uint32_t       fDrawID;   // this may wrap, but we're doing direct comparison
489                                  // so that should be okay
490    };
491
492    virtual DrawToken getCurrentDrawToken() { return DrawToken(this, 0); }
493
494    /**
495     * Used to communicate draws to GPUs / subclasses
496     */
497    class DrawInfo {
498    public:
499        DrawInfo() { fDevBounds = NULL; }
500        DrawInfo(const DrawInfo& di) { (*this) = di; }
501        DrawInfo& operator =(const DrawInfo& di);
502
503        GrPrimitiveType primitiveType() const { return fPrimitiveType; }
504        int startVertex() const { return fStartVertex; }
505        int startIndex() const { return fStartIndex; }
506        int vertexCount() const { return fVertexCount; }
507        int indexCount() const { return fIndexCount; }
508        int verticesPerInstance() const { return fVerticesPerInstance; }
509        int indicesPerInstance() const { return fIndicesPerInstance; }
510        int instanceCount() const { return fInstanceCount; }
511
512        void setPrimitiveType(GrPrimitiveType type) { fPrimitiveType = type; }
513        void setStartVertex(int startVertex) { fStartVertex = startVertex; }
514        void setStartIndex(int startIndex) { fStartIndex = startIndex; }
515        void setVertexCount(int vertexCount) { fVertexCount = vertexCount; }
516        void setIndexCount(int indexCount) { fIndexCount = indexCount; }
517        void setVerticesPerInstance(int verticesPerI) { fVerticesPerInstance = verticesPerI; }
518        void setIndicesPerInstance(int indicesPerI) { fIndicesPerInstance = indicesPerI; }
519        void setInstanceCount(int instanceCount) { fInstanceCount = instanceCount; }
520
521        bool isIndexed() const { return fIndexCount > 0; }
522#ifdef SK_DEBUG
523        bool isInstanced() const; // this version is longer because of asserts
524#else
525        bool isInstanced() const { return fInstanceCount > 0; }
526#endif
527
528        // adds or remove instances
529        void adjustInstanceCount(int instanceOffset);
530        // shifts the start vertex
531        void adjustStartVertex(int vertexOffset);
532        // shifts the start index
533        void adjustStartIndex(int indexOffset);
534
535        void setDevBounds(const SkRect& bounds) {
536            fDevBoundsStorage = bounds;
537            fDevBounds = &fDevBoundsStorage;
538        }
539        const GrVertexBuffer* vertexBuffer() const { return fVertexBuffer.get(); }
540        const GrIndexBuffer* indexBuffer() const { return fIndexBuffer.get(); }
541        void setVertexBuffer(const GrVertexBuffer* vb) {
542            fVertexBuffer.reset(vb);
543        }
544        void setIndexBuffer(const GrIndexBuffer* ib) {
545            fIndexBuffer.reset(ib);
546        }
547        const SkRect* getDevBounds() const { return fDevBounds; }
548
549    private:
550        friend class GrDrawTarget;
551
552        GrPrimitiveType         fPrimitiveType;
553
554        int                     fStartVertex;
555        int                     fStartIndex;
556        int                     fVertexCount;
557        int                     fIndexCount;
558
559        int                     fInstanceCount;
560        int                     fVerticesPerInstance;
561        int                     fIndicesPerInstance;
562
563        SkRect                  fDevBoundsStorage;
564        SkRect*                 fDevBounds;
565
566        GrPendingIOResource<const GrVertexBuffer, kRead_GrIOType> fVertexBuffer;
567        GrPendingIOResource<const GrIndexBuffer, kRead_GrIOType>  fIndexBuffer;
568    };
569
570    /**
571     * Used to populate the vertex and index buffer on the draw info before onDraw is called.
572     */
573    virtual void setDrawBuffers(DrawInfo*, size_t vertexStride) = 0;;
574    bool programUnitTest(int maxStages);
575
576protected:
577    friend class GrTargetCommands; // for PipelineInfo
578
579    enum GeometrySrcType {
580        kNone_GeometrySrcType,     //<! src has not been specified
581        kReserved_GeometrySrcType, //<! src was set using reserve*Space
582        kBuffer_GeometrySrcType    //<! src was set using set*SourceToBuffer
583    };
584
585    struct GeometrySrcState {
586        GeometrySrcType         fVertexSrc;
587        union {
588            // valid if src type is buffer
589            const GrVertexBuffer*   fVertexBuffer;
590            // valid if src type is reserved or array
591            int                     fVertexCount;
592        };
593
594        GeometrySrcType         fIndexSrc;
595        union {
596            // valid if src type is buffer
597            const GrIndexBuffer*    fIndexBuffer;
598            // valid if src type is reserved or array
599            int                     fIndexCount;
600        };
601
602        size_t                  fVertexSize;
603    };
604
605    int indexCountInCurrentSource() const {
606        const GeometrySrcState& src = this->getGeomSrc();
607        switch (src.fIndexSrc) {
608            case kNone_GeometrySrcType:
609                return 0;
610            case kReserved_GeometrySrcType:
611                return src.fIndexCount;
612            case kBuffer_GeometrySrcType:
613                return static_cast<int>(src.fIndexBuffer->gpuMemorySize() / sizeof(uint16_t));
614            default:
615                SkFAIL("Unexpected Index Source.");
616                return 0;
617        }
618    }
619
620    GrContext* getContext() { return fContext; }
621    const GrContext* getContext() const { return fContext; }
622
623    // subclasses must call this in their destructors to ensure all vertex
624    // and index sources have been released (including those held by
625    // pushGeometrySource())
626    void releaseGeometry();
627
628    // accessors for derived classes
629    const GeometrySrcState& getGeomSrc() const { return fGeoSrcStateStack.back(); }
630    // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert.
631    size_t getVertexSize() const {
632        // the vertex layout is only valid if a vertex source has been specified.
633        SkASSERT(this->getGeomSrc().fVertexSrc != kNone_GeometrySrcType);
634        return this->getGeomSrc().fVertexSize;
635    }
636
637    // Subclass must initialize this in its constructor.
638    SkAutoTUnref<const GrDrawTargetCaps> fCaps;
639
640    const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; }
641
642    // Makes a copy of the dst if it is necessary for the draw. Returns false if a copy is required
643    // but couldn't be made. Otherwise, returns true.  This method needs to be protected because it
644    // needs to be accessed by GLPrograms to setup a correct drawstate
645    bool setupDstReadIfNecessary(const GrPipelineBuilder&,
646                                 const GrProcOptInfo& colorPOI,
647                                 const GrProcOptInfo& coveragePOI,
648                                 GrDeviceCoordTexture* dstCopy,
649                                 const SkRect* drawBounds);
650
651    struct PipelineInfo {
652        PipelineInfo(GrPipelineBuilder* pipelineBuilder, GrScissorState* scissor,
653                     const GrPrimitiveProcessor* primProc,
654                     const SkRect* devBounds, GrDrawTarget* target);
655
656        PipelineInfo(GrPipelineBuilder* pipelineBuilder, GrScissorState* scissor,
657                     const GrBatch* batch, const SkRect* devBounds,
658                     GrDrawTarget* target);
659
660        bool willBlendWithDst(const GrPrimitiveProcessor* primProc) const {
661            return fPipelineBuilder->willBlendWithDst(primProc);
662        }
663    private:
664        friend class GrDrawTarget;
665
666        bool mustSkipDraw() const { return (NULL == fPipelineBuilder); }
667
668        GrPipelineBuilder*      fPipelineBuilder;
669        GrScissorState*         fScissor;
670        GrProcOptInfo           fColorPOI;
671        GrProcOptInfo           fCoveragePOI;
672        GrDeviceCoordTexture    fDstCopy;
673    };
674
675    void setupPipeline(const PipelineInfo& pipelineInfo, GrPipeline* pipeline);
676
677    // A subclass can optionally overload this function to be notified before
678    // vertex and index space is reserved.
679    virtual void willReserveVertexAndIndexSpace(int vertexCount,
680                                                size_t vertexStride,
681                                                int indexCount) {}
682
683private:
684    /**
685     * This will be called before allocating a texture as a dst for copySurface. This function
686     * populates the dstDesc's config, flags, and origin so as to maximize efficiency and guarantee
687     * success of the copySurface call.
688     */
689    void initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* dstDesc) {
690        if (!this->onInitCopySurfaceDstDesc(src, dstDesc)) {
691            dstDesc->fOrigin = kDefault_GrSurfaceOrigin;
692            dstDesc->fFlags = kRenderTarget_GrSurfaceFlag;
693            dstDesc->fConfig = src->config();
694        }
695    }
696
697    /** Internal implementation of canCopySurface. */
698    bool internalCanCopySurface(const GrSurface* dst,
699                                const GrSurface* src,
700                                const SkIRect& clippedSrcRect,
701                                const SkIPoint& clippedDstRect);
702
703    // implemented by subclass to allocate space for reserved geom
704    virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) = 0;
705    virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
706    // implemented by subclass to handle release of reserved geom space
707    virtual void releaseReservedVertexSpace() = 0;
708    virtual void releaseReservedIndexSpace() = 0;
709    // subclass overrides to be notified just before geo src state is pushed/popped.
710    virtual void geometrySourceWillPush() = 0;
711    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
712    // subclass called to perform drawing
713    virtual void onDraw(const GrGeometryProcessor*, const DrawInfo&, const PipelineInfo&) = 0;
714    virtual void onDrawBatch(GrBatch*, const PipelineInfo&) = 0;
715    // TODO copy in order drawbuffer onDrawRect to here
716    virtual void onDrawRect(GrPipelineBuilder*,
717                            GrColor color,
718                            const SkMatrix& viewMatrix,
719                            const SkRect& rect,
720                            const SkRect* localRect,
721                            const SkMatrix* localMatrix) = 0;
722
723    virtual void onStencilPath(const GrPipelineBuilder&,
724                               const GrPathProcessor*,
725                               const GrPath*,
726                               const GrScissorState&,
727                               const GrStencilSettings&) = 0;
728    virtual void onDrawPath(const GrPathProcessor*,
729                            const GrPath*,
730                            const GrStencilSettings&,
731                            const PipelineInfo&) = 0;
732    virtual void onDrawPaths(const GrPathProcessor*,
733                             const GrPathRange*,
734                             const void* indices,
735                             PathIndexType,
736                             const float transformValues[],
737                             PathTransformType,
738                             int count,
739                             const GrStencilSettings&,
740                             const PipelineInfo&) = 0;
741
742    virtual void onClear(const SkIRect* rect, GrColor color, bool canIgnoreRect,
743                         GrRenderTarget* renderTarget) = 0;
744
745    /** The subclass will get a chance to copy the surface for falling back to the default
746        implementation, which simply draws a rectangle (and fails if dst isn't a render target). It
747        should assume that any clipping has already been performed on the rect and point. It won't
748        be called if the copy can be skipped. */
749    virtual bool onCopySurface(GrSurface* dst,
750                               GrSurface* src,
751                               const SkIRect& srcRect,
752                               const SkIPoint& dstPoint) = 0;
753
754    /** Indicates whether onCopySurface would succeed. It should assume that any clipping has
755        already been performed on the rect and point. It won't be called if the copy can be
756        skipped. */
757    virtual bool onCanCopySurface(const GrSurface* dst,
758                                  const GrSurface* src,
759                                  const SkIRect& srcRect,
760                                  const SkIPoint& dstPoint) = 0;
761    /**
762     * This will be called before allocating a texture to be a dst for onCopySurface. Only the
763     * dstDesc's config, flags, and origin need be set by the function. If the subclass cannot
764     * create a surface that would succeed its implementation of onCopySurface, it should return
765     * false. The base class will fall back to creating a render target to draw into using the src.
766     */
767    virtual bool onInitCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* dstDesc) = 0;
768
769    // helpers for reserving vertex and index space.
770    bool reserveVertexSpace(size_t vertexSize,
771                            int vertexCount,
772                            void** vertices);
773    bool reserveIndexSpace(int indexCount, void** indices);
774
775    // called by drawIndexed and drawNonIndexed. Use a negative indexCount to
776    // indicate non-indexed drawing.
777    bool checkDraw(const GrPipelineBuilder&,
778                   const GrGeometryProcessor*,
779                   GrPrimitiveType type,
780                   int startVertex,
781                   int startIndex,
782                   int vertexCount,
783                   int indexCount) const;
784    // called when setting a new vert/idx source to unref prev vb/ib
785    void releasePreviousVertexSource();
786    void releasePreviousIndexSource();
787
788    // Check to see if this set of draw commands has been sent out
789    virtual bool       isIssued(uint32_t drawID) { return true; }
790    void getPathStencilSettingsForFilltype(GrPathRendering::FillType,
791                                           const GrStencilAttachment*,
792                                           GrStencilSettings*);
793    virtual GrClipMaskManager* clipMaskManager() = 0;
794    virtual bool setupClip(GrPipelineBuilder*,
795                           GrPipelineBuilder::AutoRestoreFragmentProcessors*,
796                           GrPipelineBuilder::AutoRestoreStencil*,
797                           GrScissorState*,
798                           const SkRect* devBounds) = 0;
799
800    enum {
801        kPreallocGeoSrcStateStackCnt = 4,
802    };
803    SkSTArray<kPreallocGeoSrcStateStackCnt, GeometrySrcState, true> fGeoSrcStateStack;
804    // The context owns us, not vice-versa, so this ptr is not ref'ed by DrawTarget.
805    GrContext*                                                      fContext;
806    // To keep track that we always have at least as many debug marker adds as removes
807    int                                                             fGpuTraceMarkerCount;
808    GrTraceMarkerSet                                                fActiveTraceMarkers;
809    GrTraceMarkerSet                                                fStoredTraceMarkers;
810
811    typedef SkRefCnt INHERITED;
812};
813
814/*
815 * This class is JUST for clip mask manager.  Everyone else should just use draw target above.
816 */
817class GrClipTarget : public GrDrawTarget {
818public:
819    GrClipTarget(GrContext* context) : INHERITED(context) {
820        fClipMaskManager.setClipTarget(this);
821    }
822
823    /* Clip mask manager needs access to the context.
824     * TODO we only need a very small subset of context in the CMM.
825     */
826    GrContext* getContext() { return INHERITED::getContext(); }
827    const GrContext* getContext() const { return INHERITED::getContext(); }
828
829    /**
830     * Clip Mask Manager(and no one else) needs to clear private stencil bits.
831     * ClipTarget subclass sets clip bit in the stencil buffer. The subclass
832     * is free to clear the remaining bits to zero if masked clears are more
833     * expensive than clearing all bits.
834     */
835    virtual void clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* = NULL) = 0;
836
837    /**
838     * Release any resources that are cached but not currently in use. This
839     * is intended to give an application some recourse when resources are low.
840     */
841    void purgeResources() override {
842        // The clip mask manager can rebuild all its clip masks so just
843        // get rid of them all.
844        fClipMaskManager.purgeResources();
845    };
846
847protected:
848    GrClipMaskManager           fClipMaskManager;
849
850private:
851    GrClipMaskManager* clipMaskManager() override { return &fClipMaskManager; }
852
853    virtual bool setupClip(GrPipelineBuilder*,
854                           GrPipelineBuilder::AutoRestoreFragmentProcessors*,
855                           GrPipelineBuilder::AutoRestoreStencil*,
856                           GrScissorState* scissorState,
857                           const SkRect* devBounds) override;
858
859    typedef GrDrawTarget INHERITED;
860};
861
862#endif
863