Debian Codegraph @

src/gpu/graphite/dawn/DawnCommandBuffer.cpp

raw ◀ ▶
1 Debian patch touch this file
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/DawnCommandBuffer.h"
9
10 #include "include/gpu/graphite/TextureInfo.h"
11 #include "src/gpu/graphite/ContextUtils.h"
12 #include "src/gpu/graphite/Log.h"
13 #include "src/gpu/graphite/RenderPassDesc.h"
14 #include "src/gpu/graphite/TextureProxy.h"
15 #include "src/gpu/graphite/UniformManager.h"
16 #include "src/gpu/graphite/compute/DispatchGroup.h"
17 #include "src/gpu/graphite/dawn/DawnBuffer.h"
18 #include "src/gpu/graphite/dawn/DawnCaps.h"
19 #include "src/gpu/graphite/dawn/DawnComputePipeline.h"
20 #include "src/gpu/graphite/dawn/DawnGraphicsPipeline.h"
21 #include "src/gpu/graphite/dawn/DawnGraphiteUtils.h"
22 #include "src/gpu/graphite/dawn/DawnQueueManager.h"
23 #include "src/gpu/graphite/dawn/DawnSampler.h"
24 #include "src/gpu/graphite/dawn/DawnSharedContext.h"
25 #include "src/gpu/graphite/dawn/DawnTexture.h"
26
27 #if defined(__EMSCRIPTEN__)
28 #include <emscripten/version.h>
29
30 namespace wgpu {
31 using TexelCopyBufferInfo = ImageCopyBuffer;
32 using TexelCopyTextureInfo = ImageCopyTexture;
33 } // namespace wgpu
34 #endif
35
36 namespace skgpu::graphite {
37
38 // On emsdk before 3.1.48 the API for RenderPass and ComputePass timestamps was different
39 // and does not map to current webgpu. We check this in DawnCaps but we also must avoid
40 // naming the types from the new API because they aren't defined.
41 #if defined(__EMSCRIPTEN__) \
42 && ((__EMSCRIPTEN_major__ < 3) \
43 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ < 1) \
44 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ < 48))
45 #define WGPU_TIMESTAMP_WRITES_DEFINED 0
46 #else
47 #define WGPU_TIMESTAMP_WRITES_DEFINED 1
48 #endif
49
50 // DawnCommandBuffer
51 // ----------------------------------------------------------------------------
52 std::unique_ptr<DawnCommandBuffer> DawnCommandBuffer::Make(const DawnSharedContext* sharedContext,
53 DawnResourceProvider* resourceProvider) {
54 std::unique_ptr<DawnCommandBuffer> cmdBuffer(
55 new DawnCommandBuffer(sharedContext, resourceProvider));
56 if (!cmdBuffer->setNewCommandBufferResources()) {
57 return {};
58 }
59 return cmdBuffer;
60 }
61
62 DawnCommandBuffer::DawnCommandBuffer(const DawnSharedContext* sharedContext,
63 DawnResourceProvider* resourceProvider)
64 : CommandBuffer(Protected::kNo) // Dawn doesn't support protected memory
65 , fSharedContext(sharedContext)
66 , fResourceProvider(resourceProvider) {}
67
68 DawnCommandBuffer::~DawnCommandBuffer() {}
69
70 bool DawnCommandBuffer::startTimerQuery() {
71 wgpu::QuerySet querySet = std::move(fTimestampQuerySet);
72
73 auto buffer = fResourceProvider->findOrCreateDawnBuffer(2 * sizeof(uint64_t),
74 BufferType::kQuery,
75 AccessPattern::kHostVisible,
76 "TimerQuery");
77 if (!buffer) {
78 SKGPU_LOG_W("Failed to create buffer for resolving results, timer query will "
79 "not be reported.");
80 return false;
81 }
82 sk_sp<DawnBuffer> xferBuffer;
83 if (!fSharedContext->caps()->drawBufferCanBeMapped()) {
84 xferBuffer = fResourceProvider->findOrCreateDawnBuffer(2 * sizeof(uint64_t),
85 BufferType::kXferGpuToCpu,
86 AccessPattern::kHostVisible,
87 "TimerQueryXfer");
88 if (!xferBuffer) {
89 SKGPU_LOG_W("Failed to create buffer for transferring timestamp results, timer "
90 "query will not be reported.");
91 return false;
92 }
93 }
94 if (!querySet) {
95 wgpu::QuerySetDescriptor descriptor;
96 descriptor.count = 2;
97 descriptor.label = "Command Buffer Timer Query";
98 descriptor.type = wgpu::QueryType::Timestamp;
99 descriptor.nextInChain = nullptr;
100 querySet = fSharedContext->device().CreateQuerySet(&descriptor);
101 if (!querySet) {
102 SKGPU_LOG_W("Failed to create query set, timer query will not be reported.");
103 return false;
104 }
105 }
106
107 fTimestampQuerySet = std::move(querySet);
108 fTimestampQueryBuffer = std::move(buffer);
109 fTimestampQueryXferBuffer = std::move(xferBuffer);
110
111 if (fSharedContext->dawnCaps()->supportsCommandBufferTimestamps()) {
112 // In native Dawn we use the writeTimeStamp method on CommandBuffer to bracket
113 // the whole command buffer.
114 fCommandEncoder.WriteTimestamp(fTimestampQuerySet, 0);
115 } else {
116 // On WebGPU the best we can do is add timestamps to each render/compute pass as we record
117 // them. Since we don't know a priori how many passes there will be we write a begin
118 // timestamp on the first pass and an end on every pass, overwriting the second query in the
119 // set.
120 fWroteFirstPassTimestamps = false;
121 }
122
123 return true;
124 }
125
126 void DawnCommandBuffer::endTimerQuery() {
127 SkASSERT(fTimestampQuerySet);
128 SkASSERT(fTimestampQueryBuffer);
129 if (fSharedContext->dawnCaps()->supportsCommandBufferTimestamps()) {
130 fCommandEncoder.WriteTimestamp(fTimestampQuerySet, 1);
131 } else if (!fWroteFirstPassTimestamps) {
132 // If we didn't have any passes then we can't report anything.
133 fTimestampQueryBuffer = nullptr;
134 fTimestampQueryXferBuffer = nullptr;
135 return;
136 }
137 // This resolve covers both timestamp code paths (command encoder and render/compute pass).
138 fCommandEncoder.ResolveQuerySet(
139 fTimestampQuerySet, 0, 2, fTimestampQueryBuffer->dawnBuffer(), 0);
140 if (fTimestampQueryXferBuffer) {
141 SkASSERT(fTimestampQueryBuffer->size() == fTimestampQueryBuffer->size());
142 fCommandEncoder.CopyBufferToBuffer(fTimestampQueryBuffer->dawnBuffer(),
143 /*sourceOffset=*/0,
144 fTimestampQueryXferBuffer->dawnBuffer(),
145 /*destinationOffset=*/0,
146 /*size=*/fTimestampQueryBuffer->size());
147 fTimestampQueryBuffer.reset();
148 }
149 if (fSharedContext->caps()->bufferMapsAreAsync()) {
150 sk_sp<Buffer> buffer =
151 fTimestampQueryXferBuffer ? fTimestampQueryXferBuffer : fTimestampQueryBuffer;
152 this->addBuffersToAsyncMapOnSubmit({&buffer, 1});
153 }
154 }
155
156 std::optional<GpuStats> DawnCommandBuffer::gpuStats() {
157 auto& buffer = fTimestampQueryXferBuffer ? fTimestampQueryXferBuffer : fTimestampQueryBuffer;
158 if (!buffer) {
159 return {};
160 }
161 if (fSharedContext->caps()->bufferMapsAreAsync()) {
162 if (!buffer->isMapped()) {
163 return {};
164 }
165 }
166 uint64_t* results = static_cast<uint64_t*>(buffer->map());
167 if (!results) {
168 SKGPU_LOG_W("Failed to get timer query results because buffer couldn't be mapped.");
169 return {};
170 }
171 if (results[1] < results[0]) {
172 return {};
173 }
174 GpuStats stats;
175 stats.elapsedTime = results[1] - results[0];
176 return stats;
177 }
178
179 wgpu::CommandBuffer DawnCommandBuffer::finishEncoding() {
180 SkASSERT(fCommandEncoder);
181 wgpu::CommandBuffer cmdBuffer = fCommandEncoder.Finish();
182
183 fCommandEncoder = nullptr;
184
185 return cmdBuffer;
186 }
187
188 void DawnCommandBuffer::onResetCommandBuffer() {
189 fActiveGraphicsPipeline = nullptr;
190 fActiveRenderPassEncoder = nullptr;
191 fActiveComputePassEncoder = nullptr;
192 fCommandEncoder = nullptr;
193
194 for (auto& bufferSlot : fBoundUniforms) {
195 bufferSlot = {};
196 }
197 fBoundUniformBuffersDirty = true;
198 if (fTimestampQueryBuffer && fTimestampQueryBuffer->isUnmappable()) {
199 fTimestampQueryBuffer->unmap();
200 }
201 if (fTimestampQueryXferBuffer && fTimestampQueryXferBuffer->isUnmappable()) {
202 fTimestampQueryXferBuffer->unmap();
203 }
204 fTimestampQueryBuffer = {};
205 fTimestampQueryXferBuffer = {};
206 fWroteFirstPassTimestamps = false;
207 }
208
209 bool DawnCommandBuffer::setNewCommandBufferResources() {
210 SkASSERT(!fCommandEncoder);
211 fCommandEncoder = fSharedContext->device().CreateCommandEncoder();
212 SkASSERT(fCommandEncoder);
213
214 return true;
215 }
216
217 // Requests a sampler. Dynamic samplers live in the global cache, requiring no tracking, but
218 // immutable samplers are created on the current graphics pipeline, and may outlive it, requiring
219 // further tracking.
220 const DawnSampler* DawnCommandBuffer::getSampler(
221 const DrawPassCommands::BindTexturesAndSamplers& command, int32_t index) {
222 auto desc = command.fSamplers[index];
223 if (desc.isImmutable()) {
224 const DawnSampler* immutableSampler = fActiveGraphicsPipeline->immutableSampler(index);
225 if (immutableSampler) {
226 this->trackCommandBufferResource(sk_ref_sp<Sampler>(immutableSampler));
227 }
228 return immutableSampler;
229 } else {
230 // Use the shared Sampler held in the global cache
231 return static_cast<const DawnSampler*>(
232 fSharedContext->globalCache()->getDynamicSampler(desc));
233 }
234 }
235
236 bool DawnCommandBuffer::onAddRenderPass(const RenderPassDesc& renderPassDesc,
237 SkIRect renderPassBounds,
238 const Texture* colorTexture,
239 const Texture* resolveTexture,
240 const Texture* depthStencilTexture,
241 SkIPoint resolveOffset,
242 SkIRect viewport,
243 const DrawPassList& drawPasses) {
244 // `viewport` has already been translated by the replay translation by the base CommandBuffer
245 if (!SkIRect::Intersects(viewport, fRenderPassBounds)) SK_UNLIKELY {
246 // The entire pass is offscreen
247 return true;
248 }
249
250
251 UniformManager intrinsicValues{Layout::kStd140};
252 CollectIntrinsicUniforms(fSharedContext->caps(), viewport, fDstReadBounds, &intrinsicValues);
253 const auto uniformData = UniformDataBlock::Wrap(&intrinsicValues);
254 const bool usePushConstant = fSharedContext->dawnCaps()
255 ->resourceBindingRequirements()
256 .fUsePushConstantsForIntrinsicConstants;
257
258 // If push constant is not supported, update the intrinsic constant buffer before starting a
259 // render pass.
260 if (!usePushConstant && !this->updateIntrinsicUniformsAsUBO(uniformData)) SK_UNLIKELY {
261 return false;
262 }
263
264 if (!this->beginRenderPass(renderPassDesc,
265 resolveOffset,
266 renderPassBounds,
267 colorTexture,
268 resolveTexture,
269 depthStencilTexture)) SK_UNLIKELY {
270 return false;
271 }
272
273 // If push constant is supported, update the intrinsic constants after starting a render pass.
274 if (usePushConstant && !this->updateIntrinsicUniformsAsPushConstant(uniformData)) SK_UNLIKELY {
275 return false;
276 }
277
278 this->setViewport(viewport);
279
280 for (const auto& drawPass : drawPasses) {
281 if (!this->addDrawPass(drawPass.get())) SK_UNLIKELY {
282 this->endRenderPass();
283 return false;
284 }
285 }
286
287 return this->endRenderPass();
288 }
289
290 bool DawnCommandBuffer::onAddComputePass(DispatchGroupSpan groups) {
291 this->beginComputePass();
292 for (const auto& group : groups) {
293 group->addResourceRefs(this);
294 for (const auto& dispatch : group->dispatches()) {
295 this->bindComputePipeline(group->getPipeline(dispatch.fPipelineIndex));
296 this->bindDispatchResources(*group, dispatch);
297 if (const WorkgroupSize* globalSize =
298 std::get_if<WorkgroupSize>(&dispatch.fGlobalSizeOrIndirect)) {
299 this->dispatchWorkgroups(*globalSize);
300 } else {
301 SkASSERT(std::holds_alternative<BindBufferInfo>(dispatch.fGlobalSizeOrIndirect));
302 const BindBufferInfo& indirect =
303 *std::get_if<BindBufferInfo>(&dispatch.fGlobalSizeOrIndirect);
304 this->dispatchWorkgroupsIndirect(indirect.fBuffer, indirect.fOffset);
305 }
306 }
307 }
308 this->endComputePass();
309 return true;
310 }
311
312 bool DawnCommandBuffer::beginRenderPass(const RenderPassDesc& renderPassDesc,
313 const SkIPoint& resolveOffset,
314 SkIRect renderPassBounds,
315 const Texture* colorTexture,
316 const Texture* resolveTexture,
317 const Texture* depthStencilTexture) {
318 SkASSERT(!fActiveRenderPassEncoder);
319 SkASSERT(!fActiveComputePassEncoder);
320
321 constexpr static wgpu::LoadOp wgpuLoadActionMap[]{
322 wgpu::LoadOp::Load,
323 wgpu::LoadOp::Clear,
324 wgpu::LoadOp::Clear // Don't care
325 };
326 static_assert((int)LoadOp::kLoad == 0);
327 static_assert((int)LoadOp::kClear == 1);
328 static_assert((int)LoadOp::kDiscard == 2);
329 static_assert(std::size(wgpuLoadActionMap) == kLoadOpCount);
330
331 constexpr static wgpu::StoreOp wgpuStoreActionMap[]{wgpu::StoreOp::Store,
332 wgpu::StoreOp::Discard};
333 static_assert((int)StoreOp::kStore == 0);
334 static_assert((int)StoreOp::kDiscard == 1);
335 static_assert(std::size(wgpuStoreActionMap) == kStoreOpCount);
336
337 wgpu::RenderPassDescriptor wgpuRenderPass = {};
338 wgpu::RenderPassColorAttachment wgpuColorAttachment;
339 wgpu::RenderPassDepthStencilAttachment wgpuDepthStencilAttachment;
340
341 // Set up color attachment.
342 #if !defined(__EMSCRIPTEN__)
343 wgpu::DawnRenderPassSampleCount mssaRenderToSingleSampledDesc;
344 wgpu::RenderPassDescriptorResolveRect wgpuPartialRect = {};
345 #endif
346
347 #if WGPU_TIMESTAMP_WRITES_DEFINED
348 #if defined(__EMSCRIPTEN__)
349 wgpu::RenderPassTimestampWrites wgpuTimestampWrites;
350 #else
351 wgpu::PassTimestampWrites wgpuTimestampWrites;
352 #endif
353 if (!fSharedContext->dawnCaps()->supportsCommandBufferTimestamps() && fTimestampQueryBuffer) {
354 SkASSERT(fTimestampQuerySet);
355 wgpuTimestampWrites.querySet = fTimestampQuerySet;
356 if (!fWroteFirstPassTimestamps) {
357 wgpuTimestampWrites.beginningOfPassWriteIndex = 0;
358 fWroteFirstPassTimestamps = true;
359 }
360 wgpuTimestampWrites.endOfPassWriteIndex = 1;
361 wgpuRenderPass.timestampWrites = &wgpuTimestampWrites;
362 }
363 #else
364 SkASSERT(!fTimestampQueryBuffer);
365 #endif
366
367 // Validate attachment descs and textures
368 const auto& colorInfo = renderPassDesc.fColorAttachment;
369 const auto& resolveInfo = renderPassDesc.fColorResolveAttachment;
370 const auto& depthStencilInfo = renderPassDesc.fDepthStencilAttachment;
371 SkASSERT(colorTexture ? colorInfo.isCompatible(colorTexture->textureInfo())
372 : colorInfo.fFormat == TextureFormat::kUnsupported);
373 SkASSERT(resolveTexture ? resolveInfo.isCompatible(resolveTexture->textureInfo())
374 : resolveInfo.fFormat == TextureFormat::kUnsupported);
375 SkASSERT(depthStencilTexture ? depthStencilInfo.isCompatible(depthStencilTexture->textureInfo())
376 : depthStencilInfo.fFormat == TextureFormat::kUnsupported);
377
378 // Set up color attachment
379 bool emulateLoadStoreResolveTexture = false;
380 if (colorTexture) {
381 wgpuRenderPass.colorAttachments = &wgpuColorAttachment;
382 wgpuRenderPass.colorAttachmentCount = 1;
383
384 const auto* dawnColorTexture = static_cast<const DawnTexture*>(colorTexture);
385 SkASSERT(dawnColorTexture->renderTextureView());
386 wgpuColorAttachment.view = dawnColorTexture->renderTextureView();
387
388 const std::array<float, 4>& clearColor = renderPassDesc.fClearColor;
389 wgpuColorAttachment.clearValue = {
390 clearColor[0], clearColor[1], clearColor[2], clearColor[3]};
391 wgpuColorAttachment.loadOp = wgpuLoadActionMap[static_cast<int>(colorInfo.fLoadOp)];
392 wgpuColorAttachment.storeOp = wgpuStoreActionMap[static_cast<int>(colorInfo.fStoreOp)];
393
394 // Set up resolve attachment
395 if (resolveTexture) {
396 SkASSERT(resolveInfo.fStoreOp == StoreOp::kStore);
397
398 const auto* dawnResolveTexture = static_cast<const DawnTexture*>(resolveTexture);
399 SkASSERT(dawnResolveTexture->renderTextureView());
400 wgpuColorAttachment.resolveTarget = dawnResolveTexture->renderTextureView();
401
402 // Inclusion of a resolve texture implies the client wants to finish the
403 // renderpass with a resolve.
404 SkASSERT(wgpuColorAttachment.storeOp == wgpu::StoreOp::Discard);
405 // But it also means we might have to load the resolve texture into the MSAA color attachment
406
407 if (fSharedContext->dawnCaps()->emulateLoadStoreResolve()) {
408 emulateLoadStoreResolveTexture = true;
409 } else if (resolveInfo.fLoadOp == LoadOp::kLoad) {
410 std::optional<wgpu::LoadOp> resolveLoadOp =
411 fSharedContext->dawnCaps()->resolveTextureLoadOp();
412 if (resolveLoadOp.has_value()) {
413 wgpuColorAttachment.loadOp = *resolveLoadOp;
414 } else {
415 // No Dawn built-in support, we need to manually load the resolve texture.
416 emulateLoadStoreResolveTexture = true;
417 }
418 }
419
420 if (!emulateLoadStoreResolveTexture) {
421 #if !defined(__EMSCRIPTEN__)
422 if (fSharedContext->dawnCaps()->supportsPartialLoadResolve()) {
423 SkIRect msaaArea = renderPassBounds;
424 SkAssertResult(msaaArea.intersect(SkIRect::MakeSize(
425 colorTexture->dimensions())));
426 wgpuPartialRect.colorOffsetX = msaaArea.x();
427 wgpuPartialRect.colorOffsetY = msaaArea.y();
428
429 SkIRect resolveArea = renderPassBounds;
430 resolveArea.offset(resolveOffset);
431 SkAssertResult(resolveArea.intersect(SkIRect::MakeSize(
432 resolveTexture->dimensions())));
433 wgpuPartialRect.resolveOffsetX = resolveArea.x();
434 wgpuPartialRect.resolveOffsetY = resolveArea.y();
435 wgpuPartialRect.width = resolveArea.width();
436 wgpuPartialRect.height = resolveArea.height();
437 wgpuRenderPass.nextInChain = &wgpuPartialRect;
438 } else
439 #endif
440 {
441 SkASSERT(resolveOffset.isZero());
442 }
443 }
444
445 // TODO: If the color resolve texture is read-only we can use a private (vs. memoryless)
446 // msaa attachment that's coupled to the framebuffer and the StoreAndMultisampleResolve
447 // action instead of loading as a draw.
448 } else {
449 [[maybe_unused]] bool isMSAAToSingleSampled =
450 renderPassDesc.fSampleCount > SampleCount::k1 &&
451 colorTexture->sampleCount() == SampleCount::k1;
452 #if defined(__EMSCRIPTEN__)
453 SkASSERT(!isMSAAToSingleSampled);
454 #else
455 if (isMSAAToSingleSampled) {
456 // If render pass is multi sampled but the color attachment is single sampled, we
457 // need to activate multisampled render to single sampled feature for this render
458 // pass.
459 SkASSERT(fSharedContext->device().HasFeature(
460 wgpu::FeatureName::MSAARenderToSingleSampled));
461
462 wgpuRenderPass.nextInChain = &mssaRenderToSingleSampledDesc;
463 mssaRenderToSingleSampledDesc.sampleCount = (uint8_t)renderPassDesc.fSampleCount;
464 }
465 #endif
466 }
467 }
468
469 // Set up stencil/depth attachment
470 if (depthStencilTexture) {
471 const auto* dawnDepthStencilTexture = static_cast<const DawnTexture*>(depthStencilTexture);
472
473 SkASSERT(dawnDepthStencilTexture->renderTextureView());
474 wgpuDepthStencilAttachment.view = dawnDepthStencilTexture->renderTextureView();
475
476 if (TextureFormatHasDepth(depthStencilInfo.fFormat)) {
477 wgpuDepthStencilAttachment.depthClearValue = renderPassDesc.fClearDepth;
478 wgpuDepthStencilAttachment.depthLoadOp =
479 wgpuLoadActionMap[static_cast<int>(depthStencilInfo.fLoadOp)];
480 wgpuDepthStencilAttachment.depthStoreOp =
481 wgpuStoreActionMap[static_cast<int>(depthStencilInfo.fStoreOp)];
482 }
483
484 if (TextureFormatHasStencil(depthStencilInfo.fFormat)) {
485 wgpuDepthStencilAttachment.stencilClearValue = renderPassDesc.fClearStencil;
486 wgpuDepthStencilAttachment.stencilLoadOp =
487 wgpuLoadActionMap[static_cast<int>(depthStencilInfo.fLoadOp)];
488 wgpuDepthStencilAttachment.stencilStoreOp =
489 wgpuStoreActionMap[static_cast<int>(depthStencilInfo.fStoreOp)];
490 }
491
492 wgpuRenderPass.depthStencilAttachment = &wgpuDepthStencilAttachment;
493 }
494
495 if (emulateLoadStoreResolveTexture) {
496 if (!this->emulateLoadMSAAFromResolveAndBeginRenderPassEncoder(
497 renderPassDesc,
498 wgpuRenderPass,
499 resolveOffset,
500 renderPassBounds,
501 static_cast<const DawnTexture*>(colorTexture),
502 static_cast<const DawnTexture*>(resolveTexture))) {
503 return false;
504 }
505 }
506 else {
507 fActiveRenderPassEncoder = fCommandEncoder.BeginRenderPass(&wgpuRenderPass);
508 }
509
510 return true;
511 }
512
513 bool DawnCommandBuffer::emulateLoadMSAAFromResolveAndBeginRenderPassEncoder(
514 const RenderPassDesc& intendedRenderPassDesc,
515 const wgpu::RenderPassDescriptor& intendedDawnRenderPassDesc,
516 const SkIPoint& resolveOffset,
517 const SkIRect& renderPassBounds,
518 const DawnTexture* msaaTexture,
519 const DawnTexture* resolveTexture) {
520 SkASSERT(!fActiveRenderPassEncoder);
521
522 const bool loadResolve =
523 intendedRenderPassDesc.fColorResolveAttachment.fLoadOp == LoadOp::kLoad;
524
525 // Override the render pass to exclude the resolve texture. We will emulate the loading &
526 // resolve via blit. The resovle step will be done separately after endRenderPass()
527 RenderPassDesc renderPassWithoutResolveDesc = intendedRenderPassDesc;
528 renderPassWithoutResolveDesc.fColorResolveAttachment = {};
529
530 wgpu::RenderPassColorAttachment dawnColorAttachmentWithoutResolve =
531 intendedDawnRenderPassDesc.colorAttachments[0];
532 dawnColorAttachmentWithoutResolve.resolveTarget = nullptr;
533 dawnColorAttachmentWithoutResolve.storeOp = wgpu::StoreOp::Store;
534
535 if (loadResolve) {
536 // If we intend to load the resolve texture, then override the loadOp of the MSAA attachment
537 // to Load instead of Clear.
538 // This path is intended to be used when the device doesn't support transient attachments.
539 // Which most likely means it is a non-tiled GPU. On non-tiled GPUs, load is a no-op so it
540 // should be faster than clearing the whole MSAA attachment. Note: Dawn doesn't have any
541 // DontCare loadOp.
542 dawnColorAttachmentWithoutResolve.loadOp = wgpu::LoadOp::Load;
543 }
544
545 wgpu::RenderPassDescriptor dawnRenderPassDescWithoutResolve = intendedDawnRenderPassDesc;
546 dawnRenderPassDescWithoutResolve.colorAttachments = &dawnColorAttachmentWithoutResolve;
547 dawnRenderPassDescWithoutResolve.colorAttachmentCount = 1;
548
549 auto renderPassEncoder = fCommandEncoder.BeginRenderPass(&dawnRenderPassDescWithoutResolve);
550
551 SkIRect msaaArea = renderPassBounds;
552 msaaArea.intersect(SkIRect::MakeSize(msaaTexture->dimensions()));
553 SkIRect resolveArea = renderPassBounds;
554 resolveArea.offset(resolveOffset);
555 resolveArea.intersect(SkIRect::MakeSize(resolveTexture->dimensions()));
556
557 if (loadResolve) {
558 // Blit from the resolve texture to the MSAA texture
559 if (!this->doBlitWithDraw(renderPassEncoder,
560 renderPassWithoutResolveDesc,
561 /*srcTextureView=*/resolveTexture->renderTextureView(),
562 /*srcSampleCount=*/SampleCount::k1,
563 /*srcOffset=*/resolveArea.topLeft(),
564 /*dstBounds=*/msaaArea)) {
565 renderPassEncoder.End();
566 return false;
567 }
568 }
569
570 fActiveRenderPassEncoder = renderPassEncoder;
571
572 fResolveStepEmulationInfo = {msaaTexture, resolveTexture, msaaArea.topLeft(), resolveArea};
573
574 return true;
575 }
576
577 bool DawnCommandBuffer::doBlitWithDraw(const wgpu::RenderPassEncoder& renderEncoder,
578 const RenderPassDesc& frontendRenderPassDescKey,
579 const wgpu::TextureView& srcTextureView,
580 SampleCount srcSampleCount,
581 const SkIPoint& srcOffset,
582 const SkIRect& dstBounds) {
583 DawnResourceProvider::BlitWithDrawEncoder blit =
584 fResourceProvider->findOrCreateBlitWithDrawEncoder(frontendRenderPassDescKey,
585 srcSampleCount);
586 if (!blit) {
587 SKGPU_LOG_E("Unable to create pipeline to blit with draw");
588 return false;
589 }
590
591 SkASSERT(renderEncoder);
592
593 blit.EncodeBlit(fSharedContext->device(), renderEncoder, srcTextureView, srcOffset, dstBounds);
594
595 return true;
596 }
597
598 bool DawnCommandBuffer::endRenderPass() {
599 SkASSERT(fActiveRenderPassEncoder);
600 fActiveRenderPassEncoder.End();
601 fActiveRenderPassEncoder = nullptr;
602
603 // Return early if no resolve step's emulation is needed.
604 if (!fResolveStepEmulationInfo.has_value()) {
605 return true;
606 }
607
608 // Creating an intermediate render pass to copy from the MSAA texture -> resolve texture.
609 RenderPassDesc intermediateRenderPassDesc = {};
610 intermediateRenderPassDesc.fColorAttachment = {
611 TextureInfoPriv::ViewFormat(fResolveStepEmulationInfo->fResolveTexture->textureInfo()),
612 LoadOp::kLoad,
613 StoreOp::kStore,
614 SampleCount::k1 };
615
616 wgpu::RenderPassColorAttachment dawnIntermediateColorAttachment;
617 dawnIntermediateColorAttachment.loadOp = wgpu::LoadOp::Load;
618 dawnIntermediateColorAttachment.storeOp = wgpu::StoreOp::Store;
619 dawnIntermediateColorAttachment.view =
620 fResolveStepEmulationInfo->fResolveTexture->renderTextureView();
621
622 wgpu::RenderPassDescriptor dawnIntermediateRenderPassDesc;
623 dawnIntermediateRenderPassDesc.colorAttachmentCount = 1;
624 dawnIntermediateRenderPassDesc.colorAttachments = &dawnIntermediateColorAttachment;
625
626 auto renderPassEncoder = fCommandEncoder.BeginRenderPass(&dawnIntermediateRenderPassDesc);
627
628 bool blitSucceeded = this->doBlitWithDraw(
629 renderPassEncoder,
630 intermediateRenderPassDesc,
631 /*srcTextureView=*/fResolveStepEmulationInfo->fMSAATexture->renderTextureView(),
632 /*srcSampleCount=*/fResolveStepEmulationInfo->fMSAATexture->textureInfo().sampleCount(),
633 /*srcOffset=*/fResolveStepEmulationInfo->fMSAAAOffset,
634 /*dstBounds=*/fResolveStepEmulationInfo->fResolveArea);
635
636 renderPassEncoder.End();
637
638 fResolveStepEmulationInfo.reset();
639
640 return blitSucceeded;
641 }
642
643 bool DawnCommandBuffer::addDrawPass(DrawPass* drawPass) {
644 // If there is gradient data to bind, it must be done prior to draws.
645 if (drawPass->floatStorageManager()->hasData()) {
646 this->bindUniformBuffer(drawPass->floatStorageManager()->getBufferInfo(),
647 UniformSlot::kGradient);
648 }
649
650 if (!drawPass->addResourceRefs(fResourceProvider, this)) SK_UNLIKELY {
651 return false;
652 }
653
654 for (auto [type, cmdPtr] : drawPass->commands()) {
655 switch (type) {
656 case DrawPassCommands::Type::kBindGraphicsPipeline: {
657 auto bgp = static_cast<DrawPassCommands::BindGraphicsPipeline*>(cmdPtr);
658 if (!this->bindGraphicsPipeline(drawPass->getPipeline(bgp->fPipelineIndex)))
659 SK_UNLIKELY { return false; }
660 break;
661 }
662 case DrawPassCommands::Type::kSetBlendConstants: {
663 auto sbc = static_cast<DrawPassCommands::SetBlendConstants*>(cmdPtr);
664 this->setBlendConstants(sbc->fBlendConstants);
665 break;
666 }
667 case DrawPassCommands::Type::kBindUniformBuffer: {
668 auto bub = static_cast<DrawPassCommands::BindUniformBuffer*>(cmdPtr);
669 this->bindUniformBuffer(bub->fInfo, bub->fSlot);
670 break;
671 }
672 case DrawPassCommands::Type::kBindStaticDataBuffer: {
673 auto bdb = static_cast<DrawPassCommands::BindStaticDataBuffer*>(cmdPtr);
674 this->bindInputBuffer(bdb->fStaticData.fBuffer, bdb->fStaticData.fOffset,
675 DawnGraphicsPipeline::kStaticDataBufferIndex);
676 break;
677 }
678 case DrawPassCommands::Type::kBindAppendDataBuffer: {
679 auto bdb = static_cast<DrawPassCommands::BindAppendDataBuffer*>(cmdPtr);
680 this->bindInputBuffer(bdb->fAppendData.fBuffer, bdb->fAppendData.fOffset,
681 DawnGraphicsPipeline::kAppendDataBufferIndex);
682 break;
683 }
684 case DrawPassCommands::Type::kBindIndexBuffer: {
685 auto bdb = static_cast<DrawPassCommands::BindIndexBuffer*>(cmdPtr);
686 this->bindIndexBuffer(
687 bdb->fIndices.fBuffer, bdb->fIndices.fOffset);
688 break;
689 }
690 case DrawPassCommands::Type::kBindIndirectBuffer: {
691 auto bdb = static_cast<DrawPassCommands::BindIndirectBuffer*>(cmdPtr);
692 this->bindIndirectBuffer(
693 bdb->fIndirect.fBuffer, bdb->fIndirect.fOffset);
694 break;
695 }
696 case DrawPassCommands::Type::kBindTexturesAndSamplers: {
697 auto bts = static_cast<DrawPassCommands::BindTexturesAndSamplers*>(cmdPtr);
698 this->bindTextureAndSamplers(*drawPass, *bts);
699 break;
700 }
701 case DrawPassCommands::Type::kSetScissor: {
702 auto ss = static_cast<DrawPassCommands::SetScissor*>(cmdPtr);
703 this->setScissor(ss->fScissor);
704 break;
705 }
706 case DrawPassCommands::Type::kDraw: {
707 auto draw = static_cast<DrawPassCommands::Draw*>(cmdPtr);
708 this->draw(draw->fType, draw->fBaseVertex, draw->fVertexCount);
709 break;
710 }
711 case DrawPassCommands::Type::kDrawIndexed: {
712 auto draw = static_cast<DrawPassCommands::DrawIndexed*>(cmdPtr);
713 this->drawIndexed(
714 draw->fType, draw->fBaseIndex, draw->fIndexCount, draw->fBaseVertex);
715 break;
716 }
717 case DrawPassCommands::Type::kDrawInstanced: {
718 auto draw = static_cast<DrawPassCommands::DrawInstanced*>(cmdPtr);
719 this->drawInstanced(draw->fType,
720 draw->fBaseVertex,
721 draw->fVertexCount,
722 draw->fBaseInstance,
723 draw->fInstanceCount);
724 break;
725 }
726 case DrawPassCommands::Type::kDrawIndexedInstanced: {
727 auto draw = static_cast<DrawPassCommands::DrawIndexedInstanced*>(cmdPtr);
728 this->drawIndexedInstanced(draw->fType,
729 draw->fBaseIndex,
730 draw->fIndexCount,
731 draw->fBaseVertex,
732 draw->fBaseInstance,
733 draw->fInstanceCount);
734 break;
735 }
736 case DrawPassCommands::Type::kDrawIndirect: {
737 auto draw = static_cast<DrawPassCommands::DrawIndirect*>(cmdPtr);
738 this->drawIndirect(draw->fType);
739 break;
740 }
741 case DrawPassCommands::Type::kDrawIndexedIndirect: {
742 auto draw = static_cast<DrawPassCommands::DrawIndexedIndirect*>(cmdPtr);
743 this->drawIndexedIndirect(draw->fType);
744 break;
745 }
746 case DrawPassCommands::Type::kAddBarrier: {
747 SKGPU_LOG_E("DawnCommandBuffer does not support the addition of barriers.");
748 break;
749 }
750 }
751 }
752
753 return true;
754 }
755
756 bool DawnCommandBuffer::bindGraphicsPipeline(const GraphicsPipeline* graphicsPipeline) {
757 SkASSERT(fActiveRenderPassEncoder);
758
759 auto* dawnGraphicsPipeline = static_cast<const DawnGraphicsPipeline*>(graphicsPipeline);
760 auto& wgpuPipeline = dawnGraphicsPipeline->dawnRenderPipeline();
761 if (!wgpuPipeline) SK_UNLIKELY {
762 return false;
763 }
764 fActiveGraphicsPipeline = dawnGraphicsPipeline;
765 fActiveRenderPassEncoder.SetPipeline(wgpuPipeline);
766 fBoundUniformBuffersDirty = true;
767
768 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy &&
769 fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2) {
770 // The pipeline has a single paired texture+sampler and uses texture copies for dst reads.
771 // This situation comes about when the program requires complex blending but otherwise
772 // is not referencing any images. Since there are no other images in play, the DrawPass
773 // will not have a BindTexturesAndSamplers command that we can tack the dstCopy on to.
774 // Instead we need to set the texture BindGroup ASAP to just the dstCopy.
775 // TODO(b/366254117): Once we standardize on a pipeline layout across all backends, the dst
776 // copy texture may not go in a group with the regular textures, in which case this binding
777 // can hopefully happen in a single place (e.g. here or at the start of the renderpass and
778 // not also every other time the textures are changed).
779 const auto* texture = static_cast<const DawnTexture*>(fDstCopy.first);
780 const auto* sampler = static_cast<const DawnSampler*>(fDstCopy.second);
781 wgpu::BindGroup bindGroup =
782 fResourceProvider->findOrCreateSingleTextureSamplerBindGroup(sampler, texture);
783 fActiveRenderPassEncoder.SetBindGroup(
784 DawnGraphicsPipeline::kTextureBindGroupIndex, bindGroup);
785 }
786
787 return true;
788 }
789
790 void DawnCommandBuffer::bindUniformBuffer(const BindBufferInfo& info, UniformSlot slot) {
791 SkASSERT(fActiveRenderPassEncoder);
792
793 unsigned int bufferIndex;
794 switch (slot) {
795 case UniformSlot::kCombinedUniforms:
796 bufferIndex = DawnGraphicsPipeline::kCombinedUniformIndex;
797 break;
798 case UniformSlot::kGradient:
799 bufferIndex = DawnGraphicsPipeline::kGradientBufferIndex;
800 break;
801 }
802
803 fBoundUniforms[bufferIndex] = info;
804 fBoundUniformBuffersDirty = true;
805 }
806
807 void DawnCommandBuffer::bindInputBuffer(const Buffer* buffer, size_t offset,
808 uint32_t bindingIndex) {
809 SkASSERT(fActiveRenderPassEncoder);
810 if (buffer) {
811 auto dawnBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
812 fActiveRenderPassEncoder.SetVertexBuffer(bindingIndex, dawnBuffer, offset);
813 }
814 }
815
816 void DawnCommandBuffer::bindIndexBuffer(const Buffer* indexBuffer, size_t offset) {
817 SkASSERT(fActiveRenderPassEncoder);
818 if (indexBuffer) {
819 auto dawnBuffer = static_cast<const DawnBuffer*>(indexBuffer)->dawnBuffer();
820 fActiveRenderPassEncoder.SetIndexBuffer(
821 dawnBuffer, wgpu::IndexFormat::Uint16, offset);
822 }
823 }
824
825 void DawnCommandBuffer::bindIndirectBuffer(const Buffer* indirectBuffer, size_t offset) {
826 if (indirectBuffer) {
827 fCurrentIndirectBuffer = static_cast<const DawnBuffer*>(indirectBuffer)->dawnBuffer();
828 fCurrentIndirectBufferOffset = offset;
829 } else {
830 fCurrentIndirectBuffer = nullptr;
831 fCurrentIndirectBufferOffset = 0;
832 }
833 }
834
835 void DawnCommandBuffer::bindTextureAndSamplers(
836 const DrawPass& drawPass, const DrawPassCommands::BindTexturesAndSamplers& command) {
837 SkASSERT(fActiveRenderPassEncoder);
838 SkASSERT(fActiveGraphicsPipeline);
839
840 // When there's an active graphics pipeline with a texture-copy dstread requirement, add one
841 // to account for the intrinsic dstCopy texture we bind here.
842 // NOTE: This is in units of pairs of textures and samplers, whereas the value reported by
843 // the current pipeline is in net bindings (textures + samplers).
844 int numTexturesAndSamplers = command.fNumTexSamplers;
845 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy) {
846 numTexturesAndSamplers++;
847 }
848 SkASSERT(fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2*numTexturesAndSamplers);
849
850 // If possible, it's ideal to optimize for the common case of using a single texture with one
851 // dynamic sampler. When using only one sampler, determine whether it is static or dynamic.
852 bool usingSingleStaticSampler = false;
853 #if !defined(__EMSCRIPTEN__)
854 if (command.fNumTexSamplers == 1) {
855 const wgpu::YCbCrVkDescriptor& ycbcrDesc =
856 TextureInfoPriv::Get<DawnTextureInfo>(
857 command.fTextures[0]->texture()->textureInfo())
858 .fYcbcrVkDescriptor;
859 usingSingleStaticSampler = DawnDescriptorIsValid(ycbcrDesc);
860 }
861 #endif
862
863 wgpu::BindGroup bindGroup;
864 // Optimize for single texture with dynamic sampling.
865 if (numTexturesAndSamplers == 1 && !usingSingleStaticSampler) {
866 SkASSERT(fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2);
867 SkASSERT(fActiveGraphicsPipeline->dstReadStrategy() != DstReadStrategy::kTextureCopy);
868
869 const auto* texture = static_cast<const DawnTexture*>(command.fTextures[0]->texture());
870 const auto* sampler = this->getSampler(command, 0);
871 bindGroup = fResourceProvider->findOrCreateSingleTextureSamplerBindGroup(sampler, texture);
872 } else {
873 std::vector<wgpu::BindGroupEntry> entries;
874
875 for (int i = 0; i < command.fNumTexSamplers; ++i) {
876 const auto* texture = static_cast<const DawnTexture*>(command.fTextures[i]->texture());
877 const auto* sampler = this->getSampler(command, i);
878 auto& wgpuTextureView = texture->sampleTextureView();
879 auto& wgpuSampler = sampler->dawnSampler();
880
881 #if !defined(__EMSCRIPTEN__)
882 // Assuming shader generator assigns binding slot to sampler then texture,
883 // then the next sampler and texture, and so on, we need to use
884 // 2 * i as base binding index of the sampler and texture.
885 // TODO: https://b.corp.google.com/issues/259457090:
886 // Better configurable way of assigning samplers and textures' bindings.
887 const wgpu::YCbCrVkDescriptor& ycbcrDesc =
888 texture->dawnTextureInfo().fYcbcrVkDescriptor;
889
890 // Only add a sampler as a bind group entry if it's a regular dynamic sampler. A valid
891 // YCbCrVkDescriptor indicates the usage of a static sampler, which should not be
892 // included here. They should already be fully specified in the bind group layout.
893 if (!DawnDescriptorIsValid(ycbcrDesc)) {
894 #endif
895 wgpu::BindGroupEntry samplerEntry;
896 samplerEntry.binding = 2 * i;
897 samplerEntry.sampler = wgpuSampler;
898 entries.push_back(samplerEntry);
899 #if !defined(__EMSCRIPTEN__)
900 }
901 #endif
902 wgpu::BindGroupEntry textureEntry;
903 textureEntry.binding = 2 * i + 1;
904 textureEntry.textureView = wgpuTextureView;
905 entries.push_back(textureEntry);
906 }
907
908 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy) {
909 // Append the dstCopy sampler and texture as the very last two bind group entries
910 wgpu::BindGroupEntry samplerEntry;
911 samplerEntry.binding = 2*numTexturesAndSamplers - 2;
912 samplerEntry.sampler = static_cast<const DawnSampler*>(fDstCopy.second)->dawnSampler();
913 entries.push_back(samplerEntry);
914
915 wgpu::BindGroupEntry textureEntry;
916 textureEntry.binding = 2*numTexturesAndSamplers - 1;
917 textureEntry.textureView =
918 static_cast<const DawnTexture*>(fDstCopy.first)->sampleTextureView();
919 entries.push_back(textureEntry);
920 }
921
922 wgpu::BindGroupDescriptor desc;
923 const auto& groupLayouts = fActiveGraphicsPipeline->dawnGroupLayouts();
924 desc.layout = groupLayouts[DawnGraphicsPipeline::kTextureBindGroupIndex];
925 desc.entryCount = entries.size();
926 desc.entries = entries.data();
927
928 bindGroup = fSharedContext->device().CreateBindGroup(&desc);
929 }
930
931 fActiveRenderPassEncoder.SetBindGroup(DawnGraphicsPipeline::kTextureBindGroupIndex, bindGroup);
932 }
933
934 void DawnCommandBuffer::syncUniformBuffers() {
•935 if (!fBoundUniformBuffersDirty) {
936 return;
937 }
938 fBoundUniformBuffersDirty = false;
939
•940 bool usePushConstants = fSharedContext->dawnCaps()->
941 resourceBindingRequirements().fUsePushConstantsForIntrinsicConstants;
942
•943 // We expect to have up to 3 uniforms in this bind group.
944 static constexpr int kMaxUniformsInGroup = 3;
945 // Until/unless uniform bind group structure gets reorganized, this should be equivalent to the
946 // size of our bound uniform array.
947 SkASSERT(kMaxUniformsInGroup == fBoundUniforms.size());
948
949 wgpu::BindGroup bindGroup;
950 std::array<uint32_t, kMaxUniformsInGroup> dynamicOffsets {0};
951 // Check if we can use an optimized route for single-uniform buffer bind groups:
952 if (usePushConstants &&
953 !fActiveGraphicsPipeline->hasGradientBuffer() &&
954 fActiveGraphicsPipeline->hasCombinedUniforms()) {
955 const BindBufferInfo& bufferInfo =
956 fBoundUniforms[DawnGraphicsPipeline::kCombinedUniformIndex];
957 bindGroup = fResourceProvider->findOrCreateSingleUniformBindGroup(bufferInfo);
958 dynamicOffsets[DawnGraphicsPipeline::kCombinedUniformIndex] = bufferInfo.fOffset;
959 } else {
960 std::array<bool, kMaxUniformsInGroup> enabled = {
961 !usePushConstants, // intrinsic uniforms
962 fActiveGraphicsPipeline->hasCombinedUniforms(), // paint AND renderstep uniforms!
963 fActiveGraphicsPipeline->hasGradientBuffer(), // gradient SSBO
964 };
965 constexpr uint32_t kBindingIndices[] = {
966 DawnGraphicsPipeline::kIntrinsicUniformBufferIndex,
967 DawnGraphicsPipeline::kCombinedUniformIndex,
968 DawnGraphicsPipeline::kGradientBufferIndex,
969 };
970
•971 std::array<wgpu::BindGroupEntry, kMaxUniformsInGroup> bindGroupEntries {};
972 for (int i = 0; i < kMaxUniformsInGroup; ++i) {
973 bindGroupEntries[i].binding = kBindingIndices[i];
974 if (enabled[i] && fBoundUniforms[i]) {
•975 bindGroupEntries[i].size = fBoundUniforms[i].fSize;
976 bindGroupEntries[i].buffer =
977 static_cast<const DawnBuffer*>(fBoundUniforms[i].fBuffer)->dawnBuffer();
978 dynamicOffsets[i] = fBoundUniforms[i].fOffset;
979 } else {
980 // Unused or null binding
•981 bindGroupEntries[i].buffer = fResourceProvider->getOrCreateNullBuffer();
982 }
983 }
984
•985 const auto& groupLayouts = fActiveGraphicsPipeline->dawnGroupLayouts();
986 bindGroup = fResourceProvider->createBindGroup(
987 bindGroupEntries,
988 groupLayouts[DawnGraphicsPipeline::kUniformBufferBindGroupIndex]);
989 }
•990
991 fActiveRenderPassEncoder.SetBindGroup(DawnGraphicsPipeline::kUniformBufferBindGroupIndex,
992 bindGroup,
993 dynamicOffsets.size(),
994 dynamicOffsets.data());
995 }
996
997 void DawnCommandBuffer::setScissor(const Scissor& scissor) {
998 SkASSERT(fActiveRenderPassEncoder);
999 SkIRect rect = scissor.getRect(fReplayTranslation, fRenderPassBounds);
1000 fActiveRenderPassEncoder.SetScissorRect(rect.x(), rect.y(), rect.width(), rect.height());
1001 }
1002
1003 bool DawnCommandBuffer::updateIntrinsicUniformsAsUBO(UniformDataBlock uniformData) {
1004 BindBufferInfo binding =
1005 fResourceProvider->findOrCreateIntrinsicBindBufferInfo(this, uniformData);
1006
1007 if (!binding) {
1008 return false;
1009 } else if (binding == fBoundUniforms[DawnGraphicsPipeline::kIntrinsicUniformBufferIndex]) {
1010 return true; // no binding change needed
1011 }
1012
1013 fBoundUniforms[DawnGraphicsPipeline::kIntrinsicUniformBufferIndex] = binding;
1014 fBoundUniformBuffersDirty = true;
1015 return true;
1016 }
1017
1018 bool DawnCommandBuffer::updateIntrinsicUniformsAsPushConstant(UniformDataBlock uniformData) {
1019 #if !defined(__EMSCRIPTEN__)
1020 SkASSERT(fActiveRenderPassEncoder);
1021 SkASSERT(uniformData.size() <= DawnGraphicsPipeline::kIntrinsicUniformSize);
1022 fActiveRenderPassEncoder.SetImmediates(0, uniformData.data(), uniformData.size());
1023 return true;
1024 #else
1025 SkASSERT(false); // No push constant support in WASM yet
1026 return false;
1027 #endif
1028 }
1029
1030 void DawnCommandBuffer::setViewport(SkIRect viewport) {
1031 SkASSERT(fActiveRenderPassEncoder);
1032 fActiveRenderPassEncoder.SetViewport(
1033 viewport.x(), viewport.y(), viewport.width(), viewport.height(), 0, 1);
1034 }
1035
1036 void DawnCommandBuffer::setBlendConstants(std::array<float, 4> blendConstants) {
1037 SkASSERT(fActiveRenderPassEncoder);
1038 wgpu::Color blendConst = {
1039 blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]};
1040 fActiveRenderPassEncoder.SetBlendConstant(&blendConst);
1041 }
1042
1043 void DawnCommandBuffer::draw(PrimitiveType type,
1044 unsigned int baseVertex,
1045 unsigned int vertexCount) {
1046 SkASSERT(fActiveRenderPassEncoder);
1047 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1048
1049 this->syncUniformBuffers();
1050
1051 fActiveRenderPassEncoder.Draw(vertexCount, /*instanceCount=*/1, baseVertex);
1052 }
1053
1054 void DawnCommandBuffer::drawIndexed(PrimitiveType type,
1055 unsigned int baseIndex,
1056 unsigned int indexCount,
1057 unsigned int baseVertex) {
1058 SkASSERT(fActiveRenderPassEncoder);
1059 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1060
1061 this->syncUniformBuffers();
1062
1063 fActiveRenderPassEncoder.DrawIndexed(indexCount, /*instanceCount=*/1, baseIndex, baseVertex);
1064 }
1065
1066 void DawnCommandBuffer::drawInstanced(PrimitiveType type,
1067 unsigned int baseVertex,
1068 unsigned int vertexCount,
1069 unsigned int baseInstance,
1070 unsigned int instanceCount) {
1071 SkASSERT(fActiveRenderPassEncoder);
1072 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1073
1074 this->syncUniformBuffers();
1075
1076 fActiveRenderPassEncoder.Draw(vertexCount, instanceCount, baseVertex, baseInstance);
1077 }
1078
1079 void DawnCommandBuffer::drawIndexedInstanced(PrimitiveType type,
1080 unsigned int baseIndex,
1081 unsigned int indexCount,
1082 unsigned int baseVertex,
1083 unsigned int baseInstance,
1084 unsigned int instanceCount) {
1085 SkASSERT(fActiveRenderPassEncoder);
1086 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1087
1088 this->syncUniformBuffers();
1089
1090 fActiveRenderPassEncoder.DrawIndexed(
1091 indexCount, instanceCount, baseIndex, baseVertex, baseInstance);
1092 }
1093
1094 void DawnCommandBuffer::drawIndirect(PrimitiveType type) {
1095 SkASSERT(fActiveRenderPassEncoder);
1096 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1097 SkASSERT(fCurrentIndirectBuffer);
1098
1099 this->syncUniformBuffers();
1100
1101 fActiveRenderPassEncoder.DrawIndirect(fCurrentIndirectBuffer, fCurrentIndirectBufferOffset);
1102 }
1103
1104 void DawnCommandBuffer::drawIndexedIndirect(PrimitiveType type) {
1105 SkASSERT(fActiveRenderPassEncoder);
1106 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1107 SkASSERT(fCurrentIndirectBuffer);
1108
1109 this->syncUniformBuffers();
1110
1111 fActiveRenderPassEncoder.DrawIndexedIndirect(fCurrentIndirectBuffer,
1112 fCurrentIndirectBufferOffset);
1113 }
1114
1115 void DawnCommandBuffer::beginComputePass() {
1116 SkASSERT(!fActiveRenderPassEncoder);
1117 SkASSERT(!fActiveComputePassEncoder);
1118 wgpu::ComputePassDescriptor wgpuComputePassDescriptor = {};
1119 #if WGPU_TIMESTAMP_WRITES_DEFINED
1120 #if defined(__EMSCRIPTEN__)
1121 wgpu::ComputePassTimestampWrites wgpuTimestampWrites;
1122 #else
1123 wgpu::PassTimestampWrites wgpuTimestampWrites;
1124 #endif
1125 if (!fSharedContext->dawnCaps()->supportsCommandBufferTimestamps() && fTimestampQueryBuffer) {
1126 SkASSERT(fTimestampQuerySet);
1127 wgpuTimestampWrites.querySet = fTimestampQuerySet;
1128 if (!fWroteFirstPassTimestamps) {
1129 wgpuTimestampWrites.beginningOfPassWriteIndex = 0;
1130 fWroteFirstPassTimestamps = true;
1131 }
1132 wgpuTimestampWrites.endOfPassWriteIndex = 1;
1133 wgpuComputePassDescriptor.timestampWrites = &wgpuTimestampWrites;
1134 }
1135 #else
1136 SkASSERT(!fTimestampQueryBuffer);
1137 #endif
1138 fActiveComputePassEncoder = fCommandEncoder.BeginComputePass(&wgpuComputePassDescriptor);
1139 }
1140
1141 void DawnCommandBuffer::bindComputePipeline(const ComputePipeline* computePipeline) {
1142 SkASSERT(fActiveComputePassEncoder);
1143
1144 fActiveComputePipeline = static_cast<const DawnComputePipeline*>(computePipeline);
1145 fActiveComputePassEncoder.SetPipeline(fActiveComputePipeline->dawnComputePipeline());
1146 }
1147
1148 void DawnCommandBuffer::bindDispatchResources(const DispatchGroup& group,
1149 const DispatchGroup::Dispatch& dispatch) {
1150 SkASSERT(fActiveComputePassEncoder);
1151 SkASSERT(fActiveComputePipeline);
1152
1153 // Bind all pipeline resources to a single new bind group at index 0.
1154 // NOTE: Caching the bind groups here might be beneficial based on the layout and the bound
1155 // resources (though it's questionable how often a bind group will end up getting reused since
1156 // the bound objects change often).
1157 skia_private::TArray<wgpu::BindGroupEntry> entries;
1158 entries.reserve(dispatch.fBindings.size());
1159
1160 for (const ResourceBinding& binding : dispatch.fBindings) {
1161 wgpu::BindGroupEntry& entry = entries.push_back();
1162 entry.binding = binding.fIndex;
1163 if (const BindBufferInfo* buffer = std::get_if<BindBufferInfo>(&binding.fResource)) {
1164 entry.buffer = static_cast<const DawnBuffer*>(buffer->fBuffer)->dawnBuffer();
1165 entry.offset = buffer->fOffset;
1166 entry.size = buffer->fSize;
1167 } else if (const TextureIndex* texIdx = std::get_if<TextureIndex>(&binding.fResource)) {
1168 const DawnTexture* texture =
1169 static_cast<const DawnTexture*>(group.getTexture(texIdx->fValue));
1170 SkASSERT(texture);
1171 entry.textureView = texture->sampleTextureView();
1172 } else if (const SamplerIndex* samplerIdx = std::get_if<SamplerIndex>(&binding.fResource)) {
1173 const DawnSampler* sampler =
1174 static_cast<const DawnSampler*>(group.getSampler(samplerIdx->fValue));
1175 entry.sampler = sampler->dawnSampler();
1176 } else {
1177 SK_ABORT("unsupported dispatch resource type");
1178 }
1179 }
1180
1181 wgpu::BindGroupDescriptor desc;
1182 desc.layout = fActiveComputePipeline->dawnGroupLayout();
1183 desc.entryCount = entries.size();
1184 desc.entries = entries.data();
1185
1186 auto bindGroup = fSharedContext->device().CreateBindGroup(&desc);
1187 fActiveComputePassEncoder.SetBindGroup(0, bindGroup);
1188 }
1189
1190 void DawnCommandBuffer::dispatchWorkgroups(const WorkgroupSize& globalSize) {
1191 SkASSERT(fActiveComputePassEncoder);
1192 SkASSERT(fActiveComputePipeline);
1193
1194 fActiveComputePassEncoder.DispatchWorkgroups(
1195 globalSize.fWidth, globalSize.fHeight, globalSize.fDepth);
1196 }
1197
1198 void DawnCommandBuffer::dispatchWorkgroupsIndirect(const Buffer* indirectBuffer,
1199 size_t indirectBufferOffset) {
1200 SkASSERT(fActiveComputePassEncoder);
1201 SkASSERT(fActiveComputePipeline);
1202
1203 auto& wgpuIndirectBuffer = static_cast<const DawnBuffer*>(indirectBuffer)->dawnBuffer();
1204 fActiveComputePassEncoder.DispatchWorkgroupsIndirect(wgpuIndirectBuffer, indirectBufferOffset);
1205 }
1206
1207 void DawnCommandBuffer::endComputePass() {
1208 SkASSERT(fActiveComputePassEncoder);
1209 fActiveComputePassEncoder.End();
1210 fActiveComputePassEncoder = nullptr;
1211 }
1212
1213 bool DawnCommandBuffer::onCopyBufferToBuffer(const Buffer* srcBuffer,
1214 size_t srcOffset,
1215 const Buffer* dstBuffer,
1216 size_t dstOffset,
1217 size_t size) {
1218 SkASSERT(!fActiveRenderPassEncoder);
1219 SkASSERT(!fActiveComputePassEncoder);
1220
1221 auto& wgpuBufferSrc = static_cast<const DawnBuffer*>(srcBuffer)->dawnBuffer();
1222 auto& wgpuBufferDst = static_cast<const DawnBuffer*>(dstBuffer)->dawnBuffer();
1223
1224 fCommandEncoder.CopyBufferToBuffer(wgpuBufferSrc, srcOffset, wgpuBufferDst, dstOffset, size);
1225 return true;
1226 }
1227
1228 bool DawnCommandBuffer::onCopyTextureToBuffer(const Texture* texture,
1229 SkIRect srcRect,
1230 const Buffer* buffer,
1231 size_t bufferOffset,
1232 size_t bufferRowBytes) {
1233 SkASSERT(!fActiveRenderPassEncoder);
1234 SkASSERT(!fActiveComputePassEncoder);
1235
1236 const auto* wgpuTexture = static_cast<const DawnTexture*>(texture);
1237 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1238
1239 wgpu::TexelCopyTextureInfo src;
1240 src.texture = wgpuTexture->dawnTexture();
1241 src.origin.x = srcRect.x();
1242 src.origin.y = srcRect.y();
1243 src.aspect = wgpuTexture->dawnTextureInfo().fAspect;
1244
1245 wgpu::TexelCopyBufferInfo dst;
1246 dst.buffer = wgpuBuffer;
1247 dst.layout.offset = bufferOffset;
1248 dst.layout.bytesPerRow = bufferRowBytes;
1249
1250 wgpu::Extent3D copySize = {
1251 static_cast<uint32_t>(srcRect.width()), static_cast<uint32_t>(srcRect.height()), 1};
1252 fCommandEncoder.CopyTextureToBuffer(&src, &dst, &copySize);
1253
1254 return true;
1255 }
1256
1257 bool DawnCommandBuffer::onCopyBufferToTexture(const Buffer* buffer,
1258 const Texture* texture,
1259 const BufferTextureCopyData* copyData,
1260 int count) {
1261 SkASSERT(!fActiveRenderPassEncoder);
1262 SkASSERT(!fActiveComputePassEncoder);
1263
1264 auto& wgpuTexture = static_cast<const DawnTexture*>(texture)->dawnTexture();
1265 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1266
1267 wgpu::TexelCopyBufferInfo src;
1268 src.buffer = wgpuBuffer;
1269
1270 wgpu::TexelCopyTextureInfo dst;
1271 dst.texture = wgpuTexture;
1272
1273 for (int i = 0; i < count; ++i) {
1274 src.layout.offset = copyData[i].fBufferOffset;
1275 src.layout.bytesPerRow = copyData[i].fBufferRowBytes;
1276
1277 dst.origin.x = copyData[i].fRect.x();
1278 dst.origin.y = copyData[i].fRect.y();
1279 dst.mipLevel = copyData[i].fMipLevel;
1280
1281 wgpu::Extent3D copySize = {static_cast<uint32_t>(copyData[i].fRect.width()),
1282 static_cast<uint32_t>(copyData[i].fRect.height()),
1283 1};
1284 fCommandEncoder.CopyBufferToTexture(&src, &dst, &copySize);
1285 }
1286
1287 return true;
1288 }
1289
1290 bool DawnCommandBuffer::onCopyTextureToTexture(const Texture* src,
1291 SkIRect srcRect,
1292 const Texture* dst,
1293 SkIPoint dstPoint,
1294 int mipLevel) {
1295 SkASSERT(!fActiveRenderPassEncoder);
1296 SkASSERT(!fActiveComputePassEncoder);
1297
1298 auto& wgpuTextureSrc = static_cast<const DawnTexture*>(src)->dawnTexture();
1299 auto& wgpuTextureDst = static_cast<const DawnTexture*>(dst)->dawnTexture();
1300
1301 wgpu::TexelCopyTextureInfo srcArgs;
1302 srcArgs.texture = wgpuTextureSrc;
1303 srcArgs.origin.x = srcRect.fLeft;
1304 srcArgs.origin.y = srcRect.fTop;
1305
1306 wgpu::TexelCopyTextureInfo dstArgs;
1307 dstArgs.texture = wgpuTextureDst;
1308 dstArgs.origin.x = dstPoint.fX;
1309 dstArgs.origin.y = dstPoint.fY;
1310 dstArgs.mipLevel = mipLevel;
1311
1312 wgpu::Extent3D copySize = {
1313 static_cast<uint32_t>(srcRect.width()), static_cast<uint32_t>(srcRect.height()), 1};
1314
1315 fCommandEncoder.CopyTextureToTexture(&srcArgs, &dstArgs, &copySize);
1316
1317 return true;
1318 }
1319
1320 bool DawnCommandBuffer::onSynchronizeBufferToCpu(const Buffer* buffer, bool* outDidResultInWork) {
1321 return true;
1322 }
1323
1324 bool DawnCommandBuffer::onClearBuffer(const Buffer* buffer, size_t offset, size_t size) {
1325 SkASSERT(!fActiveRenderPassEncoder);
1326 SkASSERT(!fActiveComputePassEncoder);
1327
1328 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1329 fCommandEncoder.ClearBuffer(wgpuBuffer, offset, size);
1330
1331 return true;
1332 }
1333
1334 } // namespace skgpu::graphite