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