GrGpu.h revision d53a82706ebd227bc0e4dd535118cdd8298131bd
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 "GrPathRendering.h" 13#include "GrProgramDesc.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 SkRefCnt { 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 fContext; } 56 const GrContext* getContext() const { return fContext; } 57 58 /** 59 * Gets the capabilities of the draw target. 60 */ 61 const GrDrawTargetCaps* caps() const { return fCaps.get(); } 62 63 GrPathRendering* pathRendering() { 64 return fPathRendering.get(); 65 } 66 67 // Called by GrContext when the underlying backend context has been destroyed. 68 // GrGpu should use this to ensure that no backend API calls will be made from 69 // here onward, including in its destructor. Subclasses should call 70 // INHERITED::contextAbandoned() if they override this. 71 virtual void contextAbandoned(); 72 73 /** 74 * The GrGpu object normally assumes that no outsider is setting state 75 * within the underlying 3D API's context/device/whatever. This call informs 76 * the GrGpu that the state was modified and it shouldn't make assumptions 77 * about the state. 78 */ 79 void markContextDirty(uint32_t state = kAll_GrBackendState) { 80 fResetBits |= state; 81 } 82 83 void unimpl(const char[]); 84 85 /** 86 * Creates a texture object. If desc width or height is not a power of 87 * two but underlying API requires a power of two texture then srcData 88 * will be embedded in a power of two texture. The extra width and height 89 * is filled as though srcData were rendered clamped into the texture. 90 * The exception is when using compressed data formats. In this case, the 91 * desc width and height must be a multiple of the compressed format block 92 * size otherwise this function returns NULL. Similarly, if the underlying 93 * API requires a power of two texture and the source width and height are not 94 * a power of two, then this function returns NULL. 95 * 96 * If kRenderTarget_TextureFlag is specified the GrRenderTarget is 97 * accessible via GrTexture::asRenderTarget(). The texture will hold a ref 98 * on the render target until the texture is destroyed. Compressed textures 99 * cannot have the kRenderTarget_TextureFlag set. 100 * 101 * @param desc describes the texture to be created. 102 * @param srcData texel data to load texture. Begins with full-size 103 * palette data for paletted textures. For compressed 104 * formats it contains the compressed pixel data. Otherwise, 105 * it contains width*height texels. If NULL texture data 106 * is uninitialized. 107 * @param rowBytes the number of bytes between consecutive rows. Zero 108 * means rows are tightly packed. This field is ignored 109 * for compressed formats. 110 * 111 * @return The texture object if successful, otherwise NULL. 112 */ 113 GrTexture* createTexture(const GrSurfaceDesc& desc, 114 const void* srcData, size_t rowBytes); 115 116 /** 117 * Implements GrContext::wrapBackendTexture 118 */ 119 GrTexture* wrapBackendTexture(const GrBackendTextureDesc&); 120 121 /** 122 * Implements GrContext::wrapBackendTexture 123 */ 124 GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&); 125 126 /** 127 * Creates a vertex buffer. 128 * 129 * @param size size in bytes of the vertex buffer 130 * @param dynamic hints whether the data will be frequently changed 131 * by either GrVertexBuffer::map() or 132 * GrVertexBuffer::updateData(). 133 * 134 * @return The vertex buffer if successful, otherwise NULL. 135 */ 136 GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic); 137 138 /** 139 * Creates an index buffer. 140 * 141 * @param size size in bytes of the index buffer 142 * @param dynamic hints whether the data will be frequently changed 143 * by either GrIndexBuffer::map() or 144 * GrIndexBuffer::updateData(). 145 * 146 * @return The index buffer if successful, otherwise NULL. 147 */ 148 GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic); 149 150 /** 151 * Creates an index buffer for instance drawing with a specific pattern. 152 * 153 * @param pattern the pattern to repeat 154 * @param patternSize size in bytes of the pattern 155 * @param reps number of times to repeat the pattern 156 * @param vertCount number of vertices the pattern references 157 * @param dynamic hints whether the data will be frequently changed 158 * by either GrIndexBuffer::map() or 159 * GrIndexBuffer::updateData(). 160 * 161 * @return The index buffer if successful, otherwise NULL. 162 */ 163 GrIndexBuffer* createInstancedIndexBuffer(const uint16_t* pattern, 164 int patternSize, 165 int reps, 166 int vertCount, 167 bool isDynamic = false); 168 169 /** 170 * Returns an index buffer that can be used to render quads. 171 * Six indices per quad: 0, 1, 2, 0, 2, 3, etc. 172 * The max number of quads can be queried using GrIndexBuffer::maxQuads(). 173 * Draw with kTriangles_GrPrimitiveType 174 * @ return the quad index buffer 175 */ 176 const GrIndexBuffer* getQuadIndexBuffer() const; 177 178 /** 179 * Resolves MSAA. 180 */ 181 void resolveRenderTarget(GrRenderTarget* target); 182 183 /** 184 * Gets a preferred 8888 config to use for writing/reading pixel data to/from a surface with 185 * config surfaceConfig. The returned config must have at least as many bits per channel as the 186 * readConfig or writeConfig param. 187 */ 188 virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig readConfig, 189 GrPixelConfig surfaceConfig) const { 190 return readConfig; 191 } 192 virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig writeConfig, 193 GrPixelConfig surfaceConfig) const { 194 return writeConfig; 195 } 196 197 /** 198 * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't 199 * match the texture's config. 200 */ 201 virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0; 202 203 /** 204 * OpenGL's readPixels returns the result bottom-to-top while the skia 205 * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious 206 * solution is to have the subclass do the flip using either the CPU or GPU. 207 * However, the caller (GrContext) may have transformations to apply and can 208 * simply fold in the y-flip for free. On the other hand, the subclass may 209 * be able to do it for free itself. For example, the subclass may have to 210 * do memcpys to handle rowBytes that aren't tight. It could do the y-flip 211 * concurrently. 212 * 213 * This function returns true if a y-flip is required to put the pixels in 214 * top-to-bottom order and the subclass cannot do it for free. 215 * 216 * See read pixels for the params 217 * @return true if calling readPixels with the same set of params will 218 * produce bottom-to-top data 219 */ 220 virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget, 221 int left, int top, 222 int width, int height, 223 GrPixelConfig config, 224 size_t rowBytes) const = 0; 225 /** 226 * This should return true if reading a NxM rectangle of pixels from a 227 * render target is faster if the target has dimensons N and M and the read 228 * rectangle has its top-left at 0,0. 229 */ 230 virtual bool fullReadPixelsIsFasterThanPartial() const { return false; }; 231 232 /** 233 * Reads a rectangle of pixels from a render target. 234 * 235 * @param renderTarget the render target to read from. NULL means the 236 * current render target. 237 * @param left left edge of the rectangle to read (inclusive) 238 * @param top top edge of the rectangle to read (inclusive) 239 * @param width width of rectangle to read in pixels. 240 * @param height height of rectangle to read in pixels. 241 * @param config the pixel config of the destination buffer 242 * @param buffer memory to read the rectangle into. 243 * @param rowBytes the number of bytes between consecutive rows. Zero 244 * means rows are tightly packed. 245 * @param invertY buffer should be populated bottom-to-top as opposed 246 * to top-to-bottom (skia's usual order) 247 * 248 * @return true if the read succeeded, false if not. The read can fail 249 * because of a unsupported pixel config or because no render 250 * target is currently set. 251 */ 252 bool readPixels(GrRenderTarget* renderTarget, 253 int left, int top, int width, int height, 254 GrPixelConfig config, void* buffer, size_t rowBytes); 255 256 /** 257 * Updates the pixels in a rectangle of a texture. 258 * 259 * @param left left edge of the rectangle to write (inclusive) 260 * @param top top edge of the rectangle to write (inclusive) 261 * @param width width of rectangle to write in pixels. 262 * @param height height of rectangle to write in pixels. 263 * @param config the pixel config of the source buffer 264 * @param buffer memory to read pixels from 265 * @param rowBytes number of bytes between consecutive rows. Zero 266 * means rows are tightly packed. 267 */ 268 bool writeTexturePixels(GrTexture* texture, 269 int left, int top, int width, int height, 270 GrPixelConfig config, const void* buffer, 271 size_t rowBytes); 272 273 /** 274 * Clear the passed in render target. Ignores the draw state and clip. Clears the whole thing if 275 * rect is NULL, otherwise just the rect. If canIgnoreRect is set then the entire render target 276 * can be optionally cleared. 277 */ 278 void clear(const SkIRect* rect, 279 GrColor color, 280 bool canIgnoreRect, 281 GrRenderTarget* renderTarget); 282 283 284 void clearStencilClip(const SkIRect& rect, 285 bool insideClip, 286 GrRenderTarget* renderTarget); 287 288 /** 289 * Discards the contents render target. NULL indicates that the current render target should 290 * be discarded. 291 **/ 292 virtual void discard(GrRenderTarget* = NULL) = 0; 293 294 /** 295 * This is can be called before allocating a texture to be a dst for copySurface. It will 296 * populate the origin, config, and flags fields of the desc such that copySurface is more 297 * likely to succeed and be efficient. 298 */ 299 virtual void initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc); 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 enum DrawType { 319 kDrawPoints_DrawType, 320 kDrawLines_DrawType, 321 kDrawTriangles_DrawType, 322 kStencilPath_DrawType, 323 kDrawPath_DrawType, 324 kDrawPaths_DrawType, 325 }; 326 327 static bool IsPathRenderingDrawType(DrawType type) { 328 return kDrawPath_DrawType == type || kDrawPaths_DrawType == type; 329 } 330 331 GrContext::GPUStats* gpuStats() { return &fGPUStats; } 332 333 virtual void buildProgramDesc(const GrOptDrawState&, 334 const GrProgramDesc::DescInfo&, 335 GrGpu::DrawType, 336 const GrDeviceCoordTexture* dstCopy, 337 GrProgramDesc*) = 0; 338 339 /** 340 * Called at start and end of gpu trace marking 341 * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start 342 * and end of a code block respectively 343 */ 344 void addGpuTraceMarker(const GrGpuTraceMarker* marker); 345 void removeGpuTraceMarker(const GrGpuTraceMarker* marker); 346 347 /** 348 * Takes the current active set of markers and stores them for later use. Any current marker 349 * in the active set is removed from the active set and the targets remove function is called. 350 * These functions do not work as a stack so you cannot call save a second time before calling 351 * restore. Also, it is assumed that when restore is called the current active set of markers 352 * is empty. When the stored markers are added back into the active set, the targets add marker 353 * is called. 354 */ 355 void saveActiveTraceMarkers(); 356 void restoreActiveTraceMarkers(); 357 358 // Called to determine whether an onCopySurface call would succeed or not. This is useful for 359 // proxy subclasses to test whether the copy would succeed without executing it yet. Derived 360 // classes must keep this consistent with their implementation of onCopySurface(). The inputs 361 // are the same as onCopySurface(), i.e. srcRect and dstPoint are clipped to be inside the src 362 // and dst bounds. 363 virtual bool canCopySurface(GrSurface* dst, 364 GrSurface* src, 365 const SkIRect& srcRect, 366 const SkIPoint& dstPoint) = 0; 367 368 // This method is called by copySurface The srcRect is guaranteed to be entirely within the 369 // src bounds. Likewise, the dst rect implied by dstPoint and srcRect's width and height falls 370 // entirely within the dst. The default implementation will draw a rect from the src to the 371 // dst if the src is a texture and the dst is a render target and fail otherwise. 372 virtual bool copySurface(GrSurface* dst, 373 GrSurface* src, 374 const SkIRect& srcRect, 375 const SkIPoint& dstPoint) = 0; 376 377 /** 378 * Sets source of vertex data for the next draw. Data does not have to be 379 * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances. 380 * 381 * @param buffer vertex buffer containing vertex data. Must be 382 * unlocked before draw call. Vertex size is queried 383 * from current GrDrawState. 384 */ 385 void setVertexSourceToBuffer(const GrVertexBuffer* buffer, size_t vertexStride); 386 387 /** 388 * Sets source of index data for the next indexed draw. Data does not have 389 * to be in the buffer until drawIndexed. 390 * 391 * @param buffer index buffer containing indices. Must be unlocked 392 * before indexed draw call. 393 */ 394 void setIndexSourceToBuffer(const GrIndexBuffer* buffer); 395 396 virtual void draw(const GrOptDrawState&, 397 const GrDrawTarget::DrawInfo&, 398 const GrClipMaskManager::ScissorState&); 399 virtual void stencilPath(const GrOptDrawState&, 400 const GrPath*, 401 const GrClipMaskManager::ScissorState&, 402 const GrStencilSettings&); 403 virtual void drawPath(const GrOptDrawState&, 404 const GrPath*, 405 const GrClipMaskManager::ScissorState&, 406 const GrStencilSettings&, 407 const GrDeviceCoordTexture* dstCopy); 408 virtual void drawPaths(const GrOptDrawState&, 409 const GrPathRange*, 410 const uint32_t indices[], 411 int count, 412 const float transforms[], 413 GrDrawTarget::PathTransformType, 414 const GrClipMaskManager::ScissorState&, 415 const GrStencilSettings&, 416 const GrDeviceCoordTexture*); 417 418 static DrawType PrimTypeToDrawType(GrPrimitiveType type) { 419 switch (type) { 420 case kTriangles_GrPrimitiveType: 421 case kTriangleStrip_GrPrimitiveType: 422 case kTriangleFan_GrPrimitiveType: 423 return kDrawTriangles_DrawType; 424 case kPoints_GrPrimitiveType: 425 return kDrawPoints_DrawType; 426 case kLines_GrPrimitiveType: 427 case kLineStrip_GrPrimitiveType: 428 return kDrawLines_DrawType; 429 default: 430 SkFAIL("Unexpected primitive type"); 431 return kDrawTriangles_DrawType; 432 } 433 } 434 435protected: 436 // Functions used to map clip-respecting stencil tests into normal 437 // stencil funcs supported by GPUs. 438 static GrStencilFunc ConvertStencilFunc(bool stencilInClip, 439 GrStencilFunc func); 440 static void ConvertStencilFuncAndMask(GrStencilFunc func, 441 bool clipInStencil, 442 unsigned int clipBit, 443 unsigned int userBits, 444 unsigned int* ref, 445 unsigned int* mask); 446 447 struct GeometrySrcState { 448 GeometrySrcState() : fVertexBuffer(NULL), fIndexBuffer(NULL), fVertexSize(0) {} 449 const GrVertexBuffer* fVertexBuffer; 450 const GrIndexBuffer* fIndexBuffer; 451 size_t fVertexSize; 452 }; 453 454 // accessors for derived classes 455 const GeometrySrcState& getGeomSrc() const { return fGeoSrcState; } 456 457 // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert. 458 size_t getVertexSize() const { 459 // the vertex layout is only valid if a vertex source has been specified. 460 SkASSERT(this->getGeomSrc().fVertexBuffer); 461 return this->getGeomSrc().fVertexSize; 462 } 463 464 const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; } 465 466 GrContext::GPUStats fGPUStats; 467 468 SkAutoTDelete<GrPathRendering> fPathRendering; 469 470 // Subclass must initialize this in its constructor. 471 SkAutoTUnref<const GrDrawTargetCaps> fCaps; 472 473private: 474 // called when the 3D context state is unknown. Subclass should emit any 475 // assumed 3D context state and dirty any state cache. 476 virtual void onResetContext(uint32_t resetBits) = 0; 477 478 // overridden by backend-specific derived class to create objects. 479 virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc, 480 const void* srcData, 481 size_t rowBytes) = 0; 482 virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc, 483 const void* srcData) = 0; 484 virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0; 485 virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0; 486 virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0; 487 virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0; 488 489 // overridden by backend-specific derived class to perform the clear. 490 virtual void onClear(GrRenderTarget*, const SkIRect* rect, GrColor color, 491 bool canIgnoreRect) = 0; 492 493 494 // Overridden by backend specific classes to perform a clear of the stencil clip bits. This is 495 // ONLY used by the the clip target 496 virtual void onClearStencilClip(GrRenderTarget*, 497 const SkIRect& rect, 498 bool insideClip) = 0; 499 500 // overridden by backend-specific derived class to perform the draw call. 501 virtual void onDraw(const GrOptDrawState&, const GrDrawTarget::DrawInfo&) = 0; 502 503 // overridden by backend-specific derived class to perform the read pixels. 504 virtual bool onReadPixels(GrRenderTarget* target, 505 int left, int top, int width, int height, 506 GrPixelConfig, 507 void* buffer, 508 size_t rowBytes) = 0; 509 510 // overridden by backend-specific derived class to perform the texture update 511 virtual bool onWriteTexturePixels(GrTexture* texture, 512 int left, int top, int width, int height, 513 GrPixelConfig config, const void* buffer, 514 size_t rowBytes) = 0; 515 516 // overridden by backend-specific derived class to perform the resolve 517 virtual void onResolveRenderTarget(GrRenderTarget* target) = 0; 518 519 // width and height may be larger than rt (if underlying API allows it). 520 // Should attach the SB to the RT. Returns false if compatible sb could 521 // not be created. 522 virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0; 523 524 // attaches an existing SB to an existing RT. 525 virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0; 526 527 // The GrGpu typically records the clients requested state and then flushes 528 // deltas from previous state at draw time. This function does the 529 // backend-specific flush of the state. 530 // returns false if current state is unsupported. 531 virtual bool flushGraphicsState(const GrOptDrawState&, 532 DrawType, 533 const GrClipMaskManager::ScissorState&, 534 const GrDeviceCoordTexture* dstCopy) = 0; 535 536 // clears target's entire stencil buffer to 0 537 virtual void clearStencil(GrRenderTarget* target) = 0; 538 539 // Given a rt, find or create a stencil buffer and attach it 540 bool attachStencilBufferToRenderTarget(GrRenderTarget* target); 541 542 virtual void didAddGpuTraceMarker() = 0; 543 virtual void didRemoveGpuTraceMarker() = 0; 544 545 void resetContext() { 546 this->onResetContext(fResetBits); 547 fResetBits = 0; 548 ++fResetTimestamp; 549 } 550 551 void handleDirtyContext() { 552 if (fResetBits) { 553 this->resetContext(); 554 } 555 } 556 557 GeometrySrcState fGeoSrcState; 558 ResetTimestamp fResetTimestamp; 559 uint32_t fResetBits; 560 // these are mutable so they can be created on-demand 561 mutable GrIndexBuffer* fQuadIndexBuffer; 562 // To keep track that we always have at least as many debug marker adds as removes 563 int fGpuTraceMarkerCount; 564 GrTraceMarkerSet fActiveTraceMarkers; 565 GrTraceMarkerSet fStoredTraceMarkers; 566 // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu. 567 GrContext* fContext; 568 569 typedef SkRefCnt INHERITED; 570}; 571 572#endif 573