2 * Copyright 2010 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef GrDrawTarget_DEFINED
9 #define GrDrawTarget_DEFINED
11 #include "GrClipData.h"
12 #include "GrContext.h"
13 #include "GrDrawState.h"
14 #include "GrIndexBuffer.h"
15 #include "GrPathRendering.h"
16 #include "GrTraceMarker.h"
18 #include "SkClipStack.h"
21 #include "SkStrokeRec.h"
25 #include "SkXfermode.h"
28 class GrDrawTargetCaps;
33 class GrDrawTarget : public SkRefCnt {
38 SK_DECLARE_INST_COUNT(GrDrawTarget)
41 typedef GrPathRendering::PathTransformType PathTransformType ;
43 ///////////////////////////////////////////////////////////////////////////
45 // The context may not be fully constructed and should not be used during GrDrawTarget
47 GrDrawTarget(GrContext* context);
48 virtual ~GrDrawTarget();
51 * Gets the capabilities of the draw target.
53 const GrDrawTargetCaps* caps() const { return fCaps.get(); }
56 * Sets the current clip to the region specified by clip. All draws will be
57 * clipped against this clip if kClip_StateBit is enabled.
59 * Setting the clip may (or may not) zero out the client's stencil bits.
61 * @param description of the clipping region
63 void setClip(const GrClipData* clip);
66 * Gets the current clip.
70 const GrClipData* getClip() const;
73 * Sets the draw state object for the draw target. Note that this does not
74 * make a copy. The GrDrawTarget will take a reference to passed object.
75 * Passing NULL will cause the GrDrawTarget to use its own internal draw
76 * state object rather than an externally provided one.
78 void setDrawState(GrDrawState* drawState);
81 * Read-only access to the GrDrawTarget's current draw state.
83 const GrDrawState& getDrawState() const { return *fDrawState; }
86 * Read-write access to the GrDrawTarget's current draw state. Note that
89 GrDrawState* drawState() { return fDrawState; }
91 /** When we're using coverage AA but the blend is incompatible (given gpu
92 * limitations) we should disable AA. */
93 bool shouldDisableCoverageAAForBlend() const {
94 // Enable below if we should draw with AA even when it produces
95 // incorrect blending.
97 return !this->getDrawState().couldApplyCoverage(*this->caps());
101 * There are three types of "sources" of geometry (vertices and indices) for
102 * draw calls made on the target. When performing an indexed draw, the
103 * indices and vertices can use different source types. Once a source is
104 * specified it can be used for multiple draws. However, the time at which
105 * the geometry data is no longer editable depends on the source type.
107 * Sometimes it is necessary to perform a draw while upstack code has
108 * already specified geometry that it isn't finished with. So there are push
109 * and pop methods. This allows the client to push the sources, draw
110 * something using alternate sources, and then pop to restore the original
113 * Aside from pushes and pops, a source remains valid until another source
114 * is set or resetVertexSource / resetIndexSource is called. Drawing from
115 * a reset source is an error.
117 * The three types of sources are:
119 * 1. A cpu array (set*SourceToArray). This is useful when the caller
120 * already provided vertex data in a format compatible with a
121 * GrVertexLayout. The data in the array is consumed at the time that
122 * set*SourceToArray is called and subsequent edits to the array will not
123 * be reflected in draws.
125 * 2. Reserve. This is most useful when the caller has data it must
126 * transform before drawing and is not long-lived. The caller requests
127 * that the draw target make room for some amount of vertex and/or index
128 * data. The target provides ptrs to hold the vertex and/or index data.
130 * The data is writable up until the next drawIndexed, drawNonIndexed,
131 * drawIndexedInstances, drawRect, copySurface, or pushGeometrySource. At
132 * this point the data is frozen and the ptrs are no longer valid.
134 * Where the space is allocated and how it is uploaded to the GPU is
135 * subclass-dependent.
137 * 3. Vertex and Index Buffers. This is most useful for geometry that will
138 * is long-lived. When the data in the buffer is consumed depends on the
139 * GrDrawTarget subclass. For deferred subclasses the caller has to
140 * guarantee that the data is still available in the buffers at playback.
141 * (TODO: Make this more automatic as we have done for read/write pixels)
143 * The size of each vertex is determined by querying the current GrDrawState.
147 * Reserves space for vertices and/or indices. Zero can be specifed as
148 * either the vertex or index count if the caller desires to only reserve
149 * space for only indices or only vertices. If zero is specifed for
150 * vertexCount then the vertex source will be unmodified and likewise for
153 * If the function returns true then the reserve suceeded and the vertices
154 * and indices pointers will point to the space created.
156 * If the target cannot make space for the request then this function will
157 * return false. If vertexCount was non-zero then upon failure the vertex
158 * source is reset and likewise for indexCount.
160 * The pointers to the space allocated for vertices and indices remain valid
161 * until a drawIndexed, drawNonIndexed, drawIndexedInstances, drawRect,
162 * copySurface, or push/popGeomtrySource is called. At that point logically a
163 * snapshot of the data is made and the pointers are invalid.
165 * @param vertexCount the number of vertices to reserve space for. Can be
166 * 0. Vertex size is queried from the current GrDrawState.
167 * @param indexCount the number of indices to reserve space for. Can be 0.
168 * @param vertices will point to reserved vertex space if vertexCount is
169 * non-zero. Illegal to pass NULL if vertexCount > 0.
170 * @param indices will point to reserved index space if indexCount is
171 * non-zero. Illegal to pass NULL if indexCount > 0.
173 bool reserveVertexAndIndexSpace(int vertexCount,
179 * Provides hints to caller about the number of vertices and indices
180 * that can be allocated cheaply. This can be useful if caller is reserving
181 * space but doesn't know exactly how much geometry is needed.
183 * Also may hint whether the draw target should be flushed first. This is
184 * useful for deferred targets.
186 * @param vertexCount in: hint about how many vertices the caller would
187 * like to allocate. Vertex size is queried from the
188 * current GrDrawState.
189 * out: a hint about the number of vertices that can be
190 * allocated cheaply. Negative means no hint.
192 * @param indexCount in: hint about how many indices the caller would
194 * out: a hint about the number of indices that can be
195 * allocated cheaply. Negative means no hint.
198 * @return true if target should be flushed based on the input values.
200 virtual bool geometryHints(int* vertexCount,
201 int* indexCount) const;
204 * Sets source of vertex data for the next draw. Array must contain
205 * the vertex data when this is called.
207 * @param vertexArray cpu array containing vertex data.
208 * @param vertexCount the number of vertices in the array. Vertex size is
209 * queried from the current GrDrawState.
211 void setVertexSourceToArray(const void* vertexArray, int vertexCount);
214 * Sets source of index data for the next indexed draw. Array must contain
215 * the indices when this is called.
217 * @param indexArray cpu array containing index data.
218 * @param indexCount the number of indices in the array.
220 void setIndexSourceToArray(const void* indexArray, int indexCount);
223 * Sets source of vertex data for the next draw. Data does not have to be
224 * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances.
226 * @param buffer vertex buffer containing vertex data. Must be
227 * unlocked before draw call. Vertex size is queried
228 * from current GrDrawState.
230 void setVertexSourceToBuffer(const GrVertexBuffer* buffer);
233 * Sets source of index data for the next indexed draw. Data does not have
234 * to be in the buffer until drawIndexed.
236 * @param buffer index buffer containing indices. Must be unlocked
237 * before indexed draw call.
239 void setIndexSourceToBuffer(const GrIndexBuffer* buffer);
242 * Resets vertex source. Drawing from reset vertices is illegal. Set vertex
243 * source to reserved, array, or buffer before next draw. May be able to free
244 * up temporary storage allocated by setVertexSourceToArray or
245 * reserveVertexSpace.
247 void resetVertexSource();
250 * Resets index source. Indexed Drawing from reset indices is illegal. Set
251 * index source to reserved, array, or buffer before next indexed draw. May
252 * be able to free up temporary storage allocated by setIndexSourceToArray
253 * or reserveIndexSpace.
255 void resetIndexSource();
258 * Query to find out if the vertex or index source is reserved.
260 bool hasReservedVerticesOrIndices() const {
261 return kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc ||
262 kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc;
266 * Pushes and resets the vertex/index sources. Any reserved vertex / index
267 * data is finalized (i.e. cannot be updated after the matching pop but can
268 * be drawn from). Must be balanced by a pop.
270 void pushGeometrySource();
273 * Pops the vertex / index sources from the matching push.
275 void popGeometrySource();
278 * Draws indexed geometry using the current state and current vertex / index
281 * @param type The type of primitives to draw.
282 * @param startVertex the vertex in the vertex array/buffer corresponding
284 * @param startIndex first index to read from index src.
285 * @param vertexCount one greater than the max index.
286 * @param indexCount the number of index elements to read. The index count
287 * is effectively trimmed to the last completely
288 * specified primitive.
289 * @param devBounds optional bounds hint. This is a promise from the caller,
290 * not a request for clipping.
292 void drawIndexed(GrPrimitiveType type,
297 const SkRect* devBounds = NULL);
300 * Draws non-indexed geometry using the current state and current vertex
303 * @param type The type of primitives to draw.
304 * @param startVertex the vertex in the vertex array/buffer corresponding
306 * @param vertexCount one greater than the max index.
307 * @param devBounds optional bounds hint. This is a promise from the caller,
308 * not a request for clipping.
310 void drawNonIndexed(GrPrimitiveType type,
313 const SkRect* devBounds = NULL);
316 * Draws path into the stencil buffer. The fill must be either even/odd or
317 * winding (not inverse or hairline). It will respect the HW antialias flag
318 * on the draw state (if possible in the 3D API).
320 void stencilPath(const GrPath*, SkPath::FillType fill);
323 * Draws a path. Fill must not be a hairline. It will respect the HW
324 * antialias flag on the draw state (if possible in the 3D API).
326 void drawPath(const GrPath*, SkPath::FillType fill);
329 * Draws many paths. It will respect the HW
330 * antialias flag on the draw state (if possible in the 3D API).
332 * @param pathRange Source of paths to draw from
333 * @param indices Array of indices into the the pathRange
334 * @param count Number of paths to draw (length of indices array)
335 * @param transforms Array of individual transforms, one for each path
336 * @param transformsType Type of transformations in the array. Array contains
337 PathTransformSize(transformsType) * count elements
338 * @param fill Fill type for drawing all the paths
340 void drawPaths(const GrPathRange* pathRange,
341 const uint32_t indices[], int count,
342 const float transforms[], PathTransformType transformsType,
343 SkPath::FillType fill);
346 * Helper function for drawing rects. It performs a geometry src push and pop
347 * and thus will finalize any reserved geometry.
349 * @param rect the rect to draw
350 * @param localRect optional rect that specifies local coords to map onto
351 * rect. If NULL then rect serves as the local coords.
352 * @param localMatrix optional matrix applied to localRect. If
353 * srcRect is non-NULL and srcMatrix is non-NULL
354 * then srcRect will be transformed by srcMatrix.
355 * srcMatrix can be NULL when no srcMatrix is desired.
357 void drawRect(const SkRect& rect,
358 const SkRect* localRect,
359 const SkMatrix* localMatrix) {
360 AutoGeometryPush agp(this);
361 this->onDrawRect(rect, localRect, localMatrix);
365 * Helper for drawRect when the caller doesn't need separate local rects or matrices.
367 void drawSimpleRect(const SkRect& rect) {
368 this->drawRect(rect, NULL, NULL);
370 void drawSimpleRect(const SkIRect& irect) {
371 SkRect rect = SkRect::Make(irect);
372 this->drawRect(rect, NULL, NULL);
376 * This call is used to draw multiple instances of some geometry with a
377 * given number of vertices (V) and indices (I) per-instance. The indices in
378 * the index source must have the form i[k+I] == i[k] + V. Also, all indices
379 * i[kI] ... i[(k+1)I-1] must be elements of the range kV ... (k+1)V-1. As a
380 * concrete example, the following index buffer for drawing a series of
381 * quads each as two triangles each satisfies these conditions with V=4 and
383 * (0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, ...)
385 * The call assumes that the pattern of indices fills the entire index
386 * source. The size of the index buffer limits the number of instances that
387 * can be drawn by the GPU in a single draw. However, the caller may specify
388 * any (positive) number for instanceCount and if necessary multiple GPU
389 * draws will be issued. Moreover, when drawIndexedInstances is called
390 * multiple times it may be possible for GrDrawTarget to group them into a
393 * @param type the type of primitives to draw
394 * @param instanceCount the number of instances to draw. Each instance
395 * consists of verticesPerInstance vertices indexed by
396 * indicesPerInstance indices drawn as the primitive
397 * type specified by type.
398 * @param verticesPerInstance The number of vertices in each instance (V
399 * in the above description).
400 * @param indicesPerInstance The number of indices in each instance (I
401 * in the above description).
402 * @param devBounds optional bounds hint. This is a promise from the caller,
403 * not a request for clipping.
405 void drawIndexedInstances(GrPrimitiveType type,
407 int verticesPerInstance,
408 int indicesPerInstance,
409 const SkRect* devBounds = NULL);
412 * Clear the current render target if one isn't passed in. Ignores the
413 * clip and all other draw state (blend mode, stages, etc). Clears the
414 * whole thing if rect is NULL, otherwise just the rect. If canIgnoreRect
415 * is set then the entire render target can be optionally cleared.
417 virtual void clear(const SkIRect* rect,
420 GrRenderTarget* renderTarget = NULL) = 0;
423 * Discards the contents render target. NULL indicates that the current render target should
426 virtual void discard(GrRenderTarget* = NULL) = 0;
429 * Called at start and end of gpu trace marking
430 * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start
431 * and end of a code block respectively
433 void addGpuTraceMarker(const GrGpuTraceMarker* marker);
434 void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
437 * Takes the current active set of markers and stores them for later use. Any current marker
438 * in the active set is removed from the active set and the targets remove function is called.
439 * These functions do not work as a stack so you cannot call save a second time before calling
440 * restore. Also, it is assumed that when restore is called the current active set of markers
441 * is empty. When the stored markers are added back into the active set, the targets add marker
444 void saveActiveTraceMarkers();
445 void restoreActiveTraceMarkers();
448 * Copies a pixel rectangle from one surface to another. This call may finalize
449 * reserved vertex/index data (as though a draw call was made). The src pixels
450 * copied are specified by srcRect. They are copied to a rect of the same
451 * size in dst with top left at dstPoint. If the src rect is clipped by the
452 * src bounds then pixel values in the dst rect corresponding to area clipped
453 * by the src rect are not overwritten. This method can fail and return false
454 * depending on the type of surface, configs, etc, and the backend-specific
455 * limitations. If rect is clipped out entirely by the src or dst bounds then
456 * true is returned since there is no actual copy necessary to succeed.
458 bool copySurface(GrSurface* dst,
460 const SkIRect& srcRect,
461 const SkIPoint& dstPoint);
463 * Function that determines whether a copySurface call would succeed without
464 * performing the copy.
466 bool canCopySurface(GrSurface* dst,
468 const SkIRect& srcRect,
469 const SkIPoint& dstPoint);
472 * This is can be called before allocating a texture to be a dst for copySurface. It will
473 * populate the origin, config, and flags fields of the desc such that copySurface is more
474 * likely to succeed and be efficient.
476 virtual void initCopySurfaceDstDesc(const GrSurface* src, GrTextureDesc* desc);
480 * Release any resources that are cached but not currently in use. This
481 * is intended to give an application some recourse when resources are low.
483 virtual void purgeResources() {};
486 * For subclass internal use to invoke a call to onDraw(). See DrawInfo below.
488 void executeDraw(const DrawInfo& info) { this->onDraw(info); }
491 * For subclass internal use to invoke a call to onDrawPath().
493 void executeDrawPath(const GrPath* path, SkPath::FillType fill,
494 const GrDeviceCoordTexture* dstCopy) {
495 this->onDrawPath(path, fill, dstCopy);
499 * For subclass internal use to invoke a call to onDrawPaths().
501 void executeDrawPaths(const GrPathRange* pathRange,
502 const uint32_t indices[], int count,
503 const float transforms[], PathTransformType transformsType,
504 SkPath::FillType fill,
505 const GrDeviceCoordTexture* dstCopy) {
506 this->onDrawPaths(pathRange, indices, count, transforms, transformsType, fill, dstCopy);
508 ////////////////////////////////////////////////////////////////////////////
511 * See AutoStateRestore below.
519 * Saves off the current state and restores it in the destructor. It will
520 * install a new GrDrawState object on the target (setDrawState) and restore
521 * the previous one in the destructor. The caller should call drawState() to
522 * get the new draw state after the ASR is installed.
524 * GrDrawState* state = target->drawState();
525 * AutoStateRestore asr(target, GrDrawTarget::kReset_ASRInit).
526 * state->setRenderTarget(rt); // state refers to the GrDrawState set on
527 * // target before asr was initialized.
528 * // Therefore, rt is set on the GrDrawState
529 * // that will be restored after asr's
530 * // destructor rather than target's current
533 class AutoStateRestore : public ::SkNoncopyable {
536 * Default ASR will have no effect unless set() is subsequently called.
541 * Saves the state on target. The state will be restored when the ASR
542 * is destroyed. If this constructor is used do not call set().
544 * @param init Should the newly installed GrDrawState be a copy of the
545 * previous state or a default-initialized GrDrawState.
546 * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
547 * matrix will be preconcat'ed with the param. All stages will be
548 updated to compensate for the matrix change. If init == kReset
549 then the draw state's matrix will be this matrix.
551 AutoStateRestore(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
556 * Saves the state on target. The state will be restored when the ASR
557 * is destroyed. This should only be called once per ASR object and only
558 * when the default constructor was used. For nested saves use multiple
561 * @param init Should the newly installed GrDrawState be a copy of the
562 * previous state or a default-initialized GrDrawState.
563 * @param viewMatrix Optional view matrix. If init = kPreserve then the draw state's
564 * matrix will be preconcat'ed with the param. All stages will be
565 updated to compensate for the matrix change. If init == kReset
566 then the draw state's matrix will be this matrix.
568 void set(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL);
571 * Like set() but makes the view matrix identity. When init is kReset it is as though
572 * NULL was passed to set's viewMatrix param. When init is kPreserve it is as though
573 * the inverse view matrix was passed. If kPreserve is passed and the draw state's matrix
574 * is not invertible then this may fail.
576 bool setIdentity(GrDrawTarget* target, ASRInit init);
579 GrDrawTarget* fDrawTarget;
580 SkTLazy<GrDrawState> fTempState;
581 GrDrawState* fSavedState;
584 ////////////////////////////////////////////////////////////////////////////
586 class AutoReleaseGeometry : public ::SkNoncopyable {
588 AutoReleaseGeometry(GrDrawTarget* target,
591 AutoReleaseGeometry();
592 ~AutoReleaseGeometry();
593 bool set(GrDrawTarget* target,
596 bool succeeded() const { return SkToBool(fTarget); }
597 void* vertices() const { SkASSERT(this->succeeded()); return fVertices; }
598 void* indices() const { SkASSERT(this->succeeded()); return fIndices; }
599 SkPoint* positions() const {
600 return static_cast<SkPoint*>(this->vertices());
606 GrDrawTarget* fTarget;
611 ////////////////////////////////////////////////////////////////////////////
613 class AutoClipRestore : public ::SkNoncopyable {
615 AutoClipRestore(GrDrawTarget* target) {
617 fClip = fTarget->getClip();
620 AutoClipRestore(GrDrawTarget* target, const SkIRect& newClip);
623 fTarget->setClip(fClip);
626 GrDrawTarget* fTarget;
627 const GrClipData* fClip;
628 SkTLazy<SkClipStack> fStack;
629 GrClipData fReplacementClip;
632 ////////////////////////////////////////////////////////////////////////////
635 * Saves the geometry src state at construction and restores in the destructor. It also saves
636 * and then restores the vertex attrib state.
638 class AutoGeometryPush : public ::SkNoncopyable {
640 AutoGeometryPush(GrDrawTarget* target)
641 : fAttribRestore(target->drawState()) {
644 target->pushGeometrySource();
647 ~AutoGeometryPush() { fTarget->popGeometrySource(); }
650 GrDrawTarget* fTarget;
651 GrDrawState::AutoVertexAttribRestore fAttribRestore;
655 * Combination of AutoGeometryPush and AutoStateRestore. The vertex attribs will be in default
656 * state regardless of ASRInit value.
658 class AutoGeometryAndStatePush : public ::SkNoncopyable {
660 AutoGeometryAndStatePush(GrDrawTarget* target,
662 const SkMatrix* viewMatrix = NULL)
663 : fState(target, init, viewMatrix) {
666 target->pushGeometrySource();
667 if (kPreserve_ASRInit == init) {
668 target->drawState()->setDefaultVertexAttribs();
672 ~AutoGeometryAndStatePush() { fTarget->popGeometrySource(); }
675 AutoStateRestore fState;
676 GrDrawTarget* fTarget;
679 ///////////////////////////////////////////////////////////////////////////
680 // Draw execution tracking (for font atlases and other resources)
683 DrawToken(GrDrawTarget* drawTarget, uint32_t drawID) :
684 fDrawTarget(drawTarget), fDrawID(drawID) {}
686 bool isIssued() { return fDrawTarget && fDrawTarget->isIssued(fDrawID); }
689 GrDrawTarget* fDrawTarget;
690 uint32_t fDrawID; // this may wrap, but we're doing direct comparison
691 // so that should be okay
694 virtual DrawToken getCurrentDrawToken() { return DrawToken(this, 0); }
697 // Extend access to GrRODrawState::convertToPEndeingExec to subclasses.
698 void convertDrawStateToPendingExec(GrRODrawState* ds) {
699 ds->convertToPendingExec();
702 enum GeometrySrcType {
703 kNone_GeometrySrcType, //<! src has not been specified
704 kReserved_GeometrySrcType, //<! src was set using reserve*Space
705 kArray_GeometrySrcType, //<! src was set using set*SourceToArray
706 kBuffer_GeometrySrcType //<! src was set using set*SourceToBuffer
709 struct GeometrySrcState {
710 GeometrySrcType fVertexSrc;
712 // valid if src type is buffer
713 const GrVertexBuffer* fVertexBuffer;
714 // valid if src type is reserved or array
718 GeometrySrcType fIndexSrc;
720 // valid if src type is buffer
721 const GrIndexBuffer* fIndexBuffer;
722 // valid if src type is reserved or array
729 int indexCountInCurrentSource() const {
730 const GeometrySrcState& src = this->getGeomSrc();
731 switch (src.fIndexSrc) {
732 case kNone_GeometrySrcType:
734 case kReserved_GeometrySrcType:
735 case kArray_GeometrySrcType:
736 return src.fIndexCount;
737 case kBuffer_GeometrySrcType:
738 return static_cast<int>(src.fIndexBuffer->gpuMemorySize() / sizeof(uint16_t));
740 SkFAIL("Unexpected Index Source.");
745 // This method is called by copySurface The srcRect is guaranteed to be entirely within the
746 // src bounds. Likewise, the dst rect implied by dstPoint and srcRect's width and height falls
747 // entirely within the dst. The default implementation will draw a rect from the src to the
748 // dst if the src is a texture and the dst is a render target and fail otherwise.
749 virtual bool onCopySurface(GrSurface* dst,
751 const SkIRect& srcRect,
752 const SkIPoint& dstPoint);
754 // Called to determine whether an onCopySurface call would succeed or not. This is useful for
755 // proxy subclasses to test whether the copy would succeed without executing it yet. Derived
756 // classes must keep this consistent with their implementation of onCopySurface(). The inputs
757 // are the same as onCopySurface(), i.e. srcRect and dstPoint are clipped to be inside the src
759 virtual bool onCanCopySurface(GrSurface* dst,
761 const SkIRect& srcRect,
762 const SkIPoint& dstPoint);
764 GrContext* getContext() { return fContext; }
765 const GrContext* getContext() const { return fContext; }
767 // A subclass may override this function if it wishes to be notified when the clip is changed.
768 // The override should call INHERITED::clipWillBeSet().
769 virtual void clipWillBeSet(const GrClipData* clipData);
771 // subclasses must call this in their destructors to ensure all vertex
772 // and index sources have been released (including those held by
773 // pushGeometrySource())
774 void releaseGeometry();
776 // accessors for derived classes
777 const GeometrySrcState& getGeomSrc() const { return fGeoSrcStateStack.back(); }
778 // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert.
779 size_t getVertexSize() const {
780 // the vertex layout is only valid if a vertex source has been specified.
781 SkASSERT(this->getGeomSrc().fVertexSrc != kNone_GeometrySrcType);
782 return this->getGeomSrc().fVertexSize;
785 // Subclass must initialize this in its constructor.
786 SkAutoTUnref<const GrDrawTargetCaps> fCaps;
788 const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; }
791 * Used to communicate draws to subclass's onDraw function.
795 DrawInfo(const DrawInfo& di) { (*this) = di; }
796 DrawInfo& operator =(const DrawInfo& di);
798 GrPrimitiveType primitiveType() const { return fPrimitiveType; }
799 int startVertex() const { return fStartVertex; }
800 int startIndex() const { return fStartIndex; }
801 int vertexCount() const { return fVertexCount; }
802 int indexCount() const { return fIndexCount; }
803 int verticesPerInstance() const { return fVerticesPerInstance; }
804 int indicesPerInstance() const { return fIndicesPerInstance; }
805 int instanceCount() const { return fInstanceCount; }
807 bool isIndexed() const { return fIndexCount > 0; }
809 bool isInstanced() const; // this version is longer because of asserts
811 bool isInstanced() const { return fInstanceCount > 0; }
814 // adds or remove instances
815 void adjustInstanceCount(int instanceOffset);
816 // shifts the start vertex
817 void adjustStartVertex(int vertexOffset);
818 // shifts the start index
819 void adjustStartIndex(int indexOffset);
821 void setDevBounds(const SkRect& bounds) {
822 fDevBoundsStorage = bounds;
823 fDevBounds = &fDevBoundsStorage;
825 const SkRect* getDevBounds() const { return fDevBounds; }
827 // NULL if no copy of the dst is needed for the draw.
828 const GrDeviceCoordTexture* getDstCopy() const {
829 if (fDstCopy.texture()) {
837 DrawInfo() { fDevBounds = NULL; }
839 friend class GrDrawTarget;
841 GrPrimitiveType fPrimitiveType;
849 int fVerticesPerInstance;
850 int fIndicesPerInstance;
852 SkRect fDevBoundsStorage;
855 GrDeviceCoordTexture fDstCopy;
859 // A subclass can optionally overload this function to be notified before
860 // vertex and index space is reserved.
861 virtual void willReserveVertexAndIndexSpace(int vertexCount, int indexCount) {}
863 // implemented by subclass to allocate space for reserved geom
864 virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) = 0;
865 virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
866 // implemented by subclass to handle release of reserved geom space
867 virtual void releaseReservedVertexSpace() = 0;
868 virtual void releaseReservedIndexSpace() = 0;
869 // subclass must consume array contents when set
870 virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) = 0;
871 virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) = 0;
872 // subclass is notified that geom source will be set away from an array
873 virtual void releaseVertexArray() = 0;
874 virtual void releaseIndexArray() = 0;
875 // subclass overrides to be notified just before geo src state is pushed/popped.
876 virtual void geometrySourceWillPush() = 0;
877 virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
878 // subclass called to perform drawing
879 virtual void onDraw(const DrawInfo&) = 0;
880 // Implementation of drawRect. The geometry src and vertex attribs will already
881 // be saved before this is called and restored afterwards. A subclass may override
882 // this to perform more optimal rect rendering. Its draws should be funneled through
883 // one of the public GrDrawTarget draw methods (e.g. drawNonIndexed,
884 // drawIndexedInstances, ...). The base class draws a two triangle fan using
885 // drawNonIndexed from reserved vertex space.
886 virtual void onDrawRect(const SkRect& rect,
887 const SkRect* localRect,
888 const SkMatrix* localMatrix);
890 virtual void onStencilPath(const GrPath*, SkPath::FillType) = 0;
891 virtual void onDrawPath(const GrPath*, SkPath::FillType,
892 const GrDeviceCoordTexture* dstCopy) = 0;
893 virtual void onDrawPaths(const GrPathRange*,
894 const uint32_t indices[], int count,
895 const float transforms[], PathTransformType,
896 SkPath::FillType, const GrDeviceCoordTexture*) = 0;
898 virtual void didAddGpuTraceMarker() = 0;
899 virtual void didRemoveGpuTraceMarker() = 0;
901 // helpers for reserving vertex and index space.
902 bool reserveVertexSpace(size_t vertexSize,
905 bool reserveIndexSpace(int indexCount, void** indices);
907 // called by drawIndexed and drawNonIndexed. Use a negative indexCount to
908 // indicate non-indexed drawing.
909 bool checkDraw(GrPrimitiveType type, int startVertex,
910 int startIndex, int vertexCount,
911 int indexCount) const;
912 // called when setting a new vert/idx source to unref prev vb/ib
913 void releasePreviousVertexSource();
914 void releasePreviousIndexSource();
916 // Makes a copy of the dst if it is necessary for the draw. Returns false if a copy is required
917 // but couldn't be made. Otherwise, returns true.
918 bool setupDstReadIfNecessary(DrawInfo* info) {
919 return this->setupDstReadIfNecessary(&info->fDstCopy, info->getDevBounds());
921 bool setupDstReadIfNecessary(GrDeviceCoordTexture* dstCopy, const SkRect* drawBounds);
923 // Check to see if this set of draw commands has been sent out
924 virtual bool isIssued(uint32_t drawID) { return true; }
927 kPreallocGeoSrcStateStackCnt = 4,
929 SkSTArray<kPreallocGeoSrcStateStackCnt, GeometrySrcState, true> fGeoSrcStateStack;
930 const GrClipData* fClip;
931 GrDrawState* fDrawState;
932 GrDrawState fDefaultDrawState;
933 // The context owns us, not vice-versa, so this ptr is not ref'ed by DrawTarget.
935 // To keep track that we always have at least as many debug marker adds as removes
936 int fGpuTraceMarkerCount;
937 GrTraceMarkerSet fActiveTraceMarkers;
938 GrTraceMarkerSet fStoredTraceMarkers;
940 typedef SkRefCnt INHERITED;