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