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