GrContext.h revision aa19a5fbc58e372df11443c90a25f02a04ecef52
1/* 2 * Copyright 2010 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 GrContext_DEFINED 9#define GrContext_DEFINED 10 11#include "GrCaps.h" 12#include "GrClip.h" 13#include "GrColor.h" 14#include "GrPaint.h" 15#include "GrRenderTarget.h" 16#include "GrTextureProvider.h" 17#include "SkMatrix.h" 18#include "SkPathEffect.h" 19#include "SkTypes.h" 20#include "../private/GrAuditTrail.h" 21#include "../private/GrSingleOwner.h" 22#include "../private/SkMutex.h" 23 24struct GrBatchAtlasConfig; 25class GrBatchFontCache; 26struct GrContextOptions; 27class GrContextThreadSafeProxy; 28class GrDrawingManager; 29class GrDrawContext; 30class GrDrawTarget; 31class GrFragmentProcessor; 32class GrGpu; 33class GrIndexBuffer; 34class GrLayerCache; 35class GrOvalRenderer; 36class GrPath; 37class GrPipelineBuilder; 38class GrResourceEntry; 39class GrResourceCache; 40class GrResourceProvider; 41class GrTestTarget; 42class GrTextBlobCache; 43class GrTextContext; 44class GrTextureParams; 45class GrVertexBuffer; 46class GrStrokeInfo; 47class GrSwizzle; 48class SkTraceMemoryDump; 49 50class SK_API GrContext : public SkRefCnt { 51public: 52 /** 53 * Creates a GrContext for a backend context. 54 */ 55 static GrContext* Create(GrBackend, GrBackendContext, const GrContextOptions& options); 56 static GrContext* Create(GrBackend, GrBackendContext); 57 58 /** 59 * Only defined in test apps. 60 */ 61 static GrContext* CreateMockContext(); 62 63 virtual ~GrContext(); 64 65 GrContextThreadSafeProxy* threadSafeProxy(); 66 67 /** 68 * The GrContext normally assumes that no outsider is setting state 69 * within the underlying 3D API's context/device/whatever. This call informs 70 * the context that the state was modified and it should resend. Shouldn't 71 * be called frequently for good performance. 72 * The flag bits, state, is dpendent on which backend is used by the 73 * context, either GL or D3D (possible in future). 74 */ 75 void resetContext(uint32_t state = kAll_GrBackendState); 76 77 /** 78 * Callback function to allow classes to cleanup on GrContext destruction. 79 * The 'info' field is filled in with the 'info' passed to addCleanUp. 80 */ 81 typedef void (*PFCleanUpFunc)(const GrContext* context, void* info); 82 83 /** 84 * Add a function to be called from within GrContext's destructor. 85 * This gives classes a chance to free resources held on a per context basis. 86 * The 'info' parameter will be stored and passed to the callback function. 87 */ 88 void addCleanUp(PFCleanUpFunc cleanUp, void* info) { 89 CleanUpData* entry = fCleanUpData.push(); 90 91 entry->fFunc = cleanUp; 92 entry->fInfo = info; 93 } 94 95 /** 96 * Abandons all GPU resources and assumes the underlying backend 3D API context is not longer 97 * usable. Call this if you have lost the associated GPU context, and thus internal texture, 98 * buffer, etc. references/IDs are now invalid. Calling this ensures that the destructors of the 99 * GrContext and any of its created resource objects will not make backend 3D API calls. Content 100 * rendered but not previously flushed may be lost. After this function is called all subsequent 101 * calls on the GrContext will fail or be no-ops. 102 * 103 * The typical use case for this function is that the underlying 3D context was lost and further 104 * API calls may crash. 105 */ 106 void abandonContext(); 107 108 /** 109 * This is similar to abandonContext() however the underlying 3D context is not yet lost and 110 * the GrContext will cleanup all allocated resources before returning. After returning it will 111 * assume that the underlying context may no longer be valid. 112 * 113 * The typical use case for this function is that the client is going to destroy the 3D context 114 * but can't guarantee that GrContext will be destroyed first (perhaps because it may be ref'ed 115 * elsewhere by either the client or Skia objects). 116 */ 117 void releaseResourcesAndAbandonContext(); 118 119 /////////////////////////////////////////////////////////////////////////// 120 // Resource Cache 121 122 /** 123 * Return the current GPU resource cache limits. 124 * 125 * @param maxResources If non-null, returns maximum number of resources that 126 * can be held in the cache. 127 * @param maxResourceBytes If non-null, returns maximum number of bytes of 128 * video memory that can be held in the cache. 129 */ 130 void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const; 131 132 /** 133 * Gets the current GPU resource cache usage. 134 * 135 * @param resourceCount If non-null, returns the number of resources that are held in the 136 * cache. 137 * @param maxResourceBytes If non-null, returns the total number of bytes of video memory held 138 * in the cache. 139 */ 140 void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const; 141 142 /** 143 * Specify the GPU resource cache limits. If the current cache exceeds either 144 * of these, it will be purged (LRU) to keep the cache within these limits. 145 * 146 * @param maxResources The maximum number of resources that can be held in 147 * the cache. 148 * @param maxResourceBytes The maximum number of bytes of video memory 149 * that can be held in the cache. 150 */ 151 void setResourceCacheLimits(int maxResources, size_t maxResourceBytes); 152 153 GrTextureProvider* textureProvider() { return fTextureProvider; } 154 const GrTextureProvider* textureProvider() const { return fTextureProvider; } 155 156 /** 157 * Frees GPU created by the context. Can be called to reduce GPU memory 158 * pressure. 159 */ 160 void freeGpuResources(); 161 162 /** 163 * Purge all the unlocked resources from the cache. 164 * This entry point is mainly meant for timing texture uploads 165 * and is not defined in normal builds of Skia. 166 */ 167 void purgeAllUnlockedResources(); 168 169 /** Access the context capabilities */ 170 const GrCaps* caps() const { return fCaps; } 171 172 /** 173 * Returns the recommended sample count for a render target when using this 174 * context. 175 * 176 * @param config the configuration of the render target. 177 * @param dpi the display density in dots per inch. 178 * 179 * @return sample count that should be perform well and have good enough 180 * rendering quality for the display. Alternatively returns 0 if 181 * MSAA is not supported or recommended to be used by default. 182 */ 183 int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const; 184 185 /** 186 * Returns a helper object to orchestrate draws. 187 * Callers assume the creation ref of the drawContext 188 * NULL will be returned if the context has been abandoned. 189 * 190 * @param rt the render target receiving the draws 191 * @param surfaceProps the surface properties (mainly defines text drawing) 192 * 193 * @return a draw context 194 */ 195 sk_sp<GrDrawContext> drawContext(sk_sp<GrRenderTarget> rt, const SkSurfaceProps* = nullptr); 196 197 /////////////////////////////////////////////////////////////////////////// 198 // Misc. 199 200 /** 201 * Flags that affect flush() behavior. 202 */ 203 enum FlushBits { 204 /** 205 * A client may reach a point where it has partially rendered a frame 206 * through a GrContext that it knows the user will never see. This flag 207 * causes the flush to skip submission of deferred content to the 3D API 208 * during the flush. 209 */ 210 kDiscard_FlushBit = 0x2, 211 }; 212 213 /** 214 * Call to ensure all drawing to the context has been issued to the 215 * underlying 3D API. 216 * @param flagsBitfield flags that control the flushing behavior. See 217 * FlushBits. 218 */ 219 void flush(int flagsBitfield = 0); 220 221 void flushIfNecessary() { 222 if (fFlushToReduceCacheSize || this->caps()->immediateFlush()) { 223 this->flush(); 224 } 225 } 226 227 /** 228 * These flags can be used with the read/write pixels functions below. 229 */ 230 enum PixelOpsFlags { 231 /** The GrContext will not be flushed before the surface read or write. This means that 232 the read or write may occur before previous draws have executed. */ 233 kDontFlush_PixelOpsFlag = 0x1, 234 /** Any surface writes should be flushed to the backend 3D API after the surface operation 235 is complete */ 236 kFlushWrites_PixelOp = 0x2, 237 /** The src for write or dst read is unpremultiplied. This is only respected if both the 238 config src and dst configs are an RGBA/BGRA 8888 format. */ 239 kUnpremul_PixelOpsFlag = 0x4, 240 }; 241 242 /** 243 * Reads a rectangle of pixels from a surface. 244 * @param surface the surface to read from. 245 * @param left left edge of the rectangle to read (inclusive) 246 * @param top top edge of the rectangle to read (inclusive) 247 * @param width width of rectangle to read in pixels. 248 * @param height height of rectangle to read in pixels. 249 * @param config the pixel config of the destination buffer 250 * @param buffer memory to read the rectangle into. 251 * @param rowBytes number of bytes bewtween consecutive rows. Zero means rows are tightly 252 * packed. 253 * @param pixelOpsFlags see PixelOpsFlags enum above. 254 * 255 * @return true if the read succeeded, false if not. The read can fail because of an unsupported 256 * pixel configs 257 */ 258 bool readSurfacePixels(GrSurface* surface, 259 int left, int top, int width, int height, 260 GrPixelConfig config, void* buffer, 261 size_t rowBytes = 0, 262 uint32_t pixelOpsFlags = 0); 263 264 /** 265 * Writes a rectangle of pixels to a surface. 266 * @param surface the surface to write to. 267 * @param left left edge of the rectangle to write (inclusive) 268 * @param top top edge of the rectangle to write (inclusive) 269 * @param width width of rectangle to write in pixels. 270 * @param height height of rectangle to write in pixels. 271 * @param config the pixel config of the source buffer 272 * @param buffer memory to read pixels from 273 * @param rowBytes number of bytes between consecutive rows. Zero 274 * means rows are tightly packed. 275 * @param pixelOpsFlags see PixelOpsFlags enum above. 276 * @return true if the write succeeded, false if not. The write can fail because of an 277 * unsupported combination of surface and src configs. 278 */ 279 bool writeSurfacePixels(GrSurface* surface, 280 int left, int top, int width, int height, 281 GrPixelConfig config, const void* buffer, 282 size_t rowBytes, 283 uint32_t pixelOpsFlags = 0); 284 285 /** 286 * Copies a rectangle of texels from src to dst. 287 * bounds. 288 * @param dst the surface to copy to. 289 * @param src the surface to copy from. 290 * @param srcRect the rectangle of the src that should be copied. 291 * @param dstPoint the translation applied when writing the srcRect's pixels to the dst. 292 */ 293 bool copySurface(GrSurface* dst, 294 GrSurface* src, 295 const SkIRect& srcRect, 296 const SkIPoint& dstPoint); 297 298 /** Helper that copies the whole surface but fails when the two surfaces are not identically 299 sized. */ 300 bool copySurface(GrSurface* dst, GrSurface* src) { 301 return this->copySurface(dst, src, SkIRect::MakeWH(dst->width(), dst->height()), 302 SkIPoint::Make(0,0)); 303 } 304 305 /** 306 * After this returns any pending writes to the surface will have been issued to the backend 3D API. 307 */ 308 void flushSurfaceWrites(GrSurface* surface); 309 310 /** 311 * Finalizes all pending reads and writes to the surface and also performs an MSAA resolve 312 * if necessary. 313 * 314 * It is not necessary to call this before reading the render target via Skia/GrContext. 315 * GrContext will detect when it must perform a resolve before reading pixels back from the 316 * surface or using it as a texture. 317 */ 318 void prepareSurfaceForExternalIO(GrSurface*); 319 320 /** 321 * An ID associated with this context, guaranteed to be unique. 322 */ 323 uint32_t uniqueID() { return fUniqueID; } 324 325 /////////////////////////////////////////////////////////////////////////// 326 // Functions intended for internal use only. 327 GrGpu* getGpu() { return fGpu; } 328 const GrGpu* getGpu() const { return fGpu; } 329 GrBatchFontCache* getBatchFontCache() { return fBatchFontCache; } 330 GrLayerCache* getLayerCache() { return fLayerCache.get(); } 331 GrTextBlobCache* getTextBlobCache() { return fTextBlobCache; } 332 bool abandoned() const; 333 GrResourceProvider* resourceProvider() { return fResourceProvider; } 334 const GrResourceProvider* resourceProvider() const { return fResourceProvider; } 335 GrResourceCache* getResourceCache() { return fResourceCache; } 336 337 // Called by tests that draw directly to the context via GrDrawTarget 338 void getTestTarget(GrTestTarget*, GrRenderTarget* rt); 339 340 /** Reset GPU stats */ 341 void resetGpuStats() const ; 342 343 /** Prints cache stats to the string if GR_CACHE_STATS == 1. */ 344 void dumpCacheStats(SkString*) const; 345 void dumpCacheStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const; 346 void printCacheStats() const; 347 348 /** Prints GPU stats to the string if GR_GPU_STATS == 1. */ 349 void dumpGpuStats(SkString*) const; 350 void dumpGpuStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const; 351 void printGpuStats() const; 352 353 /** Specify the TextBlob cache limit. If the current cache exceeds this limit it will purge. 354 this is for testing only */ 355 void setTextBlobCacheLimit_ForTesting(size_t bytes); 356 357 /** Specify the sizes of the GrAtlasTextContext atlases. The configs pointer below should be 358 to an array of 3 entries */ 359 void setTextContextAtlasSizes_ForTesting(const GrBatchAtlasConfig* configs); 360 361 /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */ 362 void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const; 363 364 /** Get pointer to atlas texture for given mask format */ 365 GrTexture* getFontAtlasTexture(GrMaskFormat format); 366 367 GrAuditTrail* getAuditTrail() { return &fAuditTrail; } 368 369 /** This is only useful for debug purposes */ 370 SkDEBUGCODE(GrSingleOwner* debugSingleOwner() const { return &fSingleOwner; } ) 371 372private: 373 GrGpu* fGpu; 374 const GrCaps* fCaps; 375 GrResourceCache* fResourceCache; 376 // this union exists because the inheritance of GrTextureProvider->GrResourceProvider 377 // is in a private header. 378 union { 379 GrResourceProvider* fResourceProvider; 380 GrTextureProvider* fTextureProvider; 381 }; 382 383 SkAutoTUnref<GrContextThreadSafeProxy> fThreadSafeProxy; 384 385 GrBatchFontCache* fBatchFontCache; 386 SkAutoTDelete<GrLayerCache> fLayerCache; 387 SkAutoTDelete<GrTextBlobCache> fTextBlobCache; 388 389 // Set by OverbudgetCB() to request that GrContext flush before exiting a draw. 390 bool fFlushToReduceCacheSize; 391 bool fDidTestPMConversions; 392 int fPMToUPMConversion; 393 int fUPMToPMConversion; 394 // The sw backend may call GrContext::readSurfacePixels on multiple threads 395 // We may transfer the responsibilty for using a mutex to the sw backend 396 // when there are fewer code paths that lead to a readSurfacePixels call 397 // from the sw backend. readSurfacePixels is reentrant in one case - when performing 398 // the PM conversions test. To handle this we do the PM conversions test outside 399 // of fReadPixelsMutex and use a separate mutex to guard it. When it re-enters 400 // readSurfacePixels it will grab fReadPixelsMutex and release it before the outer 401 // readSurfacePixels proceeds to grab it. 402 // TODO: Stop pretending to make GrContext thread-safe for sw rasterization and provide 403 // a mechanism to make a SkPicture safe for multithreaded sw rasterization. 404 SkMutex fReadPixelsMutex; 405 SkMutex fTestPMConversionsMutex; 406 407 // In debug builds we guard against improper thread handling 408 // This guard is passed to the GrDrawingManager and, from there to all the 409 // GrDrawContexts. It is also passed to the GrTextureProvider and SkGpuDevice. 410 mutable GrSingleOwner fSingleOwner; 411 412 struct CleanUpData { 413 PFCleanUpFunc fFunc; 414 void* fInfo; 415 }; 416 417 SkTDArray<CleanUpData> fCleanUpData; 418 419 const uint32_t fUniqueID; 420 421 SkAutoTDelete<GrDrawingManager> fDrawingManager; 422 423 GrAuditTrail fAuditTrail; 424 425 // TODO: have the CMM use drawContexts and rm this friending 426 friend class GrClipMaskManager; // the CMM is friended just so it can call 'drawingManager' 427 friend class GrDrawingManager; // for access to drawingManager for ProgramUnitTest 428 GrDrawingManager* drawingManager() { return fDrawingManager; } 429 430 GrContext(); // init must be called after the constructor. 431 bool init(GrBackend, GrBackendContext, const GrContextOptions& options); 432 433 void initMockContext(); 434 void initCommon(const GrContextOptions&); 435 436 /** 437 * These functions create premul <-> unpremul effects if it is possible to generate a pair 438 * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they 439 * return NULL. They also can perform a swizzle as part of the draw. 440 */ 441 const GrFragmentProcessor* createPMToUPMEffect(GrTexture*, const GrSwizzle&, 442 const SkMatrix&) const; 443 const GrFragmentProcessor* createUPMToPMEffect(GrTexture*, const GrSwizzle&, 444 const SkMatrix&) const; 445 /** Called before either of the above two functions to determine the appropriate fragment 446 processors for conversions. This must be called by readSurfacePixels before a mutex is 447 taken, since testingvPM conversions itself will call readSurfacePixels */ 448 void testPMConversionsIfNecessary(uint32_t flags); 449 /** Returns true if we've already determined that createPMtoUPMEffect and createUPMToPMEffect 450 will fail. In such cases fall back to SW conversion. */ 451 bool didFailPMUPMConversionTest() const; 452 453 /** 454 * This callback allows the resource cache to callback into the GrContext 455 * when the cache is still over budget after a purge. 456 */ 457 static void OverBudgetCB(void* data); 458 459 /** 460 * A callback similar to the above for use by the TextBlobCache 461 * TODO move textblob draw calls below context so we can use the call above. 462 */ 463 static void TextBlobCacheOverBudgetCB(void* data); 464 465 typedef SkRefCnt INHERITED; 466}; 467 468/** 469 * Can be used to perform actions related to the generating GrContext in a thread safe manner. The 470 * proxy does not access the 3D API (e.g. OpenGL) that backs the generating GrContext. 471 */ 472class GrContextThreadSafeProxy : public SkRefCnt { 473private: 474 GrContextThreadSafeProxy(const GrCaps* caps, uint32_t uniqueID) 475 : fCaps(SkRef(caps)) 476 , fContextUniqueID(uniqueID) {} 477 478 SkAutoTUnref<const GrCaps> fCaps; 479 uint32_t fContextUniqueID; 480 481 friend class GrContext; 482 friend class SkImage; 483 484 typedef SkRefCnt INHERITED; 485}; 486 487#endif 488