sgl-3d 0.2.0

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Raster geometry (the architecture's "Raster geometry"): the shared
//! buffers that hold what shadow casters draw from vertex and index buffers,
//! each mesh's positions and its own and its caster clusters' indices,
//! suballocated in slabs as Bevy b56fc29 packs meshes
//! (`crates/bevy_render/src/mesh/allocator.rs` over
//! `crates/bevy_render/src/slab_allocator.rs`, MIT OR Apache-2.0): slabs of
//! one element layout each, `SlabAllocatorSettings`' defaults for their
//! sizes, the first slab with room taken, a new one when none has it, data
//! at Bevy's large threshold given a slab of its own, and an emptied slab
//! released. Ranges within a slab come from the scene's range allocator
//! (`ranges`) rather than Bevy's `offset_allocator`. Where Bevy commits a
//! frame's allocations together, a range is placed and written at the scene
//! operation, and a slab grows by copying it through the queue, as the ray
//! source grows: an abandoned frame loses no content. A positions slab is
//! also bound whole as storage, through a group of its own, by the
//! GPU-built cascades' casters, which pull their positions from it
//! (bind_caster_positions.wgsl), so it stays within what the device binds.
use super::SceneError;
use super::ranges::Ranges;
use crate::shading::vertex::CasterVertex;

/// Bevy's `SlabAllocatorSettings::default()`: a slab's first size, its
/// largest size, the size of data given a slab of its own, and how a slab
/// grows.
const MIN_SLAB_BYTES: u64 = 1 << 20;
const MAX_SLAB_BYTES: u64 = 512 << 20;
const LARGE_BYTES: u64 = 256 << 20;
const GROWTH: f64 = 1.5;

/// What a slab holds: positions (`CasterVertex`), or `u32` indices, which
/// meshes and their caster clusters share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Elements {
    Positions,
    Indices,
}

impl Elements {
    /// An element's bytes, a multiple of the copy alignment, so any range
    /// of elements is written and copied whole.
    const fn size(self) -> u64 {
        match self {
            Self::Positions => std::mem::size_of::<CasterVertex>() as u64,
            Self::Indices => 4,
        }
    }

    fn usage(self) -> wgpu::BufferUsages {
        let copies = wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST;
        match self {
            Self::Positions => copies | wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE,
            Self::Indices => copies | wgpu::BufferUsages::INDEX,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Positions => "scene geometry positions",
            Self::Indices => "scene geometry indices",
        }
    }
}

/// A mesh's elements of one kind: their slab and where they start, in
/// elements. Empty ranges name no slab.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GeometryRange {
    pub slab: u32,
    pub first: u32,
    pub count: u32,
}

impl GeometryRange {
    pub const EMPTY: Self = Self {
        slab: u32::MAX,
        first: 0,
        count: 0,
    };
}

struct Slab {
    elements: Elements,
    buffer: wgpu::Buffer,
    /// A general slab's ranges, in elements; None for a slab one large
    /// range owns.
    ranges: Option<Ranges>,
    /// The elements its buffer holds.
    capacity: u32,
    /// A positions slab's caster positions group, over its buffer.
    group: Option<wgpu::BindGroup>,
}

pub(crate) struct GeometryBuffers {
    /// By identity; a released slab's identity is reused.
    slabs: Vec<Option<Slab>>,
    /// The largest slab of indices, in bytes: the device's largest buffer;
    /// and of positions, which the casters bind whole: also no more than a
    /// storage binding.
    limit: u64,
    positions_limit: u64,
    /// The caster positions layout, and its group over a stand-in buffer,
    /// which a set without slab positions binds.
    layout: wgpu::BindGroupLayout,
    no_positions: wgpu::BindGroup,
}

impl GeometryBuffers {
    pub fn new(device: &wgpu::Device) -> Self {
        let limits = device.limits();
        let layout = crate::shading::bind::caster_positions(device);
        let stand_in = crate::counters::buffer(
            device,
            &wgpu::BufferDescriptor {
                label: Some("no caster positions"),
                size: Elements::Positions.size(),
                usage: wgpu::BufferUsages::STORAGE,
                mapped_at_creation: false,
            },
        );
        Self {
            slabs: Vec::new(),
            limit: limits.max_buffer_size,
            positions_limit: limits
                .max_buffer_size
                .min(limits.max_storage_buffer_binding_size),
            no_positions: positions_group(device, &layout, &stand_in),
            layout,
        }
    }

    /// Slab `slab`'s buffer.
    pub fn buffer(&self, slab: u32) -> &wgpu::Buffer {
        &self.slabs[slab as usize]
            .as_ref()
            .expect("a placed range's slab lives")
            .buffer
    }

    /// The caster positions group of positions slab `slab`, or a stand-in
    /// for `GeometryRange::EMPTY`'s, which names none.
    pub fn positions_group(&self, slab: u32) -> &wgpu::BindGroup {
        if slab == GeometryRange::EMPTY.slab {
            return &self.no_positions;
        }
        self.slabs[slab as usize]
            .as_ref()
            .and_then(|slab| slab.group.as_ref())
            .expect("a placed positions range's slab lives")
    }

    /// Positions slabs of at most `bytes`, as on a device that binds no
    /// more, so a test's content fills several.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub fn limit_positions(&mut self, bytes: u64) {
        self.positions_limit = bytes;
    }

    /// How many positions slabs there are.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub fn positions_slabs(&self) -> usize {
        self.slabs
            .iter()
            .flatten()
            .filter(|slab| slab.elements == Elements::Positions)
            .count()
    }

    /// The largest slab of `elements`, in bytes.
    fn limit(&self, elements: Elements) -> u64 {
        match elements {
            Elements::Positions => self.positions_limit,
            Elements::Indices => self.limit,
        }
    }

    /// Places `count` elements of kind `elements`: in the first slab of
    /// that kind with room, growing it if it must, or in a new slab.
    pub fn place(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        elements: Elements,
        count: usize,
    ) -> Result<GeometryRange, SceneError> {
        if count == 0 {
            return Ok(GeometryRange::EMPTY);
        }
        let size = elements.size();
        let bytes = count as u64 * size;
        let count = u32::try_from(count).map_err(|_| SceneError::DeviceLimit)?;
        let limit = self.limit(elements);
        let largest = MAX_SLAB_BYTES.min(limit);
        if bytes >= LARGE_BYTES.min(largest) {
            self.place_large(device, elements, count, limit)
        } else {
            Ok(self.place_general(device, queue, elements, count, (largest / size) as u32))
        }
    }

    /// Writes `data`, the elements `range` was placed for.
    pub fn write(&self, queue: &wgpu::Queue, range: GeometryRange, data: &[u8]) {
        if range.count == 0 {
            return;
        }
        let slab = self.slabs[range.slab as usize]
            .as_ref()
            .expect("a placed range's slab lives");
        let size = slab.elements.size();
        debug_assert_eq!(
            data.len() as u64,
            u64::from(range.count) * size,
            "its elements"
        );
        crate::counters::write_buffer(queue, &slab.buffer, u64::from(range.first) * size, data);
    }

    /// `count` elements in the first general slab of `elements` with room,
    /// growing it by half again until they fit, up to `most` elements, or
    /// in a new slab.
    fn place_general(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        elements: Elements,
        count: u32,
        most: u32,
    ) -> GeometryRange {
        for (index, slot) in self.slabs.iter_mut().enumerate() {
            let Some(slab) = slot.as_mut().filter(|slab| slab.elements == elements) else {
                continue;
            };
            let Some(ranges) = slab.ranges.as_mut() else {
                continue;
            };
            let Some(range) = ranges.allocate(count) else {
                continue;
            };
            if range.end > most {
                ranges.free(range);
                continue;
            }
            if range.end > slab.capacity {
                let mut capacity = slab.capacity;
                while capacity < range.end {
                    capacity = ((f64::from(capacity) * GROWTH).ceil() as u32).min(most);
                }
                slab.grow(device, queue, capacity, &self.layout);
            }
            return GeometryRange {
                slab: index as u32,
                first: range.start,
                count,
            };
        }
        let capacity = (MIN_SLAB_BYTES.div_ceil(elements.size()) as u32)
            .max(count)
            .min(most);
        let mut ranges = Ranges::new(0);
        let range = ranges.allocate(count).expect("a new slab has room");
        let slab = self.insert(Slab::new(
            device,
            &self.layout,
            elements,
            Some(ranges),
            capacity,
        ));
        GeometryRange {
            slab,
            first: range.start,
            count,
        }
    }

    /// `count` elements in a slab of their own, of at most `limit` bytes.
    fn place_large(
        &mut self,
        device: &wgpu::Device,
        elements: Elements,
        count: u32,
        limit: u64,
    ) -> Result<GeometryRange, SceneError> {
        if u64::from(count) * elements.size() > limit {
            return Err(SceneError::DeviceLimit);
        }
        let slab = self.insert(Slab::new(device, &self.layout, elements, None, count));
        Ok(GeometryRange {
            slab,
            first: 0,
            count,
        })
    }

    fn insert(&mut self, slab: Slab) -> u32 {
        match self.slabs.iter().position(Option::is_none) {
            Some(free) => {
                self.slabs[free] = Some(slab);
                free as u32
            }
            None => {
                self.slabs.push(Some(slab));
                (self.slabs.len() - 1) as u32
            }
        }
    }

    /// Frees `range` for reuse, releasing its slab once it holds nothing.
    pub fn free(&mut self, range: GeometryRange) {
        if range.count == 0 {
            return;
        }
        let slot = &mut self.slabs[range.slab as usize];
        let slab = slot.as_mut().expect("a placed range's slab lives");
        let empty = match slab.ranges.as_mut() {
            Some(ranges) => {
                ranges.free(range.first..range.first + range.count);
                ranges.end() == 0
            }
            None => true,
        };
        if empty {
            *slot = None;
        }
    }

    /// The slabs' bytes, the bytes their ranges hold, and how many there
    /// are.
    #[cfg(any(test, feature = "diagnostics"))]
    pub fn sizes(&self) -> [u64; 3] {
        self.slabs
            .iter()
            .flatten()
            .fold([0; 3], |[bytes, live, count], slab| {
                let held = match &slab.ranges {
                    Some(ranges) => u64::from(ranges.end()) - ranges.free_units(),
                    None => u64::from(slab.capacity),
                };
                [
                    bytes + slab.buffer.size(),
                    live + held * slab.elements.size(),
                    count + 1,
                ]
            })
    }
}

impl Slab {
    /// A slab of `capacity` elements, with its caster positions group over
    /// `layout` where it holds positions.
    fn new(
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        elements: Elements,
        ranges: Option<Ranges>,
        capacity: u32,
    ) -> Self {
        let buffer = slab_buffer(device, elements, capacity);
        Self {
            group: (elements == Elements::Positions)
                .then(|| positions_group(device, layout, &buffer)),
            elements,
            buffer,
            ranges,
            capacity,
        }
    }

    /// Grows it to `capacity` elements, copying what it holds through the
    /// queue, never a frame's encoder, and binding the grown buffer.
    fn grow(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        capacity: u32,
        layout: &wgpu::BindGroupLayout,
    ) {
        crate::counters::geometry_growth();
        let grown = slab_buffer(device, self.elements, capacity);
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("grow scene geometry slab"),
        });
        encoder.copy_buffer_to_buffer(&self.buffer, 0, &grown, 0, self.buffer.size());
        queue.submit([encoder.finish()]);
        if self.group.is_some() {
            self.group = Some(positions_group(device, layout, &grown));
        }
        self.buffer = grown;
        self.capacity = capacity;
    }
}

/// The caster positions group (`shading::bind::caster_positions`) over
/// `buffer`.
fn positions_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    buffer: &wgpu::Buffer,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("caster positions"),
        layout,
        entries: &[wgpu::BindGroupEntry {
            binding: crate::shading::bind::caster::POSITIONS,
            resource: buffer.as_entire_binding(),
        }],
    })
}

fn slab_buffer(device: &wgpu::Device, elements: Elements, capacity: u32) -> wgpu::Buffer {
    crate::counters::buffer(
        device,
        &wgpu::BufferDescriptor {
            label: Some(elements.label()),
            size: u64::from(capacity) * elements.size(),
            usage: elements.usage(),
            mapped_at_creation: false,
        },
    )
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::{Elements, GeometryBuffers, MIN_SLAB_BYTES};
    use crate::shading::vertex::CasterVertex;
    use crate::test_support;

    // Plausible defect: a slab that grows loses what it held (a copy left
    // out, short or at the wrong offset), so every mesh placed before the
    // growth casts the wrong shadow. The oracle is the test's own data: a
    // mesh's positions, placed before a larger mesh outgrows the slab's
    // first megabyte, read back from the grown slab as they were given.
    #[test]
    fn a_grown_slab_keeps_what_it_held() {
        let Some((device, queue)) = test_support::device() else {
            return;
        };
        let mut geometry = GeometryBuffers::new(&device);
        let positions = |count: usize, from: f32| -> Vec<CasterVertex> {
            (0..count)
                .map(|index| CasterVertex {
                    position: [from + index as f32, -(index as f32), 0.5 * index as f32],
                })
                .collect()
        };
        let first = positions(100, 1.);
        let place_and_write = |geometry: &mut GeometryBuffers, data: &[CasterVertex]| {
            let range = geometry
                .place(&device, &queue, Elements::Positions, data.len())
                .unwrap();
            geometry.write(&queue, range, bytemuck::cast_slice(data));
            range
        };
        let placed = place_and_write(&mut geometry, &first);
        let larger = (MIN_SLAB_BYTES / Elements::Positions.size()) as usize;
        let grown = place_and_write(&mut geometry, &positions(larger, 1e4));
        assert_eq!(
            grown.slab, placed.slab,
            "the larger mesh grew the first slab"
        );
        let words = test_support::read_words(&device, &queue, geometry.buffer(placed.slab));
        let given: &[u32] = bytemuck::cast_slice(&first);
        let at = placed.first as usize * 3;
        assert_eq!(&words[at..at + given.len()], given);
    }
}