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