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 "GrPathRendering.h" 16 #include "GrTraceMarker.h" 17 18 #include "SkClipStack.h" 19 #include "SkMatrix.h" 20 #include "SkPath.h" 21 #include "SkStrokeRec.h" 22 #include "SkTArray.h" 23 #include "SkTLazy.h" 24 #include "SkTypes.h" 25 #include "SkXfermode.h" 26 27 class GrClipData; 28 class GrDrawTargetCaps; 29 class GrPath; 30 class GrPathRange; 31 class GrVertexBuffer; 32 33 class GrDrawTarget : public SkRefCnt { 34 protected: 35 class DrawInfo; 36 37 public: 38 SK_DECLARE_INST_COUNT(GrDrawTarget) 39 40 41 typedef GrPathRendering::PathTransformType PathTransformType ; 42 43 /////////////////////////////////////////////////////////////////////////// 44 45 // The context may not be fully constructed and should not be used during GrDrawTarget 46 // construction. 47 GrDrawTarget(GrContext* context); 48 virtual ~GrDrawTarget(); 49 50 /** 51 * Gets the capabilities of the draw target. 52 */ 53 const GrDrawTargetCaps* caps() const { return fCaps.get(); } 54 55 /** 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. 58 * 59 * Setting the clip may (or may not) zero out the client's stencil bits. 60 * 61 * @param description of the clipping region 62 */ 63 void setClip(const GrClipData* clip); 64 65 /** 66 * Gets the current clip. 67 * 68 * @return the clip. 69 */ 70 const GrClipData* getClip() const; 71 72 /** 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. 77 */ 78 void setDrawState(GrDrawState* drawState); 79 80 /** 81 * Read-only access to the GrDrawTarget's current draw state. 82 */ 83 const GrDrawState& getDrawState() const { return *fDrawState; } 84 85 /** 86 * Read-write access to the GrDrawTarget's current draw state. Note that 87 * this doesn't ref. 88 */ 89 GrDrawState* drawState() { return fDrawState; } 90 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. 96 // return false; 97 return !this->getDrawState().couldApplyCoverage(*this->caps()); 98 } 99 100 /** 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. 106 * 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 111 * sources. 112 * 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. 116 * 117 * The three types of sources are: 118 * 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. 124 * 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. 129 * 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. 133 * 134 * Where the space is allocated and how it is uploaded to the GPU is 135 * subclass-dependent. 136 * 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) 142 * 143 * The size of each vertex is determined by querying the current GrDrawState. 144 */ 145 146 /** 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 151 * indexCount. 152 * 153 * If the function returns true then the reserve suceeded and the vertices 154 * and indices pointers will point to the space created. 155 * 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. 159 * 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. 164 * 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. 172 */ 173 bool reserveVertexAndIndexSpace(int vertexCount, 174 int indexCount, 175 void** vertices, 176 void** indices); 177 178 /** 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. 182 * 183 * Also may hint whether the draw target should be flushed first. This is 184 * useful for deferred targets. 185 * 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. 191 * Ignored if NULL. 192 * @param indexCount in: hint about how many indices the caller would 193 * like to allocate. 194 * out: a hint about the number of indices that can be 195 * allocated cheaply. Negative means no hint. 196 * Ignored if NULL. 197 * 198 * @return true if target should be flushed based on the input values. 199 */ 200 virtual bool geometryHints(int* vertexCount, 201 int* indexCount) const; 202 203 /** 204 * Sets source of vertex data for the next draw. Array must contain 205 * the vertex data when this is called. 206 * 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. 210 */ 211 void setVertexSourceToArray(const void* vertexArray, int vertexCount); 212 213 /** 214 * Sets source of index data for the next indexed draw. Array must contain 215 * the indices when this is called. 216 * 217 * @param indexArray cpu array containing index data. 218 * @param indexCount the number of indices in the array. 219 */ 220 void setIndexSourceToArray(const void* indexArray, int indexCount); 221 222 /** 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. 225 * 226 * @param buffer vertex buffer containing vertex data. Must be 227 * unlocked before draw call. Vertex size is queried 228 * from current GrDrawState. 229 */ 230 void setVertexSourceToBuffer(const GrVertexBuffer* buffer); 231 232 /** 233 * Sets source of index data for the next indexed draw. Data does not have 234 * to be in the buffer until drawIndexed. 235 * 236 * @param buffer index buffer containing indices. Must be unlocked 237 * before indexed draw call. 238 */ 239 void setIndexSourceToBuffer(const GrIndexBuffer* buffer); 240 241 /** 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. 246 */ 247 void resetVertexSource(); 248 249 /** 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. 254 */ 255 void resetIndexSource(); 256 257 /** 258 * Query to find out if the vertex or index source is reserved. 259 */ 260 bool hasReservedVerticesOrIndices() const { 261 return kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc || 262 kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc; 263 } 264 265 /** 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. 269 */ 270 void pushGeometrySource(); 271 272 /** 273 * Pops the vertex / index sources from the matching push. 274 */ 275 void popGeometrySource(); 276 277 /** 278 * Draws indexed geometry using the current state and current vertex / index 279 * sources. 280 * 281 * @param type The type of primitives to draw. 282 * @param startVertex the vertex in the vertex array/buffer corresponding 283 * to index 0 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. 291 */ 292 void drawIndexed(GrPrimitiveType type, 293 int startVertex, 294 int startIndex, 295 int vertexCount, 296 int indexCount, 297 const SkRect* devBounds = NULL); 298 299 /** 300 * Draws non-indexed geometry using the current state and current vertex 301 * sources. 302 * 303 * @param type The type of primitives to draw. 304 * @param startVertex the vertex in the vertex array/buffer corresponding 305 * to index 0 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. 309 */ 310 void drawNonIndexed(GrPrimitiveType type, 311 int startVertex, 312 int vertexCount, 313 const SkRect* devBounds = NULL); 314 315 /** 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). 319 */ 320 void stencilPath(const GrPath*, SkPath::FillType fill); 321 322 /** 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). 325 */ 326 void drawPath(const GrPath*, SkPath::FillType fill); 327 328 /** 329 * Draws many paths. It will respect the HW 330 * antialias flag on the draw state (if possible in the 3D API). 331 * 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 339 */ 340 void drawPaths(const GrPathRange* pathRange, 341 const uint32_t indices[], int count, 342 const float transforms[], PathTransformType transformsType, 343 SkPath::FillType fill); 344 345 /** 346 * Helper function for drawing rects. It performs a geometry src push and pop 347 * and thus will finalize any reserved geometry. 348 * 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. 356 */ 357 void drawRect(const SkRect& rect, 358 const SkRect* localRect, 359 const SkMatrix* localMatrix) { 360 AutoGeometryPush agp(this); 361 this->onDrawRect(rect, localRect, localMatrix); 362 } 363 364 /** 365 * Helper for drawRect when the caller doesn't need separate local rects or matrices. 366 */ 367 void drawSimpleRect(const SkRect& rect) { 368 this->drawRect(rect, NULL, NULL); 369 } 370 void drawSimpleRect(const SkIRect& irect) { 371 SkRect rect = SkRect::Make(irect); 372 this->drawRect(rect, NULL, NULL); 373 } 374 375 /** 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 382 * I=6: 383 * (0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, ...) 384 * 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 391 * single GPU draw. 392 * 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. 404 */ 405 void drawIndexedInstances(GrPrimitiveType type, 406 int instanceCount, 407 int verticesPerInstance, 408 int indicesPerInstance, 409 const SkRect* devBounds = NULL); 410 411 /** 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. 416 */ 417 virtual void clear(const SkIRect* rect, 418 GrColor color, 419 bool canIgnoreRect, 420 GrRenderTarget* renderTarget = NULL) = 0; 421 422 /** 423 * Discards the contents render target. NULL indicates that the current render target should 424 * be discarded. 425 **/ 426 virtual void discard(GrRenderTarget* = NULL) = 0; 427 428 /** 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 432 */ 433 void addGpuTraceMarker(const GrGpuTraceMarker* marker); 434 void removeGpuTraceMarker(const GrGpuTraceMarker* marker); 435 436 /** 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 442 * is called. 443 */ 444 void saveActiveTraceMarkers(); 445 void restoreActiveTraceMarkers(); 446 447 /** 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. 457 */ 458 bool copySurface(GrSurface* dst, 459 GrSurface* src, 460 const SkIRect& srcRect, 461 const SkIPoint& dstPoint); 462 /** 463 * Function that determines whether a copySurface call would succeed without 464 * performing the copy. 465 */ 466 bool canCopySurface(GrSurface* dst, 467 GrSurface* src, 468 const SkIRect& srcRect, 469 const SkIPoint& dstPoint); 470 471 /** 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. 475 */ 476 virtual void initCopySurfaceDstDesc(const GrSurface* src, GrTextureDesc* desc); 477 478 479 /** 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. 482 */ 483 virtual void purgeResources() {}; 484 485 /** 486 * For subclass internal use to invoke a call to onDraw(). See DrawInfo below. 487 */ 488 void executeDraw(const DrawInfo& info) { this->onDraw(info); } 489 490 /** 491 * For subclass internal use to invoke a call to onDrawPath(). 492 */ 493 void executeDrawPath(const GrPath* path, SkPath::FillType fill, 494 const GrDeviceCoordTexture* dstCopy) { 495 this->onDrawPath(path, fill, dstCopy); 496 } 497 498 /** 499 * For subclass internal use to invoke a call to onDrawPaths(). 500 */ 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); 507 } 508 //////////////////////////////////////////////////////////////////////////// 509 510 /** 511 * See AutoStateRestore below. 512 */ 513 enum ASRInit { 514 kPreserve_ASRInit, 515 kReset_ASRInit 516 }; 517 518 /** 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. 523 * 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 531 * // GrDrawState. 532 */ 533 class AutoStateRestore : public ::SkNoncopyable { 534 public: 535 /** 536 * Default ASR will have no effect unless set() is subsequently called. 537 */ 538 AutoStateRestore(); 539 540 /** 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(). 543 * 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. 550 */ 551 AutoStateRestore(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL); 552 553 ~AutoStateRestore(); 554 555 /** 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 559 * ASR objects. 560 * 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. 567 */ 568 void set(GrDrawTarget* target, ASRInit init, const SkMatrix* viewMatrix = NULL); 569 570 /** 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. 575 */ 576 bool setIdentity(GrDrawTarget* target, ASRInit init); 577 578 private: 579 GrDrawTarget* fDrawTarget; 580 SkTLazy<GrDrawState> fTempState; 581 GrDrawState* fSavedState; 582 }; 583 584 //////////////////////////////////////////////////////////////////////////// 585 586 class AutoReleaseGeometry : public ::SkNoncopyable { 587 public: 588 AutoReleaseGeometry(GrDrawTarget* target, 589 int vertexCount, 590 int indexCount); 591 AutoReleaseGeometry(); 592 ~AutoReleaseGeometry(); 593 bool set(GrDrawTarget* target, 594 int vertexCount, 595 int indexCount); 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()); 601 } 602 603 private: 604 void reset(); 605 606 GrDrawTarget* fTarget; 607 void* fVertices; 608 void* fIndices; 609 }; 610 611 //////////////////////////////////////////////////////////////////////////// 612 613 class AutoClipRestore : public ::SkNoncopyable { 614 public: 615 AutoClipRestore(GrDrawTarget* target) { 616 fTarget = target; 617 fClip = fTarget->getClip(); 618 } 619 620 AutoClipRestore(GrDrawTarget* target, const SkIRect& newClip); 621 622 ~AutoClipRestore() { 623 fTarget->setClip(fClip); 624 } 625 private: 626 GrDrawTarget* fTarget; 627 const GrClipData* fClip; 628 SkTLazy<SkClipStack> fStack; 629 GrClipData fReplacementClip; 630 }; 631 632 //////////////////////////////////////////////////////////////////////////// 633 634 /** 635 * Saves the geometry src state at construction and restores in the destructor. It also saves 636 * and then restores the vertex attrib state. 637 */ 638 class AutoGeometryPush : public ::SkNoncopyable { 639 public: 640 AutoGeometryPush(GrDrawTarget* target) 641 : fAttribRestore(target->drawState()) { 642 SkASSERT(target); 643 fTarget = target; 644 target->pushGeometrySource(); 645 } 646 647 ~AutoGeometryPush() { fTarget->popGeometrySource(); } 648 649 private: 650 GrDrawTarget* fTarget; 651 GrDrawState::AutoVertexAttribRestore fAttribRestore; 652 }; 653 654 /** 655 * Combination of AutoGeometryPush and AutoStateRestore. The vertex attribs will be in default 656 * state regardless of ASRInit value. 657 */ 658 class AutoGeometryAndStatePush : public ::SkNoncopyable { 659 public: 660 AutoGeometryAndStatePush(GrDrawTarget* target, 661 ASRInit init, 662 const SkMatrix* viewMatrix = NULL) 663 : fState(target, init, viewMatrix) { 664 SkASSERT(target); 665 fTarget = target; 666 target->pushGeometrySource(); 667 if (kPreserve_ASRInit == init) { 668 target->drawState()->setDefaultVertexAttribs(); 669 } 670 } 671 672 ~AutoGeometryAndStatePush() { fTarget->popGeometrySource(); } 673 674 private: 675 AutoStateRestore fState; 676 GrDrawTarget* fTarget; 677 }; 678 679 /////////////////////////////////////////////////////////////////////////// 680 // Draw execution tracking (for font atlases and other resources) 681 class DrawToken { 682 public: 683 DrawToken(GrDrawTarget* drawTarget, uint32_t drawID) : 684 fDrawTarget(drawTarget), fDrawID(drawID) {} 685 686 bool isIssued() { return fDrawTarget && fDrawTarget->isIssued(fDrawID); } 687 688 private: 689 GrDrawTarget* fDrawTarget; 690 uint32_t fDrawID; // this may wrap, but we're doing direct comparison 691 // so that should be okay 692 }; 693 694 virtual DrawToken getCurrentDrawToken() { return DrawToken(this, 0); } 695 696 protected: 697 // Extend access to GrRODrawState::convertToPEndeingExec to subclasses. 698 void convertDrawStateToPendingExec(GrRODrawState* ds) { 699 ds->convertToPendingExec(); 700 } 701 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 707 }; 708 709 struct GeometrySrcState { 710 GeometrySrcType fVertexSrc; 711 union { 712 // valid if src type is buffer 713 const GrVertexBuffer* fVertexBuffer; 714 // valid if src type is reserved or array 715 int fVertexCount; 716 }; 717 718 GeometrySrcType fIndexSrc; 719 union { 720 // valid if src type is buffer 721 const GrIndexBuffer* fIndexBuffer; 722 // valid if src type is reserved or array 723 int fIndexCount; 724 }; 725 726 size_t fVertexSize; 727 }; 728 729 int indexCountInCurrentSource() const { 730 const GeometrySrcState& src = this->getGeomSrc(); 731 switch (src.fIndexSrc) { 732 case kNone_GeometrySrcType: 733 return 0; 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)); 739 default: 740 SkFAIL("Unexpected Index Source."); 741 return 0; 742 } 743 } 744 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, 750 GrSurface* src, 751 const SkIRect& srcRect, 752 const SkIPoint& dstPoint); 753 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 758 // and dst bounds. 759 virtual bool onCanCopySurface(GrSurface* dst, 760 GrSurface* src, 761 const SkIRect& srcRect, 762 const SkIPoint& dstPoint); 763 764 GrContext* getContext() { return fContext; } 765 const GrContext* getContext() const { return fContext; } 766 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); 770 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(); 775 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; 783 } 784 785 // Subclass must initialize this in its constructor. 786 SkAutoTUnref<const GrDrawTargetCaps> fCaps; 787 788 const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; } 789 790 /** 791 * Used to communicate draws to subclass's onDraw function. 792 */ 793 class DrawInfo { 794 public: 795 DrawInfo(const DrawInfo& di) { (*this) = di; } 796 DrawInfo& operator =(const DrawInfo& di); 797 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; } 806 807 bool isIndexed() const { return fIndexCount > 0; } 808 #ifdef SK_DEBUG 809 bool isInstanced() const; // this version is longer because of asserts 810 #else 811 bool isInstanced() const { return fInstanceCount > 0; } 812 #endif 813 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); 820 821 void setDevBounds(const SkRect& bounds) { 822 fDevBoundsStorage = bounds; 823 fDevBounds = &fDevBoundsStorage; 824 } 825 const SkRect* getDevBounds() const { return fDevBounds; } 826 827 // NULL if no copy of the dst is needed for the draw. 828 const GrDeviceCoordTexture* getDstCopy() const { 829 if (fDstCopy.texture()) { 830 return &fDstCopy; 831 } else { 832 return NULL; 833 } 834 } 835 836 private: 837 DrawInfo() { fDevBounds = NULL; } 838 839 friend class GrDrawTarget; 840 841 GrPrimitiveType fPrimitiveType; 842 843 int fStartVertex; 844 int fStartIndex; 845 int fVertexCount; 846 int fIndexCount; 847 848 int fInstanceCount; 849 int fVerticesPerInstance; 850 int fIndicesPerInstance; 851 852 SkRect fDevBoundsStorage; 853 SkRect* fDevBounds; 854 855 GrDeviceCoordTexture fDstCopy; 856 }; 857 858 private: 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) {} 862 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); 889 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; 897 898 virtual void didAddGpuTraceMarker() = 0; 899 virtual void didRemoveGpuTraceMarker() = 0; 900 901 // helpers for reserving vertex and index space. 902 bool reserveVertexSpace(size_t vertexSize, 903 int vertexCount, 904 void** vertices); 905 bool reserveIndexSpace(int indexCount, void** indices); 906 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(); 915 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()); 920 } 921 bool setupDstReadIfNecessary(GrDeviceCoordTexture* dstCopy, const SkRect* drawBounds); 922 923 // Check to see if this set of draw commands has been sent out 924 virtual bool isIssued(uint32_t drawID) { return true; } 925 926 enum { 927 kPreallocGeoSrcStateStackCnt = 4, 928 }; 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. 934 GrContext* fContext; 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; 939 940 typedef SkRefCnt INHERITED; 941 }; 942 943 #endif 944