GrGpu.h revision c8f7f47afaf8f9471e6d111655c5610a8bd210a2
1 2/* 3 * Copyright 2011 Google Inc. 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10#ifndef GrGpu_DEFINED 11#define GrGpu_DEFINED 12 13#include "GrDrawTarget.h" 14#include "GrRect.h" 15#include "GrRefCnt.h" 16#include "GrClipMaskManager.h" 17 18class GrContext; 19class GrIndexBufferAllocPool; 20class GrPath; 21class GrPathRenderer; 22class GrPathRendererChain; 23class GrResource; 24class GrStencilBuffer; 25class GrVertexBufferAllocPool; 26 27class GrGpu : public GrDrawTarget { 28 29public: 30 31 /** 32 * Additional blend coeffecients for dual source blending, not exposed 33 * through GrPaint/GrContext. 34 */ 35 enum ExtendedBlendCoeffs { 36 // source 2 refers to second output color when 37 // using dual source blending. 38 kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount, 39 kIS2C_GrBlendCoeff, 40 kS2A_GrBlendCoeff, 41 kIS2A_GrBlendCoeff, 42 43 kTotalGrBlendCoeffCount 44 }; 45 46 /** 47 * Create an instance of GrGpu that matches the specified Engine backend. 48 * If the requested engine is not supported (at compile-time or run-time) 49 * this returns NULL. 50 */ 51 static GrGpu* Create(GrEngine, GrPlatform3DContext context3D); 52 53 //////////////////////////////////////////////////////////////////////////// 54 55 GrGpu(); 56 virtual ~GrGpu(); 57 58 // The GrContext sets itself as the owner of this Gpu object 59 void setContext(GrContext* context) { 60 GrAssert(NULL == fContext); 61 fContext = context; 62 fClipMaskManager.setContext(context); 63 } 64 GrContext* getContext() { return fContext; } 65 const GrContext* getContext() const { return fContext; } 66 67 /** 68 * The GrGpu object normally assumes that no outsider is setting state 69 * within the underlying 3D API's context/device/whatever. This call informs 70 * the GrGpu that the state was modified and it shouldn't make assumptions 71 * about the state. 72 */ 73 void markContextDirty() { fContextIsDirty = true; } 74 75 void unimpl(const char[]); 76 77 /** 78 * Creates a texture object. If desc width or height is not a power of 79 * two but underlying API requires a power of two texture then srcData 80 * will be embedded in a power of two texture. The extra width and height 81 * is filled as though srcData were rendered clamped into the texture. 82 * 83 * If kRenderTarget_TextureFlag is specified the GrRenderTarget is 84 * accessible via GrTexture::asRenderTarget(). The texture will hold a ref 85 * on the render target until its releaseRenderTarget() is called or it is 86 * destroyed. 87 * 88 * @param desc describes the texture to be created. 89 * @param srcData texel data to load texture. Begins with full-size 90 * palette data for paletted textures. Contains width* 91 * height texels. If NULL texture data is uninitialized. 92 * 93 * @return The texture object if successful, otherwise NULL. 94 */ 95 GrTexture* createTexture(const GrTextureDesc& desc, 96 const void* srcData, size_t rowBytes); 97 98 /** 99 * Implements GrContext::createPlatformTexture 100 */ 101 GrTexture* createPlatformTexture(const GrPlatformTextureDesc& desc); 102 103 /** 104 * Implements GrContext::createPlatformTexture 105 */ 106 GrRenderTarget* createPlatformRenderTarget(const GrPlatformRenderTargetDesc& desc); 107 108 /** 109 * Creates a vertex buffer. 110 * 111 * @param size size in bytes of the vertex buffer 112 * @param dynamic hints whether the data will be frequently changed 113 * by either GrVertexBuffer::lock or 114 * GrVertexBuffer::updateData. 115 * 116 * @return The vertex buffer if successful, otherwise NULL. 117 */ 118 GrVertexBuffer* createVertexBuffer(uint32_t size, bool dynamic); 119 120 /** 121 * Creates an index buffer. 122 * 123 * @param size size in bytes of the index buffer 124 * @param dynamic hints whether the data will be frequently changed 125 * by either GrIndexBuffer::lock or 126 * GrIndexBuffer::updateData. 127 * 128 * @return The index buffer if successful, otherwise NULL. 129 */ 130 GrIndexBuffer* createIndexBuffer(uint32_t size, bool dynamic); 131 132 /** 133 * Creates a path object that can be stenciled using stencilPath(). It is 134 * only legal to call this if the caps report support for path stenciling. 135 */ 136 GrPath* createPath(const SkPath& path); 137 138 /** 139 * Returns an index buffer that can be used to render quads. 140 * Six indices per quad: 0, 1, 2, 0, 2, 3, etc. 141 * The max number of quads can be queried using GrIndexBuffer::maxQuads(). 142 * Draw with kTriangles_GrPrimitiveType 143 * @ return the quad index buffer 144 */ 145 const GrIndexBuffer* getQuadIndexBuffer() const; 146 147 /** 148 * Returns a vertex buffer with four position-only vertices [(0,0), (1,0), 149 * (1,1), (0,1)]. 150 * @ return unit square vertex buffer 151 */ 152 const GrVertexBuffer* getUnitSquareVertexBuffer() const; 153 154 /** 155 * Resolves MSAA. 156 */ 157 void resolveRenderTarget(GrRenderTarget* target); 158 159 /** 160 * Ensures that the current render target is actually set in the 161 * underlying 3D API. Used when client wants to use 3D API to directly 162 * render to the RT. 163 */ 164 void forceRenderTargetFlush(); 165 166 /** 167 * If this returns true then a sequence that reads unpremultiplied pixels 168 * from a surface, writes back the same values, and reads them again will 169 * give the same pixel values back in both reads. 170 */ 171 virtual bool canPreserveReadWriteUnpremulPixels() = 0; 172 173 /** 174 * readPixels with some configs may be slow. Given a desired config this 175 * function returns a fast-path config. The returned config must have the 176 * same components, component sizes, and not require conversion between 177 * pre- and unpremultiplied alpha. The caller is free to ignore the result 178 * and call readPixels with the original config. 179 */ 180 virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig config) 181 const { 182 return config; 183 } 184 185 /** 186 * Same as above but applies to writeTexturePixels 187 */ 188 virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig config) 189 const { 190 return config; 191 } 192 193 /** 194 * OpenGL's readPixels returns the result bottom-to-top while the skia 195 * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious 196 * solution is to have the subclass do the flip using either the CPU or GPU. 197 * However, the caller (GrContext) may have transformations to apply and can 198 * simply fold in the y-flip for free. On the other hand, the subclass may 199 * be able to do it for free itself. For example, the subclass may have to 200 * do memcpys to handle rowBytes that aren't tight. It could do the y-flip 201 * concurrently. 202 * 203 * This function returns true if a y-flip is required to put the pixels in 204 * top-to-bottom order and the subclass cannot do it for free. 205 * 206 * See read pixels for the params 207 * @return true if calling readPixels with the same set of params will 208 * produce bottom-to-top data 209 */ 210 virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget, 211 int left, int top, 212 int width, int height, 213 GrPixelConfig config, 214 size_t rowBytes) const = 0; 215 /** 216 * This should return true if reading a NxM rectangle of pixels from a 217 * render target is faster if the target has dimensons N and M and the read 218 * rectangle has its top-left at 0,0. 219 */ 220 virtual bool fullReadPixelsIsFasterThanPartial() const { return false; }; 221 222 /** 223 * Reads a rectangle of pixels from a render target. Fails if read requires 224 * conversion between premultiplied and unpremultiplied configs. The caller 225 * should do the conversion by rendering to a target with the desire config 226 * first. 227 * 228 * @param renderTarget the render target to read from. NULL means the 229 * current render target. 230 * @param left left edge of the rectangle to read (inclusive) 231 * @param top top edge of the rectangle to read (inclusive) 232 * @param width width of rectangle to read in pixels. 233 * @param height height of rectangle to read in pixels. 234 * @param config the pixel config of the destination buffer 235 * @param buffer memory to read the rectangle into. 236 * @param rowBytes the number of bytes between consecutive rows. Zero 237 * means rows are tightly packed. 238 * @param invertY buffer should be populated bottom-to-top as opposed 239 * to top-to-bottom (skia's usual order) 240 * 241 * @return true if the read succeeded, false if not. The read can fail 242 * because of a unsupported pixel config or because no render 243 * target is currently set. 244 */ 245 bool readPixels(GrRenderTarget* renderTarget, 246 int left, int top, int width, int height, 247 GrPixelConfig config, void* buffer, size_t rowBytes, 248 bool invertY); 249 250 /** 251 * Updates the pixels in a rectangle of a texture. 252 * 253 * @param left left edge of the rectangle to write (inclusive) 254 * @param top top edge of the rectangle to write (inclusive) 255 * @param width width of rectangle to write in pixels. 256 * @param height height of rectangle to write in pixels. 257 * @param config the pixel config of the source buffer 258 * @param buffer memory to read pixels from 259 * @param rowBytes number of bytes bewtween consecutive rows. Zero 260 * means rows are tightly packed. 261 */ 262 void writeTexturePixels(GrTexture* texture, 263 int left, int top, int width, int height, 264 GrPixelConfig config, const void* buffer, 265 size_t rowBytes); 266 267 /** 268 * Called to tell Gpu object that all GrResources have been lost and should 269 * be abandoned. Overrides must call INHERITED::abandonResources(). 270 */ 271 virtual void abandonResources(); 272 273 /** 274 * Called to tell Gpu object to release all GrResources. Overrides must call 275 * INHERITED::releaseResources(). 276 */ 277 void releaseResources(); 278 279 /** 280 * Add resource to list of resources. Should only be called by GrResource. 281 * @param resource the resource to add. 282 */ 283 void insertResource(GrResource* resource); 284 285 /** 286 * Remove resource from list of resources. Should only be called by 287 * GrResource. 288 * @param resource the resource to remove. 289 */ 290 void removeResource(GrResource* resource); 291 292 // GrDrawTarget overrides 293 virtual void clear(const GrIRect* rect, GrColor color) SK_OVERRIDE; 294 295 virtual void purgeResources() SK_OVERRIDE { 296 // The clip mask manager can rebuild all its clip masks so just 297 // get rid of them all. 298 fClipMaskManager.releaseResources(); 299 } 300 301 // After the client interacts directly with the 3D context state the GrGpu 302 // must resync its internal state and assumptions about 3D context state. 303 // Each time this occurs the GrGpu bumps a timestamp. 304 // state of the 3D context 305 // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about 306 // a billion years. 307 typedef uint64_t ResetTimestamp; 308 309 // This timestamp is always older than the current timestamp 310 static const ResetTimestamp kExpiredTimestamp = 0; 311 // Returns a timestamp based on the number of times the context was reset. 312 // This timestamp can be used to lazily detect when cached 3D context state 313 // is dirty. 314 ResetTimestamp getResetTimestamp() const { 315 return fResetTimestamp; 316 } 317 318 /** 319 * Can the provided configuration act as a color render target? 320 */ 321 bool isConfigRenderable(GrPixelConfig config) const { 322 GrAssert(kGrPixelConfigCount > config); 323 return fConfigRenderSupport[config]; 324 } 325 326 virtual void enableScissoring(const GrIRect& rect) = 0; 327 virtual void disableScissor() = 0; 328 329 // GrGpu subclass sets clip bit in the stencil buffer. The subclass is 330 // free to clear the remaining bits to zero if masked clears are more 331 // expensive than clearing all bits. 332 virtual void clearStencilClip(const GrIRect& rect, bool insideClip) = 0; 333 334 enum PrivateDrawStateStateBits { 335 kFirstBit = (GrDrawState::kLastPublicStateBit << 1), 336 337 kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify 338 // stencil bits used for 339 // clipping. 340 }; 341 342 virtual void postClipPush() SK_OVERRIDE { 343 fClipMaskManager.postClipPush(); 344 } 345 virtual void preClipPop() SK_OVERRIDE { 346 fClipMaskManager.preClipPop(); 347 } 348 349protected: 350 enum DrawType { 351 kDrawPoints_DrawType, 352 kDrawLines_DrawType, 353 kDrawTriangles_DrawType, 354 kStencilPath_DrawType, 355 }; 356 357 DrawType PrimTypeToDrawType(GrPrimitiveType type) { 358 switch (type) { 359 case kTriangles_GrPrimitiveType: 360 case kTriangleStrip_GrPrimitiveType: 361 case kTriangleFan_GrPrimitiveType: 362 return kDrawTriangles_DrawType; 363 case kPoints_GrPrimitiveType: 364 return kDrawPoints_DrawType; 365 case kLines_GrPrimitiveType: 366 case kLineStrip_GrPrimitiveType: 367 return kDrawLines_DrawType; 368 default: 369 GrCrash("Unexpected primitive type"); 370 return kDrawTriangles_DrawType; 371 } 372 } 373 374 // prepares clip flushes gpu state before a draw 375 bool setupClipAndFlushState(DrawType); 376 377 // Functions used to map clip-respecting stencil tests into normal 378 // stencil funcs supported by GPUs. 379 static GrStencilFunc ConvertStencilFunc(bool stencilInClip, 380 GrStencilFunc func); 381 static void ConvertStencilFuncAndMask(GrStencilFunc func, 382 bool clipInStencil, 383 unsigned int clipBit, 384 unsigned int userBits, 385 unsigned int* ref, 386 unsigned int* mask); 387 388 // stencil settings to clip drawing when stencil clipping is in effect 389 // and the client isn't using the stencil test. 390 static const GrStencilSettings* GetClipStencilSettings(); 391 392 GrClipMaskManager fClipMaskManager; 393 394 struct GeometryPoolState { 395 const GrVertexBuffer* fPoolVertexBuffer; 396 int fPoolStartVertex; 397 398 const GrIndexBuffer* fPoolIndexBuffer; 399 int fPoolStartIndex; 400 }; 401 const GeometryPoolState& getGeomPoolState() { 402 return fGeomPoolStateStack.back(); 403 } 404 405 // Derived classes need access to this so they can fill it out in their 406 // constructors 407 bool fConfigRenderSupport[kGrPixelConfigCount]; 408 409 // GrDrawTarget overrides 410 virtual bool onReserveVertexSpace(GrVertexLayout vertexLayout, 411 int vertexCount, 412 void** vertices) SK_OVERRIDE; 413 virtual bool onReserveIndexSpace(int indexCount, 414 void** indices) SK_OVERRIDE; 415 virtual void releaseReservedVertexSpace() SK_OVERRIDE; 416 virtual void releaseReservedIndexSpace() SK_OVERRIDE; 417 virtual void onSetVertexSourceToArray(const void* vertexArray, 418 int vertexCount) SK_OVERRIDE; 419 virtual void onSetIndexSourceToArray(const void* indexArray, 420 int indexCount) SK_OVERRIDE; 421 virtual void releaseVertexArray() SK_OVERRIDE; 422 virtual void releaseIndexArray() SK_OVERRIDE; 423 virtual void geometrySourceWillPush() SK_OVERRIDE; 424 virtual void geometrySourceWillPop( 425 const GeometrySrcState& restoredState) SK_OVERRIDE; 426 427 // Helpers for setting up geometry state 428 void finalizeReservedVertices(); 429 void finalizeReservedIndices(); 430 431 // called when the 3D context state is unknown. Subclass should emit any 432 // assumed 3D context state and dirty any state cache. 433 virtual void onResetContext() = 0; 434 435 436 // overridden by API-specific derived class to create objects. 437 virtual GrTexture* onCreateTexture(const GrTextureDesc& desc, 438 const void* srcData, 439 size_t rowBytes) = 0; 440 virtual GrTexture* onCreatePlatformTexture(const GrPlatformTextureDesc& desc) = 0; 441 virtual GrRenderTarget* onCreatePlatformRenderTarget(const GrPlatformRenderTargetDesc& desc) = 0; 442 virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size, 443 bool dynamic) = 0; 444 virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size, 445 bool dynamic) = 0; 446 virtual GrPath* onCreatePath(const SkPath& path) = 0; 447 448 // overridden by API-specific derivated class to perform the clear and 449 // clearRect. NULL rect means clear whole target. 450 virtual void onClear(const GrIRect* rect, GrColor color) = 0; 451 452 // overridden by API-specific derived class to perform the draw call. 453 virtual void onGpuDrawIndexed(GrPrimitiveType type, 454 uint32_t startVertex, 455 uint32_t startIndex, 456 uint32_t vertexCount, 457 uint32_t indexCount) = 0; 458 459 virtual void onGpuDrawNonIndexed(GrPrimitiveType type, 460 uint32_t vertexCount, 461 uint32_t numVertices) = 0; 462 // overridden by API-specific derived class to perform the path stenciling. 463 virtual void onGpuStencilPath(const GrPath& path, GrPathFill fill) = 0; 464 465 // overridden by API-specific derived class to perform flush 466 virtual void onForceRenderTargetFlush() = 0; 467 468 // overridden by API-specific derived class to perform the read pixels. 469 virtual bool onReadPixels(GrRenderTarget* target, 470 int left, int top, int width, int height, 471 GrPixelConfig, 472 void* buffer, 473 size_t rowBytes, 474 bool invertY) = 0; 475 476 // overridden by API-specific derived class to perform the texture update 477 virtual void onWriteTexturePixels(GrTexture* texture, 478 int left, int top, int width, int height, 479 GrPixelConfig config, const void* buffer, 480 size_t rowBytes) = 0; 481 482 // overridden by API-specific derived class to perform the resolve 483 virtual void onResolveRenderTarget(GrRenderTarget* target) = 0; 484 485 // called to program the vertex data, indexCount will be 0 if drawing non- 486 // indexed geometry. The subclass may adjust the startVertex and/or 487 // startIndex since it may have already accounted for these in the setup. 488 virtual void setupGeometry(int* startVertex, 489 int* startIndex, 490 int vertexCount, 491 int indexCount) = 0; 492 493 // width and height may be larger than rt (if underlying API allows it). 494 // Should attach the SB to the RT. Returns false if compatible sb could 495 // not be created. 496 virtual bool createStencilBufferForRenderTarget(GrRenderTarget* rt, 497 int width, 498 int height) = 0; 499 500 // attaches an existing SB to an existing RT. 501 virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer* sb, 502 GrRenderTarget* rt) = 0; 503 504 // The GrGpu typically records the clients requested state and then flushes 505 // deltas from previous state at draw time. This function does the 506 // API-specific flush of the state 507 // returns false if current state is unsupported. 508 virtual bool flushGraphicsState(DrawType) = 0; 509 510 // clears the entire stencil buffer to 0 511 virtual void clearStencil() = 0; 512 513private: 514 GrContext* fContext; // not reffed (context refs gpu) 515 516 ResetTimestamp fResetTimestamp; 517 518 GrVertexBufferAllocPool* fVertexPool; 519 520 GrIndexBufferAllocPool* fIndexPool; 521 522 // counts number of uses of vertex/index pool in the geometry stack 523 int fVertexPoolUseCnt; 524 int fIndexPoolUseCnt; 525 526 enum { 527 kPreallocGeomPoolStateStackCnt = 4, 528 }; 529 SkSTArray<kPreallocGeomPoolStateStackCnt, 530 GeometryPoolState, true> fGeomPoolStateStack; 531 532 mutable GrIndexBuffer* fQuadIndexBuffer; // mutable so it can be 533 // created on-demand 534 535 mutable GrVertexBuffer* fUnitSquareVertexBuffer; // mutable so it can be 536 // created on-demand 537 538 bool fContextIsDirty; 539 540 GrResource* fResourceHead; 541 542 // Given a rt, find or create a stencil buffer and attach it 543 bool attachStencilBufferToRenderTarget(GrRenderTarget* target); 544 545 // GrDrawTarget overrides 546 virtual void onDrawIndexed(GrPrimitiveType type, 547 int startVertex, 548 int startIndex, 549 int vertexCount, 550 int indexCount) SK_OVERRIDE; 551 virtual void onDrawNonIndexed(GrPrimitiveType type, 552 int startVertex, 553 int vertexCount) SK_OVERRIDE; 554 virtual void onStencilPath(const GrPath& path, GrPathFill fill) SK_OVERRIDE; 555 556 // readies the pools to provide vertex/index data. 557 void prepareVertexPool(); 558 void prepareIndexPool(); 559 560 void resetContext() { 561 // We call this because the client may have messed with the 562 // stencil buffer. Perhaps we should detect whether it is a 563 // internally created stencil buffer and if so skip the invalidate. 564 fClipMaskManager.invalidateStencilMask(); 565 this->onResetContext(); 566 ++fResetTimestamp; 567 } 568 569 void handleDirtyContext() { 570 if (fContextIsDirty) { 571 this->resetContext(); 572 fContextIsDirty = false; 573 } 574 } 575 576 typedef GrDrawTarget INHERITED; 577}; 578 579#endif 580