xref: /aosp_15_r20/external/skia/src/gpu/graphite/dawn/DawnCaps.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2022 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/graphite/dawn/DawnCaps.h"
9 
10 #include <algorithm>
11 #include <string>
12 
13 #include "include/core/SkTextureCompressionType.h"
14 #include "include/gpu/graphite/ContextOptions.h"
15 #include "include/gpu/graphite/TextureInfo.h"
16 #include "include/gpu/graphite/dawn/DawnBackendContext.h"
17 #include "src/gpu/SwizzlePriv.h"
18 #include "src/gpu/graphite/ComputePipelineDesc.h"
19 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
20 #include "src/gpu/graphite/GraphiteResourceKey.h"
21 #include "src/gpu/graphite/RenderPassDesc.h"
22 #include "src/gpu/graphite/RendererProvider.h"
23 #include "src/gpu/graphite/ResourceTypes.h"
24 #include "src/gpu/graphite/UniformManager.h"
25 #include "src/gpu/graphite/dawn/DawnGraphicsPipeline.h"
26 #include "src/gpu/graphite/dawn/DawnGraphiteTypesPriv.h"
27 #include "src/gpu/graphite/dawn/DawnGraphiteUtilsPriv.h"
28 #include "src/gpu/graphite/dawn/DawnUtilsPriv.h"
29 #include "src/sksl/SkSLUtil.h"
30 
31 #if defined(__EMSCRIPTEN__)
32 #include <emscripten/version.h>
33 #endif
34 
35 namespace {
36 
get_pipeline_domain()37 skgpu::UniqueKey::Domain get_pipeline_domain() {
38     static const skgpu::UniqueKey::Domain kDawnGraphicsPipelineDomain =
39             skgpu::UniqueKey::GenerateDomain();
40 
41     return kDawnGraphicsPipelineDomain;
42 }
43 
44 // These are all the valid wgpu::TextureFormat that we currently support in Skia.
45 // They are roughly ordered from most frequently used to least to improve lookup times in arrays.
46 static constexpr wgpu::TextureFormat kFormats[] = {
47         wgpu::TextureFormat::RGBA8Unorm,
48         wgpu::TextureFormat::R8Unorm,
49 #if !defined(__EMSCRIPTEN__)
50         wgpu::TextureFormat::R16Unorm,
51 #endif
52         wgpu::TextureFormat::BGRA8Unorm,
53         wgpu::TextureFormat::RGBA16Float,
54         wgpu::TextureFormat::R16Float,
55         wgpu::TextureFormat::RG8Unorm,
56 #if !defined(__EMSCRIPTEN__)
57         wgpu::TextureFormat::RG16Unorm,
58 #endif
59         wgpu::TextureFormat::RGB10A2Unorm,
60         wgpu::TextureFormat::RG16Float,
61 
62         wgpu::TextureFormat::Stencil8,
63         wgpu::TextureFormat::Depth16Unorm,
64         wgpu::TextureFormat::Depth32Float,
65         wgpu::TextureFormat::Depth24PlusStencil8,
66 
67         wgpu::TextureFormat::BC1RGBAUnorm,
68         wgpu::TextureFormat::ETC2RGB8Unorm,
69 
70 #if !defined(__EMSCRIPTEN__)
71         wgpu::TextureFormat::External,
72 #endif
73 };
74 
75 #if !defined(__EMSCRIPTEN__)
IsMultiplanarFormat(wgpu::TextureFormat format)76 bool IsMultiplanarFormat(wgpu::TextureFormat format) {
77     switch (format) {
78         case wgpu::TextureFormat::R8BG8Biplanar420Unorm:
79         case wgpu::TextureFormat::R10X6BG10X6Biplanar420Unorm:
80         case wgpu::TextureFormat::R8BG8A8Triplanar420Unorm:
81             return true;
82         default:
83             return false;
84     }
85 }
86 #endif
87 }  // anonymous namespace
88 
89 namespace skgpu::graphite {
90 
DawnCaps(const DawnBackendContext & backendContext,const ContextOptions & options)91 DawnCaps::DawnCaps(const DawnBackendContext& backendContext, const ContextOptions& options)
92     : Caps() {
93     this->initCaps(backendContext, options);
94     this->initShaderCaps(backendContext.fDevice);
95     this->initFormatTable(backendContext.fDevice);
96     this->finishInitialization(options);
97 }
98 
99 DawnCaps::~DawnCaps() = default;
100 
channelMask(const TextureInfo & info) const101 uint32_t DawnCaps::channelMask(const TextureInfo& info) const {
102     return DawnFormatChannels(TextureInfos::GetDawnTextureSpec(info).getViewFormat());
103 }
104 
onIsTexturable(const TextureInfo & info) const105 bool DawnCaps::onIsTexturable(const TextureInfo& info) const {
106     if (!info.isValid()) {
107         return false;
108     }
109 
110     const DawnTextureSpec spec = TextureInfos::GetDawnTextureSpec(info);
111 
112     if (!(spec.fUsage & wgpu::TextureUsage::TextureBinding)) {
113         return false;
114     }
115 
116 #if !defined(__EMSCRIPTEN__)
117     switch (spec.fFormat) {
118         case wgpu::TextureFormat::R8BG8Biplanar420Unorm: {
119             if (spec.fAspect == wgpu::TextureAspect::Plane0Only &&
120                 spec.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
121                 return false;
122             }
123             if (spec.fAspect == wgpu::TextureAspect::Plane1Only &&
124                 spec.getViewFormat() != wgpu::TextureFormat::RG8Unorm) {
125                 return false;
126             }
127             break;
128         }
129         case wgpu::TextureFormat::R10X6BG10X6Biplanar420Unorm: {
130             if (spec.fAspect == wgpu::TextureAspect::Plane0Only &&
131                 spec.getViewFormat() != wgpu::TextureFormat::R16Unorm) {
132                 return false;
133             }
134             if (spec.fAspect == wgpu::TextureAspect::Plane1Only &&
135                 spec.getViewFormat() != wgpu::TextureFormat::RG16Unorm) {
136                 return false;
137             }
138             break;
139         }
140         case wgpu::TextureFormat::R8BG8A8Triplanar420Unorm: {
141             if (spec.fAspect == wgpu::TextureAspect::Plane0Only &&
142                 spec.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
143                 return false;
144             }
145             if (spec.fAspect == wgpu::TextureAspect::Plane1Only &&
146                 spec.getViewFormat() != wgpu::TextureFormat::RG8Unorm) {
147                 return false;
148             }
149             if (spec.fAspect == wgpu::TextureAspect::Plane2Only &&
150                 spec.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
151                 return false;
152             }
153             break;
154         }
155         default:
156             break;
157     }
158 #endif
159 
160     return this->isTexturable(spec.getViewFormat());
161 }
162 
isTexturable(wgpu::TextureFormat format) const163 bool DawnCaps::isTexturable(wgpu::TextureFormat format) const {
164     const FormatInfo& formatInfo = this->getFormatInfo(format);
165     return SkToBool(FormatInfo::kTexturable_Flag & formatInfo.fFlags);
166 }
167 
isRenderable(const TextureInfo & info) const168 bool DawnCaps::isRenderable(const TextureInfo& info) const {
169     const DawnTextureSpec spec = TextureInfos::GetDawnTextureSpec(info);
170 
171     return info.isValid() && (spec.fUsage & wgpu::TextureUsage::RenderAttachment) &&
172            this->isRenderable(spec.getViewFormat(), info.numSamples());
173 }
174 
isStorage(const TextureInfo & info) const175 bool DawnCaps::isStorage(const TextureInfo& info) const {
176     if (!info.isValid()) {
177         return false;
178     }
179     const DawnTextureSpec spec = TextureInfos::GetDawnTextureSpec(info);
180     if (!(spec.fUsage & wgpu::TextureUsage::StorageBinding)) {
181         return false;
182     }
183     const FormatInfo& formatInfo = this->getFormatInfo(spec.getViewFormat());
184     return info.numSamples() == 1 && SkToBool(FormatInfo::kStorage_Flag & formatInfo.fFlags);
185 }
186 
maxRenderTargetSampleCount(wgpu::TextureFormat format) const187 uint32_t DawnCaps::maxRenderTargetSampleCount(wgpu::TextureFormat format) const {
188     const FormatInfo& formatInfo = this->getFormatInfo(format);
189     if (!SkToBool(formatInfo.fFlags & FormatInfo::kRenderable_Flag)) {
190         return 0;
191     }
192     if (SkToBool(formatInfo.fFlags & FormatInfo::kMSAA_Flag)) {
193         return 8;
194     } else {
195         return 1;
196     }
197 }
198 
isRenderable(wgpu::TextureFormat format,uint32_t sampleCount) const199 bool DawnCaps::isRenderable(wgpu::TextureFormat format, uint32_t sampleCount) const {
200     return sampleCount <= this->maxRenderTargetSampleCount(format);
201 }
202 
getDefaultSampledTextureInfo(SkColorType colorType,Mipmapped mipmapped,Protected,Renderable renderable) const203 TextureInfo DawnCaps::getDefaultSampledTextureInfo(SkColorType colorType,
204                                                    Mipmapped mipmapped,
205                                                    Protected,
206                                                    Renderable renderable) const {
207     wgpu::TextureUsage usage = wgpu::TextureUsage::TextureBinding |
208                                wgpu::TextureUsage::CopyDst |
209                                wgpu::TextureUsage::CopySrc;
210     if (renderable == Renderable::kYes) {
211         usage |= wgpu::TextureUsage::RenderAttachment;
212     }
213 
214     wgpu::TextureFormat format = this->getFormatFromColorType(colorType);
215     if (format == wgpu::TextureFormat::Undefined) {
216         return {};
217     }
218 
219     DawnTextureInfo info;
220     info.fSampleCount = 1;
221     info.fMipmapped = mipmapped;
222     info.fFormat = format;
223     info.fViewFormat = format;
224     info.fUsage = usage;
225 
226     return TextureInfos::MakeDawn(info);
227 }
228 
getTextureInfoForSampledCopy(const TextureInfo & textureInfo,Mipmapped mipmapped) const229 TextureInfo DawnCaps::getTextureInfoForSampledCopy(const TextureInfo& textureInfo,
230                                                    Mipmapped mipmapped) const {
231     DawnTextureInfo info;
232     if (!TextureInfos::GetDawnTextureInfo(textureInfo, &info)) {
233         return {};
234     }
235 
236     info.fSampleCount = 1;
237     info.fMipmapped = mipmapped;
238     info.fUsage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopyDst |
239                   wgpu::TextureUsage::CopySrc;
240 
241     return TextureInfos::MakeDawn(info);
242 }
243 
244 namespace {
format_from_compression(SkTextureCompressionType compression)245 wgpu::TextureFormat format_from_compression(SkTextureCompressionType compression) {
246     switch (compression) {
247         case SkTextureCompressionType::kETC2_RGB8_UNORM:
248             return wgpu::TextureFormat::ETC2RGB8Unorm;
249         case SkTextureCompressionType::kBC1_RGBA8_UNORM:
250             return wgpu::TextureFormat::BC1RGBAUnorm;
251         default:
252             return wgpu::TextureFormat::Undefined;
253     }
254 }
255 }
256 
getDefaultCompressedTextureInfo(SkTextureCompressionType compression,Mipmapped mipmapped,Protected) const257 TextureInfo DawnCaps::getDefaultCompressedTextureInfo(SkTextureCompressionType compression,
258                                                       Mipmapped mipmapped,
259                                                       Protected) const {
260     wgpu::TextureUsage usage = wgpu::TextureUsage::TextureBinding |
261                                wgpu::TextureUsage::CopyDst |
262                                wgpu::TextureUsage::CopySrc;
263 
264     wgpu::TextureFormat format = format_from_compression(compression);
265     if (format == wgpu::TextureFormat::Undefined) {
266         return {};
267     }
268 
269     DawnTextureInfo info;
270     info.fSampleCount = 1;
271     info.fMipmapped = mipmapped;
272     info.fFormat = format;
273     info.fViewFormat = format;
274     info.fUsage = usage;
275 
276     return TextureInfos::MakeDawn(info);
277 }
278 
getDefaultMSAATextureInfo(const TextureInfo & singleSampledInfo,Discardable discardable) const279 TextureInfo DawnCaps::getDefaultMSAATextureInfo(const TextureInfo& singleSampledInfo,
280                                                 Discardable discardable) const {
281     if (fDefaultMSAASamples <= 1) {
282         return {};
283     }
284     const DawnTextureSpec singleSpec = TextureInfos::GetDawnTextureSpec(singleSampledInfo);
285 
286     DawnTextureInfo info;
287     info.fSampleCount = fDefaultMSAASamples;
288     info.fMipmapped   = Mipmapped::kNo;
289     info.fFormat      = singleSpec.fFormat;
290     info.fViewFormat  = singleSpec.fFormat;
291     info.fUsage       = wgpu::TextureUsage::RenderAttachment;
292 
293     if (fSupportedTransientAttachmentUsage != wgpu::TextureUsage::None &&
294         discardable == Discardable::kYes) {
295         info.fUsage |= fSupportedTransientAttachmentUsage;
296     }
297 
298     return TextureInfos::MakeDawn(info);
299 }
300 
getDefaultDepthStencilTextureInfo(SkEnumBitMask<DepthStencilFlags> depthStencilType,uint32_t sampleCount,Protected) const301 TextureInfo DawnCaps::getDefaultDepthStencilTextureInfo(
302     SkEnumBitMask<DepthStencilFlags> depthStencilType,
303     uint32_t sampleCount,
304     Protected) const {
305     DawnTextureInfo info;
306     info.fSampleCount = sampleCount;
307     info.fMipmapped   = Mipmapped::kNo;
308     info.fFormat      = DawnDepthStencilFlagsToFormat(depthStencilType);
309     info.fViewFormat  = info.fFormat;
310     info.fUsage       = wgpu::TextureUsage::RenderAttachment;
311 
312     if (fSupportedTransientAttachmentUsage != wgpu::TextureUsage::None) {
313         info.fUsage |= fSupportedTransientAttachmentUsage;
314     }
315 
316     return TextureInfos::MakeDawn(info);
317 }
318 
getDefaultStorageTextureInfo(SkColorType colorType) const319 TextureInfo DawnCaps::getDefaultStorageTextureInfo(SkColorType colorType) const {
320     wgpu::TextureFormat format = this->getFormatFromColorType(colorType);
321     if (format == wgpu::TextureFormat::Undefined) {
322         SkDebugf("colorType=%d is not supported\n", static_cast<int>(colorType));
323         return {};
324     }
325 
326     const FormatInfo& formatInfo = this->getFormatInfo(format);
327     if (!SkToBool(FormatInfo::kStorage_Flag & formatInfo.fFlags)) {
328         return {};
329     }
330 
331     wgpu::TextureUsage usage = wgpu::TextureUsage::StorageBinding |
332                                wgpu::TextureUsage::TextureBinding |
333                                wgpu::TextureUsage::CopySrc;
334     DawnTextureInfo info;
335     info.fSampleCount = 1;
336     info.fMipmapped = Mipmapped::kNo;
337     info.fFormat = format;
338     info.fViewFormat = format;
339     info.fUsage = usage;
340 
341     return TextureInfos::MakeDawn(info);
342 }
343 
getDepthAttachmentDimensions(const TextureInfo & textureInfo,const SkISize colorAttachmentDimensions) const344 SkISize DawnCaps::getDepthAttachmentDimensions(const TextureInfo& textureInfo,
345                                                const SkISize colorAttachmentDimensions) const {
346 #if !defined(__EMSCRIPTEN__)
347     // For multiplanar textures, texture->textureInfo() uses the format of planes instead of
348     // textures (R8, R8G8, vs R8BG8Biplanar420Unorm), so we have to query texture format from
349     // wgpu::Texture object, and then use it reconstruct the full dimensions.
350     const auto dawnTextureSpec = TextureInfos::GetDawnTextureSpec(textureInfo);
351     wgpu::TextureFormat format = dawnTextureSpec.fFormat;
352     if (IsMultiplanarFormat(format) && dawnTextureSpec.fAspect == wgpu::TextureAspect::Plane1Only) {
353         // Dawn requires depth attachment to match the size of Y plane (texture size).
354         return SkISize::Make(colorAttachmentDimensions.width() * 2,
355                              colorAttachmentDimensions.height() * 2);
356     }
357 #endif
358 
359     return colorAttachmentDimensions;
360 }
361 
getColorTypeInfo(SkColorType colorType,const TextureInfo & textureInfo) const362 const Caps::ColorTypeInfo* DawnCaps::getColorTypeInfo(SkColorType colorType,
363                                                       const TextureInfo& textureInfo) const {
364     auto dawnFormat = TextureInfos::GetDawnTextureSpec(textureInfo).getViewFormat();
365     if (dawnFormat == wgpu::TextureFormat::Undefined) {
366         SkASSERT(false);
367         return nullptr;
368     }
369 
370     const FormatInfo& info = this->getFormatInfo(dawnFormat);
371     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
372         const ColorTypeInfo& ctInfo = info.fColorTypeInfos[i];
373         if (ctInfo.fColorType == colorType) {
374             return &ctInfo;
375         }
376     }
377 
378     return nullptr;
379 }
380 
supportsWritePixels(const TextureInfo & textureInfo) const381 bool DawnCaps::supportsWritePixels(const TextureInfo& textureInfo) const {
382     const auto spec = TextureInfos::GetDawnTextureSpec(textureInfo);
383     return spec.fUsage & wgpu::TextureUsage::CopyDst;
384 }
385 
supportsReadPixels(const TextureInfo & textureInfo) const386 bool DawnCaps::supportsReadPixels(const TextureInfo& textureInfo) const {
387     const auto spec = TextureInfos::GetDawnTextureSpec(textureInfo);
388     return spec.fUsage & wgpu::TextureUsage::CopySrc;
389 }
390 
supportedWritePixelsColorType(SkColorType dstColorType,const TextureInfo & dstTextureInfo,SkColorType srcColorType) const391 std::pair<SkColorType, bool /*isRGBFormat*/> DawnCaps::supportedWritePixelsColorType(
392         SkColorType dstColorType,
393         const TextureInfo& dstTextureInfo,
394         SkColorType srcColorType) const {
395     return {dstColorType, false};
396 }
397 
supportedReadPixelsColorType(SkColorType srcColorType,const TextureInfo & srcTextureInfo,SkColorType dstColorType) const398 std::pair<SkColorType, bool /*isRGBFormat*/> DawnCaps::supportedReadPixelsColorType(
399         SkColorType srcColorType,
400         const TextureInfo& srcTextureInfo,
401         SkColorType dstColorType) const {
402     auto dawnFormat = getFormatFromColorType(srcColorType);
403     const FormatInfo& info = this->getFormatInfo(dawnFormat);
404     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
405         const auto& ctInfo = info.fColorTypeInfos[i];
406         if (ctInfo.fColorType == srcColorType) {
407             return {srcColorType, false};
408         }
409     }
410     return {kUnknown_SkColorType, false};
411 }
412 
initCaps(const DawnBackendContext & backendContext,const ContextOptions & options)413 void DawnCaps::initCaps(const DawnBackendContext& backendContext, const ContextOptions& options) {
414     // GetAdapter() is not available in WASM and there's no way to get AdapterInfo off of
415     // the WGPUDevice directly.
416 #if !defined(__EMSCRIPTEN__)
417     wgpu::AdapterInfo info;
418     backendContext.fDevice.GetAdapter().GetInfo(&info);
419 
420 #if defined(GPU_TEST_UTILS)
421     this->setDeviceName(std::string(info.device));
422 #endif
423 #endif // defined(__EMSCRIPTEN__)
424 
425     wgpu::SupportedLimits limits;
426 #if defined(__EMSCRIPTEN__)
427     // TODO(crbug.com/42241199): Update Emscripten path with when webgpu.h in Emscripten is updated.
428     [[maybe_unused]] bool limitsSucceeded = backendContext.fDevice.GetLimits(&limits);
429 #if (__EMSCRIPTEN_major__ > 3 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ > 1) || \
430      (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ > 50))
431     // In Emscripten this always "fails" until
432     // https://github.com/emscripten-core/emscripten/pull/20808, which was first included in 3.1.51.
433     SkASSERT(limitsSucceeded);
434 #endif
435 #else
436     wgpu::DawnTexelCopyBufferRowAlignmentLimits alignmentLimits{};
437     if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnTexelCopyBufferRowAlignment)) {
438         limits.nextInChain = &alignmentLimits;
439     }
440     [[maybe_unused]] wgpu::Status status = backendContext.fDevice.GetLimits(&limits);
441     SkASSERT(status == wgpu::Status::Success);
442 #endif
443 
444     fMaxTextureSize = limits.limits.maxTextureDimension2D;
445 
446     fRequiredTransferBufferAlignment = 4;
447     fRequiredUniformBufferAlignment = limits.limits.minUniformBufferOffsetAlignment;
448     fRequiredStorageBufferAlignment = limits.limits.minStorageBufferOffsetAlignment;
449 
450     // Dawn requires 256 bytes per row alignment for buffer texture copies.
451     fTextureDataRowBytesAlignment = 256;
452 #if !defined(__EMSCRIPTEN__)
453     // If the device supports the DawnTexelCopyBufferRowAlignment feature, the alignment can be
454     // queried from its limits.
455     if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnTexelCopyBufferRowAlignment)) {
456         fTextureDataRowBytesAlignment = alignmentLimits.minTexelCopyBufferRowAlignment;
457     }
458 #endif
459 
460     fResourceBindingReqs.fUniformBufferLayout = Layout::kStd140;
461     // The WGSL generator assumes tightly packed std430 layout for SSBOs which is also the default
462     // for all types outside the uniform address space in WGSL.
463     fResourceBindingReqs.fStorageBufferLayout = Layout::kStd430;
464     fResourceBindingReqs.fSeparateTextureAndSamplerBinding = true;
465 
466     fResourceBindingReqs.fIntrinsicBufferBinding =
467             DawnGraphicsPipeline::kIntrinsicUniformBufferIndex;
468     fResourceBindingReqs.fRenderStepBufferBinding =
469             DawnGraphicsPipeline::kRenderStepUniformBufferIndex;
470     fResourceBindingReqs.fPaintParamsBufferBinding = DawnGraphicsPipeline::kPaintUniformBufferIndex;
471     fResourceBindingReqs.fGradientBufferBinding = DawnGraphicsPipeline::kGradientBufferIndex;
472 
473 #if !defined(__EMSCRIPTEN__)
474     // TODO(b/344963958): SSBOs contribute to OOB shader memory access and dawn device loss on
475     // Android. Once the problem is fixed SSBOs can be enabled again.
476     fStorageBufferSupport = info.backendType != wgpu::BackendType::OpenGL &&
477                             info.backendType != wgpu::BackendType::OpenGLES &&
478                             info.backendType != wgpu::BackendType::Vulkan;
479 #else
480     // WASM doesn't provide a way to query the backend, so can't tell if we are on a backend that
481     // needs to have SSBOs disabled. Pessimistically assume we could be. Once the above conditions
482     // go away in Dawn-native, then we can assume SSBOs are always supported in pure WebGPU too.
483     fStorageBufferSupport = false;
484 #endif
485 
486     fDrawBufferCanBeMapped = false;
487 
488     fComputeSupport = true;
489 
490     // TODO: support clamp to border.
491     fClampToBorderSupport = false;
492 
493 #if defined(GPU_TEST_UTILS)
494     fDrawBufferCanBeMappedForReadback = false;
495 #endif
496 
497 #if defined(__EMSCRIPTEN__)
498     // For wasm, we use async map.
499     fBufferMapsAreAsync = true;
500 #else
501     // For Dawn native, we use direct mapping.
502     fBufferMapsAreAsync = false;
503     fDrawBufferCanBeMapped =
504             backendContext.fDevice.HasFeature(wgpu::FeatureName::BufferMapExtendedUsages);
505 
506     fMSAARenderToSingleSampledSupport =
507             backendContext.fDevice.HasFeature(wgpu::FeatureName::MSAARenderToSingleSampled);
508 
509     if (backendContext.fDevice.HasFeature(wgpu::FeatureName::TransientAttachments)) {
510         fSupportedTransientAttachmentUsage = wgpu::TextureUsage::TransientAttachment;
511     }
512     if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnLoadResolveTexture)) {
513         fSupportedResolveTextureLoadOp = wgpu::LoadOp::ExpandResolveTexture;
514     }
515     fSupportsPartialLoadResolve =
516             backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnPartialLoadResolveTexture);
517 #endif
518 
519     if (backendContext.fDevice.HasFeature(wgpu::FeatureName::TimestampQuery)) {
520         // Native Dawn has an API for writing timestamps on command buffers. WebGPU only supports
521         // begin and end timestamps on render and compute passes.
522 #if !defined(__EMSCRIPTEN__)
523         fSupportsCommandBufferTimestamps = true;
524 #endif
525 
526         // The emscripten C/C++ interface before 3.1.48 for timestamp query writes on render and
527         // compute passes is different than on current emsdk. The older API isn't correctly
528         // translated to the current JS WebGPU API in emsdk. So we require 3.1.48+.
529 #if !defined(__EMSCRIPTEN__)                                                                   \
530         || (__EMSCRIPTEN_major__ > 3)                                                          \
531         || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ > 1)                             \
532         || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ >= 48)
533         fSupportedGpuStats |= GpuStatsFlags::kElapsedTime;
534 #endif
535     }
536 
537     if (!backendContext.fTick) {
538         fAllowCpuSync = false;
539         // This seems paradoxical. However, if we use the async pipeline creation methods (e.g
540         // Device::CreateRenderPipelineAsync) then we may have to synchronize before a submit that
541         // uses the pipeline. If we use the methods that look synchronous (e.g.
542         // Device::CreateRenderPipeline) they actually operate asynchronously on WebGPU but the
543         // browser becomes responsible for synchronizing when we call submit.
544         fUseAsyncPipelineCreation = false;
545 
546         // The implementation busy waits after popping.
547         fAllowScopedErrorChecks = false;
548     }
549 
550     fFullCompressedUploadSizeMustAlignToBlockDims = true;
551 }
552 
initShaderCaps(const wgpu::Device & device)553 void DawnCaps::initShaderCaps(const wgpu::Device& device) {
554     SkSL::ShaderCaps* shaderCaps = fShaderCaps.get();
555 
556     // WGSL does not support infinities regardless of hardware support. There are discussions around
557     // enabling it using an extension in the future.
558     shaderCaps->fInfinitySupport = false;
559 
560     // WGSL supports shader derivatives in the fragment shader
561     shaderCaps->fShaderDerivativeSupport = true;
562 
563 #if !defined(__EMSCRIPTEN__)
564     if (device.HasFeature(wgpu::FeatureName::DualSourceBlending)) {
565         shaderCaps->fDualSourceBlendingSupport = true;
566     }
567     if (device.HasFeature(wgpu::FeatureName::FramebufferFetch)) {
568         shaderCaps->fFBFetchSupport = true;
569     }
570 #endif
571 }
572 
initFormatTable(const wgpu::Device & device)573 void DawnCaps::initFormatTable(const wgpu::Device& device) {
574     FormatInfo* info;
575     // Format: RGBA8Unorm
576     {
577         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGBA8Unorm)];
578         info->fFlags = FormatInfo::kAllFlags;
579         info->fColorTypeInfoCount = 2;
580         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
581         int ctIdx = 0;
582         // Format: RGBA8Unorm, Surface: kRGBA_8888
583         {
584             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
585             ctInfo.fColorType = kRGBA_8888_SkColorType;
586             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
587         }
588         // Format: RGBA8Unorm, Surface: kRGB_888x
589         {
590             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
591             ctInfo.fColorType = kRGB_888x_SkColorType;
592             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
593             ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
594         }
595     }
596 
597     // Format: R8Unorm
598     {
599         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R8Unorm)];
600 #if !defined(__EMSCRIPTEN__)
601         info->fFlags = FormatInfo::kAllFlags;
602         if (!device.HasFeature(wgpu::FeatureName::R8UnormStorage)) {
603             info->fFlags &= ~FormatInfo::kStorage_Flag;
604         }
605 #else
606         info->fFlags = FormatInfo::kAllFlags & ~FormatInfo::kStorage_Flag;
607 #endif
608         info->fColorTypeInfoCount = 3;
609         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
610         int ctIdx = 0;
611         // Format: R8Unorm, Surface: kR8_unorm
612         {
613             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
614             ctInfo.fColorType = kR8_unorm_SkColorType;
615             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
616         }
617         // Format: R8Unorm, Surface: kAlpha_8
618         {
619             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
620             ctInfo.fColorType = kAlpha_8_SkColorType;
621             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
622             ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
623             ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
624         }
625         // Format: R8Unorm, Surface: kGray_8
626         {
627             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
628             ctInfo.fColorType = kGray_8_SkColorType;
629             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
630             ctInfo.fReadSwizzle = skgpu::Swizzle("rrr1");
631         }
632     }
633 
634 #if !defined(__EMSCRIPTEN__)
635     const bool supportUnorm16 = device.HasFeature(wgpu::FeatureName::Unorm16TextureFormats);
636     // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
637     // Format: R16Unorm
638     {
639         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R16Unorm)];
640         if (supportUnorm16) {
641             info->fFlags = FormatInfo::kAllFlags & ~FormatInfo::kStorage_Flag;
642             info->fColorTypeInfoCount = 1;
643             info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
644             int ctIdx = 0;
645             // Format: R16Unorm, Surface: kA16_unorm
646             {
647                 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
648                 ctInfo.fColorType = kA16_unorm_SkColorType;
649                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
650                 ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
651                 ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
652             }
653         }
654     }
655 #endif
656 
657     // Format: BGRA8Unorm
658     {
659         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::BGRA8Unorm)];
660         info->fFlags = FormatInfo::kAllFlags;
661         info->fColorTypeInfoCount = 2;
662         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
663         int ctIdx = 0;
664         // Format: BGRA8Unorm, Surface: kBGRA_8888
665         {
666             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
667             ctInfo.fColorType = kBGRA_8888_SkColorType;
668             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
669         }
670         // Format: BGRA8Unorm, Surface: kRGB_888x
671         {
672             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
673             ctInfo.fColorType = kRGB_888x_SkColorType;
674             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
675         }
676     }
677 
678     // Format: RGBA16Float
679     {
680         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGBA16Float)];
681         info->fFlags = FormatInfo::kAllFlags;
682         info->fColorTypeInfoCount = 2;
683         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
684         int ctIdx = 0;
685         // Format: RGBA16Float, Surface: RGBA_F16
686         {
687             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
688             ctInfo.fColorType = kRGBA_F16_SkColorType;
689             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
690         }
691         // Format: RGBA16Float, Surface: RGB_F16F16F16x
692         {
693             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
694             ctInfo.fColorType = kRGBA_F16_SkColorType;
695             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
696             ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
697         }
698     }
699 
700     // Format: R16Float
701     {
702         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R16Float)];
703         info->fFlags = FormatInfo::kAllFlags;
704         info->fColorTypeInfoCount = 1;
705         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
706         int ctIdx = 0;
707         // Format: R16Float, Surface: kA16_float
708         {
709             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
710             ctInfo.fColorType = kA16_float_SkColorType;
711             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
712             ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
713             ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
714         }
715     }
716 
717     // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
718     // Format: RG8Unorm
719     {
720         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG8Unorm)];
721         info->fFlags = FormatInfo::kAllFlags;
722         info->fColorTypeInfoCount = 1;
723         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
724         int ctIdx = 0;
725         // Format: RG8Unorm, Surface: kR8G8_unorm
726         {
727             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
728             ctInfo.fColorType = kR8G8_unorm_SkColorType;
729             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
730         }
731     }
732 
733 #if !defined(__EMSCRIPTEN__)
734     // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
735     // Format: RG16Unorm
736     {
737         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG16Unorm)];
738         if (supportUnorm16) {
739             info->fFlags = FormatInfo::kAllFlags;
740             info->fColorTypeInfoCount = 1;
741             info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
742             int ctIdx = 0;
743             // Format: RG16Unorm, Surface: kR16G16_unorm
744             {
745                 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
746                 ctInfo.fColorType = kR16G16_unorm_SkColorType;
747                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
748             }
749         }
750     }
751 #endif
752 
753     // Format: RGB10A2Unorm
754     {
755         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGB10A2Unorm)];
756         info->fFlags = FormatInfo::kAllFlags;
757         info->fColorTypeInfoCount = 2;
758         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
759         int ctIdx = 0;
760         // Format: RGB10A2Unorm, Surface: kRGBA_1010102
761         {
762             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
763             ctInfo.fColorType = kRGBA_1010102_SkColorType;
764             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
765         }
766         // Format: RGB10A2Unorm, Surface: kRGB_101010x
767         {
768             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
769             ctInfo.fColorType = kRGB_101010x_SkColorType;
770             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
771             ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
772         }
773     }
774 
775     // Format: RG16Float
776     {
777         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG16Float)];
778         info->fFlags = FormatInfo::kAllFlags;
779         info->fColorTypeInfoCount = 1;
780         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
781         int ctIdx = 0;
782         // Format: RG16Float, Surface: kR16G16_float
783         {
784             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
785             ctInfo.fColorType = kR16G16_float_SkColorType;
786             ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
787         }
788     }
789 
790     // Format: ETC2RGB8Unorm
791     {
792         if (device.HasFeature(wgpu::FeatureName::TextureCompressionETC2)) {
793             info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::ETC2RGB8Unorm)];
794             info->fFlags = FormatInfo::kTexturable_Flag;
795             info->fColorTypeInfoCount = 1;
796             info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
797             int ctIdx = 0;
798             // Format: ETC2RGB8Unorm, Surface: kRGB_888x
799             {
800                 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
801                 ctInfo.fColorType = kRGB_888x_SkColorType;
802                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
803             }
804         }
805     }
806 
807     // Format: BC1RGBAUnorm
808     {
809         if (device.HasFeature(wgpu::FeatureName::TextureCompressionBC)) {
810             info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::BC1RGBAUnorm)];
811             info->fFlags = FormatInfo::kTexturable_Flag;
812             info->fColorTypeInfoCount = 1;
813             info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
814             int ctIdx = 0;
815             // Format: BC1RGBAUnorm, Surface: kRGBA_8888
816             {
817                 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
818                 ctInfo.fColorType = kRGBA_8888_SkColorType;
819                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
820             }
821         }
822     }
823 
824     /*
825      * Non-color formats
826      */
827 
828     // Format: Stencil8
829     {
830         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Stencil8)];
831         info->fFlags = FormatInfo::kMSAA_Flag;
832         info->fColorTypeInfoCount = 0;
833     }
834 
835     // Format: Depth16UNorm
836     {
837         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth16Unorm)];
838         info->fFlags = FormatInfo::kMSAA_Flag;
839         info->fColorTypeInfoCount = 0;
840     }
841 
842     // Format: Depth32Float
843     {
844         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth32Float)];
845         info->fFlags = FormatInfo::kMSAA_Flag;
846         info->fColorTypeInfoCount = 0;
847     }
848 
849     // Format: Depth24PlusStencil8
850     {
851         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth24PlusStencil8)];
852         info->fFlags = FormatInfo::kMSAA_Flag;
853         info->fColorTypeInfoCount = 0;
854     }
855 
856 #if !defined(__EMSCRIPTEN__)
857     // Format: External
858     {
859         info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::External)];
860         info->fFlags = FormatInfo::kTexturable_Flag;
861         info->fColorTypeInfoCount = 1;
862         info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
863         int ctIdx = 0;
864         // Format: External, Surface: kRGBA_8888
865         {
866             auto& ctInfo = info->fColorTypeInfos[ctIdx++];
867             ctInfo.fColorType = kRGBA_8888_SkColorType;
868         }
869     }
870 #endif
871 
872     ////////////////////////////////////////////////////////////////////////////
873     // Map SkColorTypes (used for creating SkSurfaces) to wgpu::TextureFormat.
874     // The order in which the formats are passed into the setColorType function
875     // indicates the priority in selecting which format we use for a given
876     // SkColorType.
877 
878     std::fill_n(fColorTypeToFormatTable, kSkColorTypeCnt, wgpu::TextureFormat::Undefined);
879 
880     this->setColorType(kAlpha_8_SkColorType,          { wgpu::TextureFormat::R8Unorm });
881     this->setColorType(kRGBA_8888_SkColorType,        { wgpu::TextureFormat::RGBA8Unorm });
882     this->setColorType(kRGB_888x_SkColorType,
883                        {wgpu::TextureFormat::RGBA8Unorm, wgpu::TextureFormat::BGRA8Unorm});
884     this->setColorType(kBGRA_8888_SkColorType,        { wgpu::TextureFormat::BGRA8Unorm });
885     this->setColorType(kGray_8_SkColorType,           { wgpu::TextureFormat::R8Unorm });
886     this->setColorType(kR8_unorm_SkColorType,         { wgpu::TextureFormat::R8Unorm });
887     this->setColorType(kRGBA_F16_SkColorType,         { wgpu::TextureFormat::RGBA16Float });
888     this->setColorType(kRGB_F16F16F16x_SkColorType,   { wgpu::TextureFormat::RGBA16Float });
889     this->setColorType(kA16_float_SkColorType,        { wgpu::TextureFormat::R16Float });
890     this->setColorType(kR8G8_unorm_SkColorType,       { wgpu::TextureFormat::RG8Unorm });
891     this->setColorType(kRGBA_1010102_SkColorType,     { wgpu::TextureFormat::RGB10A2Unorm });
892     this->setColorType(kRGB_101010x_SkColorType,      { wgpu::TextureFormat::RGB10A2Unorm });
893     this->setColorType(kR16G16_float_SkColorType,     { wgpu::TextureFormat::RG16Float });
894 
895 #if !defined(__EMSCRIPTEN__)
896     this->setColorType(kA16_unorm_SkColorType,        { wgpu::TextureFormat::R16Unorm });
897     this->setColorType(kR16G16_unorm_SkColorType,     { wgpu::TextureFormat::RG16Unorm });
898 #endif
899 }
900 
901 // static
GetFormatIndex(wgpu::TextureFormat format)902 size_t DawnCaps::GetFormatIndex(wgpu::TextureFormat format) {
903     for (size_t i = 0; i < std::size(kFormats); ++i) {
904         if (format == kFormats[i]) {
905             return i;
906         }
907     }
908     SkDEBUGFAILF("Unsupported wgpu::TextureFormat: 0x%08X\n", static_cast<uint32_t>(format));
909     return 0;
910 }
911 
setColorType(SkColorType colorType,std::initializer_list<wgpu::TextureFormat> formats)912 void DawnCaps::setColorType(SkColorType colorType,
913                             std::initializer_list<wgpu::TextureFormat> formats) {
914     static_assert(std::size(kFormats) <= kFormatCount,
915                   "Size is not compatible for DawnCaps::fFormatTable and kFormats");
916     int idx = static_cast<int>(colorType);
917     for (auto it = formats.begin(); it != formats.end(); ++it) {
918         const auto& info = this->getFormatInfo(*it);
919         for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
920             if (info.fColorTypeInfos[i].fColorType == colorType) {
921                 fColorTypeToFormatTable[idx] = *it;
922                 return;
923             }
924         }
925     }
926 }
927 
928 // Make sure the format table indices will fit into the packed bits, with room to spare for
929 // representing an unused attachment.
930 static constexpr int kFormatBits = 11; // x2 attachments (color & depthStencil formats)
931 static constexpr int kSampleBits = 4;  // x2 attachments (color & depthStencil numSamples)
932 static constexpr int kResolveBits = 1;
933 static constexpr int kUnusedAttachmentIndex = (1 << kFormatBits) - 1;
934 static_assert(2*(kFormatBits + kSampleBits) + kResolveBits <= 32);
935 static_assert(std::size(kFormats) <= kUnusedAttachmentIndex);
936 
937 static constexpr int kDepthStencilNumSamplesOffset = kResolveBits;
938 static constexpr int kDepthStencilFormatOffset = kDepthStencilNumSamplesOffset + kSampleBits;
939 static constexpr int kColorNumSamplesOffset = kDepthStencilFormatOffset + kFormatBits;
940 static constexpr int kColorFormatOffset = kColorNumSamplesOffset + kSampleBits;
941 
942 static constexpr uint32_t kFormatMask     = (1 << kFormatBits) - 1;
943 static constexpr uint32_t kNumSamplesMask = (1 << kSampleBits) - 1;
944 static constexpr uint32_t kResolveMask    = (1 << kResolveBits) - 1;
945 
getRenderPassDescKeyForPipeline(const RenderPassDesc & renderPassDesc) const946 uint32_t DawnCaps::getRenderPassDescKeyForPipeline(const RenderPassDesc& renderPassDesc) const {
947     const TextureInfo& colorInfo = renderPassDesc.fColorAttachment.fTextureInfo;
948     const TextureInfo& depthStencilInfo = renderPassDesc.fDepthStencilAttachment.fTextureInfo;
949     // The color attachment should be valid; the depth-stencil attachment may not be if it's not
950     // being used.
951     SkASSERT(colorInfo.isValid());
952 
953     // Use format indices instead of WGPUTextureFormat values since they can be larger than 16 bits.
954     uint32_t colorFormatIndex =
955             GetFormatIndex(TextureInfos::GetDawnTextureSpec(colorInfo).getViewFormat());
956     uint32_t depthStencilFormatIndex =
957             depthStencilInfo.isValid()
958                     ? GetFormatIndex(
959                               TextureInfos::GetDawnTextureSpec(depthStencilInfo).getViewFormat())
960                     : kUnusedAttachmentIndex;
961 
962     // Note: if Dawn supports ExpandResolveTexture load op and the render pass uses it to load
963     // the resolve texture, a render pipeline will need to be created with
964     // wgpu::ColorTargetStateExpandResolveTextureDawn chained struct in order to be compatible.
965     // Hence a render pipeline created for a render pass using ExpandResolveTexture load op will
966     // be different from the one created for a render pass not using that load op.
967     // So we need to include a bit flag to differentiate the two kinds of pipelines.
968     // Also avoid returning a cached pipeline that is not compatible with the render pass using
969     // ExpandResolveTexture load op and vice versa.
970     const bool shouldIncludeLoadResolveAttachmentBit = this->resolveTextureLoadOp().has_value();
971     uint32_t loadResolveAttachmentKey = 0;
972     if (shouldIncludeLoadResolveAttachmentBit &&
973         renderPassDesc.fColorResolveAttachment.fTextureInfo.isValid() &&
974         renderPassDesc.fColorResolveAttachment.fLoadOp == LoadOp::kLoad) {
975         loadResolveAttachmentKey = 1;
976     }
977 
978     SkASSERT(colorFormatIndex < (1 << kFormatBits));
979     SkASSERT(colorInfo.numSamples() < (1 << kSampleBits));
980     SkASSERT(depthStencilFormatIndex < (1 << kFormatBits));
981     SkASSERT(depthStencilInfo.numSamples() < (1 << kSampleBits));
982     SkASSERT(loadResolveAttachmentKey < (1 << kResolveBits));
983 
984     return (colorFormatIndex              << kColorFormatOffset) |
985            (colorInfo.numSamples()        << kColorNumSamplesOffset) |
986            (depthStencilFormatIndex       << kDepthStencilFormatOffset) |
987            (depthStencilInfo.numSamples() << kDepthStencilNumSamplesOffset) |
988            loadResolveAttachmentKey;
989 }
990 
991 static constexpr int kDawnGraphicsPipelineKeyData32Count = 4;
992 
makeGraphicsPipelineKey(const GraphicsPipelineDesc & pipelineDesc,const RenderPassDesc & renderPassDesc) const993 UniqueKey DawnCaps::makeGraphicsPipelineKey(const GraphicsPipelineDesc& pipelineDesc,
994                                             const RenderPassDesc& renderPassDesc) const {
995     UniqueKey pipelineKey;
996     {
997         // 4 uint32_t's (render step id, paint id, uint32 RenderPassDesc, uint16 write swizzle key)
998         UniqueKey::Builder builder(&pipelineKey, get_pipeline_domain(),
999                                    kDawnGraphicsPipelineKeyData32Count, "DawnGraphicsPipeline");
1000         // Add GraphicsPipelineDesc key.
1001         builder[0] = pipelineDesc.renderStepID();
1002         builder[1] = pipelineDesc.paintParamsID().asUInt();
1003 
1004         // Add RenderPassDesc key and write swizzle (which is separate from the RenderPassDescKey
1005         // because it is applied in the program writing to the target, and is not actually part of
1006         // the underlying GPU render pass config).
1007         builder[2] = this->getRenderPassDescKeyForPipeline(renderPassDesc);
1008         builder[3] = renderPassDesc.fWriteSwizzle.asKey();
1009         builder.finish();
1010     }
1011 
1012     return pipelineKey;
1013 }
1014 
extractGraphicsDescs(const UniqueKey & key,GraphicsPipelineDesc * pipelineDesc,RenderPassDesc * renderPassDesc,const RendererProvider * rendererProvider) const1015 bool DawnCaps::extractGraphicsDescs(const UniqueKey& key,
1016                                     GraphicsPipelineDesc* pipelineDesc,
1017                                     RenderPassDesc* renderPassDesc,
1018                                     const RendererProvider* rendererProvider) const {
1019     SkASSERT(key.domain() == get_pipeline_domain());
1020     SkASSERT(key.dataSize() == 4 * kDawnGraphicsPipelineKeyData32Count);
1021 
1022     const uint32_t* rawKeyData = key.data();
1023 
1024     const RenderStep* renderStep = rendererProvider->lookup(rawKeyData[0]);
1025     *pipelineDesc = GraphicsPipelineDesc(renderStep, UniquePaintParamsID(rawKeyData[1]));
1026     SkASSERT(renderStep->performsShading() == pipelineDesc->paintParamsID().isValid());
1027 
1028     uint32_t renderpassDescBits = rawKeyData[2];
1029     uint32_t colorFormatIndex = (renderpassDescBits >> kColorFormatOffset) & kFormatMask;
1030     SkASSERT(colorFormatIndex < std::size(kFormats));
1031 
1032     DawnTextureInfo dawnInfo;
1033     dawnInfo.fFormat = dawnInfo.fViewFormat = kFormats[colorFormatIndex];
1034     dawnInfo.fSampleCount  = 1;
1035     dawnInfo.fMipmapped = skgpu::Mipmapped::kNo;
1036     dawnInfo.fUsage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::RenderAttachment;
1037 
1038     uint32_t colorSampleCount = (renderpassDescBits >> kColorNumSamplesOffset) & kNumSamplesMask;
1039     bool requiresMSAA = colorSampleCount > 1;
1040 
1041     SkEnumBitMask<DepthStencilFlags> dsFlags = DepthStencilFlags::kNone;
1042 
1043     uint32_t depthStencilFormatIndex =
1044             (renderpassDescBits >> kDepthStencilFormatOffset) & kFormatMask;
1045     if (depthStencilFormatIndex != kUnusedAttachmentIndex) {
1046         SkASSERT(depthStencilFormatIndex < std::size(kFormats));
1047         wgpu::TextureFormat dsFormat = kFormats[depthStencilFormatIndex];
1048         if (DawnFormatIsDepth(dsFormat)) {
1049             dsFlags |= DepthStencilFlags::kDepth;
1050         }
1051         if (DawnFormatIsStencil(dsFormat)) {
1052             dsFlags |= DepthStencilFlags::kStencil;
1053         }
1054     }
1055     SkDEBUGCODE(uint32_t dsSampleCount =
1056                     (renderpassDescBits >> kDepthStencilNumSamplesOffset) & kNumSamplesMask;)
1057     SkASSERT(colorSampleCount == dsSampleCount);
1058 
1059     LoadOp loadOp = LoadOp::kClear;
1060     if (renderpassDescBits & kResolveMask) {
1061         // This bit should only be set if Dawn supports ExpandResolveTexture load op
1062         SkASSERT(this->resolveTextureLoadOp().has_value());
1063         loadOp = LoadOp::kLoad;
1064     }
1065 
1066     Swizzle writeSwizzle = SwizzleCtorAccessor::Make(rawKeyData[3]);
1067 
1068     *renderPassDesc = RenderPassDesc::Make(this,
1069                                            TextureInfos::MakeDawn(dawnInfo),
1070                                            loadOp,
1071                                            StoreOp::kStore,
1072                                            dsFlags,
1073                                            /* clearColor= */ { .0f, .0f, .0f, .0f },
1074                                            requiresMSAA,
1075                                            writeSwizzle);
1076 
1077     return true;
1078 }
1079 
makeComputePipelineKey(const ComputePipelineDesc & pipelineDesc) const1080 UniqueKey DawnCaps::makeComputePipelineKey(const ComputePipelineDesc& pipelineDesc) const {
1081     UniqueKey pipelineKey;
1082     {
1083         static const skgpu::UniqueKey::Domain kComputePipelineDomain = UniqueKey::GenerateDomain();
1084         // The key is made up of a single uint32_t corresponding to the compute step ID.
1085         UniqueKey::Builder builder(&pipelineKey, kComputePipelineDomain, 1, "ComputePipeline");
1086         builder[0] = pipelineDesc.computeStep()->uniqueID();
1087 
1088         // TODO(b/240615224): The local work group size should factor into the key here since it is
1089         // specified in the shader text on Dawn/SPIR-V. This is not a problem right now since
1090         // ComputeSteps don't vary their workgroup size dynamically.
1091 
1092         builder.finish();
1093     }
1094     return pipelineKey;
1095 }
1096 
1097 #if !defined(__EMSCRIPTEN__)
1098 namespace {
1099 using namespace ycbcrUtils;
1100 
non_format_info_as_uint32(const wgpu::YCbCrVkDescriptor & desc)1101 uint32_t non_format_info_as_uint32(const wgpu::YCbCrVkDescriptor& desc) {
1102     static_assert(kComponentAShift + kComponentBits <= 32);
1103     SkASSERT(desc.vkYCbCrModel                          < (1u << kYcbcrModelBits    ));
1104     SkASSERT(desc.vkYCbCrRange                          < (1u << kYcbcrRangeBits    ));
1105     SkASSERT(desc.vkXChromaOffset                       < (1u << kXChromaOffsetBits ));
1106     SkASSERT(desc.vkYChromaOffset                       < (1u << kYChromaOffsetBits ));
1107     SkASSERT(static_cast<uint32_t>(desc.vkChromaFilter) < (1u << kChromaFilterBits  ));
1108     SkASSERT(desc.vkComponentSwizzleRed                 < (1u << kComponentBits     ));
1109     SkASSERT(desc.vkComponentSwizzleGreen               < (1u << kComponentBits     ));
1110     SkASSERT(desc.vkComponentSwizzleBlue                < (1u << kComponentBits     ));
1111     SkASSERT(desc.vkComponentSwizzleAlpha               < (1u << kComponentBits     ));
1112     SkASSERT(static_cast<uint32_t>(desc.forceExplicitReconstruction)
1113              < (1u << kForceExplicitReconBits));
1114 
1115     return (((uint32_t)(DawnDescriptorUsesExternalFormat(desc)) << kUsesExternalFormatShift) |
1116             ((uint32_t)(desc.vkYCbCrModel                     ) << kYcbcrModelShift        ) |
1117             ((uint32_t)(desc.vkYCbCrRange                     ) << kYcbcrRangeShift        ) |
1118             ((uint32_t)(desc.vkXChromaOffset                  ) << kXChromaOffsetShift     ) |
1119             ((uint32_t)(desc.vkYChromaOffset                  ) << kYChromaOffsetShift     ) |
1120             ((uint32_t)(desc.vkChromaFilter                   ) << kChromaFilterShift      ) |
1121             ((uint32_t)(desc.forceExplicitReconstruction      ) << kForceExplicitReconShift) |
1122             ((uint32_t)(desc.vkComponentSwizzleRed            ) << kComponentRShift        ) |
1123             ((uint32_t)(desc.vkComponentSwizzleGreen          ) << kComponentGShift        ) |
1124             ((uint32_t)(desc.vkComponentSwizzleBlue           ) << kComponentBShift        ) |
1125             ((uint32_t)(desc.vkComponentSwizzleAlpha          ) << kComponentAShift        ));
1126 }
1127 } // anonymous
1128 #endif
1129 
getImmutableSamplerInfo(const TextureProxy * proxy) const1130 ImmutableSamplerInfo DawnCaps::getImmutableSamplerInfo(const TextureProxy* proxy) const {
1131 #if !defined(__EMSCRIPTEN__)
1132     if (proxy) {
1133         const wgpu::YCbCrVkDescriptor& ycbcrConversionInfo =
1134                 TextureInfos::GetDawnTextureSpec(proxy->textureInfo()).fYcbcrVkDescriptor;
1135 
1136         if (ycbcrUtils::DawnDescriptorIsValid(ycbcrConversionInfo)) {
1137             ImmutableSamplerInfo immutableSamplerInfo;
1138             // A vkFormat of 0 indicates we are using an external format rather than a known one.
1139             immutableSamplerInfo.fFormat = (ycbcrConversionInfo.vkFormat == 0)
1140                     ? ycbcrConversionInfo.externalFormat
1141                     : ycbcrConversionInfo.vkFormat;
1142             immutableSamplerInfo.fNonFormatYcbcrConversionInfo =
1143                     non_format_info_as_uint32(ycbcrConversionInfo);
1144             return immutableSamplerInfo;
1145         }
1146     }
1147 #endif
1148 
1149     // If the proxy is null or the YCbCr conversion for that proxy is invalid, then return a
1150     // default ImmutableSamplerInfo struct.
1151     return {};
1152 }
1153 
buildKeyForTexture(SkISize dimensions,const TextureInfo & info,ResourceType type,Shareable shareable,GraphiteResourceKey * key) const1154 void DawnCaps::buildKeyForTexture(SkISize dimensions,
1155                                   const TextureInfo& info,
1156                                   ResourceType type,
1157                                   Shareable shareable,
1158                                   GraphiteResourceKey* key) const {
1159     const DawnTextureSpec dawnSpec = TextureInfos::GetDawnTextureSpec(info);
1160 
1161     SkASSERT(!dimensions.isEmpty());
1162 
1163     SkASSERT(dawnSpec.getViewFormat() != wgpu::TextureFormat::Undefined);
1164     uint32_t formatKey = static_cast<uint32_t>(dawnSpec.getViewFormat());
1165 
1166     uint32_t samplesKey = SamplesToKey(info.numSamples());
1167     // We don't have to key the number of mip levels because it is inherit in the combination of
1168     // isMipped and dimensions.
1169     bool isMipped = info.mipmapped() == Mipmapped::kYes;
1170 
1171     // Confirm all the below parts of the key can fit in a single uint32_t. The sum of the shift
1172     // amounts in the asserts must be less than or equal to 32.
1173     SkASSERT(samplesKey                             < (1u << 3));  // sample key is first 3 bits
1174     SkASSERT(static_cast<uint32_t>(isMipped)        < (1u << 1));  // isMapped is 4th bit
1175     SkASSERT(static_cast<uint32_t>(dawnSpec.fUsage) < (1u << 28)); // usage is remaining 28 bits
1176 
1177     // We need two uint32_ts for dimensions, 1 for format, and 1 for the rest of the key;
1178     int num32DataCnt = 2 + 1 + 1;
1179     bool hasYcbcrInfo = false;
1180 #if !defined(__EMSCRIPTEN__)
1181     // If we are using ycbcr texture/sampling, more key information is needed.
1182     if ((hasYcbcrInfo = ycbcrUtils::DawnDescriptorIsValid(dawnSpec.fYcbcrVkDescriptor))) {
1183         num32DataCnt += ycbcrUtils::DawnDescriptorUsesExternalFormat(dawnSpec.fYcbcrVkDescriptor)
1184                 ? SamplerDesc::kInt32sNeededExternalFormat
1185                 : SamplerDesc::kInt32sNeededKnownFormat;
1186     }
1187 #endif
1188     GraphiteResourceKey::Builder builder(key, type, num32DataCnt, shareable);
1189 
1190     builder[0] = dimensions.width();
1191     builder[1] = dimensions.height();
1192     builder[2] = formatKey;
1193     builder[3] = (samplesKey                                   << 0) |
1194                  (static_cast<uint32_t>(isMipped)              << 3) |
1195                  (static_cast<uint32_t>(dawnSpec.fUsage)       << 4);
1196 
1197 #if !defined(__EMSCRIPTEN__)
1198     if (hasYcbcrInfo) {
1199         builder[4] = non_format_info_as_uint32(dawnSpec.fYcbcrVkDescriptor);
1200         // Even though we already have formatKey appended to the texture key, we still need to add
1201         // fYcbcrVkDescriptor's vkFormat or externalFormat. The latter two are distinct from
1202         // dawnSpec's wgpu::TextureFormat.
1203         if (!ycbcrUtils::DawnDescriptorUsesExternalFormat(dawnSpec.fYcbcrVkDescriptor)) {
1204             builder[5] = dawnSpec.fYcbcrVkDescriptor.vkFormat;
1205         } else {
1206             builder[5] = (uint32_t)(dawnSpec.fYcbcrVkDescriptor.externalFormat >> 32);
1207             builder[6] = (uint32_t)dawnSpec.fYcbcrVkDescriptor.externalFormat;
1208         }
1209     }
1210 #endif
1211 }
1212 
makeSamplerKey(const SamplerDesc & samplerDesc) const1213 GraphiteResourceKey DawnCaps::makeSamplerKey(const SamplerDesc& samplerDesc) const {
1214     GraphiteResourceKey samplerKey;
1215     const SkSpan<const uint32_t>& samplerData = samplerDesc.asSpan();
1216     static const ResourceType kSamplerType = GraphiteResourceKey::GenerateResourceType();
1217     // Non-format ycbcr and sampler information are guaranteed to fit within one uint32, so the size
1218     // of the returned span accurately captures the quantity of uint32s needed whether the sampler
1219     // is immutable or not.
1220     GraphiteResourceKey::Builder builder(&samplerKey, kSamplerType, samplerData.size(),
1221                                          Shareable::kYes);
1222 
1223     for (size_t i = 0; i < samplerData.size(); i++) {
1224         builder[i] = samplerData[i];
1225     }
1226     builder.finish();
1227     return samplerKey;
1228 }
1229 
1230 } // namespace skgpu::graphite
1231