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
onCreateCompressedTexture(SkISize dimensions,const GrBackendFormat & format,skgpu::Budgeted budgeted,skgpu::Mipmapped mipMapped,GrProtected isProtected,OH_NativeBuffer * nativeBuffer,size_t bufferSize)429 sk_sp<GrTexture> GrD3DGpu::onCreateCompressedTexture(SkISize dimensions,
430 const GrBackendFormat& format,
431 skgpu::Budgeted budgeted,
432 skgpu::Mipmapped mipMapped,
433 GrProtected isProtected,
434 OH_NativeBuffer* nativeBuffer,
435 size_t bufferSize) {
436 SkASSERT(!"unimplemented");
437 return nullptr;
438 }
439
get_surface_sample_cnt(GrSurface * surf)440 static int get_surface_sample_cnt(GrSurface* surf) {
441 if (const GrRenderTarget* rt = surf->asRenderTarget()) {
442 return rt->numSamples();
443 }
444 return 0;
445 }
446
onCopySurface(GrSurface * dst,const SkIRect & dstRect,GrSurface * src,const SkIRect & srcRect,GrSamplerState::Filter)447 bool GrD3DGpu::onCopySurface(GrSurface* dst, const SkIRect& dstRect,
448 GrSurface* src, const SkIRect& srcRect,
449 GrSamplerState::Filter) {
450 if (srcRect.size() != dstRect.size()) {
451 return false;
452 }
453 if (src->isProtected() && !dst->isProtected()) {
454 SkDebugf("Can't copy from protected memory to non-protected");
455 return false;
456 }
457
458 int dstSampleCnt = get_surface_sample_cnt(dst);
459 int srcSampleCnt = get_surface_sample_cnt(src);
460
461 GrD3DTextureResource* dstTexResource;
462 GrD3DTextureResource* srcTexResource;
463 GrRenderTarget* dstRT = dst->asRenderTarget();
464 if (dstRT) {
465 GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(dstRT);
466 dstTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
467 } else {
468 SkASSERT(dst->asTexture());
469 dstTexResource = static_cast<GrD3DTexture*>(dst->asTexture());
470 }
471 GrRenderTarget* srcRT = src->asRenderTarget();
472 if (srcRT) {
473 GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(srcRT);
474 srcTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
475 } else {
476 SkASSERT(src->asTexture());
477 srcTexResource = static_cast<GrD3DTexture*>(src->asTexture());
478 }
479
480 DXGI_FORMAT dstFormat = dstTexResource->dxgiFormat();
481 DXGI_FORMAT srcFormat = srcTexResource->dxgiFormat();
482
483 const SkIPoint dstPoint = dstRect.topLeft();
484 if (this->d3dCaps().canCopyAsResolve(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
485 this->copySurfaceAsResolve(dst, src, srcRect, dstPoint);
486 return true;
487 }
488
489 if (this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
490 this->copySurfaceAsCopyTexture(dst, src, dstTexResource, srcTexResource, srcRect, dstPoint);
491 return true;
492 }
493
494 return false;
495 }
496
copySurfaceAsCopyTexture(GrSurface * dst,GrSurface * src,GrD3DTextureResource * dstResource,GrD3DTextureResource * srcResource,const SkIRect & srcRect,const SkIPoint & dstPoint)497 void GrD3DGpu::copySurfaceAsCopyTexture(GrSurface* dst, GrSurface* src,
498 GrD3DTextureResource* dstResource,
499 GrD3DTextureResource* srcResource,
500 const SkIRect& srcRect, const SkIPoint& dstPoint) {
501 #ifdef SK_DEBUG
502 int dstSampleCnt = get_surface_sample_cnt(dst);
503 int srcSampleCnt = get_surface_sample_cnt(src);
504 DXGI_FORMAT dstFormat = dstResource->dxgiFormat();
505 DXGI_FORMAT srcFormat;
506 SkAssertResult(dst->backendFormat().asDxgiFormat(&srcFormat));
507 SkASSERT(this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt));
508 #endif
509 if (src->isProtected() && !dst->isProtected()) {
510 SkDebugf("Can't copy from protected memory to non-protected");
511 return;
512 }
513
514 dstResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
515 srcResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
516
517 D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
518 dstLocation.pResource = dstResource->d3dResource();
519 dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
520 dstLocation.SubresourceIndex = 0;
521
522 D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
523 srcLocation.pResource = srcResource->d3dResource();
524 srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
525 srcLocation.SubresourceIndex = 0;
526
527 D3D12_BOX srcBox = {};
528 srcBox.left = srcRect.fLeft;
529 srcBox.top = srcRect.fTop;
530 srcBox.right = srcRect.fRight;
531 srcBox.bottom = srcRect.fBottom;
532 srcBox.front = 0;
533 srcBox.back = 1;
534 // TODO: use copyResource if copying full resource and sizes match
535 fCurrentDirectCommandList->copyTextureRegionToTexture(dstResource->resource(),
536 &dstLocation,
537 dstPoint.fX, dstPoint.fY,
538 srcResource->resource(),
539 &srcLocation,
540 &srcBox);
541
542 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
543 srcRect.width(), srcRect.height());
544 // The rect is already in device space so we pass in kTopLeft so no flip is done.
545 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
546 }
547
copySurfaceAsResolve(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)548 void GrD3DGpu::copySurfaceAsResolve(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
549 const SkIPoint& dstPoint) {
550 GrD3DRenderTarget* srcRT = static_cast<GrD3DRenderTarget*>(src->asRenderTarget());
551 SkASSERT(srcRT);
552
553 this->resolveTexture(dst, dstPoint.fX, dstPoint.fY, srcRT, srcRect);
554 SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
555 srcRect.width(), srcRect.height());
556 // The rect is already in device space so we pass in kTopLeft so no flip is done.
557 this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
558 }
559
resolveTexture(GrSurface * dst,int32_t dstX,int32_t dstY,GrD3DRenderTarget * src,const SkIRect & srcIRect)560 void GrD3DGpu::resolveTexture(GrSurface* dst, int32_t dstX, int32_t dstY,
561 GrD3DRenderTarget* src, const SkIRect& srcIRect) {
562 SkASSERT(dst);
563 SkASSERT(src && src->numSamples() > 1 && src->msaaTextureResource());
564
565 D3D12_RECT srcRect = { srcIRect.fLeft, srcIRect.fTop, srcIRect.fRight, srcIRect.fBottom };
566
567 GrD3DTextureResource* dstTextureResource;
568 GrRenderTarget* dstRT = dst->asRenderTarget();
569 if (dstRT) {
570 dstTextureResource = static_cast<GrD3DRenderTarget*>(dstRT);
571 } else {
572 SkASSERT(dst->asTexture());
573 dstTextureResource = static_cast<GrD3DTexture*>(dst->asTexture());
574 }
575
576 dstTextureResource->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_DEST);
577 src->msaaTextureResource()->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
578
579 fCurrentDirectCommandList->resolveSubresourceRegion(dstTextureResource, dstX, dstY,
580 src->msaaTextureResource(), &srcRect);
581 }
582
onResolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect)583 void GrD3DGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
584 SkASSERT(target->numSamples() > 1);
585 GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(target);
586 SkASSERT(rt->msaaTextureResource() && rt != rt->msaaTextureResource());
587
588 this->resolveTexture(target, resolveRect.fLeft, resolveRect.fTop, rt, resolveRect);
589 }
590
onReadPixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType dstColorType,void * buffer,size_t rowBytes)591 bool GrD3DGpu::onReadPixels(GrSurface* surface,
592 SkIRect rect,
593 GrColorType surfaceColorType,
594 GrColorType dstColorType,
595 void* buffer,
596 size_t rowBytes) {
597 SkASSERT(surface);
598
599 if (surfaceColorType != dstColorType) {
600 return false;
601 }
602
603 GrD3DTextureResource* texResource = nullptr;
604 GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
605 if (rt) {
606 texResource = rt;
607 } else {
608 texResource = static_cast<GrD3DTexture*>(surface->asTexture());
609 }
610
611 if (!texResource) {
612 return false;
613 }
614
615 D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
616 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
617 UINT64 transferTotalBytes;
618 fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
619 nullptr, nullptr, &transferTotalBytes);
620 SkASSERT(transferTotalBytes);
621 GrResourceProvider* resourceProvider =
622 this->getContext()->priv().resourceProvider();
623 sk_sp<GrGpuBuffer> transferBuffer = resourceProvider->createBuffer(
624 transferTotalBytes,
625 GrGpuBufferType::kXferGpuToCpu,
626 kDynamic_GrAccessPattern,
627 GrResourceProvider::ZeroInit::kNo);
628 if (!transferBuffer) {
629 return false;
630 }
631
632 this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
633 this->submitDirectCommandList(SyncQueue::kForce);
634
635 // Copy back to CPU buffer
636 size_t bpp = GrColorTypeBytesPerPixel(dstColorType);
637 if (GrDxgiFormatBytesPerBlock(texResource->dxgiFormat()) != bpp) {
638 return false;
639 }
640 size_t tightRowBytes = bpp * rect.width();
641
642 const void* mappedMemory = transferBuffer->map();
643 if (!mappedMemory) {
644 return false;
645 }
646
647 SkRectMemcpy(buffer,
648 rowBytes,
649 mappedMemory,
650 placedFootprint.Footprint.RowPitch,
651 tightRowBytes,
652 rect.height());
653
654 transferBuffer->unmap();
655
656 return true;
657 }
658
readOrTransferPixels(GrD3DTextureResource * texResource,SkIRect rect,sk_sp<GrGpuBuffer> transferBuffer,const D3D12_PLACED_SUBRESOURCE_FOOTPRINT & placedFootprint)659 void GrD3DGpu::readOrTransferPixels(GrD3DTextureResource* texResource,
660 SkIRect rect,
661 sk_sp<GrGpuBuffer> transferBuffer,
662 const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& placedFootprint) {
663 // Set up src location and box
664 D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
665 srcLocation.pResource = texResource->d3dResource();
666 SkASSERT(srcLocation.pResource);
667 srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
668 srcLocation.SubresourceIndex = 0;
669
670 D3D12_BOX srcBox = {};
671 srcBox.left = rect.left();
672 srcBox.top = rect.top();
673 srcBox.right = rect.right();
674 srcBox.bottom = rect.bottom();
675 srcBox.front = 0;
676 srcBox.back = 1;
677
678 // Set up dst location
679 D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
680 dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
681 dstLocation.PlacedFootprint = placedFootprint;
682 GrD3DBuffer* d3dBuf = static_cast<GrD3DBuffer*>(transferBuffer.get());
683 dstLocation.pResource = d3dBuf->d3dResource();
684
685 // Need to change the resource state to COPY_SOURCE in order to download from it
686 texResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
687
688 fCurrentDirectCommandList->copyTextureRegionToBuffer(transferBuffer, &dstLocation, 0, 0,
689 texResource->resource(), &srcLocation,
690 &srcBox);
691 }
692
onWritePixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,bool prepForTexSampling)693 bool GrD3DGpu::onWritePixels(GrSurface* surface,
694 SkIRect rect,
695 GrColorType surfaceColorType,
696 GrColorType srcColorType,
697 const GrMipLevel texels[],
698 int mipLevelCount,
699 bool prepForTexSampling) {
700 GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(surface->asTexture());
701 if (!d3dTex) {
702 return false;
703 }
704
705 // Make sure we have at least the base level
706 if (!mipLevelCount || !texels[0].fPixels) {
707 return false;
708 }
709
710 SkASSERT(!GrDxgiFormatIsCompressed(d3dTex->dxgiFormat()));
711 bool success = false;
712
713 // Need to change the resource state to COPY_DEST in order to upload to it
714 d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
715
716 SkASSERT(mipLevelCount <= d3dTex->maxMipmapLevel() + 1);
717 success = this->uploadToTexture(d3dTex, rect, srcColorType, texels, mipLevelCount);
718
719 if (prepForTexSampling) {
720 d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
721 }
722
723 return success;
724 }
725
uploadToTexture(GrD3DTexture * tex,SkIRect rect,GrColorType colorType,const GrMipLevel * texels,int mipLevelCount)726 bool GrD3DGpu::uploadToTexture(GrD3DTexture* tex,
727 SkIRect rect,
728 GrColorType colorType,
729 const GrMipLevel* texels,
730 int mipLevelCount) {
731 SkASSERT(this->d3dCaps().isFormatTexturable(tex->dxgiFormat()));
732 // The assumption is either that we have no mipmaps, or that our rect is the entire texture
733 SkASSERT(mipLevelCount == 1 || rect == SkIRect::MakeSize(tex->dimensions()));
734
735 // We assume that if the texture has mip levels, we either upload to all the levels or just the
736 // first.
737 SkASSERT(mipLevelCount == 1 || mipLevelCount == (tex->maxMipmapLevel() + 1));
738
739 if (rect.isEmpty()) {
740 return false;
741 }
742
743 SkASSERT(this->d3dCaps().surfaceSupportsWritePixels(tex));
744 SkASSERT(this->d3dCaps().areColorTypeAndFormatCompatible(colorType, tex->backendFormat()));
745
746 ID3D12Resource* d3dResource = tex->d3dResource();
747 SkASSERT(d3dResource);
748 D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
749 // Either upload only the first miplevel or all miplevels
750 SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels);
751
752 if (1 == mipLevelCount && !texels[0].fPixels) {
753 return true; // no data to upload
754 }
755
756 for (int i = 0; i < mipLevelCount; ++i) {
757 // We do not allow any gaps in the mip data
758 if (!texels[i].fPixels) {
759 return false;
760 }
761 }
762
763 AutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
764 UINT64 combinedBufferSize;
765 // We reset the width and height in the description to match our subrectangle size
766 // so we don't end up allocating more space than we need.
767 desc.Width = rect.width();
768 desc.Height = rect.height();
769 fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(),
770 nullptr, nullptr, &combinedBufferSize);
771 size_t bpp = GrColorTypeBytesPerPixel(colorType);
772 SkASSERT(combinedBufferSize);
773
774 GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
775 combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
776 if (!slice.fBuffer) {
777 return false;
778 }
779
780 char* bufferData = (char*)slice.fOffsetMapPtr;
781
782 int currentWidth = rect.width();
783 int currentHeight = rect.height();
784 for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) {
785 if (texels[currentMipLevel].fPixels) {
786
787 const size_t trimRowBytes = currentWidth * bpp;
788 const size_t srcRowBytes = texels[currentMipLevel].fRowBytes;
789
790 char* dst = bufferData + placedFootprints[currentMipLevel].Offset;
791
792 // copy data into the buffer, skipping any trailing bytes
793 const char* src = (const char*)texels[currentMipLevel].fPixels;
794 SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch,
795 src, srcRowBytes, trimRowBytes, currentHeight);
796 }
797 currentWidth = std::max(1, currentWidth / 2);
798 currentHeight = std::max(1, currentHeight / 2);
799 }
800
801 // Update the offsets in the footprints to be relative to the slice's offset
802 for (int i = 0; i < mipLevelCount; ++i) {
803 placedFootprints[i].Offset += slice.fOffset;
804 }
805
806 ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
807 fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
808 tex,
809 mipLevelCount,
810 placedFootprints.get(),
811 rect.left(),
812 rect.top());
813
814 if (mipLevelCount < (int)desc.MipLevels) {
815 tex->markMipmapsDirty();
816 }
817
818 return true;
819 }
820
onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,size_t srcOffset,sk_sp<GrGpuBuffer> dst,size_t dstOffset,size_t size)821 bool GrD3DGpu::onTransferFromBufferToBuffer(sk_sp<GrGpuBuffer> src,
822 size_t srcOffset,
823 sk_sp<GrGpuBuffer> dst,
824 size_t dstOffset,
825 size_t size) {
826 if (!this->currentCommandList()) {
827 return false;
828 }
829
830 sk_sp<GrD3DBuffer> d3dSrc(static_cast<GrD3DBuffer*>(src.release()));
831 sk_sp<GrD3DBuffer> d3dDst(static_cast<GrD3DBuffer*>(dst.release()));
832
833 fCurrentDirectCommandList->copyBufferToBuffer(std::move(d3dDst),
834 dstOffset,
835 d3dSrc->d3dResource(),
836 srcOffset,
837 size);
838
839 // copyBufferToBuffer refs the dst but not the src
840 this->currentCommandList()->addGrBuffer(std::move(src));
841
842 return true;
843 }
844
onTransferPixelsTo(GrTexture * texture,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t bufferOffset,size_t rowBytes)845 bool GrD3DGpu::onTransferPixelsTo(GrTexture* texture,
846 SkIRect rect,
847 GrColorType surfaceColorType,
848 GrColorType bufferColorType,
849 sk_sp<GrGpuBuffer> transferBuffer,
850 size_t bufferOffset,
851 size_t rowBytes) {
852 if (!this->currentCommandList()) {
853 return false;
854 }
855
856 if (!transferBuffer) {
857 return false;
858 }
859
860 size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
861 if (GrBackendFormatBytesPerPixel(texture->backendFormat()) != bpp) {
862 return false;
863 }
864
865 // D3D requires offsets for texture transfers to be aligned to this value
866 if (SkToBool(bufferOffset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
867 return false;
868 }
869
870 GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(texture);
871 if (!d3dTex) {
872 return false;
873 }
874
875 SkDEBUGCODE(DXGI_FORMAT format = d3dTex->dxgiFormat());
876
877 // Can't transfer compressed data
878 SkASSERT(!GrDxgiFormatIsCompressed(format));
879
880 SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
881
882 SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect));
883
884 // Set up copy region
885 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint = {};
886 ID3D12Resource* d3dResource = d3dTex->d3dResource();
887 SkASSERT(d3dResource);
888 D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
889 desc.Width = rect.width();
890 desc.Height = rect.height();
891 UINT64 totalBytes;
892 fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
893 nullptr, nullptr, &totalBytes);
894 placedFootprint.Offset = bufferOffset;
895
896 // Change state of our target so it can be copied to
897 d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
898
899 // Copy the buffer to the image.
900 ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(transferBuffer.get())->d3dResource();
901 fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
902 d3dTex,
903 1,
904 &placedFootprint,
905 rect.left(),
906 rect.top());
907 this->currentCommandList()->addGrBuffer(std::move(transferBuffer));
908
909 d3dTex->markMipmapsDirty();
910 return true;
911 }
912
onTransferPixelsFrom(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset)913 bool GrD3DGpu::onTransferPixelsFrom(GrSurface* surface,
914 SkIRect rect,
915 GrColorType surfaceColorType,
916 GrColorType bufferColorType,
917 sk_sp<GrGpuBuffer> transferBuffer,
918 size_t offset) {
919 if (!this->currentCommandList()) {
920 return false;
921 }
922 SkASSERT(surface);
923 SkASSERT(transferBuffer);
924 // TODO
925 //if (fProtectedContext == GrProtected::kYes) {
926 // return false;
927 //}
928
929 // D3D requires offsets for texture transfers to be aligned to this value
930 if (SkToBool(offset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
931 return false;
932 }
933
934 GrD3DTextureResource* texResource = nullptr;
935 GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
936 if (rt) {
937 texResource = rt;
938 } else {
939 texResource = static_cast<GrD3DTexture*>(surface->asTexture());
940 }
941
942 if (!texResource) {
943 return false;
944 }
945
946 SkDEBUGCODE(DXGI_FORMAT format = texResource->dxgiFormat());
947 SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
948
949 D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
950 desc.Width = rect.width();
951 desc.Height = rect.height();
952 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
953 UINT64 transferTotalBytes;
954 fDevice->GetCopyableFootprints(&desc, 0, 1, offset, &placedFootprint,
955 nullptr, nullptr, &transferTotalBytes);
956 SkASSERT(transferTotalBytes);
957
958 this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
959
960 // TODO: It's not clear how to ensure the transfer is done before we read from the buffer,
961 // other than maybe doing a resource state transition.
962
963 return true;
964 }
965
check_resource_info(const GrD3DTextureResourceInfo & info)966 static bool check_resource_info(const GrD3DTextureResourceInfo& info) {
967 if (!info.fResource.get()) {
968 return false;
969 }
970 return true;
971 }
972
check_tex_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info)973 static bool check_tex_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info) {
974 if (!caps.isFormatTexturable(info.fFormat)) {
975 return false;
976 }
977 // We don't support sampling from multisampled textures.
978 if (info.fSampleCount != 1) {
979 return false;
980 }
981 return true;
982 }
983
check_rt_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info,int sampleCnt)984 static bool check_rt_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info,
985 int sampleCnt) {
986 if (!caps.isFormatRenderable(info.fFormat, sampleCnt)) {
987 return false;
988 }
989 return true;
990 }
991
onWrapBackendTexture(const GrBackendTexture & tex,GrWrapOwnership,GrWrapCacheable wrapType,GrIOType ioType)992 sk_sp<GrTexture> GrD3DGpu::onWrapBackendTexture(const GrBackendTexture& tex,
993 GrWrapOwnership,
994 GrWrapCacheable wrapType,
995 GrIOType ioType) {
996 GrD3DTextureResourceInfo textureInfo;
997 if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
998 return nullptr;
999 }
1000
1001 if (!check_resource_info(textureInfo)) {
1002 return nullptr;
1003 }
1004
1005 if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
1006 return nullptr;
1007 }
1008
1009 // TODO: support protected context
1010 if (tex.isProtected()) {
1011 return nullptr;
1012 }
1013
1014 sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
1015 SkASSERT(state);
1016 return GrD3DTexture::MakeWrappedTexture(this, tex.dimensions(), wrapType, ioType, textureInfo,
1017 std::move(state));
1018 }
1019
onWrapCompressedBackendTexture(const GrBackendTexture & tex,GrWrapOwnership ownership,GrWrapCacheable wrapType)1020 sk_sp<GrTexture> GrD3DGpu::onWrapCompressedBackendTexture(const GrBackendTexture& tex,
1021 GrWrapOwnership ownership,
1022 GrWrapCacheable wrapType) {
1023 return this->onWrapBackendTexture(tex, ownership, wrapType, kRead_GrIOType);
1024 }
1025
onWrapRenderableBackendTexture(const GrBackendTexture & tex,int sampleCnt,GrWrapOwnership ownership,GrWrapCacheable cacheable)1026 sk_sp<GrTexture> GrD3DGpu::onWrapRenderableBackendTexture(const GrBackendTexture& tex,
1027 int sampleCnt,
1028 GrWrapOwnership ownership,
1029 GrWrapCacheable cacheable) {
1030 GrD3DTextureResourceInfo textureInfo;
1031 if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
1032 return nullptr;
1033 }
1034
1035 if (!check_resource_info(textureInfo)) {
1036 return nullptr;
1037 }
1038
1039 if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
1040 return nullptr;
1041 }
1042 if (!check_rt_resource_info(this->d3dCaps(), textureInfo, sampleCnt)) {
1043 return nullptr;
1044 }
1045
1046 // TODO: support protected context
1047 if (tex.isProtected()) {
1048 return nullptr;
1049 }
1050
1051 sampleCnt = this->d3dCaps().getRenderTargetSampleCount(sampleCnt, textureInfo.fFormat);
1052
1053 sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
1054 SkASSERT(state);
1055
1056 return GrD3DTextureRenderTarget::MakeWrappedTextureRenderTarget(this, tex.dimensions(),
1057 sampleCnt, cacheable,
1058 textureInfo, std::move(state));
1059 }
1060
onWrapBackendRenderTarget(const GrBackendRenderTarget & rt)1061 sk_sp<GrRenderTarget> GrD3DGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& rt) {
1062 GrD3DTextureResourceInfo info;
1063 if (!rt.getD3DTextureResourceInfo(&info)) {
1064 return nullptr;
1065 }
1066
1067 if (!check_resource_info(info)) {
1068 return nullptr;
1069 }
1070
1071 if (!check_rt_resource_info(this->d3dCaps(), info, rt.sampleCnt())) {
1072 return nullptr;
1073 }
1074
1075 // TODO: support protected context
1076 if (rt.isProtected()) {
1077 return nullptr;
1078 }
1079
1080 sk_sp<GrD3DResourceState> state = rt.getGrD3DResourceState();
1081
1082 sk_sp<GrD3DRenderTarget> tgt = GrD3DRenderTarget::MakeWrappedRenderTarget(
1083 this, rt.dimensions(), rt.sampleCnt(), info, std::move(state));
1084
1085 // We don't allow the client to supply a premade stencil buffer. We always create one if needed.
1086 SkASSERT(!rt.stencilBits());
1087 if (tgt) {
1088 SkASSERT(tgt->canAttemptStencilAttachment(tgt->numSamples() > 1));
1089 }
1090
1091 return std::move(tgt);
1092 }
1093
is_odd(int x)1094 static bool is_odd(int x) {
1095 return x > 1 && SkToBool(x & 0x1);
1096 }
1097
1098 // TODO: enable when sRGB shader supported
1099 //static bool is_srgb(DXGI_FORMAT format) {
1100 // // the only one we support at the moment
1101 // return (format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
1102 //}
1103
is_bgra(DXGI_FORMAT format)1104 static bool is_bgra(DXGI_FORMAT format) {
1105 // the only one we support at the moment
1106 return (format == DXGI_FORMAT_B8G8R8A8_UNORM);
1107 }
1108
onRegenerateMipMapLevels(GrTexture * tex)1109 bool GrD3DGpu::onRegenerateMipMapLevels(GrTexture * tex) {
1110 auto * d3dTex = static_cast<GrD3DTexture*>(tex);
1111 SkASSERT(tex->textureType() == GrTextureType::k2D);
1112 int width = tex->width();
1113 int height = tex->height();
1114
1115 // determine if we can read from and mipmap this format
1116 const GrD3DCaps & caps = this->d3dCaps();
1117 if (!caps.isFormatTexturable(d3dTex->dxgiFormat()) ||
1118 !caps.mipmapSupport()) {
1119 return false;
1120 }
1121
1122 sk_sp<GrD3DTexture> uavTexture;
1123 sk_sp<GrD3DTexture> bgraAliasTexture;
1124 DXGI_FORMAT originalFormat = d3dTex->dxgiFormat();
1125 D3D12_RESOURCE_DESC originalDesc = d3dTex->d3dResource()->GetDesc();
1126 // if the format is unordered accessible and resource flag is set, use resource for uav
1127 if (caps.isFormatUnorderedAccessible(originalFormat) &&
1128 (originalDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
1129 uavTexture = sk_ref_sp(d3dTex);
1130 } else {
1131 // need to make a copy and use that for our uav
1132 D3D12_RESOURCE_DESC uavDesc = originalDesc;
1133 uavDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
1134 // if the format is unordered accessible, copy to resource with same format and flag set
1135 if (!caps.isFormatUnorderedAccessible(originalFormat)) {
1136 // for the BGRA and sRGB cases, we find a suitable RGBA format to use instead
1137 if (is_bgra(originalFormat)) {
1138 uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1139 // Technically if this support is not available we should not be doing
1140 // aliasing. However, on Intel the BGRA and RGBA swizzle appears to be
1141 // the same so it still works. We may need to disable BGRA support
1142 // on a case-by-base basis if this doesn't hold true in general.
1143 if (caps.standardSwizzleLayoutSupport()) {
1144 uavDesc.Layout = D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE;
1145 }
1146 // TODO: enable when sRGB shader supported
1147 //} else if (is_srgb(originalFormat)) {
1148 // uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1149 } else {
1150 return false;
1151 }
1152 }
1153 // TODO: make this a scratch texture
1154 GrProtected grProtected = tex->isProtected() ? GrProtected::kYes : GrProtected::kNo;
1155 uavTexture = GrD3DTexture::MakeNewTexture(this,
1156 skgpu::Budgeted::kNo,
1157 tex->dimensions(),
1158 uavDesc,
1159 grProtected,
1160 GrMipmapStatus::kDirty,
1161 /*label=*/"RegenerateMipMapLevels");
1162 if (!uavTexture) {
1163 return false;
1164 }
1165
1166 d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1167 if (!caps.isFormatUnorderedAccessible(originalFormat) && is_bgra(originalFormat)) {
1168 // for BGRA, we alias this uavTexture with a BGRA texture and copy to that
1169 bgraAliasTexture = GrD3DTexture::MakeAliasingTexture(this, uavTexture, originalDesc,
1170 D3D12_RESOURCE_STATE_COPY_DEST);
1171 // make the BGRA version the active alias
1172 this->currentCommandList()->aliasingBarrier(nullptr,
1173 nullptr,
1174 bgraAliasTexture->resource(),
1175 bgraAliasTexture->d3dResource());
1176 // copy top miplevel to bgraAliasTexture (should already be in COPY_DEST state)
1177 this->currentCommandList()->copyTextureToTexture(bgraAliasTexture.get(), d3dTex, 0);
1178 // make the RGBA version the active alias
1179 this->currentCommandList()->aliasingBarrier(bgraAliasTexture->resource(),
1180 bgraAliasTexture->d3dResource(),
1181 uavTexture->resource(),
1182 uavTexture->d3dResource());
1183 } else {
1184 // copy top miplevel to uavTexture
1185 uavTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1186 this->currentCommandList()->copyTextureToTexture(uavTexture.get(), d3dTex, 0);
1187 }
1188 }
1189
1190 uint32_t levelCount = d3dTex->mipLevels();
1191 // SkMipmap doesn't include the base level in the level count so we have to add 1
1192 SkASSERT((int)levelCount == SkMipmap::ComputeLevelCount(tex->width(), tex->height()) + 1);
1193
1194 sk_sp<GrD3DRootSignature> rootSig = fResourceProvider.findOrCreateRootSignature(1, 1);
1195 this->currentCommandList()->setComputeRootSignature(rootSig);
1196
1197 // TODO: use linear vs. srgb shader based on texture format
1198 sk_sp<GrD3DPipeline> pipeline = this->resourceProvider().findOrCreateMipmapPipeline();
1199 if (!pipeline) {
1200 return false;
1201 }
1202 this->currentCommandList()->setPipelineState(std::move(pipeline));
1203
1204 // set sampler
1205 GrSamplerState samplerState(SkFilterMode::kLinear, SkMipmapMode::kNearest);
1206 std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(1);
1207 samplers[0] = fResourceProvider.findOrCreateCompatibleSampler(samplerState);
1208 this->currentCommandList()->addSampledTextureRef(uavTexture.get());
1209 sk_sp<GrD3DDescriptorTable> samplerTable = fResourceProvider.findOrCreateSamplerTable(samplers);
1210
1211 // Transition the top subresource to be readable in the compute shader
1212 D3D12_RESOURCE_STATES currentResourceState = uavTexture->currentState();
1213 D3D12_RESOURCE_TRANSITION_BARRIER barrier;
1214 barrier.pResource = uavTexture->d3dResource();
1215 barrier.Subresource = 0;
1216 barrier.StateBefore = currentResourceState;
1217 barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1218 this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1219
1220 // Generate the miplevels
1221 for (unsigned int dstMip = 1; dstMip < levelCount; ++dstMip) {
1222 unsigned int srcMip = dstMip - 1;
1223 width = std::max(1, width / 2);
1224 height = std::max(1, height / 2);
1225
1226 unsigned int sampleMode = 0;
1227 if (is_odd(width) && is_odd(height)) {
1228 sampleMode = 1;
1229 } else if (is_odd(width)) {
1230 sampleMode = 2;
1231 } else if (is_odd(height)) {
1232 sampleMode = 3;
1233 }
1234
1235 // set constants
1236 struct {
1237 SkSize inverseSize;
1238 uint32_t mipLevel;
1239 uint32_t sampleMode;
1240 } constantData = { {1.f / width, 1.f / height}, srcMip, sampleMode };
1241
1242 D3D12_GPU_VIRTUAL_ADDRESS constantsAddress =
1243 fResourceProvider.uploadConstantData(&constantData, sizeof(constantData));
1244 this->currentCommandList()->setComputeRootConstantBufferView(
1245 (unsigned int)GrD3DRootSignature::ParamIndex::kConstantBufferView,
1246 constantsAddress);
1247
1248 std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderViews;
1249 // create SRV
1250 GrD3DDescriptorHeap::CPUHandle srvHandle =
1251 fResourceProvider.createShaderResourceView(uavTexture->d3dResource(), srcMip, 1);
1252 shaderViews.push_back(srvHandle.fHandle);
1253 fMipmapCPUDescriptors.push_back(srvHandle);
1254 // create UAV
1255 GrD3DDescriptorHeap::CPUHandle uavHandle =
1256 fResourceProvider.createUnorderedAccessView(uavTexture->d3dResource(), dstMip);
1257 shaderViews.push_back(uavHandle.fHandle);
1258 fMipmapCPUDescriptors.push_back(uavHandle);
1259
1260 // set up shaderView descriptor table
1261 sk_sp<GrD3DDescriptorTable> srvTable =
1262 fResourceProvider.findOrCreateShaderViewTable(shaderViews);
1263
1264 // bind both descriptor tables
1265 this->currentCommandList()->setDescriptorHeaps(srvTable->heap(), samplerTable->heap());
1266 this->currentCommandList()->setComputeRootDescriptorTable(
1267 (unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable,
1268 srvTable->baseGpuDescriptor());
1269 this->currentCommandList()->setComputeRootDescriptorTable(
1270 static_cast<unsigned int>(GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable),
1271 samplerTable->baseGpuDescriptor());
1272
1273 // Transition resource state of dstMip subresource so we can write to it
1274 barrier.Subresource = dstMip;
1275 barrier.StateBefore = currentResourceState;
1276 barrier.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1277 this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1278
1279 // Using the form (x+7)/8 ensures that the remainder is covered as well
1280 this->currentCommandList()->dispatch((width+7)/8, (height+7)/8);
1281
1282 // guarantee UAV writes have completed
1283 this->currentCommandList()->uavBarrier(uavTexture->resource(), uavTexture->d3dResource());
1284
1285 // Transition resource state of dstMip subresource so we can read it in the next stage
1286 barrier.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1287 barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1288 this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1289 }
1290
1291 // copy back if necessary
1292 if (uavTexture.get() != d3dTex) {
1293 d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1294 if (bgraAliasTexture) {
1295 // make the BGRA version the active alias
1296 this->currentCommandList()->aliasingBarrier(uavTexture->resource(),
1297 uavTexture->d3dResource(),
1298 bgraAliasTexture->resource(),
1299 bgraAliasTexture->d3dResource());
1300 // copy from bgraAliasTexture to d3dTex
1301 bgraAliasTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1302 this->currentCommandList()->copyTextureToTexture(d3dTex, bgraAliasTexture.get());
1303 } else {
1304 barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1305 barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1306 barrier.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
1307 this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1308 this->currentCommandList()->copyTextureToTexture(d3dTex, uavTexture.get());
1309 }
1310 } else {
1311 // For simplicity our resource state tracking considers all subresources to have the same
1312 // state. However, we've changed that state one subresource at a time without going through
1313 // the tracking system, so we need to patch up the resource states back to the original.
1314 barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1315 barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1316 barrier.StateAfter = currentResourceState;
1317 this->addResourceBarriers(d3dTex->resource(), 1, &barrier);
1318 }
1319
1320 return true;
1321 }
1322
onCreateBuffer(size_t sizeInBytes,GrGpuBufferType type,GrAccessPattern accessPattern)1323 sk_sp<GrGpuBuffer> GrD3DGpu::onCreateBuffer(size_t sizeInBytes,
1324 GrGpuBufferType type,
1325 GrAccessPattern accessPattern) {
1326 return GrD3DBuffer::Make(this, sizeInBytes, type, accessPattern);
1327 }
1328
makeStencilAttachment(const GrBackendFormat &,SkISize dimensions,int numStencilSamples)1329 sk_sp<GrAttachment> GrD3DGpu::makeStencilAttachment(const GrBackendFormat& /*colorFormat*/,
1330 SkISize dimensions, int numStencilSamples) {
1331 DXGI_FORMAT sFmt = this->d3dCaps().preferredStencilFormat();
1332
1333 fStats.incStencilAttachmentCreates();
1334 return GrD3DAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt);
1335 }
1336
createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,SkISize dimensions,GrTexturable texturable,GrRenderable renderable,skgpu::Mipmapped mipmapped,int sampleCnt,GrD3DTextureResourceInfo * info,GrProtected isProtected)1337 bool GrD3DGpu::createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,
1338 SkISize dimensions,
1339 GrTexturable texturable,
1340 GrRenderable renderable,
1341 skgpu::Mipmapped mipmapped,
1342 int sampleCnt,
1343 GrD3DTextureResourceInfo* info,
1344 GrProtected isProtected) {
1345 SkASSERT(texturable == GrTexturable::kYes || renderable == GrRenderable::kYes);
1346
1347 if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1348 return false;
1349 }
1350
1351 if (texturable == GrTexturable::kYes && !this->d3dCaps().isFormatTexturable(dxgiFormat)) {
1352 return false;
1353 }
1354
1355 if (renderable == GrRenderable::kYes && !this->d3dCaps().isFormatRenderable(dxgiFormat, 1)) {
1356 return false;
1357 }
1358
1359 int numMipLevels = 1;
1360 if (mipmapped == skgpu::Mipmapped::kYes) {
1361 numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
1362 }
1363
1364 // create the texture
1365 D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE;
1366 if (renderable == GrRenderable::kYes) {
1367 usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
1368 }
1369
1370 D3D12_RESOURCE_DESC resourceDesc = {};
1371 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1372 resourceDesc.Alignment = 0; // use default alignment
1373 resourceDesc.Width = dimensions.fWidth;
1374 resourceDesc.Height = dimensions.fHeight;
1375 resourceDesc.DepthOrArraySize = 1;
1376 resourceDesc.MipLevels = numMipLevels;
1377 resourceDesc.Format = dxgiFormat;
1378 resourceDesc.SampleDesc.Count = sampleCnt;
1379 resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
1380 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // use driver-selected swizzle
1381 resourceDesc.Flags = usageFlags;
1382
1383 D3D12_CLEAR_VALUE* clearValuePtr = nullptr;
1384 D3D12_CLEAR_VALUE clearValue = {};
1385 if (renderable == GrRenderable::kYes) {
1386 clearValue.Format = dxgiFormat;
1387 // Assume transparent black
1388 clearValue.Color[0] = 0;
1389 clearValue.Color[1] = 0;
1390 clearValue.Color[2] = 0;
1391 clearValue.Color[3] = 0;
1392 clearValuePtr = &clearValue;
1393 }
1394
1395 D3D12_RESOURCE_STATES initialState = (renderable == GrRenderable::kYes)
1396 ? D3D12_RESOURCE_STATE_RENDER_TARGET
1397 : D3D12_RESOURCE_STATE_COPY_DEST;
1398 if (!GrD3DTextureResource::InitTextureResourceInfo(this, resourceDesc, initialState,
1399 isProtected, clearValuePtr, info)) {
1400 SkDebugf("Failed to init texture resource info\n");
1401 return false;
1402 }
1403
1404 return true;
1405 }
1406
onCreateBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,skgpu::Mipmapped mipmapped,GrProtected isProtected,std::string_view label)1407 GrBackendTexture GrD3DGpu::onCreateBackendTexture(SkISize dimensions,
1408 const GrBackendFormat& format,
1409 GrRenderable renderable,
1410 skgpu::Mipmapped mipmapped,
1411 GrProtected isProtected,
1412 std::string_view label) {
1413 const GrD3DCaps& caps = this->d3dCaps();
1414
1415 if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1416 return {};
1417 }
1418
1419 DXGI_FORMAT dxgiFormat;
1420 if (!format.asDxgiFormat(&dxgiFormat)) {
1421 return {};
1422 }
1423
1424 // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here
1425 if (!caps.isFormatTexturable(dxgiFormat)) {
1426 return {};
1427 }
1428
1429 GrD3DTextureResourceInfo info;
1430 if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kYes,
1431 renderable, mipmapped, 1, &info,
1432 isProtected)) {
1433 return {};
1434 }
1435
1436 return GrBackendTexture(dimensions.width(), dimensions.height(), info);
1437 }
1438
copy_color_data(const GrD3DCaps & caps,char * mapPtr,DXGI_FORMAT dxgiFormat,SkISize dimensions,D3D12_PLACED_SUBRESOURCE_FOOTPRINT * placedFootprints,std::array<float,4> color)1439 static bool copy_color_data(const GrD3DCaps& caps,
1440 char* mapPtr,
1441 DXGI_FORMAT dxgiFormat,
1442 SkISize dimensions,
1443 D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints,
1444 std::array<float, 4> color) {
1445 auto colorType = caps.getFormatColorType(dxgiFormat);
1446 if (colorType == GrColorType::kUnknown) {
1447 return false;
1448 }
1449 GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, dimensions);
1450 if (!GrClearImage(ii, mapPtr, placedFootprints[0].Footprint.RowPitch, color)) {
1451 return false;
1452 }
1453
1454 return true;
1455 }
1456
onClearBackendTexture(const GrBackendTexture & backendTexture,sk_sp<skgpu::RefCntedCallback> finishedCallback,std::array<float,4> color)1457 bool GrD3DGpu::onClearBackendTexture(const GrBackendTexture& backendTexture,
1458 sk_sp<skgpu::RefCntedCallback> finishedCallback,
1459 std::array<float, 4> color) {
1460 GrD3DTextureResourceInfo info;
1461 SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1462 SkASSERT(!GrDxgiFormatIsCompressed(info.fFormat));
1463
1464 sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1465 SkASSERT(state);
1466 sk_sp<GrD3DTexture> texture =
1467 GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(),
1468 GrWrapCacheable::kNo,
1469 kRW_GrIOType, info, std::move(state));
1470 if (!texture) {
1471 return false;
1472 }
1473
1474 GrD3DDirectCommandList* cmdList = this->currentCommandList();
1475 if (!cmdList) {
1476 return false;
1477 }
1478
1479 texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1480
1481 ID3D12Resource* d3dResource = texture->d3dResource();
1482 SkASSERT(d3dResource);
1483 D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1484 unsigned int mipLevelCount = 1;
1485 if (backendTexture.fMipmapped == skgpu::Mipmapped::kYes) {
1486 mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions()) + 1;
1487 }
1488 SkASSERT(mipLevelCount == info.fLevelCount);
1489 AutoSTMalloc<15, D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1490 UINT numRows;
1491 UINT64 rowSizeInBytes;
1492 UINT64 combinedBufferSize;
1493 // We reuse the same top-level buffer area for all levels, hence passing 1 for level count.
1494 fDevice->GetCopyableFootprints(&desc,
1495 /* first resource */ 0,
1496 /* mip level count */ 1,
1497 /* base offset */ 0,
1498 placedFootprints.get(),
1499 &numRows,
1500 &rowSizeInBytes,
1501 &combinedBufferSize);
1502 SkASSERT(combinedBufferSize);
1503
1504 GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1505 combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1506 if (!slice.fBuffer) {
1507 return false;
1508 }
1509
1510 char* bufferData = (char*)slice.fOffsetMapPtr;
1511 SkASSERT(bufferData);
1512 if (!copy_color_data(this->d3dCaps(),
1513 bufferData,
1514 info.fFormat,
1515 backendTexture.dimensions(),
1516 placedFootprints,
1517 color)) {
1518 return false;
1519 }
1520 // Update the offsets in the footprint to be relative to the slice's offset
1521 placedFootprints[0].Offset += slice.fOffset;
1522 // Since we're sharing data for all the levels, set all the upper level footprints to the base.
1523 UINT w = placedFootprints[0].Footprint.Width;
1524 UINT h = placedFootprints[0].Footprint.Height;
1525 for (unsigned int i = 1; i < mipLevelCount; ++i) {
1526 w = std::max(1U, w/2);
1527 h = std::max(1U, h/2);
1528 placedFootprints[i].Offset = placedFootprints[0].Offset;
1529 placedFootprints[i].Footprint.Format = placedFootprints[0].Footprint.Format;
1530 placedFootprints[i].Footprint.Width = w;
1531 placedFootprints[i].Footprint.Height = h;
1532 placedFootprints[i].Footprint.Depth = 1;
1533 placedFootprints[i].Footprint.RowPitch = placedFootprints[0].Footprint.RowPitch;
1534 }
1535
1536 ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1537 cmdList->copyBufferToTexture(d3dBuffer,
1538 texture.get(),
1539 mipLevelCount,
1540 placedFootprints.get(),
1541 /*left*/ 0,
1542 /*top */ 0);
1543
1544 if (finishedCallback) {
1545 this->addFinishedCallback(std::move(finishedCallback));
1546 }
1547
1548 return true;
1549 }
1550
onCreateCompressedBackendTexture(SkISize dimensions,const GrBackendFormat & format,skgpu::Mipmapped mipmapped,GrProtected isProtected)1551 GrBackendTexture GrD3DGpu::onCreateCompressedBackendTexture(SkISize dimensions,
1552 const GrBackendFormat& format,
1553 skgpu::Mipmapped mipmapped,
1554 GrProtected isProtected) {
1555 return this->onCreateBackendTexture(dimensions,
1556 format,
1557 GrRenderable::kNo,
1558 mipmapped,
1559 isProtected,
1560 /*label=*/"D3DGpu_CreateCompressedBackendTexture");
1561 }
1562
onUpdateCompressedBackendTexture(const GrBackendTexture & backendTexture,sk_sp<skgpu::RefCntedCallback> finishedCallback,const void * data,size_t size)1563 bool GrD3DGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1564 sk_sp<skgpu::RefCntedCallback> finishedCallback,
1565 const void* data,
1566 size_t size) {
1567 GrD3DTextureResourceInfo info;
1568 SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1569
1570 sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1571 SkASSERT(state);
1572 sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this,
1573 backendTexture.dimensions(),
1574 GrWrapCacheable::kNo,
1575 kRW_GrIOType,
1576 info,
1577 std::move(state));
1578 if (!texture) {
1579 return false;
1580 }
1581
1582 GrD3DDirectCommandList* cmdList = this->currentCommandList();
1583 if (!cmdList) {
1584 return false;
1585 }
1586
1587 texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1588
1589 ID3D12Resource* d3dResource = texture->d3dResource();
1590 SkASSERT(d3dResource);
1591 D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1592 unsigned int mipLevelCount = 1;
1593 if (backendTexture.hasMipmaps()) {
1594 mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions().width(),
1595 backendTexture.dimensions().height()) + 1;
1596 }
1597 SkASSERT(mipLevelCount == info.fLevelCount);
1598 AutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1599 UINT64 combinedBufferSize;
1600 AutoTMalloc<UINT> numRows(mipLevelCount);
1601 AutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount);
1602 fDevice->GetCopyableFootprints(&desc,
1603 0,
1604 mipLevelCount,
1605 0,
1606 placedFootprints.get(),
1607 numRows.get(),
1608 rowSizeInBytes.get(),
1609 &combinedBufferSize);
1610 SkASSERT(combinedBufferSize);
1611 SkASSERT(GrDxgiFormatIsCompressed(info.fFormat));
1612
1613 GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1614 combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1615 if (!slice.fBuffer) {
1616 return false;
1617 }
1618
1619 char* bufferData = (char*)slice.fOffsetMapPtr;
1620 SkASSERT(bufferData);
1621 copy_compressed_data(bufferData,
1622 info.fFormat,
1623 placedFootprints.get(),
1624 numRows.get(),
1625 rowSizeInBytes.get(),
1626 data,
1627 info.fLevelCount);
1628
1629 // Update the offsets in the footprints to be relative to the slice's offset
1630 for (unsigned int i = 0; i < mipLevelCount; ++i) {
1631 placedFootprints[i].Offset += slice.fOffset;
1632 }
1633
1634 ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1635 cmdList->copyBufferToTexture(d3dBuffer,
1636 texture.get(),
1637 mipLevelCount,
1638 placedFootprints.get(),
1639 0,
1640 0);
1641
1642 if (finishedCallback) {
1643 this->addFinishedCallback(std::move(finishedCallback));
1644 }
1645
1646 return true;
1647 }
1648
deleteBackendTexture(const GrBackendTexture & tex)1649 void GrD3DGpu::deleteBackendTexture(const GrBackendTexture& tex) {
1650 SkASSERT(GrBackendApi::kDirect3D == tex.fBackend);
1651 // Nothing to do here, will get cleaned up when the GrBackendTexture object goes away
1652 }
1653
compile(const GrProgramDesc &,const GrProgramInfo &)1654 bool GrD3DGpu::compile(const GrProgramDesc&, const GrProgramInfo&) {
1655 return false;
1656 }
1657
1658 #if defined(GPU_TEST_UTILS)
isTestingOnlyBackendTexture(const GrBackendTexture & tex) const1659 bool GrD3DGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const {
1660 SkASSERT(GrBackendApi::kDirect3D == tex.backend());
1661
1662 GrD3DTextureResourceInfo info;
1663 if (!tex.getD3DTextureResourceInfo(&info)) {
1664 return false;
1665 }
1666 ID3D12Resource* textureResource = info.fResource.get();
1667 if (!textureResource) {
1668 return false;
1669 }
1670 return !(textureResource->GetDesc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
1671 }
1672
createTestingOnlyBackendRenderTarget(SkISize dimensions,GrColorType colorType,int sampleCnt,GrProtected isProtected)1673 GrBackendRenderTarget GrD3DGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions,
1674 GrColorType colorType,
1675 int sampleCnt,
1676 GrProtected isProtected) {
1677 if (dimensions.width() > this->caps()->maxRenderTargetSize() ||
1678 dimensions.height() > this->caps()->maxRenderTargetSize()) {
1679 return {};
1680 }
1681
1682 DXGI_FORMAT dxgiFormat = this->d3dCaps().getFormatFromColorType(colorType);
1683
1684 GrD3DTextureResourceInfo info;
1685 if (!this->createTextureResourceForBackendSurface(dxgiFormat,
1686 dimensions,
1687 GrTexturable::kNo,
1688 GrRenderable::kYes,
1689 skgpu::Mipmapped::kNo,
1690 sampleCnt,
1691 &info,
1692 isProtected)) {
1693 return {};
1694 }
1695
1696 return GrBackendRenderTarget(dimensions.width(), dimensions.height(), info);
1697 }
1698
deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget & rt)1699 void GrD3DGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& rt) {
1700 SkASSERT(GrBackendApi::kDirect3D == rt.backend());
1701
1702 GrD3DTextureResourceInfo info;
1703 if (rt.getD3DTextureResourceInfo(&info)) {
1704 GrSubmitInfo submitInfo;
1705 submitInfo.fSync = GrSyncCpu::kYes;
1706
1707 this->submitToGpu(submitInfo);
1708 // Nothing else to do here, will get cleaned up when the GrBackendRenderTarget
1709 // is deleted.
1710 }
1711 }
1712
testingOnly_startCapture()1713 void GrD3DGpu::testingOnly_startCapture() {
1714 if (fGraphicsAnalysis) {
1715 fGraphicsAnalysis->BeginCapture();
1716 }
1717 }
1718
testingOnly_stopCapture()1719 void GrD3DGpu::testingOnly_stopCapture() {
1720 if (fGraphicsAnalysis) {
1721 fGraphicsAnalysis->EndCapture();
1722 }
1723 }
1724 #endif
1725
1726 ///////////////////////////////////////////////////////////////////////////////
1727
addResourceBarriers(sk_sp<GrManagedResource> resource,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1728 void GrD3DGpu::addResourceBarriers(sk_sp<GrManagedResource> resource,
1729 int numBarriers,
1730 D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1731 SkASSERT(fCurrentDirectCommandList);
1732 SkASSERT(resource);
1733
1734 fCurrentDirectCommandList->resourceBarrier(std::move(resource), numBarriers, barriers);
1735 }
1736
addBufferResourceBarriers(GrD3DBuffer * buffer,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1737 void GrD3DGpu::addBufferResourceBarriers(GrD3DBuffer* buffer,
1738 int numBarriers,
1739 D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1740 SkASSERT(fCurrentDirectCommandList);
1741 SkASSERT(buffer);
1742
1743 fCurrentDirectCommandList->resourceBarrier(nullptr, numBarriers, barriers);
1744 fCurrentDirectCommandList->addGrBuffer(sk_ref_sp<const GrBuffer>(buffer));
1745 }
1746
prepareSurfacesForBackendAccessAndStateUpdates(SkSpan<GrSurfaceProxy * > proxies,SkSurfaces::BackendSurfaceAccess access,const skgpu::MutableTextureState * newState)1747 void GrD3DGpu::prepareSurfacesForBackendAccessAndStateUpdates(
1748 SkSpan<GrSurfaceProxy*> proxies,
1749 SkSurfaces::BackendSurfaceAccess access,
1750 const skgpu::MutableTextureState* newState) {
1751 // prepare proxies by transitioning to PRESENT renderState
1752 if (!proxies.empty() && access == SkSurfaces::BackendSurfaceAccess::kPresent) {
1753 GrD3DTextureResource* resource;
1754 for (GrSurfaceProxy* proxy : proxies) {
1755 SkASSERT(proxy->isInstantiated());
1756 if (GrTexture* tex = proxy->peekTexture()) {
1757 resource = static_cast<GrD3DTexture*>(tex);
1758 } else {
1759 GrRenderTarget* rt = proxy->peekRenderTarget();
1760 SkASSERT(rt);
1761 resource = static_cast<GrD3DRenderTarget*>(rt);
1762 }
1763 resource->prepareForPresent(this);
1764 }
1765 }
1766 }
1767
takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer)1768 void GrD3DGpu::takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer) {
1769 fCurrentDirectCommandList->addGrBuffer(std::move(buffer));
1770 }
1771
onSubmitToGpu(const GrSubmitInfo & info)1772 bool GrD3DGpu::onSubmitToGpu(const GrSubmitInfo& info) {
1773 if (info.fSync == GrSyncCpu::kYes) {
1774 return this->submitDirectCommandList(SyncQueue::kForce);
1775 } else {
1776 return this->submitDirectCommandList(SyncQueue::kSkip);
1777 }
1778 }
1779
makeSemaphore(bool)1780 [[nodiscard]] std::unique_ptr<GrSemaphore> GrD3DGpu::makeSemaphore(bool) {
1781 return GrD3DSemaphore::Make(this);
1782 }
wrapBackendSemaphore(const GrBackendSemaphore & semaphore,GrSemaphoreWrapType,GrWrapOwnership)1783 std::unique_ptr<GrSemaphore> GrD3DGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore,
1784 GrSemaphoreWrapType /* wrapType */,
1785 GrWrapOwnership /* ownership */) {
1786 SkASSERT(this->caps()->backendSemaphoreSupport());
1787 GrD3DFenceInfo fenceInfo;
1788 if (!semaphore.getD3DFenceInfo(&fenceInfo)) {
1789 return nullptr;
1790 }
1791 return GrD3DSemaphore::MakeWrapped(fenceInfo);
1792 }
1793
insertSemaphore(GrSemaphore * semaphore)1794 void GrD3DGpu::insertSemaphore(GrSemaphore* semaphore) {
1795 SkASSERT(semaphore);
1796 GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1797 // TODO: Do we need to track the lifetime of this? How do we know it's done?
1798 fQueue->Signal(d3dSem->fence(), d3dSem->value());
1799 }
1800
waitSemaphore(GrSemaphore * semaphore)1801 void GrD3DGpu::waitSemaphore(GrSemaphore* semaphore) {
1802 SkASSERT(semaphore);
1803 GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1804 // TODO: Do we need to track the lifetime of this?
1805 fQueue->Wait(d3dSem->fence(), d3dSem->value());
1806 }
1807
finishOutstandingGpuWork()1808 void GrD3DGpu::finishOutstandingGpuWork() {
1809 this->waitForQueueCompletion();
1810 }
1811