Step 2 of the wire pipeline cold-open optimization plan. Extracts the per-wire vertex expansion into a free function and drives it from `from_batch` via `par_iter().map(...).reduce(...)`. Per-wire emission is already independent (no shared state, no order coupling — `block_cache` groups wires by style upstream), so the parallel-then-concatenate shape is correctness-preserving. Cold-open wire upload now scales with available cores; a drawing with many short wires shows the biggest win. Also collapses two near-identical emission loops (`from_batch`, `build`) into one shared helper. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
299 lines
11 KiB
Rust
299 lines
11 KiB
Rust
// Wire GPU buffers — quad (TriangleList) 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.
|
|
//
|
|
// 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.
|
|
//
|
|
// Vertex layout (96 bytes, stride = 96):
|
|
// 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
|
|
|
|
use crate::scene::wire_model::WireModel;
|
|
use iced::wgpu;
|
|
use rayon::prelude::*;
|
|
|
|
/// Allocate a VERTEX buffer with `mapped_at_creation` and write `data` directly
|
|
/// into the mapped slice. Skips the intermediate staging copy that
|
|
/// `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(
|
|
device: &wgpu::Device,
|
|
label: &str,
|
|
data: &[WireVertex],
|
|
) -> wgpu::Buffer {
|
|
let bytes: &[u8] = bytemuck::cast_slice(data);
|
|
// wgpu rejects size-0 buffers; the renderer already guards `vertex_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 buf = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some(label),
|
|
size,
|
|
usage: wgpu::BufferUsages::VERTEX,
|
|
mapped_at_creation: true,
|
|
});
|
|
{
|
|
let mut view = buf.slice(..).get_mapped_range_mut();
|
|
view[..bytes.len()].copy_from_slice(bytes);
|
|
}
|
|
buf.unmap();
|
|
buf
|
|
}
|
|
|
|
// ── Vertex layout ─────────────────────────────────────────────────────────
|
|
|
|
#[repr(C)]
|
|
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
|
pub struct WireVertex {
|
|
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 half_width: f32,
|
|
pub pattern_length: f32,
|
|
pub _pad: f32,
|
|
pub pat0: [f32; 4],
|
|
pub pat1: [f32; 4],
|
|
}
|
|
|
|
impl WireVertex {
|
|
pub fn layout<'a>() -> wgpu::VertexBufferLayout<'a> {
|
|
wgpu::VertexBufferLayout {
|
|
array_stride: std::mem::size_of::<WireVertex>() as u64,
|
|
step_mode: wgpu::VertexStepMode::Vertex,
|
|
attributes: &[
|
|
wgpu::VertexAttribute {
|
|
offset: 0,
|
|
shader_location: 0,
|
|
format: wgpu::VertexFormat::Float32x3,
|
|
}, // pos_a
|
|
wgpu::VertexAttribute {
|
|
offset: 12,
|
|
shader_location: 1,
|
|
format: wgpu::VertexFormat::Float32x3,
|
|
}, // pos_b
|
|
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: 48,
|
|
shader_location: 5,
|
|
format: wgpu::VertexFormat::Float32,
|
|
}, // distance
|
|
wgpu::VertexAttribute {
|
|
offset: 52,
|
|
shader_location: 6,
|
|
format: wgpu::VertexFormat::Float32,
|
|
}, // half_width
|
|
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,
|
|
format: wgpu::VertexFormat::Float32x4,
|
|
}, // pat1
|
|
],
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── GPU handle ────────────────────────────────────────────────────────────
|
|
|
|
pub struct WireGpu {
|
|
pub vertex_buffer: wgpu::Buffer,
|
|
pub vertex_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> {
|
|
let pat0 = [
|
|
wire.pattern[0],
|
|
wire.pattern[1],
|
|
wire.pattern[2],
|
|
wire.pattern[3],
|
|
];
|
|
let pat1 = [
|
|
wire.pattern[4],
|
|
wire.pattern[5],
|
|
wire.pattern[6],
|
|
wire.pattern[7],
|
|
];
|
|
let half_width = wire.line_weight_px * 0.5;
|
|
|
|
let n = wire.points.len();
|
|
let seg_count = n.saturating_sub(1);
|
|
if seg_count == 0 {
|
|
return Vec::new();
|
|
}
|
|
|
|
let mut dists = vec![0.0_f32; n];
|
|
for i in 1..n {
|
|
let p = wire.points[i - 1];
|
|
let q = wire.points[i];
|
|
if !p[0].is_finite() || !q[0].is_finite() {
|
|
// plinegen=false: reset to 0 at the first real point after a NaN separator.
|
|
dists[i] = if !wire.plinegen && !p[0].is_finite() && q[0].is_finite() {
|
|
0.0
|
|
} else {
|
|
dists[i - 1]
|
|
};
|
|
} else {
|
|
let dx = q[0] - p[0];
|
|
let dy = q[1] - p[1];
|
|
let dz = q[2] - p[2];
|
|
dists[i] = dists[i - 1] + (dx * dx + dy * dy + dz * dz).sqrt();
|
|
}
|
|
}
|
|
|
|
let mut vertices: Vec<WireVertex> = Vec::with_capacity(seg_count * 6);
|
|
for i in 0..seg_count {
|
|
let a = wire.points[i];
|
|
let b = wire.points[i + 1];
|
|
if !a[0].is_finite()
|
|
|| !a[1].is_finite()
|
|
|| !a[2].is_finite()
|
|
|| !b[0].is_finite()
|
|
|| !b[1].is_finite()
|
|
|| !b[2].is_finite()
|
|
{
|
|
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));
|
|
}
|
|
vertices
|
|
}
|
|
|
|
impl WireGpu {
|
|
pub fn new(device: &wgpu::Device, wire: &WireModel) -> Self {
|
|
let mut g = Self::build(device, wire, wire.color);
|
|
g.vp_scissor = wire.vp_scissor;
|
|
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.
|
|
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
|
|
.par_iter()
|
|
.map(|wire| emit_wire_vertices(wire, wire.color))
|
|
.reduce(Vec::new, |mut acc, mut chunk| {
|
|
if acc.is_empty() {
|
|
chunk
|
|
} else if chunk.is_empty() {
|
|
acc
|
|
} else {
|
|
acc.append(&mut chunk);
|
|
acc
|
|
}
|
|
});
|
|
|
|
if vertices.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>();
|
|
|
|
vertices
|
|
.chunks(MAX_VERTS)
|
|
.enumerate()
|
|
.map(|(i, chunk)| {
|
|
let label = format!("wire.batch.vbuf.{i}");
|
|
let vertex_buffer = vertex_buffer_mapped(device, &label, chunk);
|
|
Self {
|
|
vertex_buffer,
|
|
vertex_count: chunk.len() as u32,
|
|
vp_scissor: None,
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
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);
|
|
|
|
Self {
|
|
vertex_buffer,
|
|
vertex_count: vertices.len() as u32,
|
|
vp_scissor: None,
|
|
}
|
|
}
|
|
}
|
|
|