Debian Codegraph @

src/gpu/graphite/DrawWriter.h

raw
1 /*
2 * Copyright 2021 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 #ifndef skgpu_graphite_DrawWriter_DEFINED
8 #define skgpu_graphite_DrawWriter_DEFINED
9
10 #include "include/private/base/SkAlign.h"
11 #include "include/private/base/SkAssert.h"
12 #include "include/private/base/SkContainers.h"
13 #include "include/private/base/SkDebug.h"
14 #include "include/private/base/SkTFitsIn.h"
15 #include "include/private/base/SkTo.h"
16 #include "src/base/SkAutoMalloc.h"
17 #include "src/base/SkEnumBitMask.h"
18 #include "src/gpu/BufferWriter.h"
19 #include "src/gpu/graphite/BufferManager.h"
20 #include "src/gpu/graphite/DrawTypes.h"
21 #include "src/gpu/graphite/ResourceTypes.h"
22
23 #include <algorithm>
24 #include <cstddef>
25 #include <cstdint>
26 #include <optional>
27 #include <utility>
28
29 namespace skgpu::graphite {
30
31 namespace DrawPassCommands {
32 class List;
33 }
34
35 /**
36 * DrawWriter is a helper around recording draws (to a temporary buffer or directly to a
37 * CommandBuffer), particularly when the number of draws is not known ahead of time, or the vertex
38 * and instance data is computed at record time and does not have a known size.
39 *
40 * To use, construct the DrawWriter with the current pipeline layout or call newPipelineState() on
41 * an existing DrawWriter and then bind that matching pipeline. When other dynamic state needs to
42 * change between draw calls, notify the DrawWriter using newDynamicState() before recording the
43 * modifications. See the listing below for how to append dynamic data or draw with existing buffers
44 *
45 * CommandBuffer::draw(vertices)
46 * - dynamic vertex data -> DrawWriter::Vertices(writer) verts;
47 * verts.append(n) << ...;
48 * - fixed vertex data -> writer.draw(vertices, {}, vertexCount)
49 *
50 * CommandBuffer::drawIndexed(vertices, indices)
51 * - dynamic vertex data -> unsupported
52 * - fixed vertex,index data -> writer.drawIndexed(vertices, indices, indexCount)
53 *
54 * CommandBuffer::drawInstances(vertices, instances)
55 * - dynamic instance data + fixed vertex data ->
56 * DrawWriter::Instances instances(writer, vertices, {}, vertexCount);
57 * instances.append(n) << ...;
58 * - fixed vertex and instance data ->
59 * writer.drawInstanced(vertices, vertexCount, instances, instanceCount)
60 *
61 * CommandBuffer::drawIndexedInstanced(vertices, indices, instances)
62 * - dynamic instance data + fixed vertex, index data ->
63 * DrawWriter::Instances instances(writer, vertices, indices, indexCount);
64 * instances.append(n) << ...;
65 * - fixed vertex, index, and instance data ->
66 * writer.drawIndexedInstanced(vertices, indices, indexCount, instances, instanceCount)
67 *
68 * NOTE: DrawWriter automatically handles failures to find or create a GPU buffer or map it to
69 * be writable. All returned VertexWriters will have a non-null pointer to write to, even if it will
70 * be discarded due to GPU failure at Recorder::snap() time.
71 */
72 class DrawWriter {
73 public:
74 // NOTE: This constructor creates a writer that defaults 0 vertex and instance stride, so
75 // 'newPipelineState()' must be called once the pipeline properties are known before it's used.
76 DrawWriter(DrawPassCommands::List*, DrawBufferManager*);
77
78 // Cannot move or copy
79 DrawWriter(const DrawWriter&) = delete;
80 DrawWriter(DrawWriter&&) = delete;
81
82 // flush() should be called before the writer is destroyed
83 ~DrawWriter() { SkASSERT(fPendingCount == 0); }
84
85 DrawBufferManager* bufferManager() { return fManager; }
86
87 // Issue draw calls for any pending vertex and instance data collected by the writer.
88 // Use either flush() or newDynamicState() based on context and readability.
89 void flush() { this->flushInternal(this->getDefaultAppendBinding()); }
90 void newDynamicState() { this->flush(); }
91
92 // Notify the DrawWriter that a new pipeline needs to be bound, providing the primitive type,
93 // attribute strides, and render state of the new pipeline. This issues draw calls for pending
94 // data that relied on the old pipeline, so this must be called *before* binding new pipeline.
95 void newPipelineState(PrimitiveType type,
96 size_t staticStride,
97 size_t appendStride,
98 SkEnumBitMask<RenderStateFlags> newRenderState,
99 BarrierType barrierType) {
100 this->flush();
101
102 // Once flushed, any pending data must have been drawn.
103 SkASSERT(fPendingCount == 0);
104
105 fPrimitiveType = type;
106 fStaticStride = SkTo<uint32_t>(staticStride);
107 fAppendStride = SkTo<uint32_t>(appendStride);
108 fRenderState = newRenderState;
109
110 // ARM hardware(b/399631317): On a new pipeline, the initial offset when appending
111 // vertices must be 4-count aligned, otherwise align to the stride so that access can use
112 // the baseInstance parameter of draw calls.
113 const uint32_t baseAlign = newRenderState & RenderStateFlags::kAppendVertices ?
114 4 * fAppendStride : fAppendStride;
115
116 // Initializes fAppend to hold the aligned offset within fCurrentBuffer and prepares
117 // fCurrentBuffer for later reservations. Passing count=0 here means no actual space
118 // (besides alignment padding) is used up until appendMappedWithStride is called.
119 std::tie(std::ignore, fAppend) = fCurrentBuffer.getMappedSubrange(/*count=*/0,
120 fAppendStride,
121 baseAlign);
122
123
124 // Assign the barrier type. If a valid value, then the DrawWriter will append
125 // AddBarrier commands of the indicated type prior to appending any draw commands used with
126 // this pipeline.
127 fBarrierToIssueBeforeDraws = barrierType;
128 }
129
130 #ifdef SK_DEBUG
131 // Query current pipeline state for validation
132 uint32_t appendStride() const { return fAppendStride; }
133 uint32_t staticStride() const { return fStaticStride; }
134 PrimitiveType primitiveType() const { return fPrimitiveType; }
135 #endif
136
137 // Collects new vertex data for a call to CommandBuffer::draw(). Automatically accumulates
138 // vertex data into a buffer, issuing draw and bind calls as needed when a new buffer is
139 // required, so that it is seamless to the caller. The draws do not use instances or indices.
140 //
141 // Usage (assuming writer has already had 'newPipelineState()' called with correct strides):
142 // DrawWriter::Vertices verts{writer};
143 // verts.append(n) << x << y << ...;
144 //
145 // This should not be used when the vertex stride is 0.
146 class Vertices;
147
148 // Collects new instance data for a call to CommandBuffer::drawInstanced() or
149 // drawIndexedInstanced(). The specific draw call that's issued depends on if a non-null index
150 // buffer is provided for the template. Like DrawWriter::Vertices, this automatically merges
151 // the appended data into as few buffer binds and draw calls as possible, while remaining
152 // seamless to the caller.
153 //
154 // Usage for drawInstanced (assuming writer has correct strides):
155 // DrawWriter::Instances instances{writer, fixedVerts, {}, fixedVertexCount};
156 // instances.append(n) << foo << bar << ...;
157 //
158 // Usage for drawIndexedInstanced:
159 // DrawWriter::Instances instances{writer, fixedVerts, fixedIndices, fixedIndexCount};
160 // instances.append(n) << foo << bar << ...;
161 //
162 // This should not be used when the instance stride is 0. However, the fixed vertex buffer can
163 // be null (or have a stride of 0) if the vertex shader only relies on the vertex ID and no
164 // other per-vertex data.
165 class Instances;
166
167 // Collects new instance data for a call to CommandBuffer::drawInstanced() or
168 // drawIndexedInstanced() (depending on presence of index data in the template). Unlike the
169 // Instances mode, the template's index or vertex count is not provided at the time of creation.
170 // Instead, DynamicInstances can be used with pipeline programs that can have a flexible number
171 // of vertices per instance. Appended instances specify a proxy object that can be converted
172 // to the minimum index/vertex count they must be drawn with; but if they are later batched with
173 // instances that would use more, the pipeline's vertex shader knows how to handle it.
174 //
175 // The proxy object serves as a useful point of indirection when the actual index count is
176 // expensive to compute, but can be derived from correlated geometric properties. The proxy
177 // can store those properties and accumulate a "worst-case" and then calculate the index count
178 // when DrawWriter has to flush.
179 //
180 // The VertexCountProxy type must provide:
181 // - a default constructor and copy assignment, where the initial value represents the minimum
182 // supported vertex count.
183 // - an 'unsigned int' operator that converts the proxy to the actual index count that is
184 // needed in order to dispatch a draw call.
185 // - operator <<(const V&) where V is any type the caller wants to pass to append() that
186 // represents the proxy for the about-to-be-written instances. This operator then updates its
187 // internal state to represent the worst case between what had previously been recorded and
188 // the latest V value.
189 //
190 // Usage for drawInstanced (fixedIndices == {}) or drawIndexedInstanced:
191 // DrawWriter::DynamicInstances<ProxyType> instances(writer, fixedVerts, fixedIndices);
192 // instances.append(minIndexProxy1, n1) << ...;
193 // instances.append(minIndexProxy2, n2) << ...;
194 //
195 // In this example, if the two sets of instances were contiguous, a single draw call with
196 // (n1 + n2) instances would still be made using max(minIndexCount1, minIndexCount2) as the
197 // index/vertex count, 'minIndexCountX' was derived from 'minIndexProxyX'. If the available
198 // vertex data from the DrawBufferManager forced a flush after the first, then the second would
199 // use minIndexCount2 unless a subsequent compatible DynamicInstances template appended more
200 // contiguous data.
201 template <typename VertexCountProxy>
202 class DynamicInstances;
203
204 // Issues draws with fully specified data. This can be used when all instance data has already
205 // been written to known buffers, or when the vertex shader only depends on the vertex or
206 // instance IDs.
207 //
208 // This will not merge with any already appended instance or vertex data, pending data is issued
209 // in its own draw call first. These are currently unused.
210 void draw(BindBufferInfo vertices, unsigned int vertexCount) {
211 this->bindAndFlush({}, {}, vertices, 0, vertexCount);
212 }
213 void drawIndexed(BindBufferInfo vertices, BindBufferInfo indices, unsigned int indexCount) {
214 this->bindAndFlush(vertices, indices, {}, 0, indexCount);
215 }
216 void drawInstanced(BindBufferInfo vertices, unsigned int vertexCount,
217 BindBufferInfo instances, unsigned int instanceCount) {
218 SkASSERT(vertexCount > 0);
219 this->bindAndFlush(vertices, {}, instances, vertexCount, instanceCount);
220 }
221 void drawIndexedInstanced(BindBufferInfo vertices, BindBufferInfo indices,
222 unsigned int indexCount, BindBufferInfo instances,
223 unsigned int instanceCount) {
224 SkASSERT(indexCount > 0);
225 this->bindAndFlush(vertices, indices, instances, indexCount, instanceCount);
226 }
227
228 #if defined(GPU_TEST_UTILS)
229 BindBufferInfo getLastAppendedBuffer() { return this->getDefaultAppendBinding(); }
230 #endif
231
232 private:
233 // Both of these pointers must outlive the DrawWriter.
234 DrawPassCommands::List* fCommandList;
235 DrawBufferManager* fManager;
236
237 BufferSubAllocator fCurrentBuffer;
238 SkAutoMalloc fFailureStorage; // storage address for VertexWriter when GPU buffer mapping fails
239
240 // Current operating mode of the DrawWriter, dictating how draw data is provided and
241 // interpreted. Determines whether fPendingCount refers to vertices or instances, and which
242 // buffer (fVertices or fInstances) serves as the append target. Set via newPipelineState().
243 SkEnumBitMask<RenderStateFlags> fRenderState;
244 PrimitiveType fPrimitiveType;
245 BarrierType fBarrierToIssueBeforeDraws = BarrierType::kNone;
246 uint32_t fStaticStride;
247 uint32_t fAppendStride;
248
249 // - fAppend: Holds buffer information for data that is generated and appended during the
250 // drawPass. The data can be either vertex (kAppendVertices) or instance
251 // (kAppendInstances/kAppendDynamicInstances) data.
252 // - fStatic: Holds buffer information that does not change between invocations of a renderstep.
253 // Currently this only holds vertex data, but this could change in the future.
254 // - Indices: Defines the (for now static) buffer used for any kind of index drawing. A
255 // renderstep with a valid index buffer implies that it will be performing indexed
256 // drawing.
257 BindBufferInfo fAppend;
258 BindBufferInfo fStatic;
259 BindBufferInfo fIndices;
260 // These track the buffers *last bound* by the command list. Used to ensure minimal binding.
261 BindBufferInfo fBoundAppend;
262 BindBufferInfo fBoundStatic;
263 BindBufferInfo fBoundIndices;
264
265 // Per-instance count for instanced draws (vertex count if no index buffer, index count
266 // otherwise).
267 // - For fixed instancing (kAppendInstances): Represents the constant vertex/index count per
268 // instance.
269 // - For dynamic instancing (kAppendDynamicInstances): Represents the *maximum* vertex/index
270 // count required across the currently accumulated batch of instances (updated via max()).
271 // - Not used (remains 0) for non-instanced draws (kAppendVertices) or direct draw calls.
272 uint32_t fTemplateCount;
273
274 // Number of items (vertices or instances, depending on fRenderState) that have been appended
275 // via an Appender (Vertices, Instances, DynamicInstances) but not yet issued in a draw call.
276 // Reset to 0 after a flush().
277 uint32_t fPendingCount;
278
279 BindBufferInfo getDefaultAppendBinding() const {
280 return {fAppend.fBuffer, fAppend.fOffset, fPendingCount*fAppendStride};
281 }
282
283 void setTemplate(BindBufferInfo staticData, BindBufferInfo indices, uint32_t templateCount) {
284 if (fPendingCount == 0) {
285 // A pendingCount of zero indicates that a either a newPipelineState() or dynamicState()
286 // triggered a flush, so we want to update the incoming member buffers.
287 fStatic = staticData;
288 fIndices = indices;
289 fTemplateCount = templateCount;
290 } else {
291 // IF non-zero pending count, then we must not have flushed, so we cannot have called a
292 // new pipeline yet. So we know the buffers MUST be the same.
293 // IF a new buffer is acquired in reserve(), it calls a flush on the previous binding.
294 // The flush sets the pendingCount to zero, skipping this code path.
295 SkASSERT(fStatic == staticData && fIndices == indices);
296 SkASSERT(fAppendStride == 0 || fAppend.fOffset % fAppendStride == 0);
297 SkASSERT((templateCount == 0 &&
298 (fRenderState & RenderStateFlags::kAppendDynamicInstances)) ||
299 fTemplateCount == templateCount);
300 }
301 }
302
303 void bindAndFlush(BindBufferInfo staticData, BindBufferInfo indices, BindBufferInfo appendData,
304 uint32_t templateCount, unsigned int drawCount) {
305 SkASSERT(drawCount > 0);
306 SkASSERT(!fAppender); // Shouldn't be appending and manually drawing at the same time.
307 SkASSERT(fPendingCount == 0); // Any prior appends must have been flushed by now.
308 // CAUTION: If appending vertices, we make NO checks here to ensure that the initial offset
309 // is four count aligned or that the data is padded. Caller MUST ensure any unaligned data
310 // is safe.
311 this->setTemplate(staticData, indices, templateCount);
312 fPendingCount = drawCount;
313 this->flushInternal(appendData);
314 }
315
316 void flushInternal(BindBufferInfo appendData);
317
318 // RAII - Sets the DrawWriter's template and marks the writer in append mode (disabling direct
319 // draws until the Appender is destructed).
320 class Appender;
321 SkDEBUGCODE(const Appender* fAppender = nullptr;)
322
323 // Helper functions for Appender implementations:
324
325 // Reallocates at least `count` blocks of the current `fAppendStride` so that later `append()`
326 // calls with the same or smaller count should succeed. Flushes pending draws if needed.
327 template <bool AppendVertices>
328 void realloc(unsigned int count) {
329 this->flush();
330
331 // For vertex rendering (ARM bug b/399631317), kBaseMultiple should be 4, otherwise 1.
332 SkASSERT(AppendVertices == SkToBool(fRenderState & RenderStateFlags::kAppendVertices));
333 static constexpr unsigned int kBaseMultiple = AppendVertices ? 4 : 1;
334
335 // We pass 0 as the count parameter to getMappedVertexBuffer and our `count` param as
336 // the `reservedCount`, allowing the next call to append() to flexibly use less than our
337 // reserved count. Because of this we ignore the BufferWriter, which points to an empty
338 // range. `fAppend` will also have an empty size, but that will get patched as we append
339 // data and increase fPendingCount (see getDefaultAppendBinding()).
340 std::tie(std::ignore, fAppend, fCurrentBuffer) =
341 fManager->getMappedVertexBuffer(/*count=*/0,
342 /*stride=*/fAppendStride,
343 /*reservedCount=*/SkAlignTo(count, kBaseMultiple),
344 /*alignment=*/kBaseMultiple * fAppendStride);
345 }
346
347 // Append `count` fAppendStride-sized blocks to be drawn in the next flush. This requires that
348 // there be at least `count` left in the buffer, or that GPU buffer allocation failed, e.g.
349 // caller is responsible for calling realloc when necessary.
350 SK_ALWAYS_INLINE VertexWriter append(unsigned int count) {
351 SkASSERT(count > 0);
352 // realloc() should have been called first, so either we have a failed BufferSubAllocator
353 // or we have enough space for a successsful suballocation.
354 SkASSERT(!fCurrentBuffer || fCurrentBuffer.availableWithStride() >= count);
355
356 // For vertex rendering (ARM bug b/399631317), there should still be enough room to zero up
357 // to a multiple of 4 vertices.
358 SkASSERT(!SkToBool(fRenderState & RenderStateFlags::kAppendVertices) ||
359 (count + fPendingCount) <= SkAlign4(count + fPendingCount));
360
361 // Attempt suballocation from the current buffer. The reserve() call and newPipelineState()
362 // configure the current buffer to append in units of fAppendStride. Assuming reserve()
363 // succeeded (or had a larger reservation from before), this will succeed. reserve() handles
364 // moving to a new Buffer, so if this is still invalid, there is a larger problem.
365 BufferWriter writer = fCurrentBuffer.appendMappedWithStride(count);
366 if (!writer) SK_UNLIKELY {
367 // If the GPU mapped buffer failed, ensure we have a sufficiently large CPU address to
368 // write to so that RenderSteps don't have to worry about error handling. The Recording
369 // will fail since the map failure is tracked by BufferManager.
370 // Since one of the reasons for GPU mapping failure is that count*stride does not fit
371 // in 32-bits, we calculate the CPU-side size carefully.
372 uint64_t size = (uint64_t)count * (uint64_t)fAppendStride;
373 if (!SkTFitsIn<size_t>(size)) {
374 sk_report_container_overflow_and_die();
375 }
376 return VertexWriter(fFailureStorage.reset(size, SkAutoMalloc::kReuse_OnShrink),
377 SkTo<size_t>(size));
378 }
379
380 fPendingCount += count;
381 return VertexWriter(std::move(writer));
382 }
383 };
384
385 // Appender implementations for DrawWriter that set the template on creation and provide a
386 // template-specific API to accumulate vertex/instance data.
387 class DrawWriter::Appender {
388 public:
389 Appender(DrawWriter& w, SkEnumBitMask<RenderStateFlags> renderState)
390 : fDrawer(w) {
391 SkASSERT(w.fAppendStride > 0);
392 SkASSERT(!w.fAppender);
393 SkASSERT(w.fRenderState == renderState);
394 SkDEBUGCODE(w.fAppender = this;)
395 }
396
397 ~Appender() {
398 SkASSERT(fDrawer.fAppender == this);
399 SkDEBUGCODE(fDrawer.fAppender = nullptr;)
400 }
401
402 protected:
403 DrawWriter& fDrawer;
404 };
405
406 class DrawWriter::Vertices : private DrawWriter::Appender {
407 public:
408 Vertices(DrawWriter& w) :
409 Appender(w, RenderStateFlags::kAppendVertices) {
410 w.setTemplate({}, {}, 0);
411 }
412
413 SK_ALWAYS_INLINE void reserve(unsigned int count) {
414 // For ARM speculative vertex execution (b/399631317), we avoid the bug by:
415 // 1. Initial elements are aligned to a 4-aligned stride (see newPipelineState() as well),
416 // which prevents speculative execution from evaluating prior vertex data.
417 // 2. There is always enough remaining data so that the element count could be rounded up
418 // to a multiple of 4 (and if not utilized, will be zero'ed by flush()).
419 count = std::max(SkAlign4(fDrawer.fPendingCount + count) - fDrawer.fPendingCount, count);
420 if (count > fDrawer.fCurrentBuffer.availableWithStride()) SK_UNLIKELY {
421 fDrawer.realloc</*AppendVertices=*/true>(count);
422 }
423 }
424 SK_ALWAYS_INLINE VertexWriter append(unsigned int count) {
425 this->reserve(count);
426 return fDrawer.append(count);
427 }
428 };
429
430 class DrawWriter::Instances : private DrawWriter::Appender {
431 public:
432 Instances(DrawWriter& w,
433 BindBufferInfo vertices,
434 BindBufferInfo indices,
435 unsigned int vertexCount)
436 : Appender(w, RenderStateFlags::kAppendInstances) {
437 SkASSERT(vertexCount > 0);
438 w.setTemplate(vertices, indices, vertexCount);
439 }
440
441 SK_ALWAYS_INLINE void reserve(unsigned int count) {
442 if (count > fDrawer.fCurrentBuffer.availableWithStride()) SK_UNLIKELY {
443 fDrawer.realloc</*AppendVertices=*/false>(count);
444 }
445 }
446 SK_ALWAYS_INLINE VertexWriter append(unsigned int count) {
447 this->reserve(count);
448 return fDrawer.append(count);
449 }
450 };
451
452 template <typename VertexCountProxy>
453 class DrawWriter::DynamicInstances : private DrawWriter::Appender {
454 public:
455 DynamicInstances(DrawWriter& w,
456 BindBufferInfo vertices,
457 BindBufferInfo indices)
458 : Appender(w, RenderStateFlags::kAppendDynamicInstances) {
459 w.setTemplate(vertices, indices, 0);
460 }
461
462 ~DynamicInstances() {
463 // See updateTemplateCount() "Destructor Case"
464 this->updateTemplateCount();
465 }
466
467 SK_ALWAYS_INLINE void reserve(unsigned int count) {
468 if (count > fDrawer.fCurrentBuffer.availableWithStride()) SK_UNLIKELY {
469 // See updateTemplateCount() "Reserve Case"
470 this->updateTemplateCount();
471 fDrawer.realloc</*AppendVertices=*/false>(count);
472 }
473 }
474
475 template <typename V>
476 VertexWriter append(const V& vertexCount, unsigned int instanceCount) {
477 this->reserve(instanceCount);
478 VertexWriter w = fDrawer.append(instanceCount);
479 // Record vertex count after appending instance data in case the append triggered a flush
480 // and the max vertex count is reset. However, the contents of 'w' will not have been
481 // flushed so 'fProxy' will account for 'vertexCount' when it is actually drawn.
482 fProxy << vertexCount;
483 return w;
484 }
485
486 private:
487 // updateTemplateCount() is called in two places:
488 // 1. When reserve() acquires a new buffer:
489 // This ensures data from the *previous* buffer is included in the ensuing flush.
490 // The count needs updating to signal that the prior buffer holds complete data.
491 //
492 // 2. In the DrawWriter::DynamicInstances destructor:
493 // This occurs after all data appending for the dynamic instances is finished. The update
494 // makes the final index count for these instances visible for the flush or combines the
495 // count with the next draw call's DynamicInstances object if there was no pipeline change
496 // between calls to RenderStep::writeVertices
497 // - max() is used to allow batches of multiple dynamic instance appends.
498 // - Since index data gets aligned to the largest count in a batch, we use max()
499 // to ensure the recorded count matches this alignment.
500 SK_ALWAYS_INLINE void updateTemplateCount() {
501 fDrawer.fTemplateCount = std::max(fDrawer.fTemplateCount, static_cast<uint32_t>(fProxy));
502 // By resetting the proxy after updating the template count, the next batch will start over
503 // with the minimum required vertex count and grow from there.
504 fProxy = {};
505 }
506
507 VertexCountProxy fProxy = {};
508 };
509
510 } // namespace skgpu::graphite
511
512 #endif // skgpu_graphite_DrawWriter_DEFINED