Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

GPU tessellation: an empty plan no longer fails buffer validation (#5049) (#5104)

raykholo0fb4a3e86809
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 9a00bf3b7e..a99f630158 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -103,7 +103,7 @@ pub type Result<T> = std::result::Result<T, GpuError>;
/// Bytes per evaluated vertex in [`GpuMesh::vertices`]: the position (x, y, z, 1) then the
/// normal (x, y, z, 0), each four f32.
-pub const VERTEX_STRIDE: u64 = 32;
+pub const VERTEX_STRIDE: u64 = std::mem::size_of::<[f32; VERTEX_WORDS]>() as u64;
/// Byte offset of the normal within a vertex.
pub const NORMAL_OFFSET: u64 = 16;
@@ -121,6 +121,7 @@ pub struct GpuMesh {
/// Per plan (in the order given), its vertices and indices.
pub parts: Vec<Part>,
bind: wgpu::BindGroup,
+ workgroups: u32,
// The inputs, kept until the evaluation has run.
_inputs: [wgpu::Buffer; 4],
}
@@ -290,17 +291,12 @@ impl TessGpu {
}
let d = &self.device;
let count = word(packed.count)?;
- let init = |label: &str, contents: &[u8], usage| {
- // wgpu rejects empty bindings: pad to one word.
- let contents = if contents.is_empty() { &[0u8; 16][..] } else { contents };
- d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage })
- };
let words = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let floats = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
- let params = init("tess params", &words(&[count, 0, 0, 0]), wgpu::BufferUsages::UNIFORM);
- let surfaces = init("tess surfaces", &words(&packed.surfaces), wgpu::BufferUsages::STORAGE);
- let data = init("tess data", &floats(&packed.data), wgpu::BufferUsages::STORAGE);
- let verts = init("tess vertices", &words(&packed.vertices), wgpu::BufferUsages::STORAGE);
+ let params = tess_buffer::<[u32; 4]>(d, "tess params", words(&[count, 0, 0, 0]), wgpu::BufferUsages::UNIFORM);
+ let surfaces = tess_buffer::<[u32; SURFACE_WORDS]>(d, "tess surfaces", words(&packed.surfaces), wgpu::BufferUsages::STORAGE);
+ let data = tess_buffer::<f32>(d, "tess data", floats(&packed.data), wgpu::BufferUsages::STORAGE);
+ let verts = tess_buffer::<[u32; VERTEX_WORDS]>(d, "tess vertices", words(&packed.vertices), wgpu::BufferUsages::STORAGE);
let vertices = d.create_buffer(&wgpu::BufferDescriptor {
label: Some("tess mesh vertices"),
size: (packed.count.max(1) as u64) * VERTEX_STRIDE,
@@ -323,7 +319,7 @@ impl TessGpu {
}
parts.push(Part { vertices: v0..offset, indices: i0..word(tri.len())? });
}
- let indices = init("tess mesh indices", &words(&tri), wgpu::BufferUsages::INDEX);
+ let indices = tess_buffer::<u32>(d, "tess mesh indices", words(&tri), wgpu::BufferUsages::INDEX);
let bind = d.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("tess mesh"),
layout: &self.layout,
@@ -343,6 +339,7 @@ impl TessGpu {
vertex_face,
parts,
bind,
+ workgroups: if packed.surfaces.is_empty() { 0 } else { count.div_ceil(WORKGROUP) },
_inputs: [params, surfaces, data, verts],
})
}
@@ -350,28 +347,29 @@ impl TessGpu {
/// Add `mesh`'s evaluation to `encoder` (one dispatch, no wait, nothing read back): once the
/// encoder is submitted, render passes after it read the evaluated vertices.
pub fn record(&self, encoder: &mut wgpu::CommandEncoder, mesh: &GpuMesh) {
+ if mesh.workgroups == 0 {
+ return;
+ }
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tess mesh"), timestamp_writes: None });
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &mesh.bind, &[]);
- pass.dispatch_workgroups(mesh.vertex_count.div_ceil(WORKGROUP).max(1), 1, 1);
+ pass.dispatch_workgroups(mesh.workgroups, 1, 1);
}
#[cfg(not(target_arch = "wasm32"))]
fn run(&self, packed: &Packed, vertices: &[u32], n: usize) -> Result<Vec<f32>> {
+ if n == 0 || packed.surfaces.is_empty() {
+ return Ok(Vec::new());
+ }
let d = &self.device;
let bytes_u32 = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let bytes_f32 = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let count = u32::try_from(n).map_err(|_| GpuError::Failed("batch too large".into()))?;
- let init = |label: &str, contents: &[u8], usage| {
- // wgpu rejects empty bindings: pad to one word.
- let contents = if contents.is_empty() { &[0u8; 16][..] } else { contents };
- d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage })
- };
- let params = init("tess params", &bytes_u32(&[count, 0, 0, 0]), wgpu::BufferUsages::UNIFORM);
- let surfaces = init("tess surfaces", &bytes_u32(&packed.surfaces), wgpu::BufferUsages::STORAGE);
- let data = init("tess data", &bytes_f32(&packed.data), wgpu::BufferUsages::STORAGE);
- let verts = init("tess vertices", &bytes_u32(vertices), wgpu::BufferUsages::STORAGE);
- let size = (n.max(1) * 32) as u64;
+ let params = tess_buffer::<[u32; 4]>(d, "tess params", bytes_u32(&[count, 0, 0, 0]), wgpu::BufferUsages::UNIFORM);
+ let surfaces = tess_buffer::<[u32; SURFACE_WORDS]>(d, "tess surfaces", bytes_u32(&packed.surfaces), wgpu::BufferUsages::STORAGE);
+ let data = tess_buffer::<f32>(d, "tess data", bytes_f32(&packed.data), wgpu::BufferUsages::STORAGE);
+ let verts = tess_buffer::<[u32; VERTEX_WORDS]>(d, "tess vertices", bytes_u32(vertices), wgpu::BufferUsages::STORAGE);
+ let size = (n as u64) * VERTEX_STRIDE;
let out = d.create_buffer(&wgpu::BufferDescriptor {
label: Some("tess out"),
size,
@@ -400,7 +398,7 @@ impl TessGpu {
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tess"), timestamp_writes: None });
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind, &[]);
- pass.dispatch_workgroups(count.div_ceil(WORKGROUP).max(1), 1, 1);
+ pass.dispatch_workgroups(count.div_ceil(WORKGROUP), 1, 1);
}
enc.copy_buffer_to_buffer(&out, 0, &read, 0, size);
self.queue.submit([enc.finish()]);
@@ -424,6 +422,12 @@ const VERTEX_WORDS: usize = 8;
/// Words per surface header (matches `Surface` in the shader).
const SURFACE_WORDS: usize = 12;
+// Each empty binding still needs a whole element of its packed shader representation.
+fn tess_buffer<T>(device: &wgpu::Device, label: &str, mut contents: Vec<u8>, usage: wgpu::BufferUsages) -> wgpu::Buffer {
+ contents.resize(contents.len().max(std::mem::size_of::<T>()), 0);
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: &contents, usage })
+}
+
/// A plan as the shader reads it.
struct Packed {
surfaces: Vec<u32>,
diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs
index 4d12aa2b1a..9492fe9088 100644
--- a/crates/gpu/src/tests.rs
+++ b/crates/gpu/src/tests.rs
@@ -228,6 +228,44 @@ fn a_scene_in_one_dispatch_matches_each_body_on_the_cpu() {
}
}
+fn check_empty_tessellation(gpu: &TessGpu, plan: &TessPlan) {
+ let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation);
+ let evaluated = ok(gpu.evaluate(plan));
+ assert!(evaluated.positions.is_empty());
+ assert!(evaluated.normals.is_empty());
+ assert!(evaluated.triangles.is_empty());
+
+ let mesh = ok(gpu.prepare(plan));
+ assert_eq!(mesh.vertex_count, 0);
+ assert_eq!(mesh.index_count, 0);
+ assert!(mesh._inputs[1].size() >= std::mem::size_of::<[u32; SURFACE_WORDS]>() as u64);
+ assert!(mesh._inputs[2].size() >= std::mem::size_of::<f32>() as u64);
+ assert!(mesh._inputs[3].size() >= std::mem::size_of::<[u32; VERTEX_WORDS]>() as u64);
+ let mut encoder = gpu.device.create_command_encoder(&Default::default());
+ gpu.record(&mut encoder, &mesh);
+ gpu.queue.submit([encoder.finish()]);
+ ok(gpu.device.poll(wgpu::PollType::wait_indefinitely()));
+ let error = pollster::block_on(scope.pop());
+ assert!(error.is_none(), "{error:?}");
+}
+
+#[test]
+fn tessellation_without_vertices_does_not_dispatch() {
+ let Some(gpu) = gpu() else { return };
+ let plan = TessPlan {
+ surfaces: vec![EvalSurface::Plane { origin: Vec3::ZERO, du: Vec3::X, dv: Vec3::Y }],
+ faces: vec![solidcraft_geom::tess::FacePlan { surface: Some(0), ..Default::default() }],
+ ..Default::default()
+ };
+ check_empty_tessellation(&gpu, &plan);
+}
+
+#[test]
+fn tessellation_without_surfaces_does_not_dispatch() {
+ let Some(gpu) = gpu() else { return };
+ check_empty_tessellation(&gpu, &TessPlan::default());
+}
+
/// Display meshing of a 400-hole plate (#303's benchmark): reference mesher, plan, CPU and GPU
/// evaluation. `cargo test --release -p solidcraft-gpu bench_plate -- --ignored --nocapture`.
#[test]