Debian Codegraph @

src/gpu/graphite/compute/DispatchGroup.cpp

raw
1 /*
2 * Copyright 2023 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/compute/DispatchGroup.h"
9
10 #include "include/core/SkColorType.h"
11 #include "include/core/SkTypes.h"
12 #include "include/gpu/GpuTypes.h"
13 #include "include/gpu/graphite/Recorder.h"
14 #include "include/gpu/graphite/TextureInfo.h"
15 #include "include/private/base/SkSpan_impl.h"
16 #include "include/private/base/SkTo.h"
17 #include "src/gpu/BufferWriter.h"
18 #include "src/gpu/graphite/BufferManager.h"
19 #include "src/gpu/graphite/Caps.h"
20 #include "src/gpu/graphite/CommandBuffer.h"
21 #include "src/gpu/graphite/ComputePipeline.h"
22 #include "src/gpu/graphite/Log.h"
23 #include "src/gpu/graphite/RecorderPriv.h"
24 #include "src/gpu/graphite/Resource.h"
25 #include "src/gpu/graphite/ResourceProvider.h"
26 #include "src/gpu/graphite/RuntimeEffectDictionary.h"
27 #include "src/gpu/graphite/Sampler.h"
28 #include "src/gpu/graphite/Texture.h" // IWYU pragma: keep
29 #include "src/gpu/graphite/TextureProxy.h"
30 #include "src/gpu/graphite/UniformManager.h"
31 #include "src/gpu/graphite/task/ClearBuffersTask.h"
32
33 #include <utility>
34
35 namespace skgpu::graphite {
36
37 DispatchGroup::~DispatchGroup() = default;
38
39 bool DispatchGroup::prepareResources(ResourceProvider* resourceProvider) {
40 fPipelines.reserve(fPipelines.size() + fPipelineDescs.size());
41 for (const ComputePipelineDesc& desc : fPipelineDescs) {
42 auto pipeline = resourceProvider->findOrCreateComputePipeline(desc);
43 if (!pipeline) {
44 SKGPU_LOG_W("Failed to create ComputePipeline for dispatch group. Dropping group!");
45 return false;
46 }
47 fPipelines.push_back(std::move(pipeline));
48 }
49
50 for (int i = 0; i < fTextures.size(); ++i) {
51 if (!fTextures[i]->textureInfo().isValid()) {
52 SKGPU_LOG_W("Failed to validate bound texture. Dropping dispatch group!");
53 return false;
54 }
55 if (!TextureProxy::InstantiateIfNotLazy(resourceProvider, fTextures[i].get())) {
56 SKGPU_LOG_W("Failed to instantiate bound texture. Dropping dispatch group!");
57 return false;
58 }
59 }
60
61 for (const SamplerDesc& desc : fSamplerDescs) {
62 sk_sp<Sampler> sampler = resourceProvider->findOrCreateCompatibleSampler(desc);
63 if (!sampler) {
64 SKGPU_LOG_W("Failed to create sampler. Dropping dispatch group!");
65 return false;
66 }
67 fSamplers.push_back(std::move(sampler));
68 }
69
70 // The DispatchGroup may be long lived on a Recording and we no longer need the descriptors
71 // once we've created pipelines.
72 fPipelineDescs.clear();
73 fSamplerDescs.clear();
74
75 return true;
76 }
77
78 void DispatchGroup::addResourceRefs(CommandBuffer* commandBuffer) const {
79 for (int i = 0; i < fPipelines.size(); ++i) {
80 commandBuffer->trackResource(fPipelines[i]);
81 }
82 for (int i = 0; i < fTextures.size(); ++i) {
83 commandBuffer->trackCommandBufferResource(fTextures[i]->refTexture());
84 }
85 }
86
87 sk_sp<Task> DispatchGroup::snapChildTask() {
88 if (fClearList.empty()) {
89 return nullptr;
90 }
91 return ClearBuffersTask::Make(std::move(fClearList));
92 }
93
94 const Texture* DispatchGroup::getTexture(size_t index) const {
95 SkASSERT(index < SkToSizeT(fTextures.size()));
96 SkASSERT(fTextures[index]);
97 SkASSERT(fTextures[index]->texture());
98 return fTextures[index]->texture();
99 }
100
101 const Sampler* DispatchGroup::getSampler(size_t index) const {
102 SkASSERT(index < SkToSizeT(fSamplers.size()));
103 SkASSERT(fSamplers[index]);
104 return fSamplers[index].get();
105 }
106
107 using Builder = DispatchGroup::Builder;
108
109 Builder::Builder(Recorder* recorder) : fObj(new DispatchGroup()), fRecorder(recorder) {
110 SkASSERT(fRecorder);
111 }
112
113 bool Builder::appendStep(const ComputeStep* step, std::optional<WorkgroupSize> globalSize) {
114 return this->appendStepInternal(step,
115 globalSize ? *globalSize : step->calculateGlobalDispatchSize());
116 }
117
118 bool Builder::appendStepIndirect(const ComputeStep* step, BindBufferInfo indirectBuffer) {
119 return this->appendStepInternal(step, indirectBuffer);
120 }
121
122 bool Builder::appendStepInternal(
123 const ComputeStep* step,
124 const std::variant<WorkgroupSize, BindBufferInfo>& globalSizeOrIndirect) {
125 SkASSERT(fObj);
126 SkASSERT(step);
127
128 Dispatch dispatch;
129
130 // Process the step's resources.
131 auto resources = step->resources();
132 dispatch.fBindings.reserve(resources.size());
133
134 // `nextIndex` matches the declaration order of resources as specified by the ComputeStep.
135 int nextIndex = 0;
136
137 // We assign buffer, texture, and sampler indices from separate ranges. This is compatible with
138 // how Graphite assigns indices on Metal, as these map directly to the buffer/texture/sampler
139 // index ranges. On Dawn/Vulkan buffers and textures/samplers are allocated from separate bind
140 // groups/descriptor sets but texture and sampler indices need to not overlap.
141 const auto& bindingReqs = fRecorder->priv().caps()->resourceBindingRequirements();
142 const bool separateSampler = bindingReqs.fSeparateTextureAndSamplerBinding;
143 const bool texturesUseDistinctIdxRanges = bindingReqs.fComputeUsesDistinctIdxRangesForTextures;
144 // Some binding index determination logic relies upon the fact that we do not expect to
145 // encounter a backend that both uses separate sampler bindings AND requires separate index
146 // ranges for textures.
147 SkASSERT(!(separateSampler && texturesUseDistinctIdxRanges));
148
149 int bufferOrGlobalIndex = 0;
150 int texIndex = 0;
151 // NOTE: SkSL Metal codegen always assigns the same binding index to a texture and its sampler.
152 // TODO: This could cause sampler indices to not be tightly packed if the sampler2D declaration
153 // comes after 1 or more storage texture declarations (which don't have samplers).
154 for (const ComputeStep::ResourceDesc& r : resources) {
155 SkASSERT(r.fSlot == -1 || (r.fSlot >= 0 && r.fSlot < kMaxComputeDataFlowSlots));
156 const int index = nextIndex++;
157
158 DispatchResourceOptional maybeResource;
159
160 using DataFlow = ComputeStep::DataFlow;
161 using Type = ComputeStep::ResourceType;
162 switch (r.fFlow) {
163 case DataFlow::kPrivate:
164 // A sampled or fetched-type readonly texture must either get assigned via
165 // `assignSharedTexture()` or internally allocated as a storage texture of a
166 // preceding step. Such a texture always has a data slot.
167 SkASSERT(r.fType != Type::kReadOnlyTexture);
168 SkASSERT(r.fType != Type::kSampledTexture);
169 maybeResource = this->allocateResource(step, r, index);
170 break;
171 case DataFlow::kShared: {
172 SkASSERT(r.fSlot >= 0);
173 // Allocate a new resource only if the shared slot is empty (except for a
174 // SampledTexture which needs its sampler to be allocated internally).
175 DispatchResourceOptional* slot = &fOutputTable.fSharedSlots[r.fSlot];
176 if (std::holds_alternative<std::monostate>(*slot)) {
177 SkASSERT(r.fType != Type::kReadOnlyTexture);
178 SkASSERT(r.fType != Type::kSampledTexture);
179 maybeResource = this->allocateResource(step, r, index);
180 *slot = maybeResource;
181 } else {
182 SkASSERT(((r.fType == Type::kUniformBuffer ||
183 r.fType == Type::kStorageBuffer ||
184 r.fType == Type::kReadOnlyStorageBuffer ||
185 r.fType == Type::kIndirectBuffer) &&
186 std::holds_alternative<BindBufferInfo>(*slot)) ||
187 ((r.fType == Type::kReadOnlyTexture ||
188 r.fType == Type::kSampledTexture ||
189 r.fType == Type::kWriteOnlyStorageTexture) &&
190 std::holds_alternative<TextureIndex>(*slot)));
191 #ifdef SK_DEBUG
192 // Ensure that the texture has the right format if it was assigned via
193 // `assignSharedTexture()`.
194 const TextureIndex* texIdx = std::get_if<TextureIndex>(slot);
195 if (texIdx && r.fType == Type::kWriteOnlyStorageTexture) {
196 const TextureProxy* t = fObj->fTextures[texIdx->fValue].get();
197 SkASSERT(t);
198 auto [_, colorType] = step->calculateTextureParameters(index, r);
199 SkASSERT(t->textureInfo().canBeFulfilledBy(
200 fRecorder->priv().caps()->getDefaultStorageTextureInfo(colorType)));
201 }
202 #endif // SK_DEBUG
203
204 maybeResource = *slot;
205
206 if (r.fType == Type::kSampledTexture) {
207 // The shared slot holds the texture part of the sampled texture but we
208 // still need to allocate the sampler.
209 SkASSERT(std::holds_alternative<TextureIndex>(*slot));
210 auto samplerResource = this->allocateResource(step, r, index);
211 const SamplerIndex* samplerIdx =
212 std::get_if<SamplerIndex>(&samplerResource);
213 SkASSERT(samplerIdx);
214 int bindingIndex = texturesUseDistinctIdxRanges ? texIndex :
215 separateSampler ? bufferOrGlobalIndex++
216 : bufferOrGlobalIndex;
217 dispatch.fBindings.push_back(
218 {static_cast<BindingIndex>(bindingIndex), *samplerIdx});
219 }
220 }
221 break;
222 }
223 }
224
225 int bindingIndex = 0;
226 DispatchResource dispatchResource;
227 if (const BindBufferInfo* buffer = std::get_if<BindBufferInfo>(&maybeResource)) {
228 dispatchResource = *buffer;
229 bindingIndex = bufferOrGlobalIndex++;
230 } else if (const TextureIndex* texIdx = std::get_if<TextureIndex>(&maybeResource)) {
231 dispatchResource = *texIdx;
232 bindingIndex = texturesUseDistinctIdxRanges ? texIndex++ : bufferOrGlobalIndex++;
233 } else {
234 SKGPU_LOG_W("Failed to allocate resource for compute dispatch");
235 return false;
236 }
237 dispatch.fBindings.push_back({static_cast<BindingIndex>(bindingIndex), dispatchResource});
238 }
239
240 auto wgBufferDescs = step->workgroupBuffers();
241 if (!wgBufferDescs.empty()) {
242 dispatch.fWorkgroupBuffers.push_back_n(wgBufferDescs.size(), wgBufferDescs.data());
243 }
244
245 // We need to switch pipelines if this step uses a different pipeline from the previous step.
246 if (fObj->fPipelineDescs.empty() ||
247 fObj->fPipelineDescs.back().uniqueID() != step->uniqueID()) {
248 fObj->fPipelineDescs.push_back(ComputePipelineDesc(step));
249 }
250
251 dispatch.fPipelineIndex = fObj->fPipelineDescs.size() - 1;
252 dispatch.fLocalSize = step->localDispatchSize();
253 dispatch.fGlobalSizeOrIndirect = globalSizeOrIndirect;
254
255 fObj->fDispatchList.push_back(std::move(dispatch));
256
257 return true;
258 }
259
260 void Builder::assignSharedBuffer(BindBufferInfo buffer, unsigned int slot, ClearBuffer cleared) {
261 SkASSERT(fObj);
262 SkASSERT(buffer);
263 SkASSERT(buffer.fSize);
264
265 fOutputTable.fSharedSlots[slot] = buffer;
266 if (cleared == ClearBuffer::kYes) {
267 fObj->fClearList.push_back(buffer);
268 }
269 }
270
271 void Builder::assignSharedTexture(sk_sp<TextureProxy> texture, unsigned int slot) {
272 SkASSERT(fObj);
273 SkASSERT(texture);
274
275 fObj->fTextures.push_back(std::move(texture));
276 fOutputTable.fSharedSlots[slot] = TextureIndex{fObj->fTextures.size() - 1u};
277 }
278
279 std::unique_ptr<DispatchGroup> Builder::finalize() {
280 auto obj = std::move(fObj);
281 fOutputTable.reset();
282 return obj;
283 }
284
285 #if defined(GPU_TEST_UTILS)
286 void Builder::reset() {
287 fOutputTable.reset();
288 fObj.reset(new DispatchGroup);
289 }
290 #endif
291
292 BindBufferInfo Builder::getSharedBufferResource(unsigned int slot) const {
293 SkASSERT(fObj);
294
295 BindBufferInfo info;
296 if (const BindBufferInfo* slotValue =
297 std::get_if<BindBufferInfo>(&fOutputTable.fSharedSlots[slot])) {
298 info = *slotValue;
299 }
300 return info;
301 }
302
303 sk_sp<TextureProxy> Builder::getSharedTextureResource(unsigned int slot) const {
304 SkASSERT(fObj);
305
306 const TextureIndex* idx = std::get_if<TextureIndex>(&fOutputTable.fSharedSlots[slot]);
307 if (!idx) {
308 return nullptr;
309 }
310
311 SkASSERT(idx->fValue < SkToSizeT(fObj->fTextures.size()));
312 return fObj->fTextures[idx->fValue];
313 }
314
315 DispatchResourceOptional Builder::allocateResource(const ComputeStep* step,
316 const ComputeStep::ResourceDesc& resource,
317 int resourceIdx) {
318 SkASSERT(step);
319 SkASSERT(fObj);
320 using Type = ComputeStep::ResourceType;
321 using ResourcePolicy = ComputeStep::ResourcePolicy;
322
323 DrawBufferManager* bufferMgr = fRecorder->priv().drawBufferManager();
324 DispatchResourceOptional result;
325 switch (resource.fType) {
326 case Type::kReadOnlyStorageBuffer:
327 case Type::kStorageBuffer: {
328 size_t bufferSize = step->calculateBufferSize(resourceIdx, resource);
329 SkASSERT(bufferSize);
330 if (resource.fPolicy == ResourcePolicy::kMapped) {
331 auto [writer, bufInfo, _] =
332 bufferMgr->getMappedStorageBuffer(bufferSize, /*stride=*/1);
333 if (writer) {
334 step->prepareStorageBuffer(resourceIdx, resource, std::move(writer));
335 result = bufInfo;
336 }
337 } else {
338 auto bufInfo = bufferMgr->getStorage(bufferSize,
339 resource.fPolicy == ResourcePolicy::kClear
340 ? ClearBuffer::kYes
341 : ClearBuffer::kNo);
342 if (bufInfo) {
343 result = bufInfo;
344 }
345 }
346 break;
347 }
348 case Type::kIndirectBuffer: {
349 SkASSERT(resource.fPolicy != ResourcePolicy::kMapped);
350
351 size_t bufferSize = step->calculateBufferSize(resourceIdx, resource);
352 SkASSERT(bufferSize);
353 auto bufInfo = bufferMgr->getIndirectStorage(bufferSize,
354 resource.fPolicy == ResourcePolicy::kClear
355 ? ClearBuffer::kYes
356 : ClearBuffer::kNo);
357 if (bufInfo) {
358 result = bufInfo;
359 }
360 break;
361 }
362 case Type::kUniformBuffer: {
363 SkASSERT(resource.fPolicy == ResourcePolicy::kMapped);
364
365 const auto& resourceReqs = fRecorder->priv().caps()->resourceBindingRequirements();
366 UniformManager uboMgr(resourceReqs.fUniformBufferLayout);
367 step->prepareUniformBuffer(resourceIdx, resource, &uboMgr);
368
369 auto dataBlock = uboMgr.finish();
370 SkASSERT(!dataBlock.empty());
371
372 auto [writer, bufInfo, _] =
373 bufferMgr->getMappedUniformBuffer(dataBlock.size(), /*stride=*/1);
374 if (bufInfo) {
375 writer.write(dataBlock.data(), dataBlock.size());
376 result = bufInfo;
377 }
378 break;
379 }
380 case Type::kWriteOnlyStorageTexture: {
381 auto [size, colorType] = step->calculateTextureParameters(resourceIdx, resource);
382 SkASSERT(!size.isEmpty());
383 SkASSERT(colorType != kUnknown_SkColorType);
384
385 auto textureInfo = fRecorder->priv().caps()->getDefaultStorageTextureInfo(colorType);
386 sk_sp<TextureProxy> texture = TextureProxy::Make(
387 fRecorder->priv().caps(), fRecorder->priv().resourceProvider(),
388 size, textureInfo, "DispatchWriteOnlyStorageTexture", skgpu::Budgeted::kYes);
389 if (texture) {
390 fObj->fTextures.push_back(std::move(texture));
391 result = TextureIndex{fObj->fTextures.size() - 1u};
392 }
393 break;
394 }
395 case Type::kReadOnlyTexture:
396 // This resource type is meant to be populated externally (e.g. by an upload or a render
397 // pass) and only read/sampled by a ComputeStep. It's not meaningful to allocate an
398 // internal texture for a DispatchGroup if none of the ComputeSteps will write to it.
399 //
400 // Instead of using internal allocation, this texture must be assigned explicitly to a
401 // slot by calling the Builder::assignSharedTexture() method.
402 //
403 // Note: A ComputeStep is allowed to read/sample from a storage texture that a previous
404 // ComputeStep has written to.
405 SK_ABORT("a readonly texture must be externally assigned to a ComputeStep");
406 break;
407 case Type::kSampledTexture: {
408 fObj->fSamplerDescs.push_back(step->calculateSamplerParameters(resourceIdx, resource));
409 result = SamplerIndex{fObj->fSamplerDescs.size() - 1u};
410 break;
411 }
412 }
413 return result;
414 }
415
416 } // namespace skgpu::graphite