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