perf(wire): switch wire pipeline to instanced rendering

Step 3 of the wire pipeline cold-open optimization plan — the biggest
single lever.

Each segment used to upload as 6 vertices × 96 B = 576 B with the segment
payload (pos_a/pos_b/color/half_width/distance/pattern_length/pat0/pat1)
duplicated across all six corners of the quad. Wire pipeline now uploads
one INSTANCE per segment (88 B) and the vertex shader derives `which_end`
and `side` from `@builtin(vertex_index)` against a 6-entry corner table.

Net effect on cold open: ~6.5× less wire vertex memory and PCIe upload,
plus a smaller Vec to allocate and copy on the CPU side.

Wire instance attributes also collapse distance_a / distance_b into a
single mix() inside the vertex shader, so per-segment distance still
interpolates correctly for the GPU-side linetype dash test.

Touches the wire, wire_xray, and face3d-edges draw passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Hakan 2026-05-23 09:52:23 +03:00
commit 4b4f5c94cd
3 changed files with 123 additions and 133 deletions

View file

@ -158,7 +158,7 @@ impl Pipeline {
vertex: wgpu::VertexState {
module: &wire_shader,
entry_point: Some("vs_main"),
buffers: &[wire_gpu::WireVertex::layout()],
buffers: &[wire_gpu::WireInstance::layout()],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
primitive: wgpu::PrimitiveState {
@ -201,7 +201,7 @@ impl Pipeline {
vertex: wgpu::VertexState {
module: &wire_shader,
entry_point: Some("vs_main"),
buffers: &[wire_gpu::WireVertex::layout()],
buffers: &[wire_gpu::WireInstance::layout()],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
primitive: wgpu::PrimitiveState {
@ -1073,9 +1073,9 @@ impl Pipeline {
pass.set_pipeline(&self.wire_pipeline);
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
for edges in &self.gpu_face3d_edges {
if edges.vertex_count >= 6 {
pass.set_vertex_buffer(0, edges.vertex_buffer.slice(..));
pass.draw(0..edges.vertex_count, 0..1);
if edges.instance_count > 0 {
pass.set_vertex_buffer(0, edges.instance_buffer.slice(..));
pass.draw(0..6, 0..edges.instance_count);
}
}
}
@ -1109,7 +1109,7 @@ impl Pipeline {
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
let mut scissor_active = false;
for (i, wire) in self.gpu_wires.iter().enumerate() {
if wire.vertex_count < 6 {
if wire.instance_count == 0 {
continue;
}
match self.wire_pixel_scissors.get(i) {
@ -1123,8 +1123,8 @@ impl Pipeline {
}
_ => {}
}
pass.set_vertex_buffer(0, wire.vertex_buffer.slice(..));
pass.draw(0..wire.vertex_count, 0..1);
pass.set_vertex_buffer(0, wire.instance_buffer.slice(..));
pass.draw(0..6, 0..wire.instance_count);
}
if scissor_active {
pass.set_scissor_rect(0, 0, vp.width, vp.height);
@ -1213,9 +1213,9 @@ impl Pipeline {
pass.set_pipeline(&self.wire_xray_pipeline);
pass.set_bind_group(0, &self.uniform_bind_group, &[]);
for wire in &self.gpu_selected_wires {
if wire.vertex_count >= 6 {
pass.set_vertex_buffer(0, wire.vertex_buffer.slice(..));
pass.draw(0..wire.vertex_count, 0..1);
if wire.instance_count > 0 {
pass.set_vertex_buffer(0, wire.instance_buffer.slice(..));
pass.draw(0..6, 0..wire.instance_count);
}
}
}

View file

@ -1,27 +1,26 @@
// Wire GPU buffers — quad (TriangleList) rendering for thick lines.
// Wire GPU buffers — instanced quad rendering for thick lines.
//
// Each segment [A→B] emits 6 vertices (2 triangles). Every vertex carries
// both endpoints so the vertex shader can compute the screen-space
// perpendicular direction and expand the quad to the correct pixel width.
// Each segment [A→B] is one INSTANCE; the vertex shader expands a 6-vertex
// unit quad whose corners are derived from `@builtin(vertex_index)`. This
// cuts upload bandwidth by ~6.5× versus the old layout (which duplicated
// the segment payload across six vertex records).
//
// NaN sentinel: text glyphs pack multiple disconnected strokes into one
// WireModel, separated by [NaN, NaN, NaN] points. Segments where either
// endpoint contains NaN are silently skipped during upload.
// endpoint contains NaN are silently skipped during emission.
//
// Vertex layout (96 bytes, stride = 96):
// Instance layout (88 bytes, stride = 88, step_mode = Instance):
// pos_a [f32; 3] offset 0 12 B — segment start (world)
// pos_b [f32; 3] offset 12 12 B — segment end (world)
// which_end f32 offset 24 4 B — 0.0 = A end, 1.0 = B end
// side f32 offset 28 4 B — ±1.0 perpendicular side
// color [f32; 4] offset 32 16 B — RGBA [0,1]
// distance f32 offset 48 4 B — arc-length from wire start
// half_width f32 offset 52 4 B — half line width in pixels
// pattern_length f32 offset 56 4 B — dash pattern total length
// _pad f32 offset 60 4 B
// pat0 [f32; 4] offset 64 16 B — pattern elements 0-3
// pat1 [f32; 4] offset 80 16 B — pattern elements 4-7
// ------
// 96 B / vertex
// color [f32; 4] offset 24 16 B — RGBA [0,1]
// distance_a f32 offset 40 4 B — arc-length at endpoint A
// distance_b f32 offset 44 4 B — arc-length at endpoint B
// half_width f32 offset 48 4 B — half line width in pixels
// pattern_length f32 offset 52 4 B — dash pattern total length
// pat0 [f32; 4] offset 56 16 B — pattern elements 0-3
// pat1 [f32; 4] offset 72 16 B — pattern elements 4-7
// ------
// 88 B / instance
use crate::scene::wire_model::WireModel;
use iced::wgpu;
@ -32,15 +31,15 @@ use rayon::prelude::*;
/// `create_buffer_init` performs and avoids holding a second `Vec` worth of
/// memory during upload — meaningful on cold open where wire buffers can run
/// into the hundreds of MB.
fn vertex_buffer_mapped(
fn instance_buffer_mapped(
device: &wgpu::Device,
label: &str,
data: &[WireVertex],
data: &[WireInstance],
) -> wgpu::Buffer {
let bytes: &[u8] = bytemuck::cast_slice(data);
// wgpu rejects size-0 buffers; the renderer already guards `vertex_count`
// wgpu rejects size-0 buffers; the renderer already guards `instance_count`
// before issuing a draw, so a placeholder allocation is fine here.
let size = bytes.len().max(std::mem::size_of::<WireVertex>()) as u64;
let size = bytes.len().max(std::mem::size_of::<WireInstance>()) as u64;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size,
@ -55,29 +54,27 @@ fn vertex_buffer_mapped(
buf
}
// ── Vertex layout ─────────────────────────────────────────────────────────
// ── Instance layout ───────────────────────────────────────────────────────
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct WireVertex {
pub struct WireInstance {
pub pos_a: [f32; 3],
pub pos_b: [f32; 3],
pub which_end: f32,
pub side: f32,
pub color: [f32; 4],
pub distance: f32,
pub distance_a: f32,
pub distance_b: f32,
pub half_width: f32,
pub pattern_length: f32,
pub _pad: f32,
pub pat0: [f32; 4],
pub pat1: [f32; 4],
}
impl WireVertex {
impl WireInstance {
pub fn layout<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<WireVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
array_stride: std::mem::size_of::<WireInstance>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
@ -92,41 +89,36 @@ impl WireVertex {
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32,
}, // which_end
wgpu::VertexAttribute {
offset: 28,
shader_location: 3,
format: wgpu::VertexFormat::Float32,
}, // side
wgpu::VertexAttribute {
offset: 32,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
}, // color
wgpu::VertexAttribute {
offset: 40,
shader_location: 3,
format: wgpu::VertexFormat::Float32,
}, // distance_a
wgpu::VertexAttribute {
offset: 44,
shader_location: 4,
format: wgpu::VertexFormat::Float32,
}, // distance_b
wgpu::VertexAttribute {
offset: 48,
shader_location: 5,
format: wgpu::VertexFormat::Float32,
}, // distance
}, // half_width
wgpu::VertexAttribute {
offset: 52,
shader_location: 6,
format: wgpu::VertexFormat::Float32,
}, // half_width
}, // pattern_length
wgpu::VertexAttribute {
offset: 56,
shader_location: 7,
format: wgpu::VertexFormat::Float32,
}, // pattern_length
wgpu::VertexAttribute {
offset: 64,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
}, // pat0
wgpu::VertexAttribute {
offset: 80,
shader_location: 9,
offset: 72,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
}, // pat1
],
@ -137,18 +129,18 @@ impl WireVertex {
// ── GPU handle ────────────────────────────────────────────────────────────
pub struct WireGpu {
pub vertex_buffer: wgpu::Buffer,
pub vertex_count: u32,
pub instance_buffer: wgpu::Buffer,
pub instance_count: u32,
/// Paper-space bbox [x0, y0, x1, y1] for GPU scissor clipping.
/// Set only for viewport-projected wires; None for regular wires.
pub vp_scissor: Option<[f32; 4]>,
}
/// Expand one `WireModel` into its flat vertex stream (6 verts per finite
/// segment). Pulled out so both the single-wire and batched paths share the
/// same emission logic, and so the batched path can `par_iter().flat_map`
/// across wires on cold open.
fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
/// Expand one `WireModel` into its per-segment instance stream (1 instance per
/// finite segment). Pulled out so both the single-wire and batched paths share
/// the same emission logic, and so the batched path can `par_iter` across
/// wires on cold open.
fn emit_wire_instances(wire: &WireModel, color: [f32; 4]) -> Vec<WireInstance> {
let pat0 = [
wire.pattern[0],
wire.pattern[1],
@ -188,7 +180,7 @@ fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
}
}
let mut vertices: Vec<WireVertex> = Vec::with_capacity(seg_count * 6);
let mut instances: Vec<WireInstance> = Vec::with_capacity(seg_count);
for i in 0..seg_count {
let a = wire.points[i];
let b = wire.points[i + 1];
@ -201,32 +193,19 @@ fn emit_wire_vertices(wire: &WireModel, color: [f32; 4]) -> Vec<WireVertex> {
{
continue;
}
let dist_a = dists[i];
let dist_b = dists[i + 1];
let make = |which_end: f32, side: f32| -> WireVertex {
let dist = if which_end < 0.5 { dist_a } else { dist_b };
WireVertex {
pos_a: a,
pos_b: b,
which_end,
side,
color,
distance: dist,
half_width,
pattern_length: wire.pattern_length,
_pad: 0.0,
pat0,
pat1,
}
};
vertices.push(make(0.0, -1.0));
vertices.push(make(1.0, -1.0));
vertices.push(make(1.0, 1.0));
vertices.push(make(0.0, -1.0));
vertices.push(make(1.0, 1.0));
vertices.push(make(0.0, 1.0));
instances.push(WireInstance {
pos_a: a,
pos_b: b,
color,
distance_a: dists[i],
distance_b: dists[i + 1],
half_width,
pattern_length: wire.pattern_length,
pat0,
pat1,
});
}
vertices
instances
}
impl WireGpu {
@ -236,21 +215,23 @@ impl WireGpu {
g
}
/// Merge multiple WireModels into GPU buffers chunked to fit the 256 MB GPU limit.
/// Each wire keeps its own color and pattern — they're stored per-vertex.
/// Returns an empty Vec if the combined vertex list is empty.
/// Merge multiple WireModels into GPU instance buffers, chunked to fit the
/// 256 MB GPU limit. Each wire keeps its own color and pattern — they live
/// per-instance.
pub fn from_batch(device: &wgpu::Device, wires: &[WireModel]) -> Vec<Self> {
let total_segs: usize = wires.iter().map(|w| w.points.len().saturating_sub(1)).sum();
if total_segs == 0 {
return vec![];
}
// Parallel per-wire vertex emission. `flat_map_iter` keeps memory peak
// sane (one Vec<WireVertex> per wire, then concatenated) while letting
// rayon spread CPU work across cores. Ordering is preserved.
let vertices: Vec<WireVertex> = wires
// Parallel per-wire instance emission. Each wire's stream is
// independent — `block_cache` groups wires by style upstream, so order
// within a batch does not affect correctness. `reduce` concatenates the
// per-wire Vec<WireInstance> chunks while letting rayon spread work
// across cores.
let instances: Vec<WireInstance> = wires
.par_iter()
.map(|wire| emit_wire_vertices(wire, wire.color))
.map(|wire| emit_wire_instances(wire, wire.color))
.reduce(Vec::new, |mut acc, mut chunk| {
if acc.is_empty() {
chunk
@ -262,22 +243,22 @@ impl WireGpu {
}
});
if vertices.is_empty() {
if instances.is_empty() {
return vec![];
}
// GPU max buffer size is 256 MB; chunk to stay within the limit.
const MAX_VERTS: usize = 268_435_456 / std::mem::size_of::<WireVertex>();
const MAX_INSTANCES: usize = 268_435_456 / std::mem::size_of::<WireInstance>();
vertices
.chunks(MAX_VERTS)
instances
.chunks(MAX_INSTANCES)
.enumerate()
.map(|(i, chunk)| {
let label = format!("wire.batch.vbuf.{i}");
let vertex_buffer = vertex_buffer_mapped(device, &label, chunk);
let label = format!("wire.batch.ibuf.{i}");
let instance_buffer = instance_buffer_mapped(device, &label, chunk);
Self {
vertex_buffer,
vertex_count: chunk.len() as u32,
instance_buffer,
instance_count: chunk.len() as u32,
vp_scissor: None,
}
})
@ -285,15 +266,14 @@ impl WireGpu {
}
fn build(device: &wgpu::Device, wire: &WireModel, color: [f32; 4]) -> Self {
let vertices = emit_wire_vertices(wire, color);
let label = format!("wire.vbuf.{}", wire.name);
let vertex_buffer = vertex_buffer_mapped(device, &label, &vertices);
let instances = emit_wire_instances(wire, color);
let label = format!("wire.ibuf.{}", wire.name);
let instance_buffer = instance_buffer_mapped(device, &label, &instances);
Self {
vertex_buffer,
vertex_count: vertices.len() as u32,
instance_buffer,
instance_count: instances.len() as u32,
vp_scissor: None,
}
}
}