xref: /aosp_15_r20/external/skia/src/gpu/ganesh/d3d/GrD3DGpu.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2020 Google LLC
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 #include "src/gpu/ganesh/d3d/GrD3DGpu.h"
9 
10 #include "include/core/SkColorSpace.h"
11 #include "include/core/SkTextureCompressionType.h"
12 #include "include/gpu/ganesh/GrBackendSurface.h"
13 #include "include/gpu/ganesh/d3d/GrD3DBackendContext.h"
14 #include "src/base/SkRectMemcpy.h"
15 #include "src/core/SkCompressedDataUtils.h"
16 #include "src/core/SkMipmap.h"
17 #include "src/gpu/ganesh/GrBackendUtils.h"
18 #include "src/gpu/ganesh/GrDataUtils.h"
19 #include "src/gpu/ganesh/GrDirectContextPriv.h"
20 #include "src/gpu/ganesh/GrImageInfo.h"
21 #include "src/gpu/ganesh/GrResourceProvider.h"
22 #include "src/gpu/ganesh/GrTexture.h"
23 #include "src/gpu/ganesh/GrThreadSafePipelineBuilder.h"
24 #include "src/gpu/ganesh/d3d/GrD3DAMDMemoryAllocator.h"
25 #include "src/gpu/ganesh/d3d/GrD3DAttachment.h"
26 #include "src/gpu/ganesh/d3d/GrD3DBuffer.h"
27 #include "src/gpu/ganesh/d3d/GrD3DCaps.h"
28 #include "src/gpu/ganesh/d3d/GrD3DOpsRenderPass.h"
29 #include "src/gpu/ganesh/d3d/GrD3DSemaphore.h"
30 #include "src/gpu/ganesh/d3d/GrD3DTexture.h"
31 #include "src/gpu/ganesh/d3d/GrD3DTextureRenderTarget.h"
32 #include "src/gpu/ganesh/d3d/GrD3DUtil.h"
33 #include "src/sksl/SkSLCompiler.h"
34 
35 #if defined(GPU_TEST_UTILS)
36 #include <DXProgrammableCapture.h>
37 #endif
38 
39 using namespace skia_private;
40 
pipelineBuilder()41 GrThreadSafePipelineBuilder* GrD3DGpu::pipelineBuilder() {
42     return nullptr;
43 }
44 
refPipelineBuilder()45 sk_sp<GrThreadSafePipelineBuilder> GrD3DGpu::refPipelineBuilder() {
46     return nullptr;
47 }
48 
49 
Make(const GrD3DBackendContext & backendContext,const GrContextOptions & contextOptions,GrDirectContext * direct)50 std::unique_ptr<GrGpu> GrD3DGpu::Make(const GrD3DBackendContext& backendContext,
51                                       const GrContextOptions& contextOptions,
52                                       GrDirectContext* direct) {
53     sk_sp<GrD3DMemoryAllocator> memoryAllocator = backendContext.fMemoryAllocator;
54     if (!memoryAllocator) {
55         // We were not given a memory allocator at creation
56         memoryAllocator = GrD3DAMDMemoryAllocator::Make(
57                 backendContext.fAdapter.get(), backendContext.fDevice.get());
58     }
59     if (!memoryAllocator) {
60         SkDEBUGFAIL("No supplied Direct3D memory allocator and unable to create one internally.");
61         return nullptr;
62     }
63 
64     return std::unique_ptr<GrGpu>(new GrD3DGpu(direct,
65                                                contextOptions,
66                                                backendContext,
67                                                memoryAllocator));
68 }
69 
70 // This constant determines how many OutstandingCommandLists are allocated together as a block in
71 // the deque. As such it needs to balance allocating too much memory vs. incurring
72 // allocation/deallocation thrashing. It should roughly correspond to the max number of outstanding
73 // command lists we expect to see.
74 static const int kDefaultOutstandingAllocCnt = 8;
75 
76 // constants have to be aligned to 256
77 constexpr int kConstantAlignment = 256;
78 
GrD3DGpu(GrDirectContext * direct,const GrContextOptions & contextOptions,const GrD3DBackendContext & backendContext,sk_sp<GrD3DMemoryAllocator> allocator)79 GrD3DGpu::GrD3DGpu(GrDirectContext* direct, const GrContextOptions& contextOptions,
80                    const GrD3DBackendContext& backendContext,
81                    sk_sp<GrD3DMemoryAllocator> allocator)
82         : INHERITED(direct)
83         , fDevice(backendContext.fDevice)
84         , fQueue(backendContext.fQueue)
85         , fMemoryAllocator(std::move(allocator))
86         , fResourceProvider(this)
87         , fStagingBufferManager(this)
88         , fConstantsRingBuffer(this, 128 * 1024, kConstantAlignment, GrGpuBufferType::kVertex)
89         , fOutstandingCommandLists(sizeof(OutstandingCommandList), kDefaultOutstandingAllocCnt) {
90     this->initCaps(sk_make_sp<GrD3DCaps>(contextOptions,
91                                          backendContext.fAdapter.get(),
92                                          backendContext.fDevice.get()));
93 
94     fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
95     SkASSERT(fCurrentDirectCommandList);
96 
97     SkASSERT(fCurrentFenceValue == 0);
98     GR_D3D_CALL_ERRCHECK(fDevice->CreateFence(fCurrentFenceValue, D3D12_FENCE_FLAG_NONE,
99                                               IID_PPV_ARGS(&fFence)));
100 
101 #if defined(GPU_TEST_UTILS)
102     HRESULT getAnalysis = DXGIGetDebugInterface1(0, IID_PPV_ARGS(&fGraphicsAnalysis));
103     if (FAILED(getAnalysis)) {
104         fGraphicsAnalysis = nullptr;
105     }
106 #endif
107 }
108 
~GrD3DGpu()109 GrD3DGpu::~GrD3DGpu() {
110     this->destroyResources();
111 }
112 
destroyResources()113 void GrD3DGpu::destroyResources() {
114     if (fCurrentDirectCommandList) {
115         fCurrentDirectCommandList->close();
116         fCurrentDirectCommandList->reset();
117     }
118 
119     // We need to make sure everything has finished on the queue.
120     this->waitForQueueCompletion();
121 
122     SkDEBUGCODE(uint64_t fenceValue = fFence->GetCompletedValue();)
123 
124     // We used a placement new for each object in fOutstandingCommandLists, so we're responsible
125     // for calling the destructor on each of them as well.
126     while (!fOutstandingCommandLists.empty()) {
127         OutstandingCommandList* list = (OutstandingCommandList*)fOutstandingCommandLists.front();
128         SkASSERT(list->fFenceValue <= fenceValue);
129         // No reason to recycle the command lists since we are destroying all resources anyways.
130         list->~OutstandingCommandList();
131         fOutstandingCommandLists.pop_front();
132     }
133 
134     fStagingBufferManager.reset();
135 
136     fResourceProvider.destroyResources();
137 }
138 
onGetOpsRenderPass(GrRenderTarget * rt,bool,GrAttachment *,GrSurfaceOrigin origin,const SkIRect & bounds,const GrOpsRenderPass::LoadAndStoreInfo & colorInfo,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilInfo,const TArray<GrSurfaceProxy *,true> & sampledProxies,GrXferBarrierFlags renderPassXferBarriers)139 GrOpsRenderPass* GrD3DGpu::onGetOpsRenderPass(
140         GrRenderTarget* rt,
141         bool /*useMSAASurface*/,
142         GrAttachment*,
143         GrSurfaceOrigin origin,
144         const SkIRect& bounds,
145         const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
146         const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
147         const TArray<GrSurfaceProxy*, true>& sampledProxies,
148         GrXferBarrierFlags renderPassXferBarriers) {
149     if (!fCachedOpsRenderPass) {
150         fCachedOpsRenderPass.reset(new GrD3DOpsRenderPass(this));
151     }
152 
153     if (!fCachedOpsRenderPass->set(rt, origin, bounds, colorInfo, stencilInfo, sampledProxies)) {
154         return nullptr;
155     }
156     return fCachedOpsRenderPass.get();
157 }
158 
submitDirectCommandList(SyncQueue sync)159 bool GrD3DGpu::submitDirectCommandList(SyncQueue sync) {
160     SkASSERT(fCurrentDirectCommandList);
161 
162     fResourceProvider.prepForSubmit();
163     for (int i = 0; i < fMipmapCPUDescriptors.size(); ++i) {
164         fResourceProvider.recycleShaderView(fMipmapCPUDescriptors[i]);
165     }
166     fMipmapCPUDescriptors.clear();
167 
168     GrD3DDirectCommandList::SubmitResult sResult = fCurrentDirectCommandList->submit(fQueue.get());
169     if (sResult == GrD3DDirectCommandList::SubmitResult::kFailure) {
170         fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
171         return false;
172     } else if (sResult == GrD3DDirectCommandList::SubmitResult::kNoWork) {
173         if (sync == SyncQueue::kForce) {
174             this->waitForQueueCompletion();
175             this->checkForFinishedCommandLists();
176         }
177         return true;
178     }
179 
180     // We just submitted the command list so make sure all GrD3DPipelineState's mark their cached
181     // uniform data as dirty.
182     fResourceProvider.markPipelineStateUniformsDirty();
183 
184     GR_D3D_CALL_ERRCHECK(fQueue->Signal(fFence.get(), ++fCurrentFenceValue));
185     new (fOutstandingCommandLists.push_back()) OutstandingCommandList(
186             std::move(fCurrentDirectCommandList), fCurrentFenceValue);
187 
188     if (sync == SyncQueue::kForce) {
189         this->waitForQueueCompletion();
190     }
191 
192     fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
193 
194     // This should be done after we have a new command list in case the freeing of any resources
195     // held by a finished command list causes us send a new command to the gpu (like changing the
196     // resource state.
197     this->checkForFinishedCommandLists();
198 
199     SkASSERT(fCurrentDirectCommandList);
200     return true;
201 }
202 
checkForFinishedCommandLists()203 void GrD3DGpu::checkForFinishedCommandLists() {
204     uint64_t currentFenceValue = fFence->GetCompletedValue();
205 
206     // Iterate over all the outstanding command lists to see if any have finished. The commands
207     // lists are in order from oldest to newest, so we start at the front to check if their fence
208     // value is less than the last signaled value. If so we pop it off and move onto the next.
209     // Repeat till we find a command list that has not finished yet (and all others afterwards are
210     // also guaranteed to not have finished).
211     OutstandingCommandList* front = (OutstandingCommandList*)fOutstandingCommandLists.front();
212     while (front && front->fFenceValue <= currentFenceValue) {
213         std::unique_ptr<GrD3DDirectCommandList> currList(std::move(front->fCommandList));
214         // Since we used placement new we are responsible for calling the destructor manually.
215         front->~OutstandingCommandList();
216         fOutstandingCommandLists.pop_front();
217         fResourceProvider.recycleDirectCommandList(std::move(currList));
218         front = (OutstandingCommandList*)fOutstandingCommandLists.front();
219     }
220 }
221 
waitForQueueCompletion()222 void GrD3DGpu::waitForQueueCompletion() {
223     if (fFence->GetCompletedValue() < fCurrentFenceValue) {
224         HANDLE fenceEvent;
225         fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
226         SkASSERT(fenceEvent);
227         GR_D3D_CALL_ERRCHECK(fFence->SetEventOnCompletion(fCurrentFenceValue, fenceEvent));
228         WaitForSingleObject(fenceEvent, INFINITE);
229         CloseHandle(fenceEvent);
230     }
231 }
232 
submit(GrOpsRenderPass * renderPass)233 void GrD3DGpu::submit(GrOpsRenderPass* renderPass) {
234     SkASSERT(fCachedOpsRenderPass.get() == renderPass);
235 
236     fCachedOpsRenderPass->submit();
237     fCachedOpsRenderPass.reset();
238 }
239 
endRenderPass(GrRenderTarget * target,GrSurfaceOrigin origin,const SkIRect & bounds)240 void GrD3DGpu::endRenderPass(GrRenderTarget* target, GrSurfaceOrigin origin,
241                              const SkIRect& bounds) {
242     this->didWriteToSurface(target, origin, &bounds);
243 }
244 
addFinishedCallback(sk_sp<skgpu::RefCntedCallback> finishedCallback)245 void GrD3DGpu::addFinishedCallback(sk_sp<skgpu::RefCntedCallback> finishedCallback) {
246     SkASSERT(finishedCallback);
247     // Besides the current command list, we also add the finishedCallback to the newest outstanding
248     // command list. Our contract for calling the proc is that all previous submitted command lists
249     // have finished when we call it. However, if our current command list has no work when it is
250     // flushed it will drop its ref to the callback immediately. But the previous work may not have
251     // finished. It is safe to only add the proc to the newest outstanding commandlist cause that
252     // must finish after all previously submitted command lists.
253     OutstandingCommandList* back = (OutstandingCommandList*)fOutstandingCommandLists.back();
254     if (back) {
255         back->fCommandList->addFinishedCallback(finishedCallback);
256     }
257     fCurrentDirectCommandList->addFinishedCallback(std::move(finishedCallback));
258 }
259 
createD3DTexture(SkISize dimensions,DXGI_FORMAT dxgiFormat,GrRenderable renderable,int renderTargetSampleCnt,skgpu::Budgeted budgeted,GrProtected isProtected,int mipLevelCount,GrMipmapStatus mipmapStatus,std::string_view label)260 sk_sp<GrD3DTexture> GrD3DGpu::createD3DTexture(SkISize dimensions,
261                                                DXGI_FORMAT dxgiFormat,
262                                                GrRenderable renderable,
263                                                int renderTargetSampleCnt,
264                                                skgpu::Budgeted budgeted,
265                                                GrProtected isProtected,
266                                                int mipLevelCount,
267                                                GrMipmapStatus mipmapStatus,
268                                                std::string_view label) {
269     D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE;
270     if (renderable == GrRenderable::kYes) {
271         usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
272     }
273 
274     // This desc refers to a texture that will be read by the client. Thus even if msaa is
275     // requested, this describes the resolved texture. Therefore we always have samples set
276     // to 1.
277     SkASSERT(mipLevelCount > 0);
278     D3D12_RESOURCE_DESC resourceDesc = {};
279     resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
280     // TODO: will use 4MB alignment for MSAA textures and 64KB for everything else
281     //       might want to manually set alignment to 4KB for smaller textures
282     resourceDesc.Alignment = 0;
283     resourceDesc.Width = dimensions.fWidth;
284     resourceDesc.Height = dimensions.fHeight;
285     resourceDesc.DepthOrArraySize = 1;
286     resourceDesc.MipLevels = mipLevelCount;
287     resourceDesc.Format = dxgiFormat;
288     resourceDesc.SampleDesc.Count = 1;
289     resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
290     resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;  // use driver-selected swizzle
291     resourceDesc.Flags = usageFlags;
292 
293     if (renderable == GrRenderable::kYes) {
294         return GrD3DTextureRenderTarget::MakeNewTextureRenderTarget(
295                 this, budgeted, dimensions, renderTargetSampleCnt, resourceDesc, isProtected,
296                 mipmapStatus, label);
297     } else {
298         return GrD3DTexture::MakeNewTexture(this, budgeted, dimensions, resourceDesc, isProtected,
299                                             mipmapStatus, label);
300     }
301 }
302 
onCreateTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,int renderTargetSampleCnt,skgpu::Budgeted budgeted,GrProtected isProtected,int mipLevelCount,uint32_t levelClearMask,std::string_view label)303 sk_sp<GrTexture> GrD3DGpu::onCreateTexture(SkISize dimensions,
304                                            const GrBackendFormat& format,
305                                            GrRenderable renderable,
306                                            int renderTargetSampleCnt,
307                                            skgpu::Budgeted budgeted,
308                                            GrProtected isProtected,
309                                            int mipLevelCount,
310                                            uint32_t levelClearMask,
311                                            std::string_view label) {
312     DXGI_FORMAT dxgiFormat;
313     SkAssertResult(format.asDxgiFormat(&dxgiFormat));
314     SkASSERT(!GrDxgiFormatIsCompressed(dxgiFormat));
315 
316     GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kDirty
317                                                     : GrMipmapStatus::kNotAllocated;
318 
319     sk_sp<GrD3DTexture> tex = this->createD3DTexture(dimensions, dxgiFormat, renderable,
320                                                      renderTargetSampleCnt, budgeted, isProtected,
321                                                      mipLevelCount, mipmapStatus, label);
322     if (!tex) {
323         return nullptr;
324     }
325 
326     if (levelClearMask) {
327         // TODO
328     }
329 
330     return std::move(tex);
331 }
332 
copy_compressed_data(char * mapPtr,DXGI_FORMAT dxgiFormat,D3D12_PLACED_SUBRESOURCE_FOOTPRINT * placedFootprints,UINT * numRows,UINT64 * rowSizeInBytes,const void * compressedData,int numMipLevels)333 static void copy_compressed_data(char* mapPtr, DXGI_FORMAT dxgiFormat,
334                                  D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints,
335                                  UINT* numRows, UINT64* rowSizeInBytes,
336                                  const void* compressedData, int numMipLevels) {
337     SkASSERT(compressedData && numMipLevels);
338     SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat));
339     SkASSERT(mapPtr);
340 
341     const char* src = static_cast<const char*>(compressedData);
342     for (int currentMipLevel = 0; currentMipLevel < numMipLevels; currentMipLevel++) {
343         // copy data into the buffer, skipping any trailing bytes
344         char* dst = mapPtr + placedFootprints[currentMipLevel].Offset;
345         SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch,
346                      src, rowSizeInBytes[currentMipLevel], rowSizeInBytes[currentMipLevel],
347                      numRows[currentMipLevel]);
348         src += numRows[currentMipLevel] * rowSizeInBytes[currentMipLevel];
349     }
350 }
351 
onCreateCompressedTexture(SkISize dimensions,const GrBackendFormat & format,skgpu::Budgeted budgeted,skgpu::Mipmapped mipmapped,GrProtected isProtected,const void * data,size_t dataSize)352 sk_sp<GrTexture> GrD3DGpu::onCreateCompressedTexture(SkISize dimensions,
353                                                      const GrBackendFormat& format,
354                                                      skgpu::Budgeted budgeted,
355                                                      skgpu::Mipmapped mipmapped,
356                                                      GrProtected isProtected,
357                                                      const void* data,
358                                                      size_t dataSize) {
359     DXGI_FORMAT dxgiFormat;
360     SkAssertResult(format.asDxgiFormat(&dxgiFormat));
361     SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat));
362 
363     SkDEBUGCODE(SkTextureCompressionType compression = GrBackendFormatToCompressionType(format));
364     SkASSERT(dataSize == SkCompressedFormatDataSize(
365                                  compression, dimensions, mipmapped == skgpu::Mipmapped::kYes));
366 
367     int mipLevelCount = 1;
368     if (mipmapped == skgpu::Mipmapped::kYes) {
369         mipLevelCount = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
370     }
371     GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kValid
372                                                     : GrMipmapStatus::kNotAllocated;
373 
374     sk_sp<GrD3DTexture> d3dTex = this->createD3DTexture(
375         dimensions,
376         dxgiFormat,
377         GrRenderable::kNo,
378         1,
379         budgeted,
380         isProtected,
381         mipLevelCount,
382         mipmapStatus,
383         /*label=*/"D3DGpu_CreateCompressedTexture");
384     if (!d3dTex) {
385         return nullptr;
386     }
387 
388     ID3D12Resource* d3dResource = d3dTex->d3dResource();
389     SkASSERT(d3dResource);
390     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
391     // Either upload only the first miplevel or all miplevels
392     SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels);
393 
394     AutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
395     AutoTMalloc<UINT> numRows(mipLevelCount);
396     AutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount);
397     UINT64 combinedBufferSize;
398     // We reset the width and height in the description to match our subrectangle size
399     // so we don't end up allocating more space than we need.
400     desc.Width = dimensions.width();
401     desc.Height = dimensions.height();
402     fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(),
403                                    numRows.get(), rowSizeInBytes.get(), &combinedBufferSize);
404     SkASSERT(combinedBufferSize);
405 
406     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
407             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
408     if (!slice.fBuffer) {
409         return nullptr;
410     }
411 
412     char* bufferData = (char*)slice.fOffsetMapPtr;
413 
414     copy_compressed_data(bufferData, desc.Format, placedFootprints.get(), numRows.get(),
415                          rowSizeInBytes.get(), data, mipLevelCount);
416 
417     // Update the offsets in the footprints to be relative to the slice's offset
418     for (int i = 0; i < mipLevelCount; ++i) {
419         placedFootprints[i].Offset += slice.fOffset;
420     }
421 
422     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
423     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex.get(), mipLevelCount,
424                                                    placedFootprints.get(), 0, 0);
425 
426     return std::move(d3dTex);
427 }
428 
get_surface_sample_cnt(GrSurface * surf)429 static int get_surface_sample_cnt(GrSurface* surf) {
430     if (const GrRenderTarget* rt = surf->asRenderTarget()) {
431         return rt->numSamples();
432     }
433     return 0;
434 }
435 
onCopySurface(GrSurface * dst,const SkIRect & dstRect,GrSurface * src,const SkIRect & srcRect,GrSamplerState::Filter)436 bool GrD3DGpu::onCopySurface(GrSurface* dst, const SkIRect& dstRect,
437                              GrSurface* src, const SkIRect& srcRect,
438                              GrSamplerState::Filter) {
439     if (srcRect.size() != dstRect.size()) {
440         return false;
441     }
442     if (src->isProtected() && !dst->isProtected()) {
443         SkDebugf("Can't copy from protected memory to non-protected");
444         return false;
445     }
446 
447     int dstSampleCnt = get_surface_sample_cnt(dst);
448     int srcSampleCnt = get_surface_sample_cnt(src);
449 
450     GrD3DTextureResource* dstTexResource;
451     GrD3DTextureResource* srcTexResource;
452     GrRenderTarget* dstRT = dst->asRenderTarget();
453     if (dstRT) {
454         GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(dstRT);
455         dstTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
456     } else {
457         SkASSERT(dst->asTexture());
458         dstTexResource = static_cast<GrD3DTexture*>(dst->asTexture());
459     }
460     GrRenderTarget* srcRT = src->asRenderTarget();
461     if (srcRT) {
462         GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(srcRT);
463         srcTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
464     } else {
465         SkASSERT(src->asTexture());
466         srcTexResource = static_cast<GrD3DTexture*>(src->asTexture());
467     }
468 
469     DXGI_FORMAT dstFormat = dstTexResource->dxgiFormat();
470     DXGI_FORMAT srcFormat = srcTexResource->dxgiFormat();
471 
472     const SkIPoint dstPoint = dstRect.topLeft();
473     if (this->d3dCaps().canCopyAsResolve(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
474         this->copySurfaceAsResolve(dst, src, srcRect, dstPoint);
475         return true;
476     }
477 
478     if (this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
479         this->copySurfaceAsCopyTexture(dst, src, dstTexResource, srcTexResource, srcRect, dstPoint);
480         return true;
481     }
482 
483     return false;
484 }
485 
copySurfaceAsCopyTexture(GrSurface * dst,GrSurface * src,GrD3DTextureResource * dstResource,GrD3DTextureResource * srcResource,const SkIRect & srcRect,const SkIPoint & dstPoint)486 void GrD3DGpu::copySurfaceAsCopyTexture(GrSurface* dst, GrSurface* src,
487                                         GrD3DTextureResource* dstResource,
488                                         GrD3DTextureResource* srcResource,
489                                         const SkIRect& srcRect, const SkIPoint& dstPoint) {
490 #ifdef SK_DEBUG
491     int dstSampleCnt = get_surface_sample_cnt(dst);
492     int srcSampleCnt = get_surface_sample_cnt(src);
493     DXGI_FORMAT dstFormat = dstResource->dxgiFormat();
494     DXGI_FORMAT srcFormat;
495     SkAssertResult(dst->backendFormat().asDxgiFormat(&srcFormat));
496     SkASSERT(this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt));
497 #endif
498     if (src->isProtected() && !dst->isProtected()) {
499         SkDebugf("Can't copy from protected memory to non-protected");
500         return;
501     }
502 
503     dstResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
504     srcResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
505 
506     D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
507     dstLocation.pResource = dstResource->d3dResource();
508     dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
509     dstLocation.SubresourceIndex = 0;
510 
511     D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
512     srcLocation.pResource = srcResource->d3dResource();
513     srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
514     srcLocation.SubresourceIndex = 0;
515 
516     D3D12_BOX srcBox = {};
517     srcBox.left = srcRect.fLeft;
518     srcBox.top = srcRect.fTop;
519     srcBox.right = srcRect.fRight;
520     srcBox.bottom = srcRect.fBottom;
521     srcBox.front = 0;
522     srcBox.back = 1;
523     // TODO: use copyResource if copying full resource and sizes match
524     fCurrentDirectCommandList->copyTextureRegionToTexture(dstResource->resource(),
525                                                           &dstLocation,
526                                                           dstPoint.fX, dstPoint.fY,
527                                                           srcResource->resource(),
528                                                           &srcLocation,
529                                                           &srcBox);
530 
531     SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
532                                         srcRect.width(), srcRect.height());
533     // The rect is already in device space so we pass in kTopLeft so no flip is done.
534     this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
535 }
536 
copySurfaceAsResolve(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)537 void GrD3DGpu::copySurfaceAsResolve(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
538                                     const SkIPoint& dstPoint) {
539     GrD3DRenderTarget* srcRT = static_cast<GrD3DRenderTarget*>(src->asRenderTarget());
540     SkASSERT(srcRT);
541 
542     this->resolveTexture(dst, dstPoint.fX, dstPoint.fY, srcRT, srcRect);
543     SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
544                                         srcRect.width(), srcRect.height());
545     // The rect is already in device space so we pass in kTopLeft so no flip is done.
546     this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
547 }
548 
resolveTexture(GrSurface * dst,int32_t dstX,int32_t dstY,GrD3DRenderTarget * src,const SkIRect & srcIRect)549 void GrD3DGpu::resolveTexture(GrSurface* dst, int32_t dstX, int32_t dstY,
550                               GrD3DRenderTarget* src, const SkIRect& srcIRect) {
551     SkASSERT(dst);
552     SkASSERT(src && src->numSamples() > 1 && src->msaaTextureResource());
553 
554     D3D12_RECT srcRect = { srcIRect.fLeft, srcIRect.fTop, srcIRect.fRight, srcIRect.fBottom };
555 
556     GrD3DTextureResource* dstTextureResource;
557     GrRenderTarget* dstRT = dst->asRenderTarget();
558     if (dstRT) {
559         dstTextureResource = static_cast<GrD3DRenderTarget*>(dstRT);
560     } else {
561         SkASSERT(dst->asTexture());
562         dstTextureResource = static_cast<GrD3DTexture*>(dst->asTexture());
563     }
564 
565     dstTextureResource->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_DEST);
566     src->msaaTextureResource()->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
567 
568     fCurrentDirectCommandList->resolveSubresourceRegion(dstTextureResource, dstX, dstY,
569                                                         src->msaaTextureResource(), &srcRect);
570 }
571 
onResolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect)572 void GrD3DGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
573     SkASSERT(target->numSamples() > 1);
574     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(target);
575     SkASSERT(rt->msaaTextureResource() && rt != rt->msaaTextureResource());
576 
577     this->resolveTexture(target, resolveRect.fLeft, resolveRect.fTop, rt, resolveRect);
578 }
579 
onReadPixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType dstColorType,void * buffer,size_t rowBytes)580 bool GrD3DGpu::onReadPixels(GrSurface* surface,
581                             SkIRect rect,
582                             GrColorType surfaceColorType,
583                             GrColorType dstColorType,
584                             void* buffer,
585                             size_t rowBytes) {
586     SkASSERT(surface);
587 
588     if (surfaceColorType != dstColorType) {
589         return false;
590     }
591 
592     GrD3DTextureResource* texResource = nullptr;
593     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
594     if (rt) {
595         texResource = rt;
596     } else {
597         texResource = static_cast<GrD3DTexture*>(surface->asTexture());
598     }
599 
600     if (!texResource) {
601         return false;
602     }
603 
604     D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
605     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
606     UINT64 transferTotalBytes;
607     fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
608                                    nullptr, nullptr, &transferTotalBytes);
609     SkASSERT(transferTotalBytes);
610     GrResourceProvider* resourceProvider =
611         this->getContext()->priv().resourceProvider();
612     sk_sp<GrGpuBuffer> transferBuffer = resourceProvider->createBuffer(
613             transferTotalBytes,
614             GrGpuBufferType::kXferGpuToCpu,
615             kDynamic_GrAccessPattern,
616             GrResourceProvider::ZeroInit::kNo);
617     if (!transferBuffer) {
618         return false;
619     }
620 
621     this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
622     this->submitDirectCommandList(SyncQueue::kForce);
623 
624     // Copy back to CPU buffer
625     size_t bpp = GrColorTypeBytesPerPixel(dstColorType);
626     if (GrDxgiFormatBytesPerBlock(texResource->dxgiFormat()) != bpp) {
627         return false;
628     }
629     size_t tightRowBytes = bpp * rect.width();
630 
631     const void* mappedMemory = transferBuffer->map();
632     if (!mappedMemory) {
633         return false;
634     }
635 
636     SkRectMemcpy(buffer,
637                  rowBytes,
638                  mappedMemory,
639                  placedFootprint.Footprint.RowPitch,
640                  tightRowBytes,
641                  rect.height());
642 
643     transferBuffer->unmap();
644 
645     return true;
646 }
647 
readOrTransferPixels(GrD3DTextureResource * texResource,SkIRect rect,sk_sp<GrGpuBuffer> transferBuffer,const D3D12_PLACED_SUBRESOURCE_FOOTPRINT & placedFootprint)648 void GrD3DGpu::readOrTransferPixels(GrD3DTextureResource* texResource,
649                                     SkIRect rect,
650                                     sk_sp<GrGpuBuffer> transferBuffer,
651                                     const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& placedFootprint) {
652     // Set up src location and box
653     D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
654     srcLocation.pResource = texResource->d3dResource();
655     SkASSERT(srcLocation.pResource);
656     srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
657     srcLocation.SubresourceIndex = 0;
658 
659     D3D12_BOX srcBox = {};
660     srcBox.left = rect.left();
661     srcBox.top = rect.top();
662     srcBox.right = rect.right();
663     srcBox.bottom = rect.bottom();
664     srcBox.front = 0;
665     srcBox.back = 1;
666 
667     // Set up dst location
668     D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
669     dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
670     dstLocation.PlacedFootprint = placedFootprint;
671     GrD3DBuffer* d3dBuf = static_cast<GrD3DBuffer*>(transferBuffer.get());
672     dstLocation.pResource = d3dBuf->d3dResource();
673 
674     // Need to change the resource state to COPY_SOURCE in order to download from it
675     texResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
676 
677     fCurrentDirectCommandList->copyTextureRegionToBuffer(transferBuffer, &dstLocation, 0, 0,
678                                                          texResource->resource(), &srcLocation,
679                                                          &srcBox);
680 }
681 
onWritePixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,bool prepForTexSampling)682 bool GrD3DGpu::onWritePixels(GrSurface* surface,
683                              SkIRect rect,
684                              GrColorType surfaceColorType,
685                              GrColorType srcColorType,
686                              const GrMipLevel texels[],
687                              int mipLevelCount,
688                              bool prepForTexSampling) {
689     GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(surface->asTexture());
690     if (!d3dTex) {
691         return false;
692     }
693 
694     // Make sure we have at least the base level
695     if (!mipLevelCount || !texels[0].fPixels) {
696         return false;
697     }
698 
699     SkASSERT(!GrDxgiFormatIsCompressed(d3dTex->dxgiFormat()));
700     bool success = false;
701 
702     // Need to change the resource state to COPY_DEST in order to upload to it
703     d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
704 
705     SkASSERT(mipLevelCount <= d3dTex->maxMipmapLevel() + 1);
706     success = this->uploadToTexture(d3dTex, rect, srcColorType, texels, mipLevelCount);
707 
708     if (prepForTexSampling) {
709         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
710     }
711 
712     return success;
713 }
714 
uploadToTexture(GrD3DTexture * tex,SkIRect rect,GrColorType colorType,const GrMipLevel * texels,int mipLevelCount)715 bool GrD3DGpu::uploadToTexture(GrD3DTexture* tex,
716                                SkIRect rect,
717                                GrColorType colorType,
718                                const GrMipLevel* texels,
719                                int mipLevelCount) {
720     SkASSERT(this->d3dCaps().isFormatTexturable(tex->dxgiFormat()));
721     // The assumption is either that we have no mipmaps, or that our rect is the entire texture
722     SkASSERT(mipLevelCount == 1 || rect == SkIRect::MakeSize(tex->dimensions()));
723 
724     // We assume that if the texture has mip levels, we either upload to all the levels or just the
725     // first.
726     SkASSERT(mipLevelCount == 1 || mipLevelCount == (tex->maxMipmapLevel() + 1));
727 
728     if (rect.isEmpty()) {
729         return false;
730     }
731 
732     SkASSERT(this->d3dCaps().surfaceSupportsWritePixels(tex));
733     SkASSERT(this->d3dCaps().areColorTypeAndFormatCompatible(colorType, tex->backendFormat()));
734 
735     ID3D12Resource* d3dResource = tex->d3dResource();
736     SkASSERT(d3dResource);
737     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
738     // Either upload only the first miplevel or all miplevels
739     SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels);
740 
741     if (1 == mipLevelCount && !texels[0].fPixels) {
742         return true;   // no data to upload
743     }
744 
745     for (int i = 0; i < mipLevelCount; ++i) {
746         // We do not allow any gaps in the mip data
747         if (!texels[i].fPixels) {
748             return false;
749         }
750     }
751 
752     AutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
753     UINT64 combinedBufferSize;
754     // We reset the width and height in the description to match our subrectangle size
755     // so we don't end up allocating more space than we need.
756     desc.Width = rect.width();
757     desc.Height = rect.height();
758     fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(),
759                                    nullptr, nullptr, &combinedBufferSize);
760     size_t bpp = GrColorTypeBytesPerPixel(colorType);
761     SkASSERT(combinedBufferSize);
762 
763     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
764             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
765     if (!slice.fBuffer) {
766         return false;
767     }
768 
769     char* bufferData = (char*)slice.fOffsetMapPtr;
770 
771     int currentWidth = rect.width();
772     int currentHeight = rect.height();
773     for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) {
774         if (texels[currentMipLevel].fPixels) {
775 
776             const size_t trimRowBytes = currentWidth * bpp;
777             const size_t srcRowBytes = texels[currentMipLevel].fRowBytes;
778 
779             char* dst = bufferData + placedFootprints[currentMipLevel].Offset;
780 
781             // copy data into the buffer, skipping any trailing bytes
782             const char* src = (const char*)texels[currentMipLevel].fPixels;
783             SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch,
784                          src, srcRowBytes, trimRowBytes, currentHeight);
785         }
786         currentWidth = std::max(1, currentWidth / 2);
787         currentHeight = std::max(1, currentHeight / 2);
788     }
789 
790     // Update the offsets in the footprints to be relative to the slice's offset
791     for (int i = 0; i < mipLevelCount; ++i) {
792         placedFootprints[i].Offset += slice.fOffset;
793     }
794 
795     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
796     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
797                                                    tex,
798                                                    mipLevelCount,
799                                                    placedFootprints.get(),
800                                                    rect.left(),
801                                                    rect.top());
802 
803     if (mipLevelCount < (int)desc.MipLevels) {
804         tex->markMipmapsDirty();
805     }
806 
807     return true;
808 }
809 
onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,size_t srcOffset,sk_sp<GrGpuBuffer> dst,size_t dstOffset,size_t size)810 bool GrD3DGpu::onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,
811                                             size_t srcOffset,
812                                             sk_sp<GrGpuBuffer> dst,
813                                             size_t dstOffset,
814                                             size_t size) {
815     if (!this->currentCommandList()) {
816         return false;
817     }
818 
819     sk_sp<GrD3DBuffer> d3dSrc(static_cast<GrD3DBuffer*>(src.release()));
820     sk_sp<GrD3DBuffer> d3dDst(static_cast<GrD3DBuffer*>(dst.release()));
821 
822     fCurrentDirectCommandList->copyBufferToBuffer(std::move(d3dDst),
823                                                   dstOffset,
824                                                   d3dSrc->d3dResource(),
825                                                   srcOffset,
826                                                   size);
827 
828     // copyBufferToBuffer refs the dst but not the src
829     this->currentCommandList()->addGrBuffer(std::move(src));
830 
831     return true;
832 }
833 
onTransferPixelsTo(GrTexture * texture,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t bufferOffset,size_t rowBytes)834 bool GrD3DGpu::onTransferPixelsTo(GrTexture* texture,
835                                   SkIRect rect,
836                                   GrColorType surfaceColorType,
837                                   GrColorType bufferColorType,
838                                   sk_sp<GrGpuBuffer> transferBuffer,
839                                   size_t bufferOffset,
840                                   size_t rowBytes) {
841     if (!this->currentCommandList()) {
842         return false;
843     }
844 
845     if (!transferBuffer) {
846         return false;
847     }
848 
849     size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
850     if (GrBackendFormatBytesPerPixel(texture->backendFormat()) != bpp) {
851         return false;
852     }
853 
854     // D3D requires offsets for texture transfers to be aligned to this value
855     if (SkToBool(bufferOffset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
856         return false;
857     }
858 
859     GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(texture);
860     if (!d3dTex) {
861         return false;
862     }
863 
864     SkDEBUGCODE(DXGI_FORMAT format = d3dTex->dxgiFormat());
865 
866     // Can't transfer compressed data
867     SkASSERT(!GrDxgiFormatIsCompressed(format));
868 
869     SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
870 
871     SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect));
872 
873     // Set up copy region
874     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint = {};
875     ID3D12Resource* d3dResource = d3dTex->d3dResource();
876     SkASSERT(d3dResource);
877     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
878     desc.Width = rect.width();
879     desc.Height = rect.height();
880     UINT64 totalBytes;
881     fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
882                                    nullptr, nullptr, &totalBytes);
883     placedFootprint.Offset = bufferOffset;
884 
885     // Change state of our target so it can be copied to
886     d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
887 
888     // Copy the buffer to the image.
889     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(transferBuffer.get())->d3dResource();
890     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
891                                                    d3dTex,
892                                                    1,
893                                                    &placedFootprint,
894                                                    rect.left(),
895                                                    rect.top());
896     this->currentCommandList()->addGrBuffer(std::move(transferBuffer));
897 
898     d3dTex->markMipmapsDirty();
899     return true;
900 }
901 
onTransferPixelsFrom(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset)902 bool GrD3DGpu::onTransferPixelsFrom(GrSurface* surface,
903                                     SkIRect rect,
904                                     GrColorType surfaceColorType,
905                                     GrColorType bufferColorType,
906                                     sk_sp<GrGpuBuffer> transferBuffer,
907                                     size_t offset) {
908     if (!this->currentCommandList()) {
909         return false;
910     }
911     SkASSERT(surface);
912     SkASSERT(transferBuffer);
913     // TODO
914     //if (fProtectedContext == GrProtected::kYes) {
915     //    return false;
916     //}
917 
918     // D3D requires offsets for texture transfers to be aligned to this value
919     if (SkToBool(offset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
920         return false;
921     }
922 
923     GrD3DTextureResource* texResource = nullptr;
924     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
925     if (rt) {
926         texResource = rt;
927     } else {
928         texResource = static_cast<GrD3DTexture*>(surface->asTexture());
929     }
930 
931     if (!texResource) {
932         return false;
933     }
934 
935     SkDEBUGCODE(DXGI_FORMAT format = texResource->dxgiFormat());
936     SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
937 
938     D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
939     desc.Width = rect.width();
940     desc.Height = rect.height();
941     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
942     UINT64 transferTotalBytes;
943     fDevice->GetCopyableFootprints(&desc, 0, 1, offset, &placedFootprint,
944                                    nullptr, nullptr, &transferTotalBytes);
945     SkASSERT(transferTotalBytes);
946 
947     this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
948 
949     // TODO: It's not clear how to ensure the transfer is done before we read from the buffer,
950     // other than maybe doing a resource state transition.
951 
952     return true;
953 }
954 
check_resource_info(const GrD3DTextureResourceInfo & info)955 static bool check_resource_info(const GrD3DTextureResourceInfo& info) {
956     if (!info.fResource.get()) {
957         return false;
958     }
959     return true;
960 }
961 
check_tex_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info)962 static bool check_tex_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info) {
963     if (!caps.isFormatTexturable(info.fFormat)) {
964         return false;
965     }
966     // We don't support sampling from multisampled textures.
967     if (info.fSampleCount != 1) {
968         return false;
969     }
970     return true;
971 }
972 
check_rt_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info,int sampleCnt)973 static bool check_rt_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info,
974                                 int sampleCnt) {
975     if (!caps.isFormatRenderable(info.fFormat, sampleCnt)) {
976         return false;
977     }
978     return true;
979 }
980 
onWrapBackendTexture(const GrBackendTexture & tex,GrWrapOwnership,GrWrapCacheable wrapType,GrIOType ioType)981 sk_sp<GrTexture> GrD3DGpu::onWrapBackendTexture(const GrBackendTexture& tex,
982                                                 GrWrapOwnership,
983                                                 GrWrapCacheable wrapType,
984                                                 GrIOType ioType) {
985     GrD3DTextureResourceInfo textureInfo;
986     if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
987         return nullptr;
988     }
989 
990     if (!check_resource_info(textureInfo)) {
991         return nullptr;
992     }
993 
994     if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
995         return nullptr;
996     }
997 
998     // TODO: support protected context
999     if (tex.isProtected()) {
1000         return nullptr;
1001     }
1002 
1003     sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
1004     SkASSERT(state);
1005     return GrD3DTexture::MakeWrappedTexture(this, tex.dimensions(), wrapType, ioType, textureInfo,
1006                                             std::move(state));
1007 }
1008 
onWrapCompressedBackendTexture(const GrBackendTexture & tex,GrWrapOwnership ownership,GrWrapCacheable wrapType)1009 sk_sp<GrTexture> GrD3DGpu::onWrapCompressedBackendTexture(const GrBackendTexture& tex,
1010                                                           GrWrapOwnership ownership,
1011                                                           GrWrapCacheable wrapType) {
1012     return this->onWrapBackendTexture(tex, ownership, wrapType, kRead_GrIOType);
1013 }
1014 
onWrapRenderableBackendTexture(const GrBackendTexture & tex,int sampleCnt,GrWrapOwnership ownership,GrWrapCacheable cacheable)1015 sk_sp<GrTexture> GrD3DGpu::onWrapRenderableBackendTexture(const GrBackendTexture& tex,
1016                                                           int sampleCnt,
1017                                                           GrWrapOwnership ownership,
1018                                                           GrWrapCacheable cacheable) {
1019     GrD3DTextureResourceInfo textureInfo;
1020     if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
1021         return nullptr;
1022     }
1023 
1024     if (!check_resource_info(textureInfo)) {
1025         return nullptr;
1026     }
1027 
1028     if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
1029         return nullptr;
1030     }
1031     if (!check_rt_resource_info(this->d3dCaps(), textureInfo, sampleCnt)) {
1032         return nullptr;
1033     }
1034 
1035     // TODO: support protected context
1036     if (tex.isProtected()) {
1037         return nullptr;
1038     }
1039 
1040     sampleCnt = this->d3dCaps().getRenderTargetSampleCount(sampleCnt, textureInfo.fFormat);
1041 
1042     sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
1043     SkASSERT(state);
1044 
1045     return GrD3DTextureRenderTarget::MakeWrappedTextureRenderTarget(this, tex.dimensions(),
1046                                                                     sampleCnt, cacheable,
1047                                                                     textureInfo, std::move(state));
1048 }
1049 
onWrapBackendRenderTarget(const GrBackendRenderTarget & rt)1050 sk_sp<GrRenderTarget> GrD3DGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& rt) {
1051     GrD3DTextureResourceInfo info;
1052     if (!rt.getD3DTextureResourceInfo(&info)) {
1053         return nullptr;
1054     }
1055 
1056     if (!check_resource_info(info)) {
1057         return nullptr;
1058     }
1059 
1060     if (!check_rt_resource_info(this->d3dCaps(), info, rt.sampleCnt())) {
1061         return nullptr;
1062     }
1063 
1064     // TODO: support protected context
1065     if (rt.isProtected()) {
1066         return nullptr;
1067     }
1068 
1069     sk_sp<GrD3DResourceState> state = rt.getGrD3DResourceState();
1070 
1071     sk_sp<GrD3DRenderTarget> tgt = GrD3DRenderTarget::MakeWrappedRenderTarget(
1072             this, rt.dimensions(), rt.sampleCnt(), info, std::move(state));
1073 
1074     // We don't allow the client to supply a premade stencil buffer. We always create one if needed.
1075     SkASSERT(!rt.stencilBits());
1076     if (tgt) {
1077         SkASSERT(tgt->canAttemptStencilAttachment(tgt->numSamples() > 1));
1078     }
1079 
1080     return std::move(tgt);
1081 }
1082 
is_odd(int x)1083 static bool is_odd(int x) {
1084     return x > 1 && SkToBool(x & 0x1);
1085 }
1086 
1087 // TODO: enable when sRGB shader supported
1088 //static bool is_srgb(DXGI_FORMAT format) {
1089 //    // the only one we support at the moment
1090 //    return (format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
1091 //}
1092 
is_bgra(DXGI_FORMAT format)1093 static bool is_bgra(DXGI_FORMAT format) {
1094     // the only one we support at the moment
1095     return (format == DXGI_FORMAT_B8G8R8A8_UNORM);
1096 }
1097 
onRegenerateMipMapLevels(GrTexture * tex)1098 bool GrD3DGpu::onRegenerateMipMapLevels(GrTexture * tex) {
1099     auto * d3dTex = static_cast<GrD3DTexture*>(tex);
1100     SkASSERT(tex->textureType() == GrTextureType::k2D);
1101     int width = tex->width();
1102     int height = tex->height();
1103 
1104     // determine if we can read from and mipmap this format
1105     const GrD3DCaps & caps = this->d3dCaps();
1106     if (!caps.isFormatTexturable(d3dTex->dxgiFormat()) ||
1107         !caps.mipmapSupport()) {
1108         return false;
1109     }
1110 
1111     sk_sp<GrD3DTexture> uavTexture;
1112     sk_sp<GrD3DTexture> bgraAliasTexture;
1113     DXGI_FORMAT originalFormat = d3dTex->dxgiFormat();
1114     D3D12_RESOURCE_DESC originalDesc = d3dTex->d3dResource()->GetDesc();
1115     // if the format is unordered accessible and resource flag is set, use resource for uav
1116     if (caps.isFormatUnorderedAccessible(originalFormat) &&
1117         (originalDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
1118         uavTexture = sk_ref_sp(d3dTex);
1119     } else {
1120         // need to make a copy and use that for our uav
1121         D3D12_RESOURCE_DESC uavDesc = originalDesc;
1122         uavDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
1123         // if the format is unordered accessible, copy to resource with same format and flag set
1124         if (!caps.isFormatUnorderedAccessible(originalFormat)) {
1125             // for the BGRA and sRGB cases, we find a suitable RGBA format to use instead
1126             if (is_bgra(originalFormat)) {
1127                 uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1128                 // Technically if this support is not available we should not be doing
1129                 // aliasing. However, on Intel the BGRA and RGBA swizzle appears to be
1130                 // the same so it still works. We may need to disable BGRA support
1131                 // on a case-by-base basis if this doesn't hold true in general.
1132                 if (caps.standardSwizzleLayoutSupport()) {
1133                     uavDesc.Layout = D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE;
1134                 }
1135             // TODO: enable when sRGB shader supported
1136             //} else if (is_srgb(originalFormat)) {
1137             //    uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1138             } else {
1139                 return false;
1140             }
1141         }
1142         // TODO: make this a scratch texture
1143         GrProtected grProtected = tex->isProtected() ? GrProtected::kYes : GrProtected::kNo;
1144         uavTexture = GrD3DTexture::MakeNewTexture(this,
1145                                                   skgpu::Budgeted::kNo,
1146                                                   tex->dimensions(),
1147                                                   uavDesc,
1148                                                   grProtected,
1149                                                   GrMipmapStatus::kDirty,
1150                                                   /*label=*/"RegenerateMipMapLevels");
1151         if (!uavTexture) {
1152             return false;
1153         }
1154 
1155         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1156         if (!caps.isFormatUnorderedAccessible(originalFormat) && is_bgra(originalFormat)) {
1157             // for BGRA, we alias this uavTexture with a BGRA texture and copy to that
1158             bgraAliasTexture = GrD3DTexture::MakeAliasingTexture(this, uavTexture, originalDesc,
1159                                                                  D3D12_RESOURCE_STATE_COPY_DEST);
1160             // make the BGRA version the active alias
1161             this->currentCommandList()->aliasingBarrier(nullptr,
1162                                                         nullptr,
1163                                                         bgraAliasTexture->resource(),
1164                                                         bgraAliasTexture->d3dResource());
1165             // copy top miplevel to bgraAliasTexture (should already be in COPY_DEST state)
1166             this->currentCommandList()->copyTextureToTexture(bgraAliasTexture.get(), d3dTex, 0);
1167             // make the RGBA version the active alias
1168             this->currentCommandList()->aliasingBarrier(bgraAliasTexture->resource(),
1169                                                         bgraAliasTexture->d3dResource(),
1170                                                         uavTexture->resource(),
1171                                                         uavTexture->d3dResource());
1172         } else {
1173             // copy top miplevel to uavTexture
1174             uavTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1175             this->currentCommandList()->copyTextureToTexture(uavTexture.get(), d3dTex, 0);
1176         }
1177     }
1178 
1179     uint32_t levelCount = d3dTex->mipLevels();
1180     // SkMipmap doesn't include the base level in the level count so we have to add 1
1181     SkASSERT((int)levelCount == SkMipmap::ComputeLevelCount(tex->width(), tex->height()) + 1);
1182 
1183     sk_sp<GrD3DRootSignature> rootSig = fResourceProvider.findOrCreateRootSignature(1, 1);
1184     this->currentCommandList()->setComputeRootSignature(rootSig);
1185 
1186     // TODO: use linear vs. srgb shader based on texture format
1187     sk_sp<GrD3DPipeline> pipeline = this->resourceProvider().findOrCreateMipmapPipeline();
1188     if (!pipeline) {
1189         return false;
1190     }
1191     this->currentCommandList()->setPipelineState(std::move(pipeline));
1192 
1193     // set sampler
1194     GrSamplerState samplerState(SkFilterMode::kLinear, SkMipmapMode::kNearest);
1195     std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(1);
1196     samplers[0] = fResourceProvider.findOrCreateCompatibleSampler(samplerState);
1197     this->currentCommandList()->addSampledTextureRef(uavTexture.get());
1198     sk_sp<GrD3DDescriptorTable> samplerTable = fResourceProvider.findOrCreateSamplerTable(samplers);
1199 
1200     // Transition the top subresource to be readable in the compute shader
1201     D3D12_RESOURCE_STATES currentResourceState = uavTexture->currentState();
1202     D3D12_RESOURCE_TRANSITION_BARRIER barrier;
1203     barrier.pResource = uavTexture->d3dResource();
1204     barrier.Subresource = 0;
1205     barrier.StateBefore = currentResourceState;
1206     barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1207     this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1208 
1209     // Generate the miplevels
1210     for (unsigned int dstMip = 1; dstMip < levelCount; ++dstMip) {
1211         unsigned int srcMip = dstMip - 1;
1212         width = std::max(1, width / 2);
1213         height = std::max(1, height / 2);
1214 
1215         unsigned int sampleMode = 0;
1216         if (is_odd(width) && is_odd(height)) {
1217             sampleMode = 1;
1218         } else if (is_odd(width)) {
1219             sampleMode = 2;
1220         } else if (is_odd(height)) {
1221             sampleMode = 3;
1222         }
1223 
1224         // set constants
1225         struct {
1226             SkSize inverseSize;
1227             uint32_t mipLevel;
1228             uint32_t sampleMode;
1229         } constantData = { {1.f / width, 1.f / height}, srcMip, sampleMode };
1230 
1231         D3D12_GPU_VIRTUAL_ADDRESS constantsAddress =
1232             fResourceProvider.uploadConstantData(&constantData, sizeof(constantData));
1233         this->currentCommandList()->setComputeRootConstantBufferView(
1234                 (unsigned int)GrD3DRootSignature::ParamIndex::kConstantBufferView,
1235                 constantsAddress);
1236 
1237         std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderViews;
1238         // create SRV
1239         GrD3DDescriptorHeap::CPUHandle srvHandle =
1240                 fResourceProvider.createShaderResourceView(uavTexture->d3dResource(), srcMip, 1);
1241         shaderViews.push_back(srvHandle.fHandle);
1242         fMipmapCPUDescriptors.push_back(srvHandle);
1243         // create UAV
1244         GrD3DDescriptorHeap::CPUHandle uavHandle =
1245                 fResourceProvider.createUnorderedAccessView(uavTexture->d3dResource(), dstMip);
1246         shaderViews.push_back(uavHandle.fHandle);
1247         fMipmapCPUDescriptors.push_back(uavHandle);
1248 
1249         // set up shaderView descriptor table
1250         sk_sp<GrD3DDescriptorTable> srvTable =
1251                 fResourceProvider.findOrCreateShaderViewTable(shaderViews);
1252 
1253         // bind both descriptor tables
1254         this->currentCommandList()->setDescriptorHeaps(srvTable->heap(), samplerTable->heap());
1255         this->currentCommandList()->setComputeRootDescriptorTable(
1256                 (unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable,
1257                 srvTable->baseGpuDescriptor());
1258         this->currentCommandList()->setComputeRootDescriptorTable(
1259                 static_cast<unsigned int>(GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable),
1260                 samplerTable->baseGpuDescriptor());
1261 
1262         // Transition resource state of dstMip subresource so we can write to it
1263         barrier.Subresource = dstMip;
1264         barrier.StateBefore = currentResourceState;
1265         barrier.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1266         this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1267 
1268         // Using the form (x+7)/8 ensures that the remainder is covered as well
1269         this->currentCommandList()->dispatch((width+7)/8, (height+7)/8);
1270 
1271         // guarantee UAV writes have completed
1272         this->currentCommandList()->uavBarrier(uavTexture->resource(), uavTexture->d3dResource());
1273 
1274         // Transition resource state of dstMip subresource so we can read it in the next stage
1275         barrier.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1276         barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1277         this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1278     }
1279 
1280     // copy back if necessary
1281     if (uavTexture.get() != d3dTex) {
1282         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1283         if (bgraAliasTexture) {
1284             // make the BGRA version the active alias
1285             this->currentCommandList()->aliasingBarrier(uavTexture->resource(),
1286                                                         uavTexture->d3dResource(),
1287                                                         bgraAliasTexture->resource(),
1288                                                         bgraAliasTexture->d3dResource());
1289             // copy from bgraAliasTexture to d3dTex
1290             bgraAliasTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1291             this->currentCommandList()->copyTextureToTexture(d3dTex, bgraAliasTexture.get());
1292         } else {
1293             barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1294             barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1295             barrier.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
1296             this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1297             this->currentCommandList()->copyTextureToTexture(d3dTex, uavTexture.get());
1298         }
1299     } else {
1300         // For simplicity our resource state tracking considers all subresources to have the same
1301         // state. However, we've changed that state one subresource at a time without going through
1302         // the tracking system, so we need to patch up the resource states back to the original.
1303         barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1304         barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1305         barrier.StateAfter = currentResourceState;
1306         this->addResourceBarriers(d3dTex->resource(), 1, &barrier);
1307     }
1308 
1309     return true;
1310 }
1311 
onCreateBuffer(size_t sizeInBytes,GrGpuBufferType type,GrAccessPattern accessPattern)1312 sk_sp<GrGpuBuffer> GrD3DGpu::onCreateBuffer(size_t sizeInBytes,
1313                                             GrGpuBufferType type,
1314                                             GrAccessPattern accessPattern) {
1315     return GrD3DBuffer::Make(this, sizeInBytes, type, accessPattern);
1316 }
1317 
makeStencilAttachment(const GrBackendFormat &,SkISize dimensions,int numStencilSamples)1318 sk_sp<GrAttachment> GrD3DGpu::makeStencilAttachment(const GrBackendFormat& /*colorFormat*/,
1319                                                     SkISize dimensions, int numStencilSamples) {
1320     DXGI_FORMAT sFmt = this->d3dCaps().preferredStencilFormat();
1321 
1322     fStats.incStencilAttachmentCreates();
1323     return GrD3DAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt);
1324 }
1325 
createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,SkISize dimensions,GrTexturable texturable,GrRenderable renderable,skgpu::Mipmapped mipmapped,int sampleCnt,GrD3DTextureResourceInfo * info,GrProtected isProtected)1326 bool GrD3DGpu::createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,
1327                                                       SkISize dimensions,
1328                                                       GrTexturable texturable,
1329                                                       GrRenderable renderable,
1330                                                       skgpu::Mipmapped mipmapped,
1331                                                       int sampleCnt,
1332                                                       GrD3DTextureResourceInfo* info,
1333                                                       GrProtected isProtected) {
1334     SkASSERT(texturable == GrTexturable::kYes || renderable == GrRenderable::kYes);
1335 
1336     if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1337         return false;
1338     }
1339 
1340     if (texturable == GrTexturable::kYes && !this->d3dCaps().isFormatTexturable(dxgiFormat)) {
1341         return false;
1342     }
1343 
1344     if (renderable == GrRenderable::kYes && !this->d3dCaps().isFormatRenderable(dxgiFormat, 1)) {
1345         return false;
1346     }
1347 
1348     int numMipLevels = 1;
1349     if (mipmapped == skgpu::Mipmapped::kYes) {
1350         numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
1351     }
1352 
1353     // create the texture
1354     D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE;
1355     if (renderable == GrRenderable::kYes) {
1356         usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
1357     }
1358 
1359     D3D12_RESOURCE_DESC resourceDesc = {};
1360     resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1361     resourceDesc.Alignment = 0;  // use default alignment
1362     resourceDesc.Width = dimensions.fWidth;
1363     resourceDesc.Height = dimensions.fHeight;
1364     resourceDesc.DepthOrArraySize = 1;
1365     resourceDesc.MipLevels = numMipLevels;
1366     resourceDesc.Format = dxgiFormat;
1367     resourceDesc.SampleDesc.Count = sampleCnt;
1368     resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
1369     resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;  // use driver-selected swizzle
1370     resourceDesc.Flags = usageFlags;
1371 
1372     D3D12_CLEAR_VALUE* clearValuePtr = nullptr;
1373     D3D12_CLEAR_VALUE clearValue = {};
1374     if (renderable == GrRenderable::kYes) {
1375         clearValue.Format = dxgiFormat;
1376         // Assume transparent black
1377         clearValue.Color[0] = 0;
1378         clearValue.Color[1] = 0;
1379         clearValue.Color[2] = 0;
1380         clearValue.Color[3] = 0;
1381         clearValuePtr = &clearValue;
1382     }
1383 
1384     D3D12_RESOURCE_STATES initialState = (renderable == GrRenderable::kYes)
1385                                                  ? D3D12_RESOURCE_STATE_RENDER_TARGET
1386                                                  : D3D12_RESOURCE_STATE_COPY_DEST;
1387     if (!GrD3DTextureResource::InitTextureResourceInfo(this, resourceDesc, initialState,
1388                                                        isProtected, clearValuePtr, info)) {
1389         SkDebugf("Failed to init texture resource info\n");
1390         return false;
1391     }
1392 
1393     return true;
1394 }
1395 
onCreateBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,skgpu::Mipmapped mipmapped,GrProtected isProtected,std::string_view label)1396 GrBackendTexture GrD3DGpu::onCreateBackendTexture(SkISize dimensions,
1397                                                   const GrBackendFormat& format,
1398                                                   GrRenderable renderable,
1399                                                   skgpu::Mipmapped mipmapped,
1400                                                   GrProtected isProtected,
1401                                                   std::string_view label) {
1402     const GrD3DCaps& caps = this->d3dCaps();
1403 
1404     if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1405         return {};
1406     }
1407 
1408     DXGI_FORMAT dxgiFormat;
1409     if (!format.asDxgiFormat(&dxgiFormat)) {
1410         return {};
1411     }
1412 
1413     // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here
1414     if (!caps.isFormatTexturable(dxgiFormat)) {
1415         return {};
1416     }
1417 
1418     GrD3DTextureResourceInfo info;
1419     if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kYes,
1420                                                       renderable, mipmapped, 1, &info,
1421                                                       isProtected)) {
1422         return {};
1423     }
1424 
1425     return GrBackendTexture(dimensions.width(), dimensions.height(), info);
1426 }
1427 
copy_color_data(const GrD3DCaps & caps,char * mapPtr,DXGI_FORMAT dxgiFormat,SkISize dimensions,D3D12_PLACED_SUBRESOURCE_FOOTPRINT * placedFootprints,std::array<float,4> color)1428 static bool copy_color_data(const GrD3DCaps& caps,
1429                             char* mapPtr,
1430                             DXGI_FORMAT dxgiFormat,
1431                             SkISize dimensions,
1432                             D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints,
1433                             std::array<float, 4> color) {
1434     auto colorType = caps.getFormatColorType(dxgiFormat);
1435     if (colorType == GrColorType::kUnknown) {
1436         return false;
1437     }
1438     GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, dimensions);
1439     if (!GrClearImage(ii, mapPtr, placedFootprints[0].Footprint.RowPitch, color)) {
1440         return false;
1441     }
1442 
1443     return true;
1444 }
1445 
onClearBackendTexture(const GrBackendTexture & backendTexture,sk_sp<skgpu::RefCntedCallback> finishedCallback,std::array<float,4> color)1446 bool GrD3DGpu::onClearBackendTexture(const GrBackendTexture& backendTexture,
1447                                      sk_sp<skgpu::RefCntedCallback> finishedCallback,
1448                                      std::array<float, 4> color) {
1449     GrD3DTextureResourceInfo info;
1450     SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1451     SkASSERT(!GrDxgiFormatIsCompressed(info.fFormat));
1452 
1453     sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1454     SkASSERT(state);
1455     sk_sp<GrD3DTexture> texture =
1456             GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(),
1457                                              GrWrapCacheable::kNo,
1458                                              kRW_GrIOType, info, std::move(state));
1459     if (!texture) {
1460         return false;
1461     }
1462 
1463     GrD3DDirectCommandList* cmdList = this->currentCommandList();
1464     if (!cmdList) {
1465         return false;
1466     }
1467 
1468     texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1469 
1470     ID3D12Resource* d3dResource = texture->d3dResource();
1471     SkASSERT(d3dResource);
1472     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1473     unsigned int mipLevelCount = 1;
1474     if (backendTexture.fMipmapped == skgpu::Mipmapped::kYes) {
1475         mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions()) + 1;
1476     }
1477     SkASSERT(mipLevelCount == info.fLevelCount);
1478     AutoSTMalloc<15, D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1479     UINT numRows;
1480     UINT64 rowSizeInBytes;
1481     UINT64 combinedBufferSize;
1482     // We reuse the same top-level buffer area for all levels, hence passing 1 for level count.
1483     fDevice->GetCopyableFootprints(&desc,
1484                                    /* first resource  */ 0,
1485                                    /* mip level count */ 1,
1486                                    /* base offset     */ 0,
1487                                    placedFootprints.get(),
1488                                    &numRows,
1489                                    &rowSizeInBytes,
1490                                    &combinedBufferSize);
1491     SkASSERT(combinedBufferSize);
1492 
1493     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1494             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1495     if (!slice.fBuffer) {
1496         return false;
1497     }
1498 
1499     char* bufferData = (char*)slice.fOffsetMapPtr;
1500     SkASSERT(bufferData);
1501     if (!copy_color_data(this->d3dCaps(),
1502                          bufferData,
1503                          info.fFormat,
1504                          backendTexture.dimensions(),
1505                          placedFootprints,
1506                          color)) {
1507         return false;
1508     }
1509     // Update the offsets in the footprint to be relative to the slice's offset
1510     placedFootprints[0].Offset += slice.fOffset;
1511     // Since we're sharing data for all the levels, set all the upper level footprints to the base.
1512     UINT w = placedFootprints[0].Footprint.Width;
1513     UINT h = placedFootprints[0].Footprint.Height;
1514     for (unsigned int i = 1; i < mipLevelCount; ++i) {
1515         w = std::max(1U, w/2);
1516         h = std::max(1U, h/2);
1517         placedFootprints[i].Offset = placedFootprints[0].Offset;
1518         placedFootprints[i].Footprint.Format   = placedFootprints[0].Footprint.Format;
1519         placedFootprints[i].Footprint.Width    = w;
1520         placedFootprints[i].Footprint.Height   = h;
1521         placedFootprints[i].Footprint.Depth    = 1;
1522         placedFootprints[i].Footprint.RowPitch = placedFootprints[0].Footprint.RowPitch;
1523     }
1524 
1525     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1526     cmdList->copyBufferToTexture(d3dBuffer,
1527                                  texture.get(),
1528                                  mipLevelCount,
1529                                  placedFootprints.get(),
1530                                  /*left*/ 0,
1531                                  /*top */ 0);
1532 
1533     if (finishedCallback) {
1534         this->addFinishedCallback(std::move(finishedCallback));
1535     }
1536 
1537     return true;
1538 }
1539 
onCreateCompressedBackendTexture(SkISize dimensions,const GrBackendFormat & format,skgpu::Mipmapped mipmapped,GrProtected isProtected)1540 GrBackendTexture GrD3DGpu::onCreateCompressedBackendTexture(SkISize dimensions,
1541                                                             const GrBackendFormat& format,
1542                                                             skgpu::Mipmapped mipmapped,
1543                                                             GrProtected isProtected) {
1544     return this->onCreateBackendTexture(dimensions,
1545                                         format,
1546                                         GrRenderable::kNo,
1547                                         mipmapped,
1548                                         isProtected,
1549                                         /*label=*/"D3DGpu_CreateCompressedBackendTexture");
1550 }
1551 
onUpdateCompressedBackendTexture(const GrBackendTexture & backendTexture,sk_sp<skgpu::RefCntedCallback> finishedCallback,const void * data,size_t size)1552 bool GrD3DGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1553                                                 sk_sp<skgpu::RefCntedCallback> finishedCallback,
1554                                                 const void* data,
1555                                                 size_t size) {
1556     GrD3DTextureResourceInfo info;
1557     SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1558 
1559     sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1560     SkASSERT(state);
1561     sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this,
1562                                                                    backendTexture.dimensions(),
1563                                                                    GrWrapCacheable::kNo,
1564                                                                    kRW_GrIOType,
1565                                                                    info,
1566                                                                    std::move(state));
1567     if (!texture) {
1568         return false;
1569     }
1570 
1571     GrD3DDirectCommandList* cmdList = this->currentCommandList();
1572     if (!cmdList) {
1573         return false;
1574     }
1575 
1576     texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1577 
1578     ID3D12Resource* d3dResource = texture->d3dResource();
1579     SkASSERT(d3dResource);
1580     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1581     unsigned int mipLevelCount = 1;
1582     if (backendTexture.hasMipmaps()) {
1583         mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions().width(),
1584                                                     backendTexture.dimensions().height()) + 1;
1585     }
1586     SkASSERT(mipLevelCount == info.fLevelCount);
1587     AutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1588     UINT64 combinedBufferSize;
1589     AutoTMalloc<UINT> numRows(mipLevelCount);
1590     AutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount);
1591     fDevice->GetCopyableFootprints(&desc,
1592                                    0,
1593                                    mipLevelCount,
1594                                    0,
1595                                    placedFootprints.get(),
1596                                    numRows.get(),
1597                                    rowSizeInBytes.get(),
1598                                    &combinedBufferSize);
1599     SkASSERT(combinedBufferSize);
1600     SkASSERT(GrDxgiFormatIsCompressed(info.fFormat));
1601 
1602     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1603             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1604     if (!slice.fBuffer) {
1605         return false;
1606     }
1607 
1608     char* bufferData = (char*)slice.fOffsetMapPtr;
1609     SkASSERT(bufferData);
1610     copy_compressed_data(bufferData,
1611                          info.fFormat,
1612                          placedFootprints.get(),
1613                          numRows.get(),
1614                          rowSizeInBytes.get(),
1615                          data,
1616                          info.fLevelCount);
1617 
1618     // Update the offsets in the footprints to be relative to the slice's offset
1619     for (unsigned int i = 0; i < mipLevelCount; ++i) {
1620         placedFootprints[i].Offset += slice.fOffset;
1621     }
1622 
1623     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1624     cmdList->copyBufferToTexture(d3dBuffer,
1625                                  texture.get(),
1626                                  mipLevelCount,
1627                                  placedFootprints.get(),
1628                                  0,
1629                                  0);
1630 
1631     if (finishedCallback) {
1632         this->addFinishedCallback(std::move(finishedCallback));
1633     }
1634 
1635     return true;
1636 }
1637 
deleteBackendTexture(const GrBackendTexture & tex)1638 void GrD3DGpu::deleteBackendTexture(const GrBackendTexture& tex) {
1639     SkASSERT(GrBackendApi::kDirect3D == tex.fBackend);
1640     // Nothing to do here, will get cleaned up when the GrBackendTexture object goes away
1641 }
1642 
compile(const GrProgramDesc &,const GrProgramInfo &)1643 bool GrD3DGpu::compile(const GrProgramDesc&, const GrProgramInfo&) {
1644     return false;
1645 }
1646 
1647 #if defined(GPU_TEST_UTILS)
isTestingOnlyBackendTexture(const GrBackendTexture & tex) const1648 bool GrD3DGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const {
1649     SkASSERT(GrBackendApi::kDirect3D == tex.backend());
1650 
1651     GrD3DTextureResourceInfo info;
1652     if (!tex.getD3DTextureResourceInfo(&info)) {
1653         return false;
1654     }
1655     ID3D12Resource* textureResource = info.fResource.get();
1656     if (!textureResource) {
1657         return false;
1658     }
1659     return !(textureResource->GetDesc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
1660 }
1661 
createTestingOnlyBackendRenderTarget(SkISize dimensions,GrColorType colorType,int sampleCnt,GrProtected isProtected)1662 GrBackendRenderTarget GrD3DGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions,
1663                                                                      GrColorType colorType,
1664                                                                      int sampleCnt,
1665                                                                      GrProtected isProtected) {
1666     if (dimensions.width()  > this->caps()->maxRenderTargetSize() ||
1667         dimensions.height() > this->caps()->maxRenderTargetSize()) {
1668         return {};
1669     }
1670 
1671     DXGI_FORMAT dxgiFormat = this->d3dCaps().getFormatFromColorType(colorType);
1672 
1673     GrD3DTextureResourceInfo info;
1674     if (!this->createTextureResourceForBackendSurface(dxgiFormat,
1675                                                       dimensions,
1676                                                       GrTexturable::kNo,
1677                                                       GrRenderable::kYes,
1678                                                       skgpu::Mipmapped::kNo,
1679                                                       sampleCnt,
1680                                                       &info,
1681                                                       isProtected)) {
1682         return {};
1683     }
1684 
1685     return GrBackendRenderTarget(dimensions.width(), dimensions.height(), info);
1686 }
1687 
deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget & rt)1688 void GrD3DGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& rt) {
1689     SkASSERT(GrBackendApi::kDirect3D == rt.backend());
1690 
1691     GrD3DTextureResourceInfo info;
1692     if (rt.getD3DTextureResourceInfo(&info)) {
1693         GrSubmitInfo submitInfo;
1694         submitInfo.fSync = GrSyncCpu::kYes;
1695 
1696         this->submitToGpu(submitInfo);
1697         // Nothing else to do here, will get cleaned up when the GrBackendRenderTarget
1698         // is deleted.
1699     }
1700 }
1701 
testingOnly_startCapture()1702 void GrD3DGpu::testingOnly_startCapture() {
1703     if (fGraphicsAnalysis) {
1704         fGraphicsAnalysis->BeginCapture();
1705     }
1706 }
1707 
testingOnly_stopCapture()1708 void GrD3DGpu::testingOnly_stopCapture() {
1709     if (fGraphicsAnalysis) {
1710         fGraphicsAnalysis->EndCapture();
1711     }
1712 }
1713 #endif
1714 
1715 ///////////////////////////////////////////////////////////////////////////////
1716 
addResourceBarriers(sk_sp<GrManagedResource> resource,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1717 void GrD3DGpu::addResourceBarriers(sk_sp<GrManagedResource> resource,
1718                                    int numBarriers,
1719                                    D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1720     SkASSERT(fCurrentDirectCommandList);
1721     SkASSERT(resource);
1722 
1723     fCurrentDirectCommandList->resourceBarrier(std::move(resource), numBarriers, barriers);
1724 }
1725 
addBufferResourceBarriers(GrD3DBuffer * buffer,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1726 void GrD3DGpu::addBufferResourceBarriers(GrD3DBuffer* buffer,
1727                                          int numBarriers,
1728                                          D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1729     SkASSERT(fCurrentDirectCommandList);
1730     SkASSERT(buffer);
1731 
1732     fCurrentDirectCommandList->resourceBarrier(nullptr, numBarriers, barriers);
1733     fCurrentDirectCommandList->addGrBuffer(sk_ref_sp<const GrBuffer>(buffer));
1734 }
1735 
prepareSurfacesForBackendAccessAndStateUpdates(SkSpan<GrSurfaceProxy * > proxies,SkSurfaces::BackendSurfaceAccess access,const skgpu::MutableTextureState * newState)1736 void GrD3DGpu::prepareSurfacesForBackendAccessAndStateUpdates(
1737         SkSpan<GrSurfaceProxy*> proxies,
1738         SkSurfaces::BackendSurfaceAccess access,
1739         const skgpu::MutableTextureState* newState) {
1740     // prepare proxies by transitioning to PRESENT renderState
1741     if (!proxies.empty() && access == SkSurfaces::BackendSurfaceAccess::kPresent) {
1742         GrD3DTextureResource* resource;
1743         for (GrSurfaceProxy* proxy : proxies) {
1744             SkASSERT(proxy->isInstantiated());
1745             if (GrTexture* tex = proxy->peekTexture()) {
1746                 resource = static_cast<GrD3DTexture*>(tex);
1747             } else {
1748                 GrRenderTarget* rt = proxy->peekRenderTarget();
1749                 SkASSERT(rt);
1750                 resource = static_cast<GrD3DRenderTarget*>(rt);
1751             }
1752             resource->prepareForPresent(this);
1753         }
1754     }
1755 }
1756 
takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer)1757 void GrD3DGpu::takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer) {
1758     fCurrentDirectCommandList->addGrBuffer(std::move(buffer));
1759 }
1760 
onSubmitToGpu(const GrSubmitInfo & info)1761 bool GrD3DGpu::onSubmitToGpu(const GrSubmitInfo& info) {
1762     if (info.fSync == GrSyncCpu::kYes) {
1763         return this->submitDirectCommandList(SyncQueue::kForce);
1764     } else {
1765         return this->submitDirectCommandList(SyncQueue::kSkip);
1766     }
1767 }
1768 
makeSemaphore(bool)1769 [[nodiscard]] std::unique_ptr<GrSemaphore> GrD3DGpu::makeSemaphore(bool) {
1770     return GrD3DSemaphore::Make(this);
1771 }
wrapBackendSemaphore(const GrBackendSemaphore & semaphore,GrSemaphoreWrapType,GrWrapOwnership)1772 std::unique_ptr<GrSemaphore> GrD3DGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore,
1773                                                             GrSemaphoreWrapType /* wrapType */,
1774                                                             GrWrapOwnership /* ownership */) {
1775     SkASSERT(this->caps()->backendSemaphoreSupport());
1776     GrD3DFenceInfo fenceInfo;
1777     if (!semaphore.getD3DFenceInfo(&fenceInfo)) {
1778         return nullptr;
1779     }
1780     return GrD3DSemaphore::MakeWrapped(fenceInfo);
1781 }
1782 
insertSemaphore(GrSemaphore * semaphore)1783 void GrD3DGpu::insertSemaphore(GrSemaphore* semaphore) {
1784     SkASSERT(semaphore);
1785     GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1786     // TODO: Do we need to track the lifetime of this? How do we know it's done?
1787     fQueue->Signal(d3dSem->fence(), d3dSem->value());
1788 }
1789 
waitSemaphore(GrSemaphore * semaphore)1790 void GrD3DGpu::waitSemaphore(GrSemaphore* semaphore) {
1791     SkASSERT(semaphore);
1792     GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1793     // TODO: Do we need to track the lifetime of this?
1794     fQueue->Wait(d3dSem->fence(), d3dSem->value());
1795 }
1796 
finishOutstandingGpuWork()1797 void GrD3DGpu::finishOutstandingGpuWork() {
1798     this->waitForQueueCompletion();
1799 }
1800