Skip to main content

gpu/
web_cmd.rs

1// web_cmd -- command recording in the browser: CommandEncoder -> CommandBuffer
2//
3// The commands become words here and a GPUCommandEncoder in web/gpu.js, all in the one call of
4// Queue::submit (the op numbers: GpuHost.submit there): a frame costs one crossing into JavaScript, not
5// one per command, and nothing of WebGPU lives across calls.  What the API lets go on anywhere WebGPU
6// wants in a pass: the host opens a compute pass at the first dispatch and ends it before the next
7// thing that is no dispatch.  Barriers and layouts mean nothing here (WebGPU's usage scopes do that);
8// their calls stay so that the same code runs on every target.
9//
10// Every command checks what can be known here (the pipeline and pass state, bind group layouts, buffer
11// usages, ranges and alignments, row lengths of 256 bytes on copies); a failed check skips the
12// command and finish() returns it as GpuError::Invalid.  The rest is the browser's, later (web_dev.rs).
13// The level Voll's commands are Invalid.
14
15use alloc::rc::Rc;
16use alloc::vec::Vec;
17use core::marker::PhantomData;
18
19use crate::web_dev::{DevInner, Device};
20use crate::*;
21
22/// the row length WebGPU wants of copies between buffers and textures
23const COPY_ROW: u32 = 256;
24
25const OP_COPY_BUFFER: u32 = 1;
26const OP_FILL: u32 = 2;
27const OP_BUFFER_TO_TEXTURE: u32 = 3;
28const OP_TEXTURE_TO_BUFFER: u32 = 4;
29const OP_COMPUTE_PIPELINE: u32 = 5;
30const OP_BIND_GROUP: u32 = 6;
31const OP_PUSH: u32 = 7;
32const OP_DISPATCH: u32 = 8;
33const OP_DISPATCH_INDIRECT: u32 = 9;
34const OP_BEGIN_RENDER: u32 = 10;
35const OP_END_RENDER: u32 = 11;
36const OP_RENDER_PIPELINE: u32 = 12;
37const OP_VIEWPORT: u32 = 13;
38const OP_SCISSOR: u32 = 14;
39const OP_VERTEX: u32 = 15;
40const OP_INDEX: u32 = 16;
41const OP_DRAW: u32 = 17;
42const OP_DRAW_INDEXED: u32 = 18;
43const OP_DRAW_INDIRECT: u32 = 19;
44const OP_DRAW_INDEXED_INDIRECT: u32 = 20;
45
46/// records commands; finish() makes a CommandBuffer for Queue::submit
47pub struct CommandEncoder<'a> {
48    #[allow(dead_code)]
49    d: Rc<DevInner>,
50    w: Vec<u32>,
51    err: Option<GpuError>,
52    rendering: bool,
53    compute: Option<&'a ComputePipeline>,
54    render: Option<&'a RenderPipeline>,
55    // the running render pass's formats
56    colors: Vec<Format>,
57    depth: Option<Format>,
58}
59
60/// recorded commands, ready to submit (dropped unsubmitted: discarded)
61pub struct CommandBuffer<'a> {
62    pub(crate) words: Vec<u32>,
63    _p: PhantomData<&'a ()>,
64}
65
66impl Device {
67    /// a command encoder
68    pub fn encoder(&self) -> Result<CommandEncoder<'_>> {
69        self.d.check()?;
70        Ok(CommandEncoder { d: self.d.clone(), w: Vec::with_capacity(64), err: None, rendering: false, compute: None, render: None, colors: Vec::new(), depth: None })
71    }
72}
73
74fn split(v: u64) -> [u32; 2] {
75    [v as u32, (v >> 32) as u32]
76}
77
78impl<'a> CommandEncoder<'a> {
79    fn fail(&mut self, what: &'static str) {
80        if self.err.is_none() {
81            self.err = Some(GpuError::Invalid(what));
82        }
83    }
84
85    // not in a render pass (else the misuse)
86    fn outside(&mut self, what: &'static str) -> bool {
87        if self.rendering {
88            self.fail(what);
89        }
90        !self.rendering
91    }
92
93    fn inside(&mut self, what: &'static str) -> bool {
94        if !self.rendering {
95            self.fail(what);
96        }
97        self.rendering
98    }
99
100    pub fn copy_buffer(&mut self, src: &'a Buffer, src_off: u64, dst: &'a Buffer, dst_off: u64, size: u64) {
101        if !self.outside("copy_buffer in a render pass") {
102            return;
103        }
104        if src_off % 4 != 0 || dst_off % 4 != 0 || size % 4 != 0 || src_off + size > src.size() || dst_off + size > dst.size() {
105            return self.fail("copy_buffer: outside the buffers, or not in multiples of 4");
106        }
107        let (a, b, c) = (split(src_off), split(dst_off), split(size));
108        self.w.extend_from_slice(&[OP_COPY_BUFFER, src.handle(), a[0], a[1], dst.handle(), b[0], b[1], c[0], c[1]]);
109    }
110
111    /// fill size bytes at offset with a 32-bit value (both multiples of 4)
112    pub fn fill_buffer(&mut self, buf: &'a Buffer, offset: u64, size: u64, value: u32) {
113        if !self.outside("fill_buffer in a render pass") {
114            return;
115        }
116        if offset % 4 != 0 || size % 4 != 0 || offset + size > buf.size() {
117            return self.fail("fill_buffer: outside the buffer, or not in multiples of 4");
118        }
119        let (a, b) = (split(offset), split(size));
120        self.w.extend_from_slice(&[OP_FILL, buf.handle(), a[0], a[1], b[0], b[1], value]);
121    }
122
123    // what a copy between a buffer and a texture needs of its layout: rows of 256 bytes -> bytes per row,
124    // rows per image
125    fn copy_layout(&mut self, r: &TextureRegion<'a>, l: &DataLayout) -> Option<(u32, u32)> {
126        let f = r.texture.format();
127        if f.is_depth() {
128            self.fail("copies of depth textures");
129            return None;
130        }
131        let (bw, bb) = (f.block_dim(), f.block_bytes());
132        let tight = r.size[0].div_ceil(bw) * bb;
133        let row = if l.bytes_per_row == 0 { tight } else { l.bytes_per_row };
134        let rows = r.size[1].div_ceil(bw);
135        if row < tight {
136            self.fail("a copy's row is shorter than the region");
137            return None;
138        }
139        // (WebGPU's rule; a tight row is fine only when it is a single row)
140        if row % COPY_ROW != 0 && rows.max(r.layers).max(r.size[2]) > 1 {
141            self.fail("a copy's rows must be multiples of 256 bytes in WebGPU");
142            return None;
143        }
144        if l.offset % bb as u64 != 0 {
145            self.fail("a copy's offset must be a multiple of the texel size");
146            return None;
147        }
148        let per = if l.rows_per_image == 0 { rows } else { l.rows_per_image };
149        Some((row, per))
150    }
151
152    /// buffer data -> a texture region
153    pub fn copy_buffer_to_texture(&mut self, src: &'a Buffer, layout: DataLayout, dst: TextureRegion<'a>) {
154        if !self.outside("copy_buffer_to_texture in a render pass") {
155            return;
156        }
157        let Some((row, per)) = self.copy_layout(&dst, &layout) else { return };
158        let o = split(layout.offset);
159        let (z, d) = if dst.texture.depth() > 1 { (dst.origin[2], dst.size[2].max(1)) } else { (dst.base_layer, dst.layers.max(1)) };
160        self.w.extend_from_slice(&[OP_BUFFER_TO_TEXTURE, src.handle(), o[0], o[1], row, per, dst.texture.handle(), dst.mip, dst.origin[0], dst.origin[1], z, dst.size[0], dst.size[1], d]);
161    }
162
163    /// a texture region -> buffer data
164    pub fn copy_texture_to_buffer(&mut self, src: TextureRegion<'a>, dst: &'a Buffer, layout: DataLayout) {
165        if !self.outside("copy_texture_to_buffer in a render pass") {
166            return;
167        }
168        let Some((row, per)) = self.copy_layout(&src, &layout) else { return };
169        let o = split(layout.offset);
170        let (z, d) = if src.texture.depth() > 1 { (src.origin[2], src.size[2].max(1)) } else { (src.base_layer, src.layers.max(1)) };
171        self.w.extend_from_slice(&[OP_TEXTURE_TO_BUFFER, src.texture.handle(), src.mip, src.origin[0], src.origin[1], z, src.size[0], src.size[1], d, dst.handle(), o[0], o[1], row, per]);
172    }
173
174    /// (WebGPU's usage scopes do this)
175    pub fn barrier(&mut self, _before: Access, _after: Access) {}
176    pub fn texture_barrier(&mut self, _tex: &'a Texture, _before: Layout, _after: Layout) {}
177    pub fn texture_barrier_range(&mut self, _tex: &'a Texture, _base_mip: u32, _mips: u32, _base_layer: u32, _layers: u32, _before: Layout, _after: Layout) {}
178
179    pub fn set_compute_pipeline(&mut self, p: &'a ComputePipeline) {
180        if self.outside("set_compute_pipeline in a render pass") {
181            self.compute = Some(p);
182            self.w.extend_from_slice(&[OP_COMPUTE_PIPELINE, p.0.h.h]);
183        }
184    }
185
186    /// bind group g (= @group(g)) of the current pipeline's layout
187    pub fn set_bind_group(&mut self, index: u32, group: &'a BindGroup) {
188        self.w.extend_from_slice(&[OP_BIND_GROUP, index, group.handle()]);
189        let layout = if self.rendering { self.render.map(|p| &p.0.layout) } else { self.compute.map(|p| &p.0.layout) };
190        let Some(layout) = layout else {
191            return self.fail("set_bind_group before a pipeline");
192        };
193        if !layout.0.groups.get(index as usize).is_some_and(|l| group.fits(l)) {
194            self.fail("set_bind_group: the group does not fit the pipeline's layout");
195        }
196    }
197
198    /// push constants at offset (bytes) for the current pipeline (a uniform block in the browser)
199    pub fn push_constants<T: Pod>(&mut self, offset: u32, data: &[T]) {
200        let bytes = bytes_of(data);
201        let layout = if self.rendering { self.render.map(|p| &p.0.layout) } else { self.compute.map(|p| &p.0.layout) };
202        let Some(layout) = layout else {
203            return self.fail("push_constants before a pipeline");
204        };
205        if offset % 4 != 0 || bytes.len() % 4 != 0 || offset as usize + bytes.len() > layout.0.push as usize {
206            return self.fail("push_constants: beyond the layout's block, or not in multiples of 4");
207        }
208        self.w.extend_from_slice(&[OP_PUSH, offset, bytes.len() as u32 / 4]);
209        self.w.extend(bytes.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])));
210    }
211
212    pub fn dispatch(&mut self, x: u32, y: u32, z: u32) {
213        if !self.outside("dispatch in a render pass") {
214            return;
215        }
216        if self.compute.is_none() {
217            return self.fail("dispatch without a pipeline");
218        }
219        self.w.extend_from_slice(&[OP_DISPATCH, x, y, z]);
220    }
221
222    /// workgroup counts (3 x u32) from buf at offset
223    pub fn dispatch_indirect(&mut self, buf: &'a Buffer, offset: u64) {
224        if !self.outside("dispatch_indirect in a render pass") {
225            return;
226        }
227        if self.compute.is_none() || !buf.usage().contains(BufferUsage::INDIRECT) || offset % 4 != 0 || offset + 12 > buf.size() {
228            return self.fail("dispatch_indirect: no pipeline, no INDIRECT usage, or outside the buffer");
229        }
230        let o = split(offset);
231        self.w.extend_from_slice(&[OP_DISPATCH_INDIRECT, buf.handle(), o[0], o[1]]);
232    }
233
234    pub fn begin_render(&mut self, desc: &RenderPassDesc<'_, 'a>) {
235        if !self.outside("begin_render in a render pass") {
236            return;
237        }
238        if desc.color.len() > COLOR_TARGETS_MAX || (desc.color.is_empty() && desc.depth.is_none()) {
239            return self.fail("begin_render: no attachments, or too many");
240        }
241        self.rendering = true;
242        self.render = None;
243        self.colors.clear();
244        self.colors.extend(desc.color.iter().map(|c| c.view.format()));
245        self.depth = desc.depth.as_ref().map(|d| d.view.format());
246        self.w.extend_from_slice(&[OP_BEGIN_RENDER, desc.color.len() as u32]);
247        for c in desc.color {
248            self.w.extend_from_slice(&[c.view.handle(), (c.load == Load::Keep) as u32, c.store as u32, c.clear[0].to_bits(), c.clear[1].to_bits(), c.clear[2].to_bits(), c.clear[3].to_bits()]);
249        }
250        match &desc.depth {
251            Some(d) => self.w.extend_from_slice(&[d.view.handle(), (d.load == Load::Keep) as u32, d.store as u32, d.clear.to_bits(), d.view.format().has_stencil() as u32]),
252            None => self.w.extend_from_slice(&[0; 5]),
253        }
254    }
255
256    pub fn end_render(&mut self) {
257        if self.inside("end_render outside a render pass") {
258            self.rendering = false;
259            self.render = None;
260            self.w.push(OP_END_RENDER);
261        }
262    }
263
264    pub fn set_render_pipeline(&mut self, p: &'a RenderPipeline) {
265        if self.inside("set_render_pipeline outside a render pass") {
266            if p.0.targets != self.colors || p.0.depth != self.depth {
267                return self.fail("set_render_pipeline: the pipeline's formats are not the render pass's");
268            }
269            self.render = Some(p);
270            self.w.extend_from_slice(&[OP_RENDER_PIPELINE, p.0.h.h]);
271        }
272    }
273
274    /// the viewport in pixels from the top left (depth range min ..= max)
275    pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
276        if self.inside("set_viewport outside a render pass") {
277            self.w.extend_from_slice(&[OP_VIEWPORT, x.to_bits(), y.to_bits(), w.to_bits(), h.to_bits(), min_depth.to_bits(), max_depth.to_bits()]);
278        }
279    }
280
281    pub fn set_scissor(&mut self, x: u32, y: u32, w: u32, h: u32) {
282        if self.inside("set_scissor outside a render pass") {
283            self.w.extend_from_slice(&[OP_SCISSOR, x, y, w, h]);
284        }
285    }
286
287    pub fn set_vertex_buffer(&mut self, slot: u32, buf: &'a Buffer, offset: u64) {
288        if !self.inside("set_vertex_buffer outside a render pass") {
289            return;
290        }
291        if !buf.usage().contains(BufferUsage::VERTEX) {
292            return self.fail("set_vertex_buffer: no VERTEX usage");
293        }
294        let o = split(offset);
295        self.w.extend_from_slice(&[OP_VERTEX, slot, buf.handle(), o[0], o[1]]);
296    }
297
298    pub fn set_index_buffer(&mut self, buf: &'a Buffer, offset: u64, format: IndexFormat) {
299        if !self.inside("set_index_buffer outside a render pass") {
300            return;
301        }
302        if !buf.usage().contains(BufferUsage::INDEX) {
303            return self.fail("set_index_buffer: no INDEX usage");
304        }
305        let o = split(offset);
306        self.w.extend_from_slice(&[OP_INDEX, buf.handle(), o[0], o[1], (format == IndexFormat::U32) as u32]);
307    }
308
309    fn drawing(&mut self) -> bool {
310        if !self.inside("a draw outside a render pass") {
311            return false;
312        }
313        if self.render.is_none() {
314            self.fail("a draw without a pipeline");
315            return false;
316        }
317        true
318    }
319
320    pub fn draw(&mut self, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
321        if self.drawing() {
322            self.w.extend_from_slice(&[OP_DRAW, vertices, instances, first_vertex, first_instance]);
323        }
324    }
325
326    pub fn draw_indexed(&mut self, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) {
327        if self.drawing() {
328            self.w.extend_from_slice(&[OP_DRAW_INDEXED, indices, instances, first_index, base_vertex as u32, first_instance]);
329        }
330    }
331
332    /// one draw: vertex count, instance count, first vertex, first instance (4 x u32)
333    pub fn draw_indirect(&mut self, buf: &'a Buffer, offset: u64) {
334        if !self.drawing() {
335            return;
336        }
337        if !buf.usage().contains(BufferUsage::INDIRECT) || offset % 4 != 0 || offset + 16 > buf.size() {
338            return self.fail("draw_indirect: no INDIRECT usage, or outside the buffer");
339        }
340        let o = split(offset);
341        self.w.extend_from_slice(&[OP_DRAW_INDIRECT, buf.handle(), o[0], o[1]]);
342    }
343
344    /// one indexed draw: index count, instance count, first index, base vertex (i32), first instance
345    pub fn draw_indexed_indirect(&mut self, buf: &'a Buffer, offset: u64) {
346        if !self.drawing() {
347            return;
348        }
349        if !buf.usage().contains(BufferUsage::INDIRECT) || offset % 4 != 0 || offset + 20 > buf.size() {
350            return self.fail("draw_indexed_indirect: no INDIRECT usage, or outside the buffer");
351        }
352        let o = split(offset);
353        self.w.extend_from_slice(&[OP_DRAW_INDEXED_INDIRECT, buf.handle(), o[0], o[1]]);
354    }
355
356    /// (level Voll)
357    pub fn draw_indexed_indirect_multi(&mut self, _buf: &'a Buffer, _offset: u64, _count: u32, _stride: u32) {
358        self.fail("draw_indexed_indirect_multi: level Voll");
359    }
360
361    /// (level Voll)
362    pub fn draw_indexed_indirect_count(&mut self, _buf: &'a Buffer, _offset: u64, _count_buf: &'a Buffer, _count_offset: u64, _max_count: u32, _stride: u32) {
363        self.fail("draw_indexed_indirect_count: level Voll");
364    }
365
366    /// (not built in the browser)
367    pub fn reset_timestamps(&mut self, _ts: &'a Timestamps, _first: u32, _n: u32) {
368        self.fail("timestamps in the browser");
369    }
370
371    /// (not built in the browser)
372    pub fn timestamp(&mut self, _ts: &'a Timestamps, _i: u32) {
373        self.fail("timestamps in the browser");
374    }
375
376    /// the recorded commands, or the first misuse
377    pub fn finish(mut self) -> Result<CommandBuffer<'a>> {
378        if self.rendering {
379            self.fail("finish inside a render pass");
380        }
381        if let Some(e) = self.err {
382            return Err(e);
383        }
384        Ok(CommandBuffer { words: core::mem::take(&mut self.w), _p: PhantomData })
385    }
386}