Debian Codegraph @

src/gpu/ganesh/GrDirectContext.cpp

raw
1 /*
2 * Copyright 2018 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 #include "include/gpu/ganesh/GrDirectContext.h"
8
9 #include "include/core/SkImageInfo.h"
10 #include "include/core/SkPixmap.h"
11 #include "include/core/SkSize.h"
12 #include "include/core/SkSurface.h"
13 #include "include/core/SkTextureCompressionType.h"
14 #include "include/core/SkTraceMemoryDump.h"
15 #include "include/gpu/GpuTypes.h"
16 #include "include/gpu/ganesh/GrBackendSemaphore.h"
17 #include "include/gpu/ganesh/GrBackendSurface.h"
18 #include "include/gpu/ganesh/GrContextThreadSafeProxy.h"
19 #include "include/private/base/SingleOwner.h"
20 #include "include/private/base/SkTArray.h"
21 #include "include/private/base/SkTemplates.h"
22 #include "include/private/gpu/ganesh/GrTypesPriv.h"
23 #include "src/base/SkAutoMalloc.h"
24 #include "src/core/SkCompressedDataUtils.h"
25 #include "src/core/SkMipmap.h"
26 #include "src/core/SkTaskGroup.h"
27 #include "src/core/SkTraceEvent.h"
28 #include "src/gpu/DataUtils.h"
29 #include "src/gpu/GpuTypesPriv.h"
30 #include "src/gpu/RefCntedCallback.h"
31 #include "src/gpu/Swizzle.h"
32 #include "src/gpu/ganesh/Device.h"
33 #include "src/gpu/ganesh/GrBackendUtils.h"
34 #include "src/gpu/ganesh/GrCaps.h"
35 #include "src/gpu/ganesh/GrClientMappedBufferManager.h"
36 #include "src/gpu/ganesh/GrColorInfo.h"
37 #include "src/gpu/ganesh/GrContextThreadSafeProxyPriv.h"
38 #include "src/gpu/ganesh/GrDirectContextPriv.h"
39 #include "src/gpu/ganesh/GrDrawOpAtlas.h"
40 #include "src/gpu/ganesh/GrDrawingManager.h"
41 #include "src/gpu/ganesh/GrGpu.h"
42 #include "src/gpu/ganesh/GrPixmap.h"
43 #include "src/gpu/ganesh/GrProxyProvider.h"
44 #include "src/gpu/ganesh/GrRenderTargetProxy.h"
45 #include "src/gpu/ganesh/GrResourceCache.h"
46 #include "src/gpu/ganesh/GrResourceProvider.h"
47 #include "src/gpu/ganesh/GrSemaphore.h" // IWYU pragma: keep
48 #include "src/gpu/ganesh/GrShaderCaps.h"
49 #include "src/gpu/ganesh/GrSurfaceProxy.h"
50 #include "src/gpu/ganesh/GrSurfaceProxyView.h"
51 #include "src/gpu/ganesh/GrThreadSafePipelineBuilder.h" // IWYU pragma: keep
52 #include "src/gpu/ganesh/SurfaceContext.h"
53 #include "src/gpu/ganesh/image/SkImage_GaneshBase.h"
54 #include "src/gpu/ganesh/mock/GrMockGpu.h"
55 #include "src/gpu/ganesh/ops/SmallPathAtlasMgr.h"
56 #include "src/gpu/ganesh/surface/SkSurface_Ganesh.h"
57 #include "src/gpu/ganesh/text/GrAtlasManager.h"
58 #include "src/image/SkImage_Base.h"
59 #include "src/image/SkSurface_Base.h"
60 #include "src/text/gpu/StrikeCache.h"
61 #include "src/text/gpu/TextBlobRedrawCoordinator.h"
62
63 #include <array>
64 #include <atomic>
65 #include <forward_list>
66 #include <memory>
67 #include <utility>
68
69 #ifdef SK_DIRECT3D
70 #include "src/gpu/ganesh/d3d/GrD3DGpu.h"
71 #endif
72
73 using namespace skia_private;
74
75 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())
76
77 using StrikeCache = sktext::gpu::StrikeCache;
78
79 GrDirectContext::DirectContextID GrDirectContext::DirectContextID::Next() {
80 static std::atomic<uint32_t> nextID{1};
81 uint32_t id;
82 do {
83 id = nextID.fetch_add(1, std::memory_order_relaxed);
84 } while (id == SK_InvalidUniqueID);
85 return DirectContextID(id);
86 }
87
88 GrDirectContext::GrDirectContext(GrBackendApi backend,
89 const GrContextOptions& options,
90 sk_sp<GrContextThreadSafeProxy> proxy)
91 : GrRecordingContext(std::move(proxy), false)
92 , fDeleteCallbackHelper(new DeleteCallbackHelper(options.fContextDeleteContext,
93 options.fContextDeleteProc))
94 , fDirectContextID(DirectContextID::Next()) {}
95
96 GrDirectContext::~GrDirectContext() {
97 ASSERT_SINGLE_OWNER
98 // this if-test protects against the case where the context is being destroyed
99 // before having been fully created
100 if (fGpu) {
101 this->flushAndSubmit();
102 }
103
104 // We need to make sure all work is finished on the gpu before we start releasing resources.
105 this->syncAllOutstandingGpuWork(/*shouldExecuteWhileAbandoned=*/false);
106
107 this->destroyDrawingManager();
108
109 // Ideally we could just let the ptr drop, but resource cache queries this ptr in releaseAll.
110 if (fResourceCache) {
111 fResourceCache->releaseAll();
112 }
113 // This has to be after GrResourceCache::releaseAll so that other threads that are holding
114 // async pixel result don't try to destroy buffers off thread.
115 fMappedBufferManager.reset();
116 }
117
118 sk_sp<GrContextThreadSafeProxy> GrDirectContext::threadSafeProxy() {
119 return GrRecordingContext::threadSafeProxy();
120 }
121
122 void GrDirectContext::resetGLTextureBindings() {
123 if (this->abandoned() || this->backend() != GrBackendApi::kOpenGL) {
124 return;
125 }
126 fGpu->resetTextureBindings();
127 }
128
129 void GrDirectContext::resetContext(uint32_t state) {
130 ASSERT_SINGLE_OWNER
131 fGpu->markContextDirty(state);
132 }
133
134 void GrDirectContext::abandonContext() {
135 if (GrRecordingContext::abandoned()) {
136 return;
137 }
138
139 if (fInsideReleaseProcCnt) {
140 SkDEBUGFAIL("Calling GrDirectContext::abandonContext() while inside a ReleaseProc is not "
141 "allowed");
142 return;
143 }
144
145 GrRecordingContext::abandonContext();
146
147 // We need to make sure all work is finished on the gpu before we start releasing resources.
148 this->syncAllOutstandingGpuWork(this->caps()->mustSyncGpuDuringAbandon());
149
150 fStrikeCache->freeAll();
151
152 fMappedBufferManager->abandon();
153
154 fResourceProvider->abandon();
155
156 // abandon first so destructors don't try to free the resources in the API.
157 fResourceCache->abandonAll();
158
159 fGpu->disconnect(GrGpu::DisconnectType::kAbandon);
160
161 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
162 if (fSmallPathAtlasMgr) {
163 fSmallPathAtlasMgr->reset();
164 }
165 #endif
166 fAtlasManager->freeAll();
167 }
168
169 bool GrDirectContext::abandoned() {
170 if (GrRecordingContext::abandoned()) {
171 return true;
172 }
173
174 if (fGpu && fGpu->isDeviceLost()) {
175 this->abandonContext();
176 return true;
177 }
178 return false;
179 }
180
181 bool GrDirectContext::isDeviceLost() {
182 if (fGpu && fGpu->isDeviceLost()) {
183 if (!GrRecordingContext::abandoned()) {
184 this->abandonContext();
185 }
186 return true;
187 }
188 return false;
189 }
190
191 bool GrDirectContext::oomed() { return fGpu ? fGpu->checkAndResetOOMed() : false; }
192
193 void GrDirectContext::releaseResourcesAndAbandonContext() {
194 if (GrRecordingContext::abandoned()) {
195 return;
196 }
197
198 GrRecordingContext::abandonContext();
199
200 // We need to make sure all work is finished on the gpu before we start releasing resources.
201 this->syncAllOutstandingGpuWork(/*shouldExecuteWhileAbandoned=*/true);
202
203 fResourceProvider->abandon();
204
205 // Release all resources in the backend 3D API.
206 fResourceCache->releaseAll();
207
208 // Must be after GrResourceCache::releaseAll().
209 fMappedBufferManager.reset();
210
211 fGpu->disconnect(GrGpu::DisconnectType::kCleanup);
212 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
213 if (fSmallPathAtlasMgr) {
214 fSmallPathAtlasMgr->reset();
215 }
216 #endif
217 fAtlasManager->freeAll();
218 }
219
220 void GrDirectContext::freeGpuResources() {
221 ASSERT_SINGLE_OWNER
222
223 if (this->abandoned()) {
224 return;
225 }
226
227 this->flushAndSubmit();
228 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
229 if (fSmallPathAtlasMgr) {
230 fSmallPathAtlasMgr->reset();
231 }
232 #endif
233 fAtlasManager->freeAll();
234
235 // TODO: the glyph cache doesn't hold any GpuResources so this call should not be needed here.
236 // Some slack in the GrTextBlob's implementation requires it though. That could be fixed.
237 fStrikeCache->freeAll();
238
239 this->drawingManager()->freeGpuResources();
240
241 fResourceCache->purgeUnlockedResources(GrPurgeResourceOptions::kAllResources);
242 }
243
244 bool GrDirectContext::init() {
245 ASSERT_SINGLE_OWNER
246 if (!fGpu) {
247 return false;
248 }
249
250 fThreadSafeProxy->priv().init(fGpu->refCaps(), fGpu->refPipelineBuilder());
251 if (!GrRecordingContext::init()) {
252 return false;
253 }
254
255 SkASSERT(this->getTextBlobRedrawCoordinator());
256 SkASSERT(this->threadSafeCache());
257
258 fStrikeCache = std::make_unique<StrikeCache>();
259 fResourceCache = std::make_unique<GrResourceCache>(this->singleOwner(),
260 this->directContextID(),
261 this->contextID());
262 fResourceCache->setProxyProvider(this->proxyProvider());
263 fResourceCache->setThreadSafeCache(this->threadSafeCache());
264 #if defined(GPU_TEST_UTILS)
265 if (this->options().fResourceCacheLimitOverride != -1) {
266 this->setResourceCacheLimit(this->options().fResourceCacheLimitOverride);
267 }
268 #endif
269 fResourceProvider = std::make_unique<GrResourceProvider>(fGpu.get(), fResourceCache.get(),
270 this->singleOwner());
271 fMappedBufferManager = std::make_unique<GrClientMappedBufferManager>(this->directContextID());
272
273 fDidTestPMConversions = false;
274
275 // DDL TODO: we need to think through how the task group & persistent cache
276 // get passed on to/shared between all the DDLRecorders created with this context.
277 if (this->options().fExecutor) {
278 fTaskGroup = std::make_unique<SkTaskGroup>(*this->options().fExecutor);
279 }
280
281 fPersistentCache = this->options().fPersistentCache;
282
283 GrDrawOpAtlas::AllowMultitexturing allowMultitexturing;
284 if (GrContextOptions::Enable::kNo == this->options().fAllowMultipleGlyphCacheTextures ||
285 // multitexturing supported only if range can represent the index + texcoords fully
286 !(this->caps()->shaderCaps()->fFloatIs32Bits ||
287 this->caps()->shaderCaps()->fIntegerSupport)) {
288 allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kNo;
289 } else {
290 allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kYes;
291 }
292
293 GrProxyProvider* proxyProvider = this->priv().proxyProvider();
294
295 fAtlasManager = std::make_unique<GrAtlasManager>(proxyProvider,
296 this->options().fGlyphCacheTextureMaximumBytes,
297 allowMultitexturing,
298 this->options().fSupportBilerpFromGlyphAtlas);
299 this->priv().addOnFlushCallbackObject(fAtlasManager.get());
300
301 return true;
302 }
303
304 void GrDirectContext::getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const {
305 ASSERT_SINGLE_OWNER
306
307 if (resourceCount) {
308 *resourceCount = fResourceCache->getBudgetedResourceCount();
309 }
310 if (resourceBytes) {
311 *resourceBytes = fResourceCache->getBudgetedResourceBytes();
312 }
313 }
314
315 size_t GrDirectContext::getResourceCachePurgeableBytes() const {
316 ASSERT_SINGLE_OWNER
317 return fResourceCache->getPurgeableBytes();
318 }
319
320 void GrDirectContext::getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const {
321 ASSERT_SINGLE_OWNER
322 if (maxResources) {
323 *maxResources = -1;
324 }
325 if (maxResourceBytes) {
326 *maxResourceBytes = this->getResourceCacheLimit();
327 }
328 }
329
330 size_t GrDirectContext::getResourceCacheLimit() const {
331 ASSERT_SINGLE_OWNER
332 return fResourceCache->getMaxResourceBytes();
333 }
334
335 void GrDirectContext::setResourceCacheLimits(int unused, size_t maxResourceBytes) {
336 ASSERT_SINGLE_OWNER
337 this->setResourceCacheLimit(maxResourceBytes);
338 }
339
340 void GrDirectContext::setResourceCacheLimit(size_t maxResourceBytes) {
341 ASSERT_SINGLE_OWNER
342 fResourceCache->setLimit(maxResourceBytes);
343 }
344
345 void GrDirectContext::purgeUnlockedResources(GrPurgeResourceOptions opts) {
346 ASSERT_SINGLE_OWNER
347
348 if (this->abandoned()) {
349 return;
350 }
351
352 fResourceCache->purgeUnlockedResources(opts);
353 fResourceCache->purgeAsNeeded();
354
355 // The textBlob Cache doesn't actually hold any GPU resource but this is a convenient
356 // place to purge stale blobs
357 this->getTextBlobRedrawCoordinator()->purgeStaleBlobs();
358
359 fGpu->releaseUnlockedBackendObjects();
360 }
361
362 void GrDirectContext::performDeferredCleanup(std::chrono::milliseconds msNotUsed,
363 GrPurgeResourceOptions opts) {
364 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
365
366 ASSERT_SINGLE_OWNER
367
368 if (this->abandoned()) {
369 return;
370 }
371
372 this->checkAsyncWorkCompletion();
373 fMappedBufferManager->process();
374 auto purgeTime = skgpu::StdSteadyClock::now() - msNotUsed;
375
376 fResourceCache->purgeAsNeeded();
377 fResourceCache->purgeResourcesNotUsedSince(purgeTime, opts);
378
379 // The textBlob Cache doesn't actually hold any GPU resource but this is a convenient
380 // place to purge stale blobs
381 this->getTextBlobRedrawCoordinator()->purgeStaleBlobs();
382 }
383
384 void GrDirectContext::purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources) {
385 ASSERT_SINGLE_OWNER
386
387 if (this->abandoned()) {
388 return;
389 }
390
391 fResourceCache->purgeUnlockedResources(bytesToPurge, preferScratchResources);
392 }
393
394 ////////////////////////////////////////////////////////////////////////////////
395 bool GrDirectContext::wait(int numSemaphores, const GrBackendSemaphore waitSemaphores[],
396 bool deleteSemaphoresAfterWait) {
397 if (!fGpu || !fGpu->caps()->backendSemaphoreSupport()) {
398 return false;
399 }
400 GrWrapOwnership ownership =
401 deleteSemaphoresAfterWait ? kAdopt_GrWrapOwnership : kBorrow_GrWrapOwnership;
402 for (int i = 0; i < numSemaphores; ++i) {
403 std::unique_ptr<GrSemaphore> sema = fResourceProvider->wrapBackendSemaphore(
404 waitSemaphores[i], GrSemaphoreWrapType::kWillWait, ownership);
405 // If we failed to wrap the semaphore it means the client didn't give us a valid semaphore
406 // to begin with. Therefore, it is fine to not wait on it.
407 if (sema) {
408 fGpu->waitSemaphore(sema.get());
409 }
410 }
411 return true;
412 }
413
414 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
415 skgpu::ganesh::SmallPathAtlasMgr* GrDirectContext::onGetSmallPathAtlasMgr() {
416 if (!fSmallPathAtlasMgr) {
417 fSmallPathAtlasMgr = std::make_unique<skgpu::ganesh::SmallPathAtlasMgr>();
418
419 this->priv().addOnFlushCallbackObject(fSmallPathAtlasMgr.get());
420 }
421
422 if (!fSmallPathAtlasMgr->initAtlas(this->proxyProvider(), this->caps())) {
423 return nullptr;
424 }
425
426 return fSmallPathAtlasMgr.get();
427 }
428 #endif
429
430 ////////////////////////////////////////////////////////////////////////////////
431
432 skgpu::GpuStatsFlags GrDirectContext::supportedGpuStats() const {
433 return this->caps()->supportedGpuStats();
434 }
435
436 GrSemaphoresSubmitted GrDirectContext::flush(const GrFlushInfo& info) {
437 ASSERT_SINGLE_OWNER
438 if (this->abandoned()) {
439 if (info.fFinishedProc) {
440 info.fFinishedProc(info.fFinishedContext);
441 }
442 if (info.fSubmittedProc) {
443 info.fSubmittedProc(info.fSubmittedContext, false);
444 }
445 return GrSemaphoresSubmitted::kNo;
446 }
447
448 return this->drawingManager()->flushSurfaces(
449 {}, SkSurfaces::BackendSurfaceAccess::kNoAccess, info, nullptr);
450 }
451
452 bool GrDirectContext::submit(const GrSubmitInfo& info) {
453 ASSERT_SINGLE_OWNER
454 if (this->abandoned()) {
455 return false;
456 }
457
458 if (!fGpu) {
459 return false;
460 }
461
462 return fGpu->submitToGpu(info);
463 }
464
465 GrSemaphoresSubmitted GrDirectContext::flush(const sk_sp<const SkImage>& image,
466 const GrFlushInfo& flushInfo) {
467 if (!image) {
468 return GrSemaphoresSubmitted::kNo;
469 }
470 auto ib = as_IB(image);
471 if (!ib->isGaneshBacked()) {
472 return GrSemaphoresSubmitted::kNo;
473 }
474 auto igb = static_cast<const SkImage_GaneshBase*>(image.get());
475 return igb->flush(this, flushInfo);
476 }
477
478 void GrDirectContext::flush(const sk_sp<const SkImage>& image) {
479 this->flush(image, {});
480 }
481
482 void GrDirectContext::flushAndSubmit(const sk_sp<const SkImage>& image) {
483 this->flush(image, {});
484 this->submit();
485 }
486
487 GrSemaphoresSubmitted GrDirectContext::flush(SkSurface* surface,
488 SkSurfaces::BackendSurfaceAccess access,
489 const GrFlushInfo& info) {
490 if (!surface) {
491 return GrSemaphoresSubmitted::kNo;
492 }
493 auto sb = asSB(surface);
494 if (!sb->isGaneshBacked()) {
495 return GrSemaphoresSubmitted::kNo;
496 }
497
498 auto gs = static_cast<SkSurface_Ganesh*>(surface);
499 SkASSERT(this->priv().matches(gs->getDevice()->recordingContext()->asDirectContext()));
500 GrRenderTargetProxy* rtp = gs->getDevice()->targetProxy();
501
502 return this->priv().flushSurface(rtp, access, info, nullptr);
503 }
504
505 GrSemaphoresSubmitted GrDirectContext::flush(SkSurface* surface,
506 const GrFlushInfo& info,
507 const skgpu::MutableTextureState* newState) {
508 if (!surface) {
509 return GrSemaphoresSubmitted::kNo;
510 }
511 auto sb = asSB(surface);
512 if (!sb->isGaneshBacked()) {
513 return GrSemaphoresSubmitted::kNo;
514 }
515
516 auto gs = static_cast<SkSurface_Ganesh*>(surface);
517 SkASSERT(this->priv().matches(gs->getDevice()->recordingContext()->asDirectContext()));
518 GrRenderTargetProxy* rtp = gs->getDevice()->targetProxy();
519
520 return this->priv().flushSurface(
521 rtp, SkSurfaces::BackendSurfaceAccess::kNoAccess, info, newState);
522 }
523
524 void GrDirectContext::flushAndSubmit(SkSurface* surface, GrSyncCpu sync) {
525 this->flush(surface, SkSurfaces::BackendSurfaceAccess::kNoAccess, GrFlushInfo());
526 this->submit(sync);
527 }
528
529 void GrDirectContext::flush(SkSurface* surface) {
530 this->flush(surface, GrFlushInfo(), nullptr);
531 }
532
533 ////////////////////////////////////////////////////////////////////////////////
534
535 void GrDirectContext::checkAsyncWorkCompletion() {
536 if (fGpu) {
537 fGpu->checkFinishedCallbacks();
538 }
539 }
540
541 void GrDirectContext::syncAllOutstandingGpuWork(bool shouldExecuteWhileAbandoned) {
542 if (fGpu && (!this->abandoned() || shouldExecuteWhileAbandoned)) {
543 fGpu->finishOutstandingGpuWork();
544 this->checkAsyncWorkCompletion();
545 }
546 }
547
548 ////////////////////////////////////////////////////////////////////////////////
549
550 bool GrDirectContext::canDetectNewVkPipelineCacheData() const {
551 if (!fGpu) {
552 return false;
553 }
554
555 return fGpu->canDetectNewVkPipelineCacheData();
556 }
557
558 bool GrDirectContext::hasNewVkPipelineCacheData() const {
559 if (!fGpu) {
560 return false;
561 }
562
563 return fGpu->hasNewVkPipelineCacheData();
564 }
565
566 void GrDirectContext::storeVkPipelineCacheData() {
567 this->storeVkPipelineCacheData(SIZE_MAX);
568 }
569
570 void GrDirectContext::storeVkPipelineCacheData(size_t maxSize) {
571 if (fGpu) {
572 fGpu->storeVkPipelineCacheData(maxSize);
573 }
574 }
575
576 ////////////////////////////////////////////////////////////////////////////////
577
578 bool GrDirectContext::supportsDistanceFieldText() const {
579 return this->caps()->shaderCaps()->supportsDistanceFieldText();
580 }
581
582 //////////////////////////////////////////////////////////////////////////////
583
584 void GrDirectContext::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
585 ASSERT_SINGLE_OWNER
586 fResourceCache->dumpMemoryStatistics(traceMemoryDump);
587 traceMemoryDump->dumpNumericValue("skia/gr_text_blob_cache", "size", "bytes",
588 this->getTextBlobRedrawCoordinator()->usedBytes());
589 }
590
591 GrBackendTexture GrDirectContext::createBackendTexture(int width,
592 int height,
593 const GrBackendFormat& backendFormat,
594 skgpu::Mipmapped mipmapped,
595 GrRenderable renderable,
596 GrProtected isProtected,
597 std::string_view label) {
598 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
599 if (this->abandoned()) {
600 return GrBackendTexture();
601 }
602
603 return fGpu->createBackendTexture({width, height}, backendFormat, renderable,
604 mipmapped, isProtected, label);
605 }
606
607 GrBackendTexture GrDirectContext::createBackendTexture(const SkPixmap& srcData,
608 GrSurfaceOrigin textureOrigin,
609 GrRenderable renderable,
610 GrProtected isProtected,
611 GrGpuFinishedProc finishedProc,
612 GrGpuFinishedContext finishedContext,
613 std::string_view label) {
614 return this->createBackendTexture(&srcData, 1, textureOrigin, renderable, isProtected,
615 finishedProc, finishedContext, label);
616 }
617
618 GrBackendTexture GrDirectContext::createBackendTexture(const SkPixmap& srcData,
619 GrRenderable renderable,
620 GrProtected isProtected,
621 GrGpuFinishedProc finishedProc,
622 GrGpuFinishedContext finishedContext,
623 std::string_view label) {
624 return this->createBackendTexture(&srcData,
625 1,
626 renderable,
627 isProtected,
628 finishedProc,
629 finishedContext,
630 label);
631 }
632
633 GrBackendTexture GrDirectContext::createBackendTexture(const SkPixmap srcData[],
634 int numLevels,
635 GrRenderable renderable,
636 GrProtected isProtected,
637 GrGpuFinishedProc finishedProc,
638 GrGpuFinishedContext finishedContext,
639 std::string_view label) {
640 return this->createBackendTexture(srcData,
641 numLevels,
642 kTopLeft_GrSurfaceOrigin,
643 renderable,
644 isProtected,
645 finishedProc,
646 finishedContext,
647 label);
648 }
649
650 GrBackendTexture GrDirectContext::createBackendTexture(int width,
651 int height,
652 SkColorType skColorType,
653 skgpu::Mipmapped mipmapped,
654 GrRenderable renderable,
655 GrProtected isProtected,
656 std::string_view label) {
657 if (this->abandoned()) {
658 return GrBackendTexture();
659 }
660
661 const GrBackendFormat format = this->defaultBackendFormat(skColorType, renderable);
662
663 return this->createBackendTexture(
664 width, height, format, mipmapped, renderable, isProtected, label);
665 }
666
667 static GrBackendTexture create_and_clear_backend_texture(
668 GrDirectContext* dContext,
669 SkISize dimensions,
670 const GrBackendFormat& backendFormat,
671 skgpu::Mipmapped mipmapped,
672 GrRenderable renderable,
673 GrProtected isProtected,
674 sk_sp<skgpu::RefCntedCallback> finishedCallback,
675 std::array<float, 4> color,
676 std::string_view label) {
677 GrGpu* gpu = dContext->priv().getGpu();
678 GrBackendTexture beTex = gpu->createBackendTexture(dimensions, backendFormat, renderable,
679 mipmapped, isProtected, label);
680 if (!beTex.isValid()) {
681 return {};
682 }
683
684 if (!dContext->priv().getGpu()->clearBackendTexture(beTex,
685 std::move(finishedCallback),
686 color)) {
687 dContext->deleteBackendTexture(beTex);
688 return {};
689 }
690 return beTex;
691 }
692
693 static bool update_texture_with_pixmaps(GrDirectContext* context,
694 const SkPixmap src[],
695 int numLevels,
696 const GrBackendTexture& backendTexture,
697 GrSurfaceOrigin textureOrigin,
698 sk_sp<skgpu::RefCntedCallback> finishedCallback) {
699 GrColorType ct = SkColorTypeToGrColorType(src[0].colorType());
700 const GrBackendFormat& format = backendTexture.getBackendFormat();
701
702 if (!context->priv().caps()->areColorTypeAndFormatCompatible(ct, format)) {
703 return false;
704 }
705
706 auto proxy = context->priv().proxyProvider()->wrapBackendTexture(backendTexture,
707 kBorrow_GrWrapOwnership,
708 GrWrapCacheable::kNo,
709 kRW_GrIOType,
710 std::move(finishedCallback));
711 if (!proxy) {
712 return false;
713 }
714
715 skgpu::Swizzle swizzle = context->priv().caps()->getReadSwizzle(format, ct);
716 GrSurfaceProxyView view(std::move(proxy), textureOrigin, swizzle);
717 skgpu::ganesh::SurfaceContext surfaceContext(
718 context, std::move(view), src[0].info().colorInfo());
719 AutoSTArray<15, GrCPixmap> tmpSrc(numLevels);
720 for (int i = 0; i < numLevels; ++i) {
721 tmpSrc[i] = src[i];
722 }
723 if (!surfaceContext.writePixels(context, tmpSrc.get(), numLevels)) {
724 return false;
725 }
726
727 GrSurfaceProxy* p = surfaceContext.asSurfaceProxy();
728 GrFlushInfo info;
729 context->priv().drawingManager()->flushSurfaces(
730 {&p, 1}, SkSurfaces::BackendSurfaceAccess::kNoAccess, info, nullptr);
731 return true;
732 }
733
734 GrBackendTexture GrDirectContext::createBackendTexture(int width,
735 int height,
736 const GrBackendFormat& backendFormat,
737 const SkColor4f& color,
738 skgpu::Mipmapped mipmapped,
739 GrRenderable renderable,
740 GrProtected isProtected,
741 GrGpuFinishedProc finishedProc,
742 GrGpuFinishedContext finishedContext,
743 std::string_view label) {
744 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
745
746 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
747 if (this->abandoned()) {
748 return {};
749 }
750
751 return create_and_clear_backend_texture(this,
752 {width, height},
753 backendFormat,
754 mipmapped,
755 renderable,
756 isProtected,
757 std::move(finishedCallback),
758 color.array(),
759 label);
760 }
761
762 GrBackendTexture GrDirectContext::createBackendTexture(int width,
763 int height,
764 SkColorType skColorType,
765 const SkColor4f& color,
766 skgpu::Mipmapped mipmapped,
767 GrRenderable renderable,
768 GrProtected isProtected,
769 GrGpuFinishedProc finishedProc,
770 GrGpuFinishedContext finishedContext,
771 std::string_view label) {
772 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
773
774 if (this->abandoned()) {
775 return {};
776 }
777
778 GrBackendFormat format = this->defaultBackendFormat(skColorType, renderable);
779 if (!format.isValid()) {
780 return {};
781 }
782
783 GrColorType grColorType = SkColorTypeToGrColorType(skColorType);
784 SkColor4f swizzledColor = this->caps()->getWriteSwizzle(format, grColorType).applyTo(color);
785
786 return create_and_clear_backend_texture(this,
787 {width, height},
788 format,
789 mipmapped,
790 renderable,
791 isProtected,
792 std::move(finishedCallback),
793 swizzledColor.array(),
794 label);
795 }
796
797 GrBackendTexture GrDirectContext::createBackendTexture(const SkPixmap srcData[],
798 int numProvidedLevels,
799 GrSurfaceOrigin textureOrigin,
800 GrRenderable renderable,
801 GrProtected isProtected,
802 GrGpuFinishedProc finishedProc,
803 GrGpuFinishedContext finishedContext,
804 std::string_view label) {
805 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
806
807 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
808
809 if (this->abandoned()) {
810 return {};
811 }
812
813 if (!srcData || numProvidedLevels <= 0) {
814 return {};
815 }
816
817 SkColorType colorType = srcData[0].colorType();
818
819 skgpu::Mipmapped mipmapped = skgpu::Mipmapped::kNo;
820 if (numProvidedLevels > 1) {
821 mipmapped = skgpu::Mipmapped::kYes;
822 }
823
824 GrBackendFormat backendFormat = this->defaultBackendFormat(colorType, renderable);
825 GrBackendTexture beTex = this->createBackendTexture(srcData[0].width(),
826 srcData[0].height(),
827 backendFormat,
828 mipmapped,
829 renderable,
830 isProtected,
831 label);
832 if (!beTex.isValid()) {
833 return {};
834 }
835 if (!update_texture_with_pixmaps(this,
836 srcData,
837 numProvidedLevels,
838 beTex,
839 textureOrigin,
840 std::move(finishedCallback))) {
841 this->deleteBackendTexture(beTex);
842 return {};
843 }
844 return beTex;
845 }
846
847 bool GrDirectContext::updateBackendTexture(const GrBackendTexture& texture,
848 const SkPixmap srcData[],
849 int numLevels,
850 GrGpuFinishedProc finishedProc,
851 GrGpuFinishedContext finishedContext) {
852 return this->updateBackendTexture(texture,
853 srcData,
854 numLevels,
855 kTopLeft_GrSurfaceOrigin,
856 finishedProc,
857 finishedContext);
858 }
859
860 bool GrDirectContext::updateBackendTexture(const GrBackendTexture& backendTexture,
861 const SkColor4f& color,
862 GrGpuFinishedProc finishedProc,
863 GrGpuFinishedContext finishedContext) {
864 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
865
866 if (this->abandoned()) {
867 return false;
868 }
869
870 return fGpu->clearBackendTexture(backendTexture, std::move(finishedCallback), color.array());
871 }
872
873 bool GrDirectContext::updateBackendTexture(const GrBackendTexture& backendTexture,
874 SkColorType skColorType,
875 const SkColor4f& color,
876 GrGpuFinishedProc finishedProc,
877 GrGpuFinishedContext finishedContext) {
878 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
879
880 if (this->abandoned()) {
881 return false;
882 }
883
884 GrBackendFormat format = backendTexture.getBackendFormat();
885 GrColorType grColorType = SkColorTypeToGrColorType(skColorType);
886
887 if (!this->caps()->areColorTypeAndFormatCompatible(grColorType, format)) {
888 return false;
889 }
890
891 skgpu::Swizzle swizzle = this->caps()->getWriteSwizzle(format, grColorType);
892 SkColor4f swizzledColor = swizzle.applyTo(color);
893
894 return fGpu->clearBackendTexture(backendTexture,
895 std::move(finishedCallback),
896 swizzledColor.array());
897 }
898
899 bool GrDirectContext::updateBackendTexture(const GrBackendTexture& backendTexture,
900 const SkPixmap srcData[],
901 int numLevels,
902 GrSurfaceOrigin textureOrigin,
903 GrGpuFinishedProc finishedProc,
904 GrGpuFinishedContext finishedContext) {
905 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
906
907 if (this->abandoned()) {
908 return false;
909 }
910
911 if (!srcData || numLevels <= 0) {
912 return false;
913 }
914
915 // If the texture has MIP levels then we require that the full set is overwritten.
916 int numExpectedLevels = 1;
917 if (backendTexture.hasMipmaps()) {
918 numExpectedLevels = SkMipmap::ComputeLevelCount(backendTexture.width(),
919 backendTexture.height()) + 1;
920 }
921 if (numLevels != numExpectedLevels) {
922 return false;
923 }
924 return update_texture_with_pixmaps(this,
925 srcData,
926 numLevels,
927 backendTexture,
928 textureOrigin,
929 std::move(finishedCallback));
930 }
931
932 //////////////////////////////////////////////////////////////////////////////
933
934 static GrBackendTexture create_and_update_compressed_backend_texture(
935 GrDirectContext* dContext,
936 SkISize dimensions,
937 const GrBackendFormat& backendFormat,
938 skgpu::Mipmapped mipmapped,
939 GrProtected isProtected,
940 sk_sp<skgpu::RefCntedCallback> finishedCallback,
941 const void* data,
942 size_t size) {
943 GrGpu* gpu = dContext->priv().getGpu();
944
945 GrBackendTexture beTex = gpu->createCompressedBackendTexture(dimensions, backendFormat,
946 mipmapped, isProtected);
947 if (!beTex.isValid()) {
948 return {};
949 }
950
951 if (!dContext->priv().getGpu()->updateCompressedBackendTexture(
952 beTex, std::move(finishedCallback), data, size)) {
953 dContext->deleteBackendTexture(beTex);
954 return {};
955 }
956 return beTex;
957 }
958
959 GrBackendTexture GrDirectContext::createCompressedBackendTexture(
960 int width,
961 int height,
962 const GrBackendFormat& backendFormat,
963 const SkColor4f& color,
964 skgpu::Mipmapped mipmapped,
965 GrProtected isProtected,
966 GrGpuFinishedProc finishedProc,
967 GrGpuFinishedContext finishedContext) {
968 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
969 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
970
971 if (this->abandoned()) {
972 return {};
973 }
974
975 SkTextureCompressionType compression = GrBackendFormatToCompressionType(backendFormat);
976 if (compression == SkTextureCompressionType::kNone) {
977 return {};
978 }
979
980 size_t size = SkCompressedDataSize(
981 compression, {width, height}, nullptr, mipmapped == skgpu::Mipmapped::kYes);
982 auto storage = std::make_unique<char[]>(size);
983 skgpu::FillInCompressedData(compression, {width, height}, mipmapped, storage.get(), color);
984 return create_and_update_compressed_backend_texture(this,
985 {width, height},
986 backendFormat,
987 mipmapped,
988 isProtected,
989 std::move(finishedCallback),
990 storage.get(),
991 size);
992 }
993
994 GrBackendTexture GrDirectContext::createCompressedBackendTexture(
995 int width,
996 int height,
997 SkTextureCompressionType compression,
998 const SkColor4f& color,
999 skgpu::Mipmapped mipmapped,
1000 GrProtected isProtected,
1001 GrGpuFinishedProc finishedProc,
1002 GrGpuFinishedContext finishedContext) {
1003 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
1004 GrBackendFormat format = this->compressedBackendFormat(compression);
1005 return this->createCompressedBackendTexture(width, height, format, color,
1006 mipmapped, isProtected, finishedProc,
1007 finishedContext);
1008 }
1009
1010 GrBackendTexture GrDirectContext::createCompressedBackendTexture(
1011 int width,
1012 int height,
1013 const GrBackendFormat& backendFormat,
1014 const void* compressedData,
1015 size_t dataSize,
1016 skgpu::Mipmapped mipmapped,
1017 GrProtected isProtected,
1018 GrGpuFinishedProc finishedProc,
1019 GrGpuFinishedContext finishedContext) {
1020 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
1021 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
1022
1023 if (this->abandoned()) {
1024 return {};
1025 }
1026
1027 return create_and_update_compressed_backend_texture(this,
1028 {width, height},
1029 backendFormat,
1030 mipmapped,
1031 isProtected,
1032 std::move(finishedCallback),
1033 compressedData,
1034 dataSize);
1035 }
1036
1037 GrBackendTexture GrDirectContext::createCompressedBackendTexture(
1038 int width,
1039 int height,
1040 SkTextureCompressionType compression,
1041 const void* data,
1042 size_t dataSize,
1043 skgpu::Mipmapped mipmapped,
1044 GrProtected isProtected,
1045 GrGpuFinishedProc finishedProc,
1046 GrGpuFinishedContext finishedContext) {
1047 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
1048 GrBackendFormat format = this->compressedBackendFormat(compression);
1049 return this->createCompressedBackendTexture(width, height, format, data, dataSize, mipmapped,
1050 isProtected, finishedProc, finishedContext);
1051 }
1052
1053 bool GrDirectContext::updateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1054 const SkColor4f& color,
1055 GrGpuFinishedProc finishedProc,
1056 GrGpuFinishedContext finishedContext) {
1057 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
1058
1059 if (this->abandoned()) {
1060 return false;
1061 }
1062
1063 SkTextureCompressionType compression =
1064 GrBackendFormatToCompressionType(backendTexture.getBackendFormat());
1065 if (compression == SkTextureCompressionType::kNone) {
1066 return {};
1067 }
1068 size_t size = SkCompressedDataSize(compression,
1069 backendTexture.dimensions(),
1070 nullptr,
1071 backendTexture.hasMipmaps());
1072 SkAutoMalloc storage(size);
1073 skgpu::FillInCompressedData(compression,
1074 backendTexture.dimensions(),
1075 backendTexture.mipmapped(),
1076 static_cast<char*>(storage.get()),
1077 color);
1078 return fGpu->updateCompressedBackendTexture(backendTexture,
1079 std::move(finishedCallback),
1080 storage.get(),
1081 size);
1082 }
1083
1084 bool GrDirectContext::updateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1085 const void* compressedData,
1086 size_t dataSize,
1087 GrGpuFinishedProc finishedProc,
1088 GrGpuFinishedContext finishedContext) {
1089 auto finishedCallback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
1090
1091 if (this->abandoned()) {
1092 return false;
1093 }
1094
1095 if (!compressedData) {
1096 return false;
1097 }
1098
1099 return fGpu->updateCompressedBackendTexture(backendTexture,
1100 std::move(finishedCallback),
1101 compressedData,
1102 dataSize);
1103 }
1104
1105 //////////////////////////////////////////////////////////////////////////////
1106
1107 bool GrDirectContext::setBackendTextureState(const GrBackendTexture& backendTexture,
1108 const skgpu::MutableTextureState& state,
1109 skgpu::MutableTextureState* previousState,
1110 GrGpuFinishedProc finishedProc,
1111 GrGpuFinishedContext finishedContext) {
1112 auto callback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
1113
1114 if (this->abandoned()) {
1115 return false;
1116 }
1117
1118 return fGpu->setBackendTextureState(backendTexture, state, previousState, std::move(callback));
1119 }
1120
1121
1122 bool GrDirectContext::setBackendRenderTargetState(const GrBackendRenderTarget& backendRenderTarget,
1123 const skgpu::MutableTextureState& state,
1124 skgpu::MutableTextureState* previousState,
1125 GrGpuFinishedProc finishedProc,
1126 GrGpuFinishedContext finishedContext) {
1127 auto callback = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
1128
1129 if (this->abandoned()) {
1130 return false;
1131 }
1132
1133 return fGpu->setBackendRenderTargetState(backendRenderTarget, state, previousState,
1134 std::move(callback));
1135 }
1136
1137 void GrDirectContext::deleteBackendTexture(const GrBackendTexture& backendTex) {
1138 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
1139 // For the Vulkan backend we still must destroy the backend texture when the context is
1140 // abandoned.
1141 if ((this->abandoned() && this->backend() != GrBackendApi::kVulkan) || !backendTex.isValid()) {
1142 return;
1143 }
1144
1145 fGpu->deleteBackendTexture(backendTex);
1146 }
1147
1148 //////////////////////////////////////////////////////////////////////////////
1149
1150 bool GrDirectContext::precompileShader(const SkData& key, const SkData& data) {
1151 return fGpu->precompileShader(key, data);
1152 }
1153
1154 #if defined(SK_ENABLE_DUMP_GPU)
1155 #include "include/core/SkString.h"
1156 #include "src/gpu/ganesh/GrUtil.h"
1157 #include "src/utils/SkJSONWriter.h"
1158
1159 SkString GrDirectContext::dump() const {
1160 SkDynamicMemoryWStream stream;
1161 SkJSONWriter writer(&stream, SkJSONWriter::Mode::kPretty);
1162 writer.beginObject();
1163
1164 writer.appendCString("backend", GrBackendApiToStr(this->backend()));
1165
1166 writer.appendName("caps");
1167 this->caps()->dumpJSON(&writer);
1168
1169 writer.appendName("gpu");
1170 this->fGpu->dumpJSON(&writer);
1171
1172 writer.appendName("context");
1173 this->dumpJSON(&writer);
1174
1175 // Flush JSON to the memory stream
1176 writer.endObject();
1177 writer.flush();
1178
1179 // Null terminate the JSON data in the memory stream
1180 stream.write8(0);
1181
1182 // Allocate a string big enough to hold all the data, then copy out of the stream
1183 SkString result(stream.bytesWritten());
1184 stream.copyToAndReset(result.data());
1185 return result;
1186 }
1187 #endif
1188
1189 /*************************************************************************************************/
1190 sk_sp<GrDirectContext> GrDirectContext::MakeMock(const GrMockOptions* mockOptions) {
1191 GrContextOptions defaultOptions;
1192 return MakeMock(mockOptions, defaultOptions);
1193 }
1194
1195 sk_sp<GrDirectContext> GrDirectContext::MakeMock(const GrMockOptions* mockOptions,
1196 const GrContextOptions& options) {
1197 sk_sp<GrDirectContext> direct(
1198 new GrDirectContext(GrBackendApi::kMock,
1199 options,
1200 GrContextThreadSafeProxyPriv::Make(GrBackendApi::kMock, options)));
1201
1202 direct->fGpu = GrMockGpu::Make(mockOptions, options, direct.get());
1203 if (!direct->init()) {
1204 return nullptr;
1205 }
1206
1207 return direct;
1208 }
1209
1210 #ifdef SK_DIRECT3D
1211 /*************************************************************************************************/
1212 sk_sp<GrDirectContext> GrDirectContext::MakeDirect3D(const GrD3DBackendContext& backendContext) {
1213 GrContextOptions defaultOptions;
1214 return MakeDirect3D(backendContext, defaultOptions);
1215 }
1216
1217 sk_sp<GrDirectContext> GrDirectContext::MakeDirect3D(const GrD3DBackendContext& backendContext,
1218 const GrContextOptions& options) {
1219 sk_sp<GrDirectContext> direct(new GrDirectContext(
1220 GrBackendApi::kDirect3D,
1221 options,
1222 GrContextThreadSafeProxyPriv::Make(GrBackendApi::kDirect3D, options)));
1223
1224 direct->fGpu = GrD3DGpu::Make(backendContext, options, direct.get());
1225 if (!direct->init()) {
1226 return nullptr;
1227 }
1228
1229 return direct;
1230 }
1231 #endif