1 /* 2 Copyright 2010 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 18 #ifndef GrDrawTarget_DEFINED 19 #define GrDrawTarget_DEFINED 20 21 #include "GrMatrix.h" 22 #include "GrColor.h" 23 #include "GrRefCnt.h" 24 #include "GrSamplerState.h" 25 #include "GrClip.h" 26 #include "GrTexture.h" 27 #include "GrStencil.h" 28 29 #include "SkXfermode.h" 30 31 class GrTexture; 32 class GrClipIterator; 33 class GrVertexBuffer; 34 class GrIndexBuffer; 35 36 class GrDrawTarget : public GrRefCnt { 37 public: 38 /** 39 * Number of texture stages. Each stage takes as input a color and 40 * 2D texture coordinates. The color input to the first enabled stage is the 41 * per-vertex color or the constant color (setColor/setAlpha) if there are 42 * no per-vertex colors. For subsequent stages the input color is the output 43 * color from the previous enabled stage. The output color of each stage is 44 * the input color modulated with the result of a texture lookup. Texture 45 * lookups are specified by a texture a sampler (setSamplerState). Texture 46 * coordinates for each stage come from the vertices based on a 47 * GrVertexLayout bitfield. The output fragment color is the output color of 48 * the last enabled stage. The presence or absence of texture coordinates 49 * for each stage in the vertex layout indicates whether a stage is enabled 50 * or not. 51 */ 52 enum { 53 kNumStages = 3, 54 kMaxTexCoords = kNumStages 55 }; 56 57 58 /** 59 * The absolute maximum number of edges that may be specified for 60 * a single draw call when performing edge antialiasing. This is used for 61 * the size of several static buffers, so implementations of getMaxEdges() 62 * (below) should clamp to this value. 63 */ 64 enum { 65 kMaxEdges = 32 66 }; 67 68 /** 69 * Bitfield used to indicate which stages are in use. 70 */ 71 typedef int StageBitfield; 72 GR_STATIC_ASSERT(sizeof(StageBitfield)*8 >= kNumStages); 73 74 /** 75 * Flags that affect rendering. Controlled using enable/disableState(). All 76 * default to disabled. 77 */ 78 enum StateBits { 79 kDither_StateBit = 0x01, //<! Perform color dithering 80 kAntialias_StateBit = 0x02, //<! Perform anti-aliasing. The render- 81 // target must support some form of AA 82 // (msaa, coverage sampling, etc). For 83 // GrGpu-created rendertarget/textures 84 // this is controlled by parameters 85 // passed to createTexture. 86 kClip_StateBit = 0x04, //<! Controls whether drawing is clipped 87 // against the region specified by 88 // setClip. 89 kNoColorWrites_StateBit = 0x08, //<! If set it disables writing colors. 90 // Useful while performing stencil 91 // ops. 92 93 // subclass may use additional bits internally 94 kDummyStateBit, 95 kLastPublicStateBit = kDummyStateBit-1 96 }; 97 98 enum DrawFace { 99 kBoth_DrawFace, 100 kCCW_DrawFace, 101 kCW_DrawFace, 102 }; 103 104 /** 105 * The DrawTarget may reserve some of the high bits of the stencil. The draw 106 * target will automatically trim reference and mask values so that the 107 * client doesn't overwrite these bits. 108 * The number of bits available is relative to the currently set render 109 *target. 110 * @return the number of bits usable by the draw target client. 111 */ getUsableStencilBits()112 int getUsableStencilBits() const { 113 int bits = fCurrDrawState.fRenderTarget->stencilBits(); 114 if (bits) { 115 return bits - 1; 116 } else { 117 return 0; 118 } 119 } 120 121 /** 122 * Sets the stencil settings to use for the next draw. 123 * Changing the clip has the side-effect of possibly zeroing 124 * out the client settable stencil bits. So multipass algorithms 125 * using stencil should not change the clip between passes. 126 * @param settings the stencil settings to use. 127 */ setStencil(const GrStencilSettings & settings)128 void setStencil(const GrStencilSettings& settings) { 129 fCurrDrawState.fStencilSettings = settings; 130 } 131 132 /** 133 * Shortcut to disable stencil testing and ops. 134 */ disableStencil()135 void disableStencil() { 136 fCurrDrawState.fStencilSettings.setDisabled(); 137 } 138 139 class Edge { 140 public: Edge()141 Edge() {} Edge(float x,float y,float z)142 Edge(float x, float y, float z) : fX(x), fY(y), fZ(z) {} intersect(const Edge & other)143 GrPoint intersect(const Edge& other) { 144 return GrPoint::Make( 145 (fY * other.fZ - other.fY * fZ) / 146 (fX * other.fY - other.fX * fY), 147 (fX * other.fZ - other.fX * fZ) / 148 (other.fX * fY - fX * other.fY)); 149 } 150 float fX, fY, fZ; 151 }; 152 153 protected: 154 155 struct DrState { DrStateDrState156 DrState() { 157 // make sure any pad is zero for memcmp 158 // all DrState members should default to something 159 // valid by the memset 160 memset(this, 0, sizeof(DrState)); 161 162 // memset exceptions 163 fColorFilterXfermode = SkXfermode::kDstIn_Mode; 164 fFirstCoverageStage = kNumStages; 165 166 // pedantic assertion that our ptrs will 167 // be NULL (0 ptr is mem addr 0) 168 GrAssert((intptr_t)(void*)NULL == 0LL); 169 170 // default stencil setting should be disabled 171 GrAssert(fStencilSettings.isDisabled()); 172 fFirstCoverageStage = kNumStages; 173 } 174 uint32_t fFlagBits; 175 GrBlendCoeff fSrcBlend; 176 GrBlendCoeff fDstBlend; 177 GrColor fBlendConstant; 178 GrTexture* fTextures[kNumStages]; 179 GrSamplerState fSamplerStates[kNumStages]; 180 int fFirstCoverageStage; 181 GrRenderTarget* fRenderTarget; 182 GrColor fColor; 183 DrawFace fDrawFace; 184 GrColor fColorFilterColor; 185 SkXfermode::Mode fColorFilterXfermode; 186 187 GrStencilSettings fStencilSettings; 188 GrMatrix fViewMatrix; 189 Edge fEdgeAAEdges[kMaxEdges]; 190 int fEdgeAANumEdges; 191 bool operator ==(const DrState& s) const { 192 return 0 == memcmp(this, &s, sizeof(DrState)); 193 } 194 bool operator !=(const DrState& s) const { return !(*this == s); } 195 }; 196 197 public: 198 /////////////////////////////////////////////////////////////////////////// 199 200 GrDrawTarget(); 201 202 /** 203 * Sets the current clip to the region specified by clip. All draws will be 204 * clipped against this clip if kClip_StateBit is enabled. 205 * 206 * Setting the clip may (or may not) zero out the client's stencil bits. 207 * 208 * @param description of the clipping region 209 */ 210 void setClip(const GrClip& clip); 211 212 /** 213 * Gets the current clip. 214 * 215 * @return the clip. 216 */ 217 const GrClip& getClip() const; 218 219 /** 220 * Sets the texture used at the next drawing call 221 * 222 * @param stage The texture stage for which the texture will be set 223 * 224 * @param texture The texture to set. Can be NULL though there is no advantage 225 * to settings a NULL texture if doing non-textured drawing 226 */ 227 void setTexture(int stage, GrTexture* texture); 228 229 /** 230 * Retrieves the currently set texture. 231 * 232 * @return The currently set texture. The return value will be NULL if no 233 * texture has been set, NULL was most recently passed to 234 * setTexture, or the last setTexture was destroyed. 235 */ 236 const GrTexture* getTexture(int stage) const; 237 GrTexture* getTexture(int stage); 238 239 /** 240 * Sets the rendertarget used at the next drawing call 241 * 242 * @param target The render target to set. 243 */ 244 void setRenderTarget(GrRenderTarget* target); 245 246 /** 247 * Retrieves the currently set rendertarget. 248 * 249 * @return The currently set render target. 250 */ 251 const GrRenderTarget* getRenderTarget() const; 252 GrRenderTarget* getRenderTarget(); 253 254 /** 255 * Sets the sampler state for a stage used in subsequent draws. 256 * 257 * The sampler state determines how texture coordinates are 258 * intepretted and used to sample the texture. 259 * 260 * @param stage the stage of the sampler to set 261 * @param samplerState Specifies the sampler state. 262 */ 263 void setSamplerState(int stage, const GrSamplerState& samplerState); 264 265 /** 266 * Concats the matrix of a stage's sampler. 267 * 268 * @param stage the stage of the sampler to set 269 * @param matrix the matrix to concat 270 */ preConcatSamplerMatrix(int stage,const GrMatrix & matrix)271 void preConcatSamplerMatrix(int stage, const GrMatrix& matrix) { 272 GrAssert(stage >= 0 && stage < kNumStages); 273 fCurrDrawState.fSamplerStates[stage].preConcatMatrix(matrix); 274 } 275 276 /** 277 * Shortcut for preConcatSamplerMatrix on all stages in mask with same 278 * matrix 279 */ preConcatSamplerMatrices(int stageMask,const GrMatrix & matrix)280 void preConcatSamplerMatrices(int stageMask, const GrMatrix& matrix) { 281 for (int i = 0; i < kNumStages; ++i) { 282 if ((1 << i) & stageMask) { 283 this->preConcatSamplerMatrix(i, matrix); 284 } 285 } 286 } 287 288 /** 289 * Gets the matrix of a stage's sampler 290 * 291 * @param stage the stage to of sampler to get 292 * @return the sampler state's matrix 293 */ getSamplerMatrix(int stage)294 const GrMatrix& getSamplerMatrix(int stage) const { 295 return fCurrDrawState.fSamplerStates[stage].getMatrix(); 296 } 297 298 /** 299 * Sets the matrix of a stage's sampler 300 * 301 * @param stage the stage of sampler set 302 * @param matrix the matrix to set 303 */ setSamplerMatrix(int stage,const GrMatrix & matrix)304 void setSamplerMatrix(int stage, const GrMatrix& matrix) { 305 fCurrDrawState.fSamplerStates[stage].setMatrix(matrix); 306 } 307 308 /** 309 * Sets the matrix applied to veretx positions. 310 * 311 * In the post-view-matrix space the rectangle [0,w]x[0,h] 312 * fully covers the render target. (w and h are the width and height of the 313 * the rendertarget.) 314 * 315 * @param m the matrix used to transform the vertex positions. 316 */ 317 void setViewMatrix(const GrMatrix& m); 318 319 /** 320 * Multiplies the current view matrix by a matrix 321 * 322 * After this call V' = V*m where V is the old view matrix, 323 * m is the parameter to this function, and V' is the new view matrix. 324 * (We consider positions to be column vectors so position vector p is 325 * transformed by matrix X as p' = X*p.) 326 * 327 * @param m the matrix used to modify the view matrix. 328 */ 329 void preConcatViewMatrix(const GrMatrix& m); 330 331 /** 332 * Multiplies the current view matrix by a matrix 333 * 334 * After this call V' = m*V where V is the old view matrix, 335 * m is the parameter to this function, and V' is the new view matrix. 336 * (We consider positions to be column vectors so position vector p is 337 * transformed by matrix X as p' = X*p.) 338 * 339 * @param m the matrix used to modify the view matrix. 340 */ 341 void postConcatViewMatrix(const GrMatrix& m); 342 343 /** 344 * Retrieves the current view matrix 345 * @return the current view matrix. 346 */ 347 const GrMatrix& getViewMatrix() const; 348 349 /** 350 * Retrieves the inverse of the current view matrix. 351 * 352 * If the current view matrix is invertible, return true, and if matrix 353 * is non-null, copy the inverse into it. If the current view matrix is 354 * non-invertible, return false and ignore the matrix parameter. 355 * 356 * @param matrix if not null, will receive a copy of the current inverse. 357 */ 358 bool getViewInverse(GrMatrix* matrix) const; 359 360 /** 361 * Sets color for next draw to a premultiplied-alpha color. 362 * 363 * @param the color to set. 364 */ 365 void setColor(GrColor); 366 367 /** 368 * Add a color filter that can be represented by a color and a mode. 369 */ 370 void setColorFilter(GrColor, SkXfermode::Mode); 371 372 /** 373 * Sets the color to be used for the next draw to be 374 * (r,g,b,a) = (alpha, alpha, alpha, alpha). 375 * 376 * @param alpha The alpha value to set as the color. 377 */ 378 void setAlpha(uint8_t alpha); 379 380 /** 381 * Controls whether clockwise, counterclockwise, or both faces are drawn. 382 * @param face the face(s) to draw. 383 */ setDrawFace(DrawFace face)384 void setDrawFace(DrawFace face) { fCurrDrawState.fDrawFace = face; } 385 386 /** 387 * A common pattern is to compute a color with the initial stages and then 388 * modulate that color by a coverage value in later stage(s) (AA, mask- 389 * filters, glyph mask, etc). Color-filters, xfermodes, etc should be 390 * computed based on the pre-coverage-modulated color. The division of 391 * stages between color-computing and coverage-computing is specified by 392 * this method. Initially this is kNumStages (all stages are color- 393 * computing). 394 */ setFirstCoverageStage(int firstCoverageStage)395 void setFirstCoverageStage(int firstCoverageStage) { 396 fCurrDrawState.fFirstCoverageStage = firstCoverageStage; 397 } 398 399 /** 400 * Gets the index of the first coverage-computing stage. 401 */ getFirstCoverageStage()402 int getFirstCoverageStage() const { 403 return fCurrDrawState.fFirstCoverageStage; 404 } 405 406 /** 407 * Gets whether the target is drawing clockwise, counterclockwise, 408 * or both faces. 409 * @return the current draw face(s). 410 */ getDrawFace()411 DrawFace getDrawFace() const { return fCurrDrawState.fDrawFace; } 412 413 /** 414 * Enable render state settings. 415 * 416 * @param flags bitfield of StateBits specifing the states to enable 417 */ 418 void enableState(uint32_t stateBits); 419 420 /** 421 * Disable render state settings. 422 * 423 * @param flags bitfield of StateBits specifing the states to disable 424 */ 425 void disableState(uint32_t stateBits); 426 isDitherState()427 bool isDitherState() const { 428 return 0 != (fCurrDrawState.fFlagBits & kDither_StateBit); 429 } 430 isAntialiasState()431 bool isAntialiasState() const { 432 return 0 != (fCurrDrawState.fFlagBits & kAntialias_StateBit); 433 } 434 isClipState()435 bool isClipState() const { 436 return 0 != (fCurrDrawState.fFlagBits & kClip_StateBit); 437 } 438 isColorWriteDisabled()439 bool isColorWriteDisabled() const { 440 return 0 != (fCurrDrawState.fFlagBits & kNoColorWrites_StateBit); 441 } 442 443 /** 444 * Sets the blending function coeffecients. 445 * 446 * The blend function will be: 447 * D' = sat(S*srcCoef + D*dstCoef) 448 * 449 * where D is the existing destination color, S is the incoming source 450 * color, and D' is the new destination color that will be written. sat() 451 * is the saturation function. 452 * 453 * @param srcCoef coeffecient applied to the src color. 454 * @param dstCoef coeffecient applied to the dst color. 455 */ 456 void setBlendFunc(GrBlendCoeff srcCoeff, GrBlendCoeff dstCoeff); 457 458 /** 459 * Sets the blending function constant referenced by the following blending 460 * coeffecients: 461 * kConstC_BlendCoeff 462 * kIConstC_BlendCoeff 463 * kConstA_BlendCoeff 464 * kIConstA_BlendCoeff 465 * 466 * @param constant the constant to set 467 */ setBlendConstant(GrColor constant)468 void setBlendConstant(GrColor constant) { fCurrDrawState.fBlendConstant = constant; } 469 470 /** 471 * Retrieves the last value set by setBlendConstant() 472 * @return the blending constant value 473 */ getBlendConstant()474 GrColor getBlendConstant() const { return fCurrDrawState.fBlendConstant; } 475 476 /** 477 * Used to save and restore the GrGpu's drawing state 478 */ 479 struct SavedDrawState { 480 private: 481 DrState fState; 482 friend class GrDrawTarget; 483 }; 484 485 /** 486 * Saves the current draw state. The state can be restored at a later time 487 * with restoreDrawState. 488 * 489 * See also AutoStateRestore class. 490 * 491 * @param state will hold the state after the function returns. 492 */ 493 void saveCurrentDrawState(SavedDrawState* state) const; 494 495 /** 496 * Restores previously saved draw state. The client guarantees that state 497 * was previously passed to saveCurrentDrawState and that the rendertarget 498 * and texture set at save are still valid. 499 * 500 * See also AutoStateRestore class. 501 * 502 * @param state the previously saved state to restore. 503 */ 504 void restoreDrawState(const SavedDrawState& state); 505 506 /** 507 * Copies the draw state from another target to this target. 508 * 509 * @param srcTarget draw target used as src of the draw state. 510 */ 511 void copyDrawState(const GrDrawTarget& srcTarget); 512 513 /** 514 * The format of vertices is represented as a bitfield of flags. 515 * Flags that indicate the layout of vertex data. Vertices always contain 516 * positions and may also contain up to kMaxTexCoords sets of 2D texture 517 * coordinates and per-vertex colors. Each stage can use any of the texture 518 * coordinates as its input texture coordinates or it may use the positions. 519 * 520 * If no texture coordinates are specified for a stage then the stage is 521 * disabled. 522 * 523 * Only one type of texture coord can be specified per stage. For 524 * example StageTexCoordVertexLayoutBit(0, 2) and 525 * StagePosAsTexCoordVertexLayoutBit(0) cannot both be specified. 526 * 527 * The order in memory is always (position, texture coord 0, ..., color) 528 * with any unused fields omitted. Note that this means that if only texture 529 * coordinates 1 is referenced then there is no texture coordinates 0 and 530 * the order would be (position, texture coordinate 1[, color]). 531 */ 532 533 /** 534 * Generates a bit indicating that a texture stage uses texture coordinates 535 * 536 * @param stage the stage that will use texture coordinates. 537 * @param texCoordIdx the index of the texture coordinates to use 538 * 539 * @return the bit to add to a GrVertexLayout bitfield. 540 */ StageTexCoordVertexLayoutBit(int stage,int texCoordIdx)541 static int StageTexCoordVertexLayoutBit(int stage, int texCoordIdx) { 542 GrAssert(stage < kNumStages); 543 GrAssert(texCoordIdx < kMaxTexCoords); 544 return 1 << (stage + (texCoordIdx * kNumStages)); 545 } 546 547 /** 548 * Determines if blend is effectively disabled. 549 * 550 * @return true if blend can be disabled without changing the rendering 551 * result given the current state including the vertex layout specified 552 * with the vertex source. 553 */ 554 bool canDisableBlend() const; 555 556 /** 557 * Sets the edge data required for edge antialiasing. 558 * 559 * @param edges 3 * 6 float values, representing the edge 560 * equations in Ax + By + C form 561 */ 562 void setEdgeAAData(const Edge* edges, int numEdges); 563 564 private: 565 static const int TEX_COORD_BIT_CNT = kNumStages*kMaxTexCoords; 566 public: 567 /** 568 * Generates a bit indicating that a texture stage uses the position 569 * as its texture coordinate. 570 * 571 * @param stage the stage that will use position as texture 572 * coordinates. 573 * 574 * @return the bit to add to a GrVertexLayout bitfield. 575 */ StagePosAsTexCoordVertexLayoutBit(int stage)576 static int StagePosAsTexCoordVertexLayoutBit(int stage) { 577 GrAssert(stage < kNumStages); 578 return (1 << (TEX_COORD_BIT_CNT + stage)); 579 } 580 private: 581 static const int STAGE_BIT_CNT = TEX_COORD_BIT_CNT + kNumStages; 582 583 public: 584 585 /** 586 * Additional Bits that can be specified in GrVertexLayout. 587 */ 588 enum VertexLayoutBits { 589 590 kColor_VertexLayoutBit = 1 << (STAGE_BIT_CNT + 0), 591 //<! vertices have colors 592 kTextFormat_VertexLayoutBit = 1 << (STAGE_BIT_CNT + 1), 593 //<! use text vertices. (Pos 594 // and tex coords may be 595 // a different type for 596 // text [GrGpuTextVertex vs 597 // GrPoint].) 598 // for below assert 599 kDummyVertexLayoutBit, 600 kHighVertexLayoutBit = kDummyVertexLayoutBit - 1 601 }; 602 // make sure we haven't exceeded the number of bits in GrVertexLayout. 603 GR_STATIC_ASSERT(kHighVertexLayoutBit < ((uint64_t)1 << 8*sizeof(GrVertexLayout))); 604 605 /** 606 * There are three paths for specifying geometry (vertices and optionally 607 * indices) to the draw target. When indexed drawing the indices and vertices 608 * can be each use a different path. 609 * 610 * 1. Provide a cpu array (set*SourceToArray). This is useful when the 611 * caller's client has already provided vertex data in a format 612 * the time compatible with a GrVertexLayout. The array must contain the 613 * data at set*SourceToArray is called. The source stays in effect for 614 * drawIndexed & drawNonIndexed calls until set*SourceToArray is called 615 * again or one of the other two paths is chosen. 616 * 617 * 2. Reserve and Lock. This is most useful when the caller has data it must 618 * transform before drawing and will not likely render it again. The 619 * caller requests that the draw target make room for some amount of 620 * vertex and/or index data. The target provides ptrs to hold the data 621 * data. The caller can write the data into the pts up until the first 622 * drawIndexed or drawNonIndexed call. At this point the data is frozen 623 * and the ptrs are no longer guaranteed to be valid. All subsequent 624 * drawIndexed & drawNonIndexed calls will use this data until 625 * releaseReserved geometry is called. This must be called before another 626 * source is set. 627 * 628 * 3. Vertex and Index Buffers. This is most useful for geometry that will 629 * be rendered multiple times. SetVertexSourceToBuffer & 630 * SetIndexSourceToBuffer are used to set the buffer and subsequent 631 * drawIndexed and drawNonIndexed calls use this source until another 632 * source is set. 633 */ 634 635 /** 636 * Reserves space for vertices and/or indices. Draw target will use 637 * reserved vertices / indices at next draw. 638 * 639 * If succeeds: 640 * if vertexCount is nonzero, *vertices will be the array 641 * of vertices to be filled by caller. The next draw will read 642 * these vertices. 643 * 644 * if indexCount is nonzero, *indices will be the array of indices 645 * to be filled by caller. The next indexed draw will read from 646 * these indices. 647 * 648 * If a client does not already have a vertex buffer then this is the 649 * preferred way to allocate vertex/index array. It allows the subclass of 650 * GrDrawTarget to decide whether to put data in buffers, to group vertex 651 * data that uses the same state (e.g. for deferred rendering), etc. 652 * 653 * Following the first draw after reserveAndLockGeometry the ptrs returned 654 * by releaseReservedGeometry are no longer valid and the geometry data 655 * cannot be further modified. The contents that were put in the reserved 656 * space can be drawn by multiple draws, however. 657 * 658 * reserveAndLockGeometry must be matched with a releaseReservedGeometry 659 * call after all draws that reference the reserved geometry data have 660 * been called. 661 * 662 * AutoGeometryRelease can be used to automatically call the release. 663 * 664 * @param vertexCount the number of vertices to reserve space for. Can be 0. 665 * @param indexCount the number of indices to reserve space for. Can be 0. 666 * @param vertexLayout the format of vertices (ignored if vertexCount == 0). 667 * @param vertices will point to reserved vertex space if vertexCount is 668 * non-zero. Illegal to pass NULL if vertexCount > 0. 669 * @param indices will point to reserved index space if indexCount is 670 * non-zero. Illegal to pass NULL if indexCount > 0. 671 * 672 * @return true if succeeded in allocating space for the vertices and false 673 * if not. 674 */ 675 bool reserveAndLockGeometry(GrVertexLayout vertexLayout, 676 uint32_t vertexCount, 677 uint32_t indexCount, 678 void** vertices, 679 void** indices); 680 /** 681 * Provides hints to caller about the number of vertices and indices 682 * that can be allocated cheaply. This can be useful if caller is reserving 683 * space but doesn't know exactly how much geometry is needed. 684 * 685 * Also may hint whether the draw target should be flushed first. This is 686 * useful for deferred targets. 687 * 688 * @param vertexLayout layout of vertices caller would like to reserve 689 * @param vertexCount in: hint about how many vertices the caller would 690 * like to allocate. 691 * out: a hint about the number of vertices that can be 692 * allocated cheaply. Negative means no hint. 693 * Ignored if NULL. 694 * @param indexCount in: hint about how many indices the caller would 695 * like to allocate. 696 * out: a hint about the number of indices that can be 697 * allocated cheaply. Negative means no hint. 698 * Ignored if NULL. 699 * 700 * @return true if target should be flushed based on the input values. 701 */ 702 virtual bool geometryHints(GrVertexLayout vertexLayout, 703 int* vertexCount, 704 int* indexCount) const; 705 706 /** 707 * Releases reserved vertex/index data from reserveAndLockGeometry(). 708 */ 709 void releaseReservedGeometry(); 710 711 /** 712 * Sets source of vertex data for the next draw. Array must contain 713 * the vertex data when this is called. 714 * 715 * @param array cpu array containing vertex data. 716 * @param size size of the vertex data. 717 * @param vertexCount the number of vertices in the array. 718 */ 719 void setVertexSourceToArray(GrVertexLayout vertexLayout, 720 const void* vertexArray, 721 int vertexCount); 722 723 /** 724 * Sets source of index data for the next indexed draw. Array must contain 725 * the indices when this is called. 726 * 727 * @param array cpu array containing index data. 728 * @param indexCount the number of indices in the array. 729 */ 730 void setIndexSourceToArray(const void* indexArray, int indexCount); 731 732 /** 733 * Sets source of vertex data for the next draw. Data does not have to be 734 * in the buffer until drawIndexed or drawNonIndexed. 735 * 736 * @param buffer vertex buffer containing vertex data. Must be 737 * unlocked before draw call. 738 * @param vertexLayout layout of the vertex data in the buffer. 739 */ 740 void setVertexSourceToBuffer(GrVertexLayout vertexLayout, 741 const GrVertexBuffer* buffer); 742 743 /** 744 * Sets source of index data for the next indexed draw. Data does not have 745 * to be in the buffer until drawIndexed or drawNonIndexed. 746 * 747 * @param buffer index buffer containing indices. Must be unlocked 748 * before indexed draw call. 749 */ 750 void setIndexSourceToBuffer(const GrIndexBuffer* buffer); 751 752 /** 753 * Draws indexed geometry using the current state and current vertex / index 754 * sources. 755 * 756 * @param type The type of primitives to draw. 757 * @param startVertex the vertex in the vertex array/buffer corresponding 758 * to index 0 759 * @param startIndex first index to read from index src. 760 * @param vertexCount one greater than the max index. 761 * @param indexCount the number of index elements to read. The index count 762 * is effectively trimmed to the last completely 763 * specified primitive. 764 */ 765 virtual void drawIndexed(GrPrimitiveType type, 766 int startVertex, 767 int startIndex, 768 int vertexCount, 769 int indexCount) = 0; 770 771 /** 772 * Draws non-indexed geometry using the current state and current vertex 773 * sources. 774 * 775 * @param type The type of primitives to draw. 776 * @param startVertex the vertex in the vertex array/buffer corresponding 777 * to index 0 778 * @param vertexCount one greater than the max index. 779 */ 780 virtual void drawNonIndexed(GrPrimitiveType type, 781 int startVertex, 782 int vertexCount) = 0; 783 784 /** 785 * Helper function for drawing rects. This does not use the current index 786 * and vertex sources. After returning, the vertex and index sources may 787 * have changed. They should be reestablished before the next drawIndexed 788 * or drawNonIndexed. This cannot be called between reserving and releasing 789 * geometry. The GrDrawTarget subclass may be able to perform additional 790 * optimizations if drawRect is used rather than drawIndexed or 791 * drawNonIndexed. 792 * @param rect the rect to draw 793 * @param matrix optional matrix applied to rect (before viewMatrix) 794 * @param stageEnableBitfield bitmask indicating which stages are enabled. 795 * Bit i indicates whether stage i is enabled. 796 * @param srcRects specifies rects for stages enabled by stageEnableMask. 797 * if stageEnableMask bit i is 1, srcRects is not NULL, 798 * and srcRects[i] is not NULL, then srcRects[i] will be 799 * used as coordinates for stage i. Otherwise, if stage i 800 * is enabled then rect is used as the coordinates. 801 * @param srcMatrices optional matrices applied to srcRects. If 802 * srcRect[i] is non-NULL and srcMatrices[i] is 803 * non-NULL then srcRect[i] will be transformed by 804 * srcMatrix[i]. srcMatrices can be NULL when no 805 * srcMatrices are desired. 806 */ 807 virtual void drawRect(const GrRect& rect, 808 const GrMatrix* matrix, 809 StageBitfield stageEnableBitfield, 810 const GrRect* srcRects[], 811 const GrMatrix* srcMatrices[]); 812 813 /** 814 * Helper for drawRect when the caller doesn't need separate src rects or 815 * matrices. 816 */ drawSimpleRect(const GrRect & rect,const GrMatrix * matrix,StageBitfield stageEnableBitfield)817 void drawSimpleRect(const GrRect& rect, 818 const GrMatrix* matrix, 819 StageBitfield stageEnableBitfield) { 820 drawRect(rect, matrix, stageEnableBitfield, NULL, NULL); 821 } 822 823 /** 824 * Clear the render target. Ignores the clip and all other draw state 825 * (blend mode, stages, etc). Clears the whole thing if rect is NULL, 826 * otherwise just the rect. 827 */ 828 virtual void clear(const GrIRect* rect, GrColor color) = 0; 829 830 /** 831 * Returns the maximum number of edges that may be specified in a single 832 * draw call when performing edge antialiasing. This is usually limited 833 * by the number of fragment uniforms which may be uploaded. Must be a 834 * minimum of six, since a triangle's vertices each belong to two boundary 835 * edges which may be distinct. 836 */ getMaxEdges()837 virtual int getMaxEdges() const { return 6; } 838 839 /////////////////////////////////////////////////////////////////////////// 840 841 class AutoStateRestore : ::GrNoncopyable { 842 public: 843 AutoStateRestore(); 844 AutoStateRestore(GrDrawTarget* target); 845 ~AutoStateRestore(); 846 847 /** 848 * if this object is already saving state for param target then 849 * this does nothing. Otherise, it restores previously saved state on 850 * previous target (if any) and saves current state on param target. 851 */ 852 void set(GrDrawTarget* target); 853 854 private: 855 GrDrawTarget* fDrawTarget; 856 SavedDrawState fDrawState; 857 }; 858 859 /////////////////////////////////////////////////////////////////////////// 860 861 class AutoViewMatrixRestore : ::GrNoncopyable { 862 public: AutoViewMatrixRestore()863 AutoViewMatrixRestore() { 864 fDrawTarget = NULL; 865 } 866 AutoViewMatrixRestore(GrDrawTarget * target)867 AutoViewMatrixRestore(GrDrawTarget* target) 868 : fDrawTarget(target), fMatrix(fDrawTarget->getViewMatrix()) { 869 GrAssert(NULL != target); 870 } 871 set(GrDrawTarget * target)872 void set(GrDrawTarget* target) { 873 GrAssert(NULL != target); 874 if (NULL != fDrawTarget) { 875 fDrawTarget->setViewMatrix(fMatrix); 876 } 877 fDrawTarget = target; 878 fMatrix = target->getViewMatrix(); 879 } 880 ~AutoViewMatrixRestore()881 ~AutoViewMatrixRestore() { 882 if (NULL != fDrawTarget) { 883 fDrawTarget->setViewMatrix(fMatrix); 884 } 885 } 886 887 private: 888 GrDrawTarget* fDrawTarget; 889 GrMatrix fMatrix; 890 }; 891 892 /////////////////////////////////////////////////////////////////////////// 893 894 class AutoReleaseGeometry : ::GrNoncopyable { 895 public: AutoReleaseGeometry(GrDrawTarget * target,GrVertexLayout vertexLayout,uint32_t vertexCount,uint32_t indexCount)896 AutoReleaseGeometry(GrDrawTarget* target, 897 GrVertexLayout vertexLayout, 898 uint32_t vertexCount, 899 uint32_t indexCount) { 900 fTarget = NULL; 901 this->set(target, vertexLayout, vertexCount, indexCount); 902 } 903 AutoReleaseGeometry()904 AutoReleaseGeometry() { 905 fTarget = NULL; 906 } 907 ~AutoReleaseGeometry()908 ~AutoReleaseGeometry() { 909 if (NULL != fTarget) { 910 fTarget->releaseReservedGeometry(); 911 } 912 } 913 set(GrDrawTarget * target,GrVertexLayout vertexLayout,uint32_t vertexCount,uint32_t indexCount)914 bool set(GrDrawTarget* target, 915 GrVertexLayout vertexLayout, 916 uint32_t vertexCount, 917 uint32_t indexCount) { 918 if (NULL != fTarget) { 919 fTarget->releaseReservedGeometry(); 920 } 921 fTarget = target; 922 if (NULL != fTarget) { 923 if (!fTarget->reserveAndLockGeometry(vertexLayout, 924 vertexCount, 925 indexCount, 926 &fVertices, 927 &fIndices)) { 928 fTarget = NULL; 929 } 930 } 931 return NULL != fTarget; 932 } 933 succeeded()934 bool succeeded() const { return NULL != fTarget; } vertices()935 void* vertices() const { return fVertices; } indices()936 void* indices() const { return fIndices; } 937 positions()938 GrPoint* positions() const { 939 return static_cast<GrPoint*>(fVertices); 940 } 941 942 private: 943 GrDrawTarget* fTarget; 944 void* fVertices; 945 void* fIndices; 946 }; 947 948 /////////////////////////////////////////////////////////////////////////// 949 950 class AutoClipRestore : ::GrNoncopyable { 951 public: AutoClipRestore(GrDrawTarget * target)952 AutoClipRestore(GrDrawTarget* target) { 953 fTarget = target; 954 fClip = fTarget->getClip(); 955 } 956 ~AutoClipRestore()957 ~AutoClipRestore() { 958 fTarget->setClip(fClip); 959 } 960 private: 961 GrDrawTarget* fTarget; 962 GrClip fClip; 963 }; 964 965 //////////////////////////////////////////////////////////////////////////// 966 // Helpers for picking apart vertex layouts 967 968 /** 969 * Helper function to compute the size of a vertex from a vertex layout 970 * @return size of a single vertex. 971 */ 972 static size_t VertexSize(GrVertexLayout vertexLayout); 973 974 /** 975 * Helper function for determining the index of texture coordinates that 976 * is input for a texture stage. Note that a stage may instead use positions 977 * as texture coordinates, in which case the result of the function is 978 * indistinguishable from the case when the stage is disabled. 979 * 980 * @param stage the stage to query 981 * @param vertexLayout layout to query 982 * 983 * @return the texture coordinate index or -1 if the stage doesn't use 984 * separate (non-position) texture coordinates. 985 */ 986 static int VertexTexCoordsForStage(int stage, GrVertexLayout vertexLayout); 987 988 /** 989 * Helper function to compute the offset of texture coordinates in a vertex 990 * @return offset of texture coordinates in vertex layout or -1 if the 991 * layout has no texture coordinates. Will be 0 if positions are 992 * used as texture coordinates for the stage. 993 */ 994 static int VertexStageCoordOffset(int stage, GrVertexLayout vertexLayout); 995 996 /** 997 * Helper function to compute the offset of the color in a vertex 998 * @return offset of color in vertex layout or -1 if the 999 * layout has no color. 1000 */ 1001 static int VertexColorOffset(GrVertexLayout vertexLayout); 1002 1003 /** 1004 * Helper function to determine if vertex layout contains explicit texture 1005 * coordinates of some index. 1006 * 1007 * @param coordIndex the tex coord index to query 1008 * @param vertexLayout layout to query 1009 * 1010 * @return true if vertex specifies texture coordinates for the index, 1011 * false otherwise. 1012 */ 1013 static bool VertexUsesTexCoordIdx(int coordIndex, 1014 GrVertexLayout vertexLayout); 1015 1016 /** 1017 * Helper function to determine if vertex layout contains either explicit or 1018 * implicit texture coordinates for a stage. 1019 * 1020 * @param stage the stage to query 1021 * @param vertexLayout layout to query 1022 * 1023 * @return true if vertex specifies texture coordinates for the stage, 1024 * false otherwise. 1025 */ 1026 static bool VertexUsesStage(int stage, GrVertexLayout vertexLayout); 1027 1028 /** 1029 * Helper function to compute the size of each vertex and the offsets of 1030 * texture coordinates and color. Determines tex coord offsets by tex coord 1031 * index rather than by stage. (Each stage can be mapped to any t.c. index 1032 * by StageTexCoordVertexLayoutBit.) 1033 * 1034 * @param vertexLayout the layout to query 1035 * @param texCoordOffsetsByIdx after return it is the offset of each 1036 * tex coord index in the vertex or -1 if 1037 * index isn't used. 1038 * @return size of a single vertex 1039 */ 1040 static int VertexSizeAndOffsetsByIdx(GrVertexLayout vertexLayout, 1041 int texCoordOffsetsByIdx[kMaxTexCoords], 1042 int *colorOffset); 1043 1044 /** 1045 * Helper function to compute the size of each vertex and the offsets of 1046 * texture coordinates and color. Determines tex coord offsets by stage 1047 * rather than by index. (Each stage can be mapped to any t.c. index 1048 * by StageTexCoordVertexLayoutBit.) If a stage uses positions for 1049 * tex coords then that stage's offset will be 0 (positions are always at 0). 1050 * 1051 * @param vertexLayout the layout to query 1052 * @param texCoordOffsetsByStage after return it is the offset of each 1053 * tex coord index in the vertex or -1 if 1054 * index isn't used. 1055 * @return size of a single vertex 1056 */ 1057 static int VertexSizeAndOffsetsByStage(GrVertexLayout vertexLayout, 1058 int texCoordOffsetsByStage[kNumStages], 1059 int *colorOffset); 1060 1061 /** 1062 * Accessing positions, texture coords, or colors, of a vertex within an 1063 * array is a hassle involving casts and simple math. These helpers exist 1064 * to keep GrDrawTarget clients' code a bit nicer looking. 1065 */ 1066 1067 /** 1068 * Gets a pointer to a GrPoint of a vertex's position or texture 1069 * coordinate. 1070 * @param vertices the vetex array 1071 * @param vertexIndex the index of the vertex in the array 1072 * @param vertexSize the size of each vertex in the array 1073 * @param offset the offset in bytes of the vertex component. 1074 * Defaults to zero (corresponding to vertex position) 1075 * @return pointer to the vertex component as a GrPoint 1076 */ 1077 static GrPoint* GetVertexPoint(void* vertices, 1078 int vertexIndex, 1079 int vertexSize, 1080 int offset = 0) { 1081 intptr_t start = GrTCast<intptr_t>(vertices); 1082 return GrTCast<GrPoint*>(start + offset + 1083 vertexIndex * vertexSize); 1084 } 1085 static const GrPoint* GetVertexPoint(const void* vertices, 1086 int vertexIndex, 1087 int vertexSize, 1088 int offset = 0) { 1089 intptr_t start = GrTCast<intptr_t>(vertices); 1090 return GrTCast<const GrPoint*>(start + offset + 1091 vertexIndex * vertexSize); 1092 } 1093 1094 /** 1095 * Gets a pointer to a GrColor inside a vertex within a vertex array. 1096 * @param vertices the vetex array 1097 * @param vertexIndex the index of the vertex in the array 1098 * @param vertexSize the size of each vertex in the array 1099 * @param offset the offset in bytes of the vertex color 1100 * @return pointer to the vertex component as a GrColor 1101 */ GetVertexColor(void * vertices,int vertexIndex,int vertexSize,int offset)1102 static GrColor* GetVertexColor(void* vertices, 1103 int vertexIndex, 1104 int vertexSize, 1105 int offset) { 1106 intptr_t start = GrTCast<intptr_t>(vertices); 1107 return GrTCast<GrColor*>(start + offset + 1108 vertexIndex * vertexSize); 1109 } GetVertexColor(const void * vertices,int vertexIndex,int vertexSize,int offset)1110 static const GrColor* GetVertexColor(const void* vertices, 1111 int vertexIndex, 1112 int vertexSize, 1113 int offset) { 1114 const intptr_t start = GrTCast<intptr_t>(vertices); 1115 return GrTCast<const GrColor*>(start + offset + 1116 vertexIndex * vertexSize); 1117 } 1118 1119 static void VertexLayoutUnitTest(); 1120 1121 protected: 1122 // given a vertex layout and a draw state, will a stage be used? StageWillBeUsed(int stage,GrVertexLayout layout,const DrState & state)1123 static bool StageWillBeUsed(int stage, GrVertexLayout layout, 1124 const DrState& state) { 1125 return NULL != state.fTextures[stage] && VertexUsesStage(stage, layout); 1126 } 1127 isStageEnabled(int stage)1128 bool isStageEnabled(int stage) const { 1129 return StageWillBeUsed(stage, fGeometrySrc.fVertexLayout, fCurrDrawState); 1130 } 1131 1132 // Helpers for GrDrawTarget subclasses that won't have private access to 1133 // SavedDrawState but need to peek at the state values. accessSavedDrawState(SavedDrawState & sds)1134 static DrState& accessSavedDrawState(SavedDrawState& sds) 1135 { return sds.fState; } accessSavedDrawState(const SavedDrawState & sds)1136 static const DrState& accessSavedDrawState(const SavedDrawState& sds) 1137 { return sds.fState; } 1138 1139 // implemented by subclass 1140 virtual bool onAcquireGeometry(GrVertexLayout vertexLayout, 1141 void** vertices, 1142 void** indices) = 0; 1143 1144 virtual void onReleaseGeometry() = 0; 1145 1146 // subclass overrides to be notified when clip is set. 1147 virtual void clipWillBeSet(const GrClip& clip) = 0; 1148 1149 virtual void onSetVertexSourceToArray(const void* vertexArray, 1150 int vertexCount) = 0; 1151 1152 virtual void onSetIndexSourceToArray(const void* indexArray, 1153 int indexCount) = 0; 1154 1155 // Helpers for drawRect, protected so subclasses that override drawRect 1156 // can use them. 1157 static GrVertexLayout GetRectVertexLayout(StageBitfield stageEnableBitfield, 1158 const GrRect* srcRects[]); 1159 1160 static void SetRectVertices(const GrRect& rect, 1161 const GrMatrix* matrix, 1162 const GrRect* srcRects[], 1163 const GrMatrix* srcMatrices[], 1164 GrVertexLayout layout, 1165 void* vertices); 1166 1167 enum GeometrySrcType { 1168 kReserved_GeometrySrcType, // src was set using reserveAndLockGeometry 1169 kArray_GeometrySrcType, // src was set using set*SourceToArray 1170 kBuffer_GeometrySrcType // src was set using set*SourceToBuffer 1171 }; 1172 1173 struct ReservedGeometry { 1174 bool fLocked; 1175 uint32_t fVertexCount; 1176 uint32_t fIndexCount; 1177 } fReservedGeometry; 1178 1179 struct GeometrySrc { 1180 GeometrySrcType fVertexSrc; 1181 const GrVertexBuffer* fVertexBuffer; // valid if src type is buffer 1182 GeometrySrcType fIndexSrc; 1183 const GrIndexBuffer* fIndexBuffer; // valid if src type is buffer 1184 GrVertexLayout fVertexLayout; 1185 } fGeometrySrc; 1186 1187 GrClip fClip; 1188 1189 DrState fCurrDrawState; 1190 1191 // Not meant for external use. Only setVertexSourceToBuffer and 1192 // setIndexSourceToBuffer will work since GrDrawTarget subclasses don't 1193 // support nested reserveAndLockGeometry (and cpu arrays internally use the 1194 // same path). 1195 class AutoGeometrySrcRestore { 1196 public: AutoGeometrySrcRestore(GrDrawTarget * target)1197 AutoGeometrySrcRestore(GrDrawTarget* target) { 1198 fTarget = target; 1199 fGeometrySrc = fTarget->fGeometrySrc; 1200 } ~AutoGeometrySrcRestore()1201 ~AutoGeometrySrcRestore() { 1202 fTarget->fGeometrySrc = fGeometrySrc; 1203 } 1204 private: 1205 GrDrawTarget *fTarget; 1206 GeometrySrc fGeometrySrc; 1207 1208 AutoGeometrySrcRestore(); 1209 AutoGeometrySrcRestore(const AutoGeometrySrcRestore&); 1210 AutoGeometrySrcRestore& operator =(AutoGeometrySrcRestore&); 1211 }; 1212 }; 1213 1214 #endif 1215