1 /* 2 * Copyright 2020 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 GrDirectContext_DEFINED 9 #define GrDirectContext_DEFINED 10 11 #include <set> 12 13 #include "include/gpu/GrRecordingContext.h" 14 15 #include "include/gpu/GrBackendSurface.h" 16 17 #include "src/gpu/GrGpuResource.h" 18 19 // We shouldn't need this but currently Android is relying on this being include transitively. 20 #include "include/core/SkUnPreMultiply.h" 21 22 class GrAtlasManager; 23 class GrBackendSemaphore; 24 class GrClientMappedBufferManager; 25 class GrDirectContextPriv; 26 class GrContextThreadSafeProxy; 27 struct GrD3DBackendContext; 28 class GrFragmentProcessor; 29 class GrGpu; 30 struct GrGLInterface; 31 struct GrMtlBackendContext; 32 struct GrMockOptions; 33 class GrPath; 34 class GrResourceCache; 35 class GrResourceProvider; 36 class GrStrikeCache; 37 class GrSurfaceProxy; 38 class GrSwizzle; 39 class GrTextureProxy; 40 struct GrVkBackendContext; 41 42 class SkImage; 43 class SkString; 44 class SkSurfaceCharacterization; 45 class SkSurfaceProps; 46 class SkTaskGroup; 47 class SkTraceMemoryDump; 48 49 namespace skgpu { namespace v1 { class SmallPathAtlasMgr; }} 50 51 class SK_API GrDirectContext : public GrRecordingContext { 52 public: 53 #ifdef SK_GL 54 /** 55 * Creates a GrDirectContext for a backend context. If no GrGLInterface is provided then the 56 * result of GrGLMakeNativeInterface() is used if it succeeds. 57 */ 58 static sk_sp<GrDirectContext> MakeGL(sk_sp<const GrGLInterface>, const GrContextOptions&); 59 static sk_sp<GrDirectContext> MakeGL(sk_sp<const GrGLInterface>); 60 static sk_sp<GrDirectContext> MakeGL(const GrContextOptions&); 61 static sk_sp<GrDirectContext> MakeGL(); 62 #endif 63 64 #ifdef SK_VULKAN 65 /** 66 * The Vulkan context (VkQueue, VkDevice, VkInstance) must be kept alive until the returned 67 * GrDirectContext is destroyed. This also means that any objects created with this 68 * GrDirectContext (e.g. SkSurfaces, SkImages, etc.) must also be released as they may hold 69 * refs on the GrDirectContext. Once all these objects and the GrDirectContext are released, 70 * then it is safe to delete the vulkan objects. 71 */ 72 static sk_sp<GrDirectContext> MakeVulkan(const GrVkBackendContext&, const GrContextOptions&); 73 static sk_sp<GrDirectContext> MakeVulkan(const GrVkBackendContext&); 74 #endif 75 76 #ifdef SK_METAL 77 /** 78 * Makes a GrDirectContext which uses Metal as the backend. The GrMtlBackendContext contains a 79 * MTLDevice and MTLCommandQueue which should be used by the backend. These objects must 80 * have their own ref which will be released when the GrMtlBackendContext is destroyed. 81 * Ganesh will take its own ref on the objects which will be released when the GrDirectContext 82 * is destroyed. 83 */ 84 static sk_sp<GrDirectContext> MakeMetal(const GrMtlBackendContext&, const GrContextOptions&); 85 static sk_sp<GrDirectContext> MakeMetal(const GrMtlBackendContext&); 86 /** 87 * Deprecated. 88 * 89 * Makes a GrDirectContext which uses Metal as the backend. The device parameter is an 90 * MTLDevice and queue is an MTLCommandQueue which should be used by the backend. These objects 91 * must have a ref on them that can be transferred to Ganesh, which will release the ref 92 * when the GrDirectContext is destroyed. 93 */ 94 static sk_sp<GrDirectContext> MakeMetal(void* device, void* queue, const GrContextOptions&); 95 static sk_sp<GrDirectContext> MakeMetal(void* device, void* queue); 96 #endif 97 98 #ifdef SK_DIRECT3D 99 /** 100 * Makes a GrDirectContext which uses Direct3D as the backend. The Direct3D context 101 * must be kept alive until the returned GrDirectContext is first destroyed or abandoned. 102 */ 103 static sk_sp<GrDirectContext> MakeDirect3D(const GrD3DBackendContext&, const GrContextOptions&); 104 static sk_sp<GrDirectContext> MakeDirect3D(const GrD3DBackendContext&); 105 #endif 106 107 #ifdef SK_DAWN 108 static sk_sp<GrDirectContext> MakeDawn(const wgpu::Device&, 109 const GrContextOptions&); 110 static sk_sp<GrDirectContext> MakeDawn(const wgpu::Device&); 111 #endif 112 113 static sk_sp<GrDirectContext> MakeMock(const GrMockOptions*, const GrContextOptions&); 114 static sk_sp<GrDirectContext> MakeMock(const GrMockOptions*); 115 116 ~GrDirectContext() override; 117 118 /** 119 * The context normally assumes that no outsider is setting state 120 * within the underlying 3D API's context/device/whatever. This call informs 121 * the context that the state was modified and it should resend. Shouldn't 122 * be called frequently for good performance. 123 * The flag bits, state, is dependent on which backend is used by the 124 * context, either GL or D3D (possible in future). 125 */ 126 void resetContext(uint32_t state = kAll_GrBackendState); 127 128 /** 129 * If the backend is GrBackendApi::kOpenGL, then all texture unit/target combinations for which 130 * the context has modified the bound texture will have texture id 0 bound. This does not 131 * flush the context. Calling resetContext() does not change the set that will be bound 132 * to texture id 0 on the next call to resetGLTextureBindings(). After this is called 133 * all unit/target combinations are considered to have unmodified bindings until the context 134 * subsequently modifies them (meaning if this is called twice in a row with no intervening 135 * context usage then the second call is a no-op.) 136 */ 137 void resetGLTextureBindings(); 138 139 /** 140 * Abandons all GPU resources and assumes the underlying backend 3D API context is no longer 141 * usable. Call this if you have lost the associated GPU context, and thus internal texture, 142 * buffer, etc. references/IDs are now invalid. Calling this ensures that the destructors of the 143 * context and any of its created resource objects will not make backend 3D API calls. Content 144 * rendered but not previously flushed may be lost. After this function is called all subsequent 145 * calls on the context will fail or be no-ops. 146 * 147 * The typical use case for this function is that the underlying 3D context was lost and further 148 * API calls may crash. 149 * 150 * For Vulkan, even if the device becomes lost, the VkQueue, VkDevice, or VkInstance used to 151 * create the context must be kept alive even after abandoning the context. Those objects must 152 * live for the lifetime of the context object itself. The reason for this is so that 153 * we can continue to delete any outstanding GrBackendTextures/RenderTargets which must be 154 * cleaned up even in a device lost state. 155 */ 156 void abandonContext() override; 157 158 /** 159 * Returns true if the context was abandoned or if the if the backend specific context has 160 * gotten into an unrecoverarble, lost state (e.g. in Vulkan backend if we've gotten a 161 * VK_ERROR_DEVICE_LOST). If the backend context is lost, this call will also abandon this 162 * context. 163 */ 164 bool abandoned() override; 165 166 // TODO: Remove this from public after migrating Chrome. 167 sk_sp<GrContextThreadSafeProxy> threadSafeProxy(); 168 169 /** 170 * Checks if the underlying 3D API reported an out-of-memory error. If this returns true it is 171 * reset and will return false until another out-of-memory error is reported by the 3D API. If 172 * the context is abandoned then this will report false. 173 * 174 * Currently this is implemented for: 175 * 176 * OpenGL [ES] - Note that client calls to glGetError() may swallow GL_OUT_OF_MEMORY errors and 177 * therefore hide the error from Skia. Also, it is not advised to use this in combination with 178 * enabling GrContextOptions::fSkipGLErrorChecks. That option may prevent the context from ever 179 * checking the GL context for OOM. 180 * 181 * Vulkan - Reports true if VK_ERROR_OUT_OF_HOST_MEMORY or VK_ERROR_OUT_OF_DEVICE_MEMORY has 182 * occurred. 183 */ 184 bool oomed(); 185 186 /** 187 * This is similar to abandonContext() however the underlying 3D context is not yet lost and 188 * the context will cleanup all allocated resources before returning. After returning it will 189 * assume that the underlying context may no longer be valid. 190 * 191 * The typical use case for this function is that the client is going to destroy the 3D context 192 * but can't guarantee that context will be destroyed first (perhaps because it may be ref'ed 193 * elsewhere by either the client or Skia objects). 194 * 195 * For Vulkan, even if the device becomes lost, the VkQueue, VkDevice, or VkInstance used to 196 * create the context must be alive before calling releaseResourcesAndAbandonContext. 197 */ 198 void releaseResourcesAndAbandonContext(); 199 200 /////////////////////////////////////////////////////////////////////////// 201 // Resource Cache 202 203 /** DEPRECATED 204 * Return the current GPU resource cache limits. 205 * 206 * @param maxResources If non-null, will be set to -1. 207 * @param maxResourceBytes If non-null, returns maximum number of bytes of 208 * video memory that can be held in the cache. 209 */ 210 void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const; 211 212 /** 213 * Return the current GPU resource cache limit in bytes. 214 */ 215 size_t getResourceCacheLimit() const; 216 217 /** 218 * Gets the current GPU resource cache usage. 219 * 220 * @param resourceCount If non-null, returns the number of resources that are held in the 221 * cache. 222 * @param maxResourceBytes If non-null, returns the total number of bytes of video memory held 223 * in the cache. 224 */ 225 void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const; 226 227 /** 228 * Gets the number of bytes in the cache consumed by purgeable (e.g. unlocked) resources. 229 */ 230 size_t getResourceCachePurgeableBytes() const; 231 232 /** DEPRECATED 233 * Specify the GPU resource cache limits. If the current cache exceeds the maxResourceBytes 234 * limit, it will be purged (LRU) to keep the cache within the limit. 235 * 236 * @param maxResources Unused. 237 * @param maxResourceBytes The maximum number of bytes of video memory 238 * that can be held in the cache. 239 */ 240 void setResourceCacheLimits(int maxResources, size_t maxResourceBytes); 241 242 /** 243 * Specify the GPU resource cache limit. If the cache currently exceeds this limit, 244 * it will be purged (LRU) to keep the cache within the limit. 245 * 246 * @param maxResourceBytes The maximum number of bytes of video memory 247 * that can be held in the cache. 248 */ 249 void setResourceCacheLimit(size_t maxResourceBytes); 250 251 /** 252 * Frees GPU created by the context. Can be called to reduce GPU memory 253 * pressure. 254 */ 255 void freeGpuResources(); 256 257 /** 258 * Purge GPU resources that haven't been used in the past 'msNotUsed' milliseconds or are 259 * otherwise marked for deletion, regardless of whether the context is under budget. 260 * 261 * If 'scratchResourcesOnly' is true all unlocked scratch resources older than 'msNotUsed' will 262 * be purged but the unlocked resources with persistent data will remain. If 263 * 'scratchResourcesOnly' is false then all unlocked resources older than 'msNotUsed' will be 264 * purged. 265 * 266 * @param msNotUsed Only unlocked resources not used in these last milliseconds 267 * will be cleaned up. 268 * @param scratchResourcesOnly If true only unlocked scratch resources will be purged. 269 */ 270 void performDeferredCleanup(std::chrono::milliseconds msNotUsed, 271 bool scratchResourcesOnly=false); 272 273 // Temporary compatibility API for Android. purgeResourcesNotUsedInMs(std::chrono::milliseconds msNotUsed)274 void purgeResourcesNotUsedInMs(std::chrono::milliseconds msNotUsed) { 275 this->performDeferredCleanup(msNotUsed); 276 } 277 278 /** 279 * Purge unlocked resources from the cache until the the provided byte count has been reached 280 * or we have purged all unlocked resources. The default policy is to purge in LRU order, but 281 * can be overridden to prefer purging scratch resources (in LRU order) prior to purging other 282 * resource types. 283 * 284 * @param maxBytesToPurge the desired number of bytes to be purged. 285 * @param preferScratchResources If true scratch resources will be purged prior to other 286 * resource types. 287 */ 288 void purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources); 289 void purgeUnlockedResourcesByTag(bool scratchResourcesOnly, const GrGpuResourceTag tag); 290 void purgeUnlockAndSafeCacheGpuResources(); 291 292 /** 293 * This entry point is intended for instances where an app has been backgrounded or 294 * suspended. 295 * If 'scratchResourcesOnly' is true all unlocked scratch resources will be purged but the 296 * unlocked resources with persistent data will remain. If 'scratchResourcesOnly' is false 297 * then all unlocked resources will be purged. 298 * In either case, after the unlocked resources are purged a separate pass will be made to 299 * ensure that resource usage is under budget (i.e., even if 'scratchResourcesOnly' is true 300 * some resources with persistent data may be purged to be under budget). 301 * 302 * @param scratchResourcesOnly If true only unlocked scratch resources will be purged prior 303 * enforcing the budget requirements. 304 */ 305 void purgeUnlockedResources(bool scratchResourcesOnly); 306 307 /** 308 * Gets the maximum supported texture size. 309 */ 310 using GrRecordingContext::maxTextureSize; 311 312 /** 313 * Gets the maximum supported render target size. 314 */ 315 using GrRecordingContext::maxRenderTargetSize; 316 317 /** 318 * Can a SkImage be created with the given color type. 319 */ 320 using GrRecordingContext::colorTypeSupportedAsImage; 321 322 /** 323 * Can a SkSurface be created with the given color type. To check whether MSAA is supported 324 * use maxSurfaceSampleCountForColorType(). 325 */ 326 using GrRecordingContext::colorTypeSupportedAsSurface; 327 328 /** 329 * Gets the maximum supported sample count for a color type. 1 is returned if only non-MSAA 330 * rendering is supported for the color type. 0 is returned if rendering to this color type 331 * is not supported at all. 332 */ 333 using GrRecordingContext::maxSurfaceSampleCountForColorType; 334 335 /////////////////////////////////////////////////////////////////////////// 336 // Misc. 337 338 /** 339 * Inserts a list of GPU semaphores that the current GPU-backed API must wait on before 340 * executing any more commands on the GPU. If this call returns false, then the GPU back-end 341 * will not wait on any passed in semaphores, and the client will still own the semaphores, 342 * regardless of the value of deleteSemaphoresAfterWait. 343 * 344 * If deleteSemaphoresAfterWait is false then Skia will not delete the semaphores. In this case 345 * it is the client's responsibility to not destroy or attempt to reuse the semaphores until it 346 * knows that Skia has finished waiting on them. This can be done by using finishedProcs on 347 * flush calls. 348 */ 349 bool wait(int numSemaphores, const GrBackendSemaphore* waitSemaphores, 350 bool deleteSemaphoresAfterWait = true); 351 352 /** 353 * Call to ensure all drawing to the context has been flushed and submitted to the underlying 3D 354 * API. This is equivalent to calling GrContext::flush with a default GrFlushInfo followed by 355 * GrContext::submit(syncCpu). 356 */ 357 void flushAndSubmit(bool syncCpu = false) { 358 this->flush(GrFlushInfo()); 359 this->submit(syncCpu); 360 } 361 362 /** 363 * Call to ensure all drawing to the context has been flushed to underlying 3D API specific 364 * objects. A call to `submit` is always required to ensure work is actually sent to 365 * the gpu. Some specific API details: 366 * GL: Commands are actually sent to the driver, but glFlush is never called. Thus some 367 * sync objects from the flush will not be valid until a submission occurs. 368 * 369 * Vulkan/Metal/D3D/Dawn: Commands are recorded to the backend APIs corresponding command 370 * buffer or encoder objects. However, these objects are not sent to the gpu until a 371 * submission occurs. 372 * 373 * If the return is GrSemaphoresSubmitted::kYes, only initialized GrBackendSemaphores will be 374 * submitted to the gpu during the next submit call (it is possible Skia failed to create a 375 * subset of the semaphores). The client should not wait on these semaphores until after submit 376 * has been called, and must keep them alive until then. If this call returns 377 * GrSemaphoresSubmitted::kNo, the GPU backend will not submit any semaphores to be signaled on 378 * the GPU. Thus the client should not have the GPU wait on any of the semaphores passed in with 379 * the GrFlushInfo. Regardless of whether semaphores were submitted to the GPU or not, the 380 * client is still responsible for deleting any initialized semaphores. 381 * Regardleess of semaphore submission the context will still be flushed. It should be 382 * emphasized that a return value of GrSemaphoresSubmitted::kNo does not mean the flush did not 383 * happen. It simply means there were no semaphores submitted to the GPU. A caller should only 384 * take this as a failure if they passed in semaphores to be submitted. 385 */ 386 GrSemaphoresSubmitted flush(const GrFlushInfo& info); 387 flush()388 void flush() { this->flush({}); } 389 390 /** 391 * Submit outstanding work to the gpu from all previously un-submitted flushes. The return 392 * value of the submit will indicate whether or not the submission to the GPU was successful. 393 * 394 * If the call returns true, all previously passed in semaphores in flush calls will have been 395 * submitted to the GPU and they can safely be waited on. The caller should wait on those 396 * semaphores or perform some other global synchronization before deleting the semaphores. 397 * 398 * If it returns false, then those same semaphores will not have been submitted and we will not 399 * try to submit them again. The caller is free to delete the semaphores at any time. 400 * 401 * If the syncCpu flag is true this function will return once the gpu has finished with all 402 * submitted work. 403 */ 404 bool submit(bool syncCpu = false); 405 406 /** 407 * Checks whether any asynchronous work is complete and if so calls related callbacks. 408 */ 409 void checkAsyncWorkCompletion(); 410 411 /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */ 412 // Chrome is using this! 413 void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const; 414 void dumpMemoryStatisticsByTag(SkTraceMemoryDump* traceMemoryDump, const GrGpuResourceTag tag) const; 415 416 bool supportsDistanceFieldText() const; 417 418 void storeVkPipelineCacheData(); 419 420 /** 421 * Retrieve the default GrBackendFormat for a given SkColorType and renderability. 422 * It is guaranteed that this backend format will be the one used by the following 423 * SkColorType and SkSurfaceCharacterization-based createBackendTexture methods. 424 * 425 * The caller should check that the returned format is valid. 426 */ 427 using GrRecordingContext::defaultBackendFormat; 428 429 /** 430 * The explicitly allocated backend texture API allows clients to use Skia to create backend 431 * objects outside of Skia proper (i.e., Skia's caching system will not know about them.) 432 * 433 * It is the client's responsibility to delete all these objects (using deleteBackendTexture) 434 * before deleting the context used to create them. If the backend is Vulkan, the textures must 435 * be deleted before abandoning the context as well. Additionally, clients should only delete 436 * these objects on the thread for which that context is active. 437 * 438 * The client is responsible for ensuring synchronization between different uses 439 * of the backend object (i.e., wrapping it in a surface, rendering to it, deleting the 440 * surface, rewrapping it in a image and drawing the image will require explicit 441 * synchronization on the client's part). 442 */ 443 444 /** 445 * If possible, create an uninitialized backend texture. The client should ensure that the 446 * returned backend texture is valid. 447 * For the Vulkan backend the layout of the created VkImage will be: 448 * VK_IMAGE_LAYOUT_UNDEFINED. 449 */ 450 GrBackendTexture createBackendTexture(int width, int height, 451 const GrBackendFormat&, 452 GrMipmapped, 453 GrRenderable, 454 GrProtected = GrProtected::kNo); 455 456 /** 457 * If possible, create an uninitialized backend texture. The client should ensure that the 458 * returned backend texture is valid. 459 * If successful, the created backend texture will be compatible with the provided 460 * SkColorType. 461 * For the Vulkan backend the layout of the created VkImage will be: 462 * VK_IMAGE_LAYOUT_UNDEFINED. 463 */ 464 GrBackendTexture createBackendTexture(int width, int height, 465 SkColorType, 466 GrMipmapped, 467 GrRenderable, 468 GrProtected = GrProtected::kNo); 469 470 /** 471 * If possible, create a backend texture initialized to a particular color. The client should 472 * ensure that the returned backend texture is valid. The client can pass in a finishedProc 473 * to be notified when the data has been uploaded by the gpu and the texture can be deleted. The 474 * client is required to call `submit` to send the upload work to the gpu. The 475 * finishedProc will always get called even if we failed to create the GrBackendTexture. 476 * For the Vulkan backend the layout of the created VkImage will be: 477 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 478 */ 479 GrBackendTexture createBackendTexture(int width, int height, 480 const GrBackendFormat&, 481 const SkColor4f& color, 482 GrMipmapped, 483 GrRenderable, 484 GrProtected = GrProtected::kNo, 485 GrGpuFinishedProc finishedProc = nullptr, 486 GrGpuFinishedContext finishedContext = nullptr); 487 488 /** 489 * If possible, create a backend texture initialized to a particular color. The client should 490 * ensure that the returned backend texture is valid. The client can pass in a finishedProc 491 * to be notified when the data has been uploaded by the gpu and the texture can be deleted. The 492 * client is required to call `submit` to send the upload work to the gpu. The 493 * finishedProc will always get called even if we failed to create the GrBackendTexture. 494 * If successful, the created backend texture will be compatible with the provided 495 * SkColorType. 496 * For the Vulkan backend the layout of the created VkImage will be: 497 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 498 */ 499 GrBackendTexture createBackendTexture(int width, int height, 500 SkColorType, 501 const SkColor4f& color, 502 GrMipmapped, 503 GrRenderable, 504 GrProtected = GrProtected::kNo, 505 GrGpuFinishedProc finishedProc = nullptr, 506 GrGpuFinishedContext finishedContext = nullptr); 507 508 /** 509 * If possible, create a backend texture initialized with the provided pixmap data. The client 510 * should ensure that the returned backend texture is valid. The client can pass in a 511 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 512 * deleted. The client is required to call `submit` to send the upload work to the gpu. 513 * The finishedProc will always get called even if we failed to create the GrBackendTexture. 514 * If successful, the created backend texture will be compatible with the provided 515 * pixmap(s). Compatible, in this case, means that the backend format will be the result 516 * of calling defaultBackendFormat on the base pixmap's colortype. The src data can be deleted 517 * when this call returns. 518 * If numLevels is 1 a non-mipMapped texture will result. If a mipMapped texture is desired 519 * the data for all the mipmap levels must be provided. In the mipmapped case all the 520 * colortypes of the provided pixmaps must be the same. Additionally, all the miplevels 521 * must be sized correctly (please see SkMipmap::ComputeLevelSize and ComputeLevelCount). The 522 * GrSurfaceOrigin controls whether the pixmap data is vertically flipped in the texture. 523 * Note: the pixmap's alphatypes and colorspaces are ignored. 524 * For the Vulkan backend the layout of the created VkImage will be: 525 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 526 */ 527 GrBackendTexture createBackendTexture(const SkPixmap srcData[], 528 int numLevels, 529 GrSurfaceOrigin, 530 GrRenderable, 531 GrProtected, 532 GrGpuFinishedProc finishedProc = nullptr, 533 GrGpuFinishedContext finishedContext = nullptr); 534 535 /** 536 * Convenience version createBackendTexture() that takes just a base level pixmap. 537 */ 538 GrBackendTexture createBackendTexture(const SkPixmap& srcData, 539 GrSurfaceOrigin textureOrigin, 540 GrRenderable renderable, 541 GrProtected isProtected, 542 GrGpuFinishedProc finishedProc = nullptr, 543 GrGpuFinishedContext finishedContext = nullptr) { 544 return this->createBackendTexture(&srcData, 1, textureOrigin, renderable, isProtected, 545 finishedProc, finishedContext); 546 } 547 548 // Deprecated versions that do not take origin and assume top-left. 549 GrBackendTexture createBackendTexture(const SkPixmap srcData[], 550 int numLevels, 551 GrRenderable renderable, 552 GrProtected isProtected, 553 GrGpuFinishedProc finishedProc = nullptr, 554 GrGpuFinishedContext finishedContext = nullptr) { 555 return this->createBackendTexture(srcData, 556 numLevels, 557 kTopLeft_GrSurfaceOrigin, 558 renderable, 559 isProtected, 560 finishedProc, 561 finishedContext); 562 } 563 GrBackendTexture createBackendTexture(const SkPixmap& srcData, 564 GrRenderable renderable, 565 GrProtected isProtected, 566 GrGpuFinishedProc finishedProc = nullptr, 567 GrGpuFinishedContext finishedContext = nullptr) { 568 return this->createBackendTexture(&srcData, 569 1, 570 renderable, 571 isProtected, 572 finishedProc, 573 finishedContext); 574 } 575 576 /** 577 * If possible, updates a backend texture to be filled to a particular color. The client should 578 * check the return value to see if the update was successful. The client can pass in a 579 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 580 * deleted. The client is required to call `submit` to send the upload work to the gpu. 581 * The finishedProc will always get called even if we failed to update the GrBackendTexture. 582 * For the Vulkan backend after a successful update the layout of the created VkImage will be: 583 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 584 */ 585 bool updateBackendTexture(const GrBackendTexture&, 586 const SkColor4f& color, 587 GrGpuFinishedProc finishedProc, 588 GrGpuFinishedContext finishedContext); 589 590 /** 591 * If possible, updates a backend texture to be filled to a particular color. The data in 592 * GrBackendTexture and passed in color is interpreted with respect to the passed in 593 * SkColorType. The client should check the return value to see if the update was successful. 594 * The client can pass in a finishedProc to be notified when the data has been uploaded by the 595 * gpu and the texture can be deleted. The client is required to call `submit` to send 596 * the upload work to the gpu. The finishedProc will always get called even if we failed to 597 * update the GrBackendTexture. 598 * For the Vulkan backend after a successful update the layout of the created VkImage will be: 599 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 600 */ 601 bool updateBackendTexture(const GrBackendTexture&, 602 SkColorType skColorType, 603 const SkColor4f& color, 604 GrGpuFinishedProc finishedProc, 605 GrGpuFinishedContext finishedContext); 606 607 /** 608 * If possible, updates a backend texture filled with the provided pixmap data. The client 609 * should check the return value to see if the update was successful. The client can pass in a 610 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 611 * deleted. The client is required to call `submit` to send the upload work to the gpu. 612 * The finishedProc will always get called even if we failed to create the GrBackendTexture. 613 * The backend texture must be compatible with the provided pixmap(s). Compatible, in this case, 614 * means that the backend format is compatible with the base pixmap's colortype. The src data 615 * can be deleted when this call returns. 616 * If the backend texture is mip mapped, the data for all the mipmap levels must be provided. 617 * In the mipmapped case all the colortypes of the provided pixmaps must be the same. 618 * Additionally, all the miplevels must be sized correctly (please see 619 * SkMipmap::ComputeLevelSize and ComputeLevelCount). The GrSurfaceOrigin controls whether the 620 * pixmap data is vertically flipped in the texture. 621 * Note: the pixmap's alphatypes and colorspaces are ignored. 622 * For the Vulkan backend after a successful update the layout of the created VkImage will be: 623 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 624 */ 625 bool updateBackendTexture(const GrBackendTexture&, 626 const SkPixmap srcData[], 627 int numLevels, 628 GrSurfaceOrigin = kTopLeft_GrSurfaceOrigin, 629 GrGpuFinishedProc finishedProc = nullptr, 630 GrGpuFinishedContext finishedContext = nullptr); 631 632 /** 633 * Convenience version of updateBackendTexture that takes just a base level pixmap. 634 */ 635 bool updateBackendTexture(const GrBackendTexture& texture, 636 const SkPixmap& srcData, 637 GrSurfaceOrigin textureOrigin = kTopLeft_GrSurfaceOrigin, 638 GrGpuFinishedProc finishedProc = nullptr, 639 GrGpuFinishedContext finishedContext = nullptr) { 640 return this->updateBackendTexture(texture, 641 &srcData, 642 1, 643 textureOrigin, 644 finishedProc, 645 finishedContext); 646 } 647 648 // Deprecated version that does not take origin and assumes top-left. updateBackendTexture(const GrBackendTexture & texture,const SkPixmap srcData[],int numLevels,GrGpuFinishedProc finishedProc,GrGpuFinishedContext finishedContext)649 bool updateBackendTexture(const GrBackendTexture& texture, 650 const SkPixmap srcData[], 651 int numLevels, 652 GrGpuFinishedProc finishedProc, 653 GrGpuFinishedContext finishedContext) { 654 return this->updateBackendTexture(texture, 655 srcData, 656 numLevels, 657 kTopLeft_GrSurfaceOrigin, 658 finishedProc, 659 finishedContext); 660 } 661 662 /** 663 * Retrieve the GrBackendFormat for a given SkImage::CompressionType. This is 664 * guaranteed to match the backend format used by the following 665 * createCompressedBackendTexture methods that take a CompressionType. 666 * 667 * The caller should check that the returned format is valid. 668 */ 669 using GrRecordingContext::compressedBackendFormat; 670 671 /** 672 *If possible, create a compressed backend texture initialized to a particular color. The 673 * client should ensure that the returned backend texture is valid. The client can pass in a 674 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 675 * deleted. The client is required to call `submit` to send the upload work to the gpu. 676 * The finishedProc will always get called even if we failed to create the GrBackendTexture. 677 * For the Vulkan backend the layout of the created VkImage will be: 678 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 679 */ 680 GrBackendTexture createCompressedBackendTexture(int width, int height, 681 const GrBackendFormat&, 682 const SkColor4f& color, 683 GrMipmapped, 684 GrProtected = GrProtected::kNo, 685 GrGpuFinishedProc finishedProc = nullptr, 686 GrGpuFinishedContext finishedContext = nullptr); 687 688 GrBackendTexture createCompressedBackendTexture(int width, int height, 689 SkImage::CompressionType, 690 const SkColor4f& color, 691 GrMipmapped, 692 GrProtected = GrProtected::kNo, 693 GrGpuFinishedProc finishedProc = nullptr, 694 GrGpuFinishedContext finishedContext = nullptr); 695 696 /** 697 * If possible, create a backend texture initialized with the provided raw data. The client 698 * should ensure that the returned backend texture is valid. The client can pass in a 699 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 700 * deleted. The client is required to call `submit` to send the upload work to the gpu. 701 * The finishedProc will always get called even if we failed to create the GrBackendTexture 702 * If numLevels is 1 a non-mipMapped texture will result. If a mipMapped texture is desired 703 * the data for all the mipmap levels must be provided. Additionally, all the miplevels 704 * must be sized correctly (please see SkMipmap::ComputeLevelSize and ComputeLevelCount). 705 * For the Vulkan backend the layout of the created VkImage will be: 706 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 707 */ 708 GrBackendTexture createCompressedBackendTexture(int width, int height, 709 const GrBackendFormat&, 710 const void* data, size_t dataSize, 711 GrMipmapped, 712 GrProtected = GrProtected::kNo, 713 GrGpuFinishedProc finishedProc = nullptr, 714 GrGpuFinishedContext finishedContext = nullptr); 715 716 GrBackendTexture createCompressedBackendTexture(int width, int height, 717 SkImage::CompressionType, 718 const void* data, size_t dataSize, 719 GrMipmapped, 720 GrProtected = GrProtected::kNo, 721 GrGpuFinishedProc finishedProc = nullptr, 722 GrGpuFinishedContext finishedContext = nullptr); 723 724 /** 725 * If possible, updates a backend texture filled with the provided color. If the texture is 726 * mipmapped, all levels of the mip chain will be updated to have the supplied color. The client 727 * should check the return value to see if the update was successful. The client can pass in a 728 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 729 * deleted. The client is required to call `submit` to send the upload work to the gpu. 730 * The finishedProc will always get called even if we failed to create the GrBackendTexture. 731 * For the Vulkan backend after a successful update the layout of the created VkImage will be: 732 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 733 */ 734 bool updateCompressedBackendTexture(const GrBackendTexture&, 735 const SkColor4f& color, 736 GrGpuFinishedProc finishedProc, 737 GrGpuFinishedContext finishedContext); 738 739 /** 740 * If possible, updates a backend texture filled with the provided raw data. The client 741 * should check the return value to see if the update was successful. The client can pass in a 742 * finishedProc to be notified when the data has been uploaded by the gpu and the texture can be 743 * deleted. The client is required to call `submit` to send the upload work to the gpu. 744 * The finishedProc will always get called even if we failed to create the GrBackendTexture. 745 * If a mipMapped texture is passed in, the data for all the mipmap levels must be provided. 746 * Additionally, all the miplevels must be sized correctly (please see 747 * SkMipMap::ComputeLevelSize and ComputeLevelCount). 748 * For the Vulkan backend after a successful update the layout of the created VkImage will be: 749 * VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL 750 */ 751 bool updateCompressedBackendTexture(const GrBackendTexture&, 752 const void* data, 753 size_t dataSize, 754 GrGpuFinishedProc finishedProc, 755 GrGpuFinishedContext finishedContext); 756 757 /** 758 * Updates the state of the GrBackendTexture/RenderTarget to have the passed in 759 * GrBackendSurfaceMutableState. All objects that wrap the backend surface (i.e. SkSurfaces and 760 * SkImages) will also be aware of this state change. This call does not submit the state change 761 * to the gpu, but requires the client to call `submit` to send it to the GPU. The work 762 * for this call is ordered linearly with all other calls that require GrContext::submit to be 763 * called (e.g updateBackendTexture and flush). If finishedProc is not null then it will be 764 * called with finishedContext after the state transition is known to have occurred on the GPU. 765 * 766 * See GrBackendSurfaceMutableState to see what state can be set via this call. 767 * 768 * If the backend API is Vulkan, the caller can set the GrBackendSurfaceMutableState's 769 * VkImageLayout to VK_IMAGE_LAYOUT_UNDEFINED or queueFamilyIndex to VK_QUEUE_FAMILY_IGNORED to 770 * tell Skia to not change those respective states. 771 * 772 * If previousState is not null and this returns true, then Skia will have filled in 773 * previousState to have the values of the state before this call. 774 */ 775 bool setBackendTextureState(const GrBackendTexture&, 776 const GrBackendSurfaceMutableState&, 777 GrBackendSurfaceMutableState* previousState = nullptr, 778 GrGpuFinishedProc finishedProc = nullptr, 779 GrGpuFinishedContext finishedContext = nullptr); 780 bool setBackendRenderTargetState(const GrBackendRenderTarget&, 781 const GrBackendSurfaceMutableState&, 782 GrBackendSurfaceMutableState* previousState = nullptr, 783 GrGpuFinishedProc finishedProc = nullptr, 784 GrGpuFinishedContext finishedContext = nullptr); 785 786 void deleteBackendTexture(GrBackendTexture); 787 788 // This interface allows clients to pre-compile shaders and populate the runtime program cache. 789 // The key and data blobs should be the ones passed to the PersistentCache, in SkSL format. 790 // 791 // Steps to use this API: 792 // 793 // 1) Create a GrDirectContext as normal, but set fPersistentCache on GrContextOptions to 794 // something that will save the cached shader blobs. Set fShaderCacheStrategy to kSkSL. This 795 // will ensure that the blobs are SkSL, and are suitable for pre-compilation. 796 // 2) Run your application, and save all of the key/data pairs that are fed to the cache. 797 // 798 // 3) Switch over to shipping your application. Include the key/data pairs from above. 799 // 4) At startup (or any convenient time), call precompileShader for each key/data pair. 800 // This will compile the SkSL to create a GL program, and populate the runtime cache. 801 // 802 // This is only guaranteed to work if the context/device used in step #2 are created in the 803 // same way as the one used in step #4, and the same GrContextOptions are specified. 804 // Using cached shader blobs on a different device or driver are undefined. 805 bool precompileShader(const SkData& key, const SkData& data); 806 807 #ifdef SK_ENABLE_DUMP_GPU 808 /** Returns a string with detailed information about the context & GPU, in JSON format. */ 809 SkString dump() const; 810 #endif 811 812 class DirectContextID { 813 public: 814 static GrDirectContext::DirectContextID Next(); 815 DirectContextID()816 DirectContextID() : fID(SK_InvalidUniqueID) {} 817 818 bool operator==(const DirectContextID& that) const { return fID == that.fID; } 819 bool operator!=(const DirectContextID& that) const { return !(*this == that); } 820 makeInvalid()821 void makeInvalid() { fID = SK_InvalidUniqueID; } isValid()822 bool isValid() const { return fID != SK_InvalidUniqueID; } 823 824 private: DirectContextID(uint32_t id)825 constexpr DirectContextID(uint32_t id) : fID(id) {} 826 uint32_t fID; 827 }; 828 directContextID()829 DirectContextID directContextID() const { return fDirectContextID; } 830 831 // Provides access to functions that aren't part of the public API. 832 GrDirectContextPriv priv(); 833 const GrDirectContextPriv priv() const; // NOLINT(readability-const-return-type) 834 835 /** 836 * Set current resource tag for gpu cache recycle. 837 */ 838 void setCurrentGrResourceTag(const GrGpuResourceTag tag); 839 840 /** 841 * Get current resource tag for gpu cache recycle. 842 * 843 * @return all GrGpuResourceTags. 844 */ 845 GrGpuResourceTag getCurrentGrResourceTag() const; 846 847 /** 848 * Releases GrGpuResource objects and removes them from the cache by tag. 849 */ 850 void releaseByTag(const GrGpuResourceTag tag); 851 852 /** 853 * Get all GrGpuResource tag. 854 * 855 * @return all GrGpuResourceTags. 856 */ 857 std::set<GrGpuResourceTag> getAllGrGpuResourceTags() const; 858 859 protected: 860 GrDirectContext(GrBackendApi backend, const GrContextOptions& options); 861 862 bool init() override; 863 onGetAtlasManager()864 GrAtlasManager* onGetAtlasManager() { return fAtlasManager.get(); } 865 skgpu::v1::SmallPathAtlasMgr* onGetSmallPathAtlasMgr(); 866 asDirectContext()867 GrDirectContext* asDirectContext() override { return this; } 868 869 private: 870 // This call will make sure out work on the GPU is finished and will execute any outstanding 871 // asynchronous work (e.g. calling finished procs, freeing resources, etc.) related to the 872 // outstanding work on the gpu. The main use currently for this function is when tearing down or 873 // abandoning the context. 874 // 875 // When we finish up work on the GPU it could trigger callbacks to the client. In the case we 876 // are abandoning the context we don't want the client to be able to use the GrDirectContext to 877 // issue more commands during the callback. Thus before calling this function we set the 878 // GrDirectContext's state to be abandoned. However, we need to be able to get by the abaonded 879 // check in the call to know that it is safe to execute this. The shouldExecuteWhileAbandoned 880 // bool is used for this signal. 881 void syncAllOutstandingGpuWork(bool shouldExecuteWhileAbandoned); 882 883 const DirectContextID fDirectContextID; 884 // fTaskGroup must appear before anything that uses it (e.g. fGpu), so that it is destroyed 885 // after all of its users. Clients of fTaskGroup will generally want to ensure that they call 886 // wait() on it as they are being destroyed, to avoid the possibility of pending tasks being 887 // invoked after objects they depend upon have already been destroyed. 888 std::unique_ptr<SkTaskGroup> fTaskGroup; 889 std::unique_ptr<GrStrikeCache> fStrikeCache; 890 sk_sp<GrGpu> fGpu; 891 std::unique_ptr<GrResourceCache> fResourceCache; 892 std::unique_ptr<GrResourceProvider> fResourceProvider; 893 894 bool fDidTestPMConversions; 895 // true if the PM/UPM conversion succeeded; false otherwise 896 bool fPMUPMConversionsRoundTrip; 897 898 GrContextOptions::PersistentCache* fPersistentCache; 899 900 std::unique_ptr<GrClientMappedBufferManager> fMappedBufferManager; 901 std::unique_ptr<GrAtlasManager> fAtlasManager; 902 903 std::unique_ptr<skgpu::v1::SmallPathAtlasMgr> fSmallPathAtlasMgr; 904 905 friend class GrDirectContextPriv; 906 907 using INHERITED = GrRecordingContext; 908 }; 909 910 911 #endif 912