Viewport: draw faded and see-through bodies from their plans with OIT (#7423)
* Viewport: palette-indexed scene and incremental appearance updates - Move triangle, line and instance colours and opacity into a per-scene palette (an R32Uint texture, WebGL2-safe); appearance edits update palette entries instead of vertex bytes. - Build CPU body triangles as one canonical vertex stream per block with opaque/glass/faded index lists; an opacity class change rewrites only the index list. - Cache resolved body appearances by a per-body key, so an edit resolves only the bodies whose look changed. - Split the model scene key from the session revision: selection and view-only commands no longer rebuild or upload the model scene. - Replace the O(n^2) section-index lookup and per-placement instance scan with hash lookups. Co-Authored-By: Claude Code <noreply@anthropic.com> * Viewport: skip unchanged palette work when rebuilding - Reuse each body's appearance key while the document is unchanged. - Leave a palette slot alone when its value did not change, and allocate every body's slots once before the build loop. Co-Authored-By: Claude Code <noreply@anthropic.com> * Viewport: measure scene rebuild cost by edit kind An ignored scale test times the scene build after selection, appearance, theme and one-body geometry edits at 200, 1,000 and 5,000 bodies. Co-Authored-By: Claude Code <noreply@anthropic.com> * Viewport: read faded grid alphas through the scene palette The grid-fade tests now resolve line palette indices instead of reading the line record's old colour byte. Co-Authored-By: Claude Code <noreply@anthropic.com> * Viewport: measure rebuild cost on few large meshes Adds the 20/100-torus case where a block rebuild used to re-emit a large part of the model. Co-Authored-By: Claude Code <noreply@anthropic.com> * Viewport: measure rebuild cost on an assembly Unique detailed parts plus one component placed many times, timed for selection, part and component colour, opacity, theme, hide and move. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: draw block classes as vertex runs, not index lists A body's vertices are three per triangle in mesh order, so each draw class is a few runs of the block's vertex buffer: all-opaque blocks need no index buffer, and an opacity class change uploads nothing. A fragmented class (more than 64 runs) falls back to one index buffer. Each triangle is written as one record into a block reserved up front, which takes the cold scene build of a 7.1M-triangle assembly from 97 ms to 55 ms (main: 83 ms). Also fix reindexing a block whose bodies are drawn elsewhere: it walked the mesh's triangles from that body's start, past its own vertices. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: draw the highlight's own block, and light faded bodies without copies The highlight scene keeps its feedback (a hovered face, a body copied on the CPU) in a block of its own; since blocks became vertex runs, only the model's blocks were drawn, so that feedback was uploaded and never shown. Draw the highlight's blocks with its triangles. Whole faded and see-through bodies (another component active, or an appearance below full opacity) were lit by copying every triangle on the CPU at each hover change: 85 ms for a design row of 812 bodies. They are now drawn again from the model's own block vertices, in the highlight palette with their slots set to the highlight colour, or as placements of the model's shared triangles. The picture is the same as the copy's. Adds a GPU frame benchmark for document-tree hover (ignored test). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: count scene uploads, and keep the sorted glass stream across colour edits Renderer::uploads reports the bytes the model scene's last change uploaded (geometry, placements, palette rows, planned colours, re-evaluated vertices). Without order-independent transparency the global glass stream is kept while the blocks' see-through triangles are the same, so a colour edit on a glass body uploads palette rows only. Tests assert both on a GPU. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: keep palette slots and looks without rehashing every body A rebuild found every body's palette slots by name and wrote them back, allocating and hashing a new key per body, and copied every shown name into a set to check the arena still belongs to the design. Slots are written back only when a body's faces grew, and the looks cache is pruned only when it holds more bodies than are shown. Adds the STEP-file benchmark (SOLIDCRAFT_SCALE_STEP) and the colour command's own time to the assembly benchmark. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: round-pick construction lines through the scene palette The axis and centre feedback for round picks (#4610) drew with a raw colour; on the palette scene it is interned once like the other construction geometry. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Viewport: draw faded and see-through bodies from their plans with OIT A body faded outside the active component, or see-through, left the GPU tessellation path and was built triangle by triangle on the CPU, so working in a component of a large assembly rebuilt every other body. Where the renderer blends see-through surfaces order-independently (GpuTarget::oit, set by the renderer), a body whose faces share one class is drawn from its plan: chunks are split by class, opaque passes, AO and the section draw only opaque chunks, and the OIT pass draws the rest. The sorted fallback keeps them on the CPU. The model and its highlights decide through one rule (model_plan_class). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -37,6 +37,15 @@ fn clipped(p: vec3<f32>) -> bool {
|
||||
return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w;
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> u: U;
|
||||
// The scene's colours, 2048 entries to a row: an R32Uint texture rather than a storage buffer,
|
||||
// so the viewport draws on WebGL2 (which has no storage buffers) as well.
|
||||
@group(0) @binding(1) var pal: texture_2d<u32>;
|
||||
|
||||
/// The colour at palette entry `i`, as byte/255 (the old Unorm8x4 conversion, bit for bit).
|
||||
fn palette(i: u32) -> vec4<f32> {
|
||||
let v = textureLoad(pal, vec2<i32>(i32(i & 2047u), i32(i >> 11u)), 0).x;
|
||||
return vec4<f32>(f32(v & 255u), f32((v >> 8u) & 255u), f32((v >> 16u) & 255u), f32((v >> 24u) & 255u)) / 255.0;
|
||||
}
|
||||
|
||||
fn to_linear(c: vec3<f32>) -> vec3<f32> {
|
||||
return select(c, pow((c + vec3<f32>(0.055)) / vec3<f32>(1.055), vec3<f32>(2.4)), c > vec3<f32>(0.04045));
|
||||
@@ -57,11 +66,11 @@ struct TOut {
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_tri(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: vec4<f32>) -> TOut {
|
||||
fn vs_tri(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: u32) -> TOut {
|
||||
var o: TOut;
|
||||
o.pos = u.vp * vec4<f32>(p, 1.0);
|
||||
o.n = n;
|
||||
o.c = c;
|
||||
o.c = palette(c);
|
||||
o.wp = p;
|
||||
return o;
|
||||
}
|
||||
@@ -76,14 +85,14 @@ fn vs_tri_inst(
|
||||
@location(3) r0: vec4<f32>,
|
||||
@location(4) r1: vec4<f32>,
|
||||
@location(5) r2: vec4<f32>,
|
||||
@location(6) c: vec4<f32>,
|
||||
@location(6) c: u32,
|
||||
) -> TOut {
|
||||
let q = vec4<f32>(p, 1.0);
|
||||
let wp = vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q));
|
||||
var o: TOut;
|
||||
o.pos = u.vp * vec4<f32>(wp, 1.0);
|
||||
o.n = vec3<f32>(dot(r0.xyz, n), dot(r1.xyz, n), dot(r2.xyz, n));
|
||||
o.c = c;
|
||||
o.c = palette(c);
|
||||
o.wp = wp;
|
||||
return o;
|
||||
}
|
||||
@@ -106,14 +115,14 @@ fn vs_tri_inst_flat(
|
||||
@location(3) r0: vec4<f32>,
|
||||
@location(4) r1: vec4<f32>,
|
||||
@location(5) r2: vec4<f32>,
|
||||
@location(6) c: vec4<f32>,
|
||||
@location(6) c: u32,
|
||||
) -> FOut {
|
||||
let q = vec4<f32>(p, 1.0);
|
||||
let wp = vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q));
|
||||
var o: FOut;
|
||||
o.pos = u.vp * vec4<f32>(wp, 1.0);
|
||||
o.rp = wp - u.eye.xyz;
|
||||
o.c = c;
|
||||
o.c = palette(c);
|
||||
return o;
|
||||
}
|
||||
|
||||
@@ -546,7 +555,7 @@ fn lifted_z(p: vec3<f32>, c: vec4<f32>, px: f32, half: vec2<f32>) -> f32 {
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(1) b: vec3<f32>, @location(2) c: vec4<f32>, @location(3) wbits: u32) -> LOut {
|
||||
fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(1) b: vec3<f32>, @location(2) c: u32, @location(3) wbits: u32) -> LOut {
|
||||
var pa = a;
|
||||
var pb = b;
|
||||
var ca = u.vp * vec4<f32>(a, 1.0);
|
||||
@@ -596,7 +605,8 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(
|
||||
}
|
||||
var o: LOut;
|
||||
o.pos = vec4<f32>(base.xy + off / half * base.w, z, base.w);
|
||||
o.c = vec4<f32>(c.rgb, c.a * (wa / wd));
|
||||
let col = palette(c);
|
||||
o.c = vec4<f32>(col.rgb, col.a * (wa / wd));
|
||||
o.wp = select(pa, pb, t > 0.5);
|
||||
return o;
|
||||
}
|
||||
|
||||
+17
-13
@@ -76,7 +76,7 @@ impl Capturer {
|
||||
let samples =
|
||||
if samples > 1 && flags(FORMAT).sample_count_supported(samples) && flags(depth).sample_count_supported(samples) { samples } else { 1 };
|
||||
let scopes = error_scopes(&device);
|
||||
let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false }, None);
|
||||
let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false, oit: false }, None);
|
||||
let background = background_pipeline(&device, samples, depth);
|
||||
caught(scopes).map_or(Ok(()), |e| Err(GpuError::Pipeline(e)))?;
|
||||
let max_side = device.limits().max_texture_dimension_2d.min(MAX_SIDE);
|
||||
@@ -417,7 +417,7 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene {
|
||||
let faces: HashMap<u32, Rgb> = m.face_colors.iter().copied().collect();
|
||||
let mesh = &m.mesh;
|
||||
for (ti, t) in mesh.triangles.iter().enumerate() {
|
||||
let col = c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color));
|
||||
let col = sc.color(c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color)));
|
||||
let [Some(a), Some(b), Some(c)] = t.map(|k| mesh.positions.get(k as usize).copied()) else { continue };
|
||||
let flat = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z);
|
||||
for (k, p) in t.iter().zip([a, b, c]) {
|
||||
@@ -430,15 +430,17 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene {
|
||||
}
|
||||
}
|
||||
}
|
||||
let c4 = |c: Rgb, a: f32| [c.0, c.1, c.2, (a.clamp(0.0, 1.0) * 255.0).round() as u8];
|
||||
let alpha = |a: f32| (a.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
for l in &scene.grid {
|
||||
let col = sc.color([l.color.0, l.color.1, l.color.2, alpha(l.alpha)]);
|
||||
for w in l.points.windows(2) {
|
||||
sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32);
|
||||
sc.under_line(w[0].to_f32(), w[1].to_f32(), col, l.width as f32);
|
||||
}
|
||||
}
|
||||
for l in &scene.lines {
|
||||
let col = sc.color([l.color.0, l.color.1, l.color.2, alpha(l.alpha)]);
|
||||
for w in l.points.windows(2) {
|
||||
sc.line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32, l.on_top);
|
||||
sc.line(w[0].to_f32(), w[1].to_f32(), col, l.width as f32, l.on_top);
|
||||
}
|
||||
}
|
||||
sc
|
||||
@@ -567,9 +569,10 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
/// The alpha of a triangle `scene_geometry` wrote (the last byte of its first vertex).
|
||||
fn alpha(bytes: &[u8]) -> Option<u8> {
|
||||
bytes.get(TRI_SIZE - 1).copied()
|
||||
/// The colour of a triangle `scene_geometry` wrote (its first vertex's palette entry).
|
||||
fn color(scene: &GpuScene, bytes: &[u8]) -> Option<[u8; 4]> {
|
||||
let index = bytes.get(TRI_SIZE - 4..TRI_SIZE)?.try_into().ok().map(u32::from_le_bytes)?;
|
||||
scene.palette.get(crate::view::PaletteIndex(index))
|
||||
}
|
||||
|
||||
/// A body the design draws see-through goes into the scene's glass, at its own alpha, and
|
||||
@@ -582,17 +585,19 @@ mod tests {
|
||||
|
||||
let solid = geometry(1.0);
|
||||
assert_eq!((solid.tris.len(), solid.glass.len()), (3 * TRI_SIZE, 0));
|
||||
assert_eq!(alpha(&solid.tris), Some(255), "a solid body is drawn opaque");
|
||||
assert_eq!(color(&solid, &solid.tris), Some([200, 30, 30, 255]), "a solid body is drawn opaque");
|
||||
|
||||
let glass = geometry(0.3);
|
||||
assert_eq!((glass.tris.len(), glass.glass.len()), (0, 3 * TRI_SIZE), "a see-through body is glass, not a solid triangle");
|
||||
assert_eq!(alpha(&glass.glass), Some(77), "0.3 of 255");
|
||||
assert_eq!(color(&glass, &glass.glass).map(|c| c[3]), Some(77), "0.3 of 255");
|
||||
|
||||
// The threshold and the floor are the viewport's: an appearance a hair under 1 stays
|
||||
// solid, and opacity 0 still leaves a trace rather than vanishing.
|
||||
let almost = geometry(0.9995);
|
||||
assert_eq!((almost.tris.len(), almost.glass.len()), (3 * TRI_SIZE, 0), "an appearance a hair under 1 is still solid");
|
||||
assert_eq!(alpha(&geometry(0.0).glass), Some(13), "0.05 of 255");
|
||||
assert_eq!(color(&almost, &almost.tris).map(|c| c[3]), Some(255));
|
||||
let trace = geometry(0.0);
|
||||
assert_eq!(color(&trace, &trace.glass).map(|c| c[3]), Some(13), "0.05 of 255");
|
||||
}
|
||||
|
||||
/// A face with a colour of its own is drawn in that colour, and takes its body's opacity:
|
||||
@@ -602,7 +607,6 @@ mod tests {
|
||||
let mesh = SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: vec![(0, Rgb(0, 255, 0))], opacity: 0.5 };
|
||||
let sc = scene_geometry(&Scene { meshes: vec![mesh], ..Default::default() });
|
||||
assert_eq!(sc.tris.len(), 0);
|
||||
let first = sc.glass.get(TRI_SIZE - 4..TRI_SIZE);
|
||||
assert_eq!(first, Some(&[0, 255, 0, 128][..]), "the face's own colour at the body's alpha");
|
||||
assert_eq!(color(&sc, &sc.glass), Some([0, 255, 0, 128]), "the face's own colour at the body's alpha");
|
||||
}
|
||||
}
|
||||
|
||||
+894
-141
File diff suppressed because it is too large
Load Diff
@@ -116,7 +116,7 @@ impl Resources {
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
uniform: &wgpu::BindGroup,
|
||||
binds: [&wgpu::BindGroup; 2],
|
||||
radius: f32,
|
||||
size_px: [f32; 2],
|
||||
reversed: bool,
|
||||
@@ -152,8 +152,8 @@ impl Resources {
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_bind_group(0, uniform, &[]);
|
||||
for batch in batches {
|
||||
for (batch, bind) in batches.into_iter().zip(binds) {
|
||||
pass.set_bind_group(0, bind, &[]);
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
if let Some(tris) = &batch.tris {
|
||||
for (buffer, count) in &tris.parts {
|
||||
@@ -161,15 +161,21 @@ impl Resources {
|
||||
pass.draw(0..*count, 0..1);
|
||||
}
|
||||
}
|
||||
// The depth prepass is left out of the performance overlay's counts, as before.
|
||||
let uncounted = super::Tally::default();
|
||||
// The blocks' opaque triangles, for the same depth.
|
||||
for key in &batch.block_order {
|
||||
if let Some(block) = batch.blocks.get(key) {
|
||||
block.draw(&mut pass, super::TriClass::Opaque, &uncounted);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.planned_pipeline);
|
||||
for draw in &batch.planned {
|
||||
for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) {
|
||||
pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..));
|
||||
pass.set_vertex_buffer(1, draw.colors.slice(..));
|
||||
pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1);
|
||||
}
|
||||
// The depth prepass is left out of the performance overlay's counts, as before.
|
||||
let uncounted = super::Tally::default();
|
||||
for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) {
|
||||
draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted);
|
||||
}
|
||||
|
||||
@@ -80,12 +80,14 @@ impl Renderer {
|
||||
fn probe_pixels(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, blank_samples: u32) -> Result<bool> {
|
||||
const SIZE: u32 = 16;
|
||||
let mut model = GpuScene::default();
|
||||
let red = model.color([255, 0, 0, 255]);
|
||||
for p in [[-0.9, -0.9, 0.0], [0.9, -0.9, 0.0], [0.0, 0.9, 0.0]] {
|
||||
model.tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 255]);
|
||||
model.tri(p, [0.0, 0.0, 1.0], red);
|
||||
}
|
||||
let mut highlight = GpuScene::default();
|
||||
let blue = highlight.color([0, 0, 255, 64]);
|
||||
for p in [[-0.8, -0.8, 0.0], [0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, 0.8, 0.0]] {
|
||||
highlight.xray_tri(p, [0.0, 0.0, 1.0], [0, 0, 255, 64]);
|
||||
highlight.xray_tri(p, [0.0, 0.0, 1.0], blue);
|
||||
}
|
||||
let slot = |scene| Arc::new(Mutex::new(scene));
|
||||
let frame = Frame {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! sorted, on the CPU or the GPU, however many see-through triangles there are. The targets share
|
||||
//! the frame's depth (tested, not written), so the opaque model hides what lies behind it.
|
||||
|
||||
use super::{TriSource, depth_compare, instance_layout, shared_layout, tri_layout};
|
||||
use super::{TriSource, color_layout, depth_compare, instance_layout, planned_layout, shared_layout, tri_layout};
|
||||
|
||||
/// The accumulated colour (premultiplied, weighted) and alpha.
|
||||
const ACCUM: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
|
||||
@@ -38,6 +38,8 @@ fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
pub(super) struct Pipelines {
|
||||
/// Built triangles ([`tri_layout`]), and instanced meshes smooth and flat.
|
||||
pub built: wgpu::RenderPipeline,
|
||||
/// Faded and see-through bodies drawn from their plans' evaluated vertices.
|
||||
pub planned: wgpu::RenderPipeline,
|
||||
pub instanced: wgpu::RenderPipeline,
|
||||
pub instanced_flat: wgpu::RenderPipeline,
|
||||
composite: wgpu::RenderPipeline,
|
||||
@@ -90,6 +92,7 @@ impl Pipelines {
|
||||
}),
|
||||
];
|
||||
let built_buffers = [Some(tri_layout())];
|
||||
let evaluated = [Some(planned_layout()), Some(color_layout())];
|
||||
let placed = [Some(shared_layout()), Some(instance_layout())];
|
||||
let pipeline = |label: &str, source: TriSource| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
@@ -98,7 +101,11 @@ impl Pipelines {
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some(source.entry()),
|
||||
buffers: if source == TriSource::Built { &built_buffers[..] } else { &placed[..] },
|
||||
buffers: match source {
|
||||
TriSource::Built => &built_buffers[..],
|
||||
TriSource::Planned => &evaluated[..],
|
||||
TriSource::Instanced | TriSource::InstancedFlat => &placed[..],
|
||||
},
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
|
||||
@@ -121,6 +128,7 @@ impl Pipelines {
|
||||
})
|
||||
};
|
||||
let built = pipeline("sc_oit", TriSource::Built);
|
||||
let planned = pipeline("sc_oit_planned", TriSource::Planned);
|
||||
let instanced = pipeline("sc_oit_instanced", TriSource::Instanced);
|
||||
let instanced_flat = pipeline("sc_oit_instanced_flat", TriSource::InstancedFlat);
|
||||
let texture = |binding| wgpu::BindGroupLayoutEntry {
|
||||
@@ -183,7 +191,7 @@ impl Pipelines {
|
||||
log::info!("see-through surfaces are sorted (no order-independent transparency here: {e})");
|
||||
return None;
|
||||
}
|
||||
Some(Pipelines { built, instanced, instanced_flat, composite, bgl })
|
||||
Some(Pipelines { built, planned, instanced, instanced_flat, composite, bgl })
|
||||
}
|
||||
|
||||
/// The targets for a frame of `size` pixels at `samples` per pixel.
|
||||
|
||||
@@ -197,7 +197,8 @@ fn an_edge_on_a_face_draws_whole_at_any_angle() {
|
||||
fn a_selected_edge_on_a_grazing_face_draws_whole() {
|
||||
let highlight = |a: Vec3, b: Vec3, n: Vec3| {
|
||||
let mut sc = solidcraft_gpu::view::GpuScene::default();
|
||||
sc.lifted_line(a.to_f32(), b.to_f32(), [255, 0, 0, 255], 6.0, [n.to_f32(), n.to_f32()]);
|
||||
let red = sc.color([255, 0, 0, 255]);
|
||||
sc.lifted_line(a.to_f32(), b.to_f32(), red, 6.0, [n.to_f32(), n.to_f32()]);
|
||||
sc
|
||||
};
|
||||
let reference = |a: Vec3, b: Vec3| vec![SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), alpha: 1.0, width: 6.0, on_top: true }];
|
||||
|
||||
@@ -105,13 +105,15 @@ impl StraightPreview {
|
||||
let cache = self.cached.as_ref()?;
|
||||
let mut scene = GpuScene::default();
|
||||
let mut bounds = cache.bounds;
|
||||
let color = if operation == "cut" {
|
||||
colors.removed
|
||||
let (color, cut_edge) = if operation == "cut" {
|
||||
(colors.removed, [colors.removed[0], colors.removed[1], colors.removed[2], 255])
|
||||
} else if operation == "intersect" {
|
||||
[colors.added[0], colors.added[1], colors.added[2], colors.removed[3]]
|
||||
([colors.added[0], colors.added[1], colors.added[2], colors.removed[3]], colors.edge)
|
||||
} else {
|
||||
colors.added
|
||||
(colors.added, colors.edge)
|
||||
};
|
||||
let color = scene.color(color);
|
||||
let cut_edge = scene.color(cut_edge);
|
||||
let triangle = |scene: &mut GpuScene, points: [Vec3; 3], normal: Vec3| {
|
||||
for point in points {
|
||||
if matches!(operation, "cut" | "intersect") {
|
||||
@@ -131,7 +133,7 @@ impl StraightPreview {
|
||||
bounds.add(point);
|
||||
}
|
||||
}
|
||||
let edge_color = if operation == "cut" { [color[0], color[1], color[2], 255] } else { colors.edge };
|
||||
let edge_color = if operation == "cut" { cut_edge } else { scene.color(colors.edge) };
|
||||
for &[a, b] in &surface.edges {
|
||||
let normal = (b - a).cross(surface.normal).normalized()?;
|
||||
triangle(&mut scene, [a + low, b + low, b + high], normal);
|
||||
|
||||
+106
-4
@@ -8,9 +8,9 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui_wgpu::wgpu;
|
||||
pub use solidcraft_gpu::view::{
|
||||
AccessMap, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook, InstancedMesh,
|
||||
LINE_SIZE, LOD_PX, PBR_SIZE, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot, SharedTris, TRI_SIZE, level_for, placement_scale,
|
||||
supersampled_size,
|
||||
AccessMap, BlockBuilder, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook,
|
||||
InstancedMesh, LINE_SIZE, LOD_PX, MAX_PALETTE, PBR_SIZE, Palette, PaletteIndex, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot,
|
||||
SharedTris, TRI_SIZE, TriClass, extend_runs, level_for, placement_scale, runs_within, supersampled_size,
|
||||
};
|
||||
|
||||
/// A frame of the viewport as an egui paint callback.
|
||||
@@ -27,6 +27,8 @@ pub fn install(rs: &egui_wgpu::RenderState, scene: GpuTarget, window: GpuTarget,
|
||||
let scene = GpuTarget { tess: tess.is_some(), ..scene };
|
||||
let window = GpuTarget { tess: tess.is_some(), ..window };
|
||||
let res = Renderer::with_window_target(&rs.device, scene, window, tess);
|
||||
// What the renderer can do (order-independent transparency), not only what was asked for.
|
||||
let scene = res.target();
|
||||
let stats = res.stats();
|
||||
rs.renderer.write().callback_resources.insert(res);
|
||||
(scene, stats)
|
||||
@@ -333,7 +335,7 @@ fn offscreen(
|
||||
let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm };
|
||||
let depth = solidcraft_gpu::depth_format(&device, true);
|
||||
let compute = tess.and_then(|shader| solidcraft_gpu::view::tessellation(&adapter, &device, &queue, shader));
|
||||
let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some() };
|
||||
let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some(), oit: false };
|
||||
let mut resources = egui_wgpu::CallbackResources::default();
|
||||
resources.insert(Renderer::new(&device, target, compute));
|
||||
let none = || Arc::new(Mutex::new(None));
|
||||
@@ -428,6 +430,106 @@ fn offscreen(
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// A viewport renderer kept on an offscreen device of its own, for timing frames (prepare, paint,
|
||||
/// and the GPU finishing them) as the window would draw them. Scale measurements only.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) struct OffscreenFrames {
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
resources: egui_wgpu::CallbackResources,
|
||||
color: wgpu::TextureView,
|
||||
depth: wgpu::TextureView,
|
||||
size: u32,
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
impl OffscreenFrames {
|
||||
/// `None` without a GPU adapter. With `tess`, planned bodies are evaluated on the GPU.
|
||||
pub(crate) fn new(size: u32, tess: bool) -> Option<OffscreenFrames> {
|
||||
let (adapter, device, queue) = offscreen_device()?;
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let depth = solidcraft_gpu::depth_format(&device, true);
|
||||
let compute = if tess { solidcraft_gpu::view::tessellation(&adapter, &device, &queue, solidcraft_gpu::SHADER) } else { None };
|
||||
let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some(), oit: false };
|
||||
let mut resources = egui_wgpu::CallbackResources::default();
|
||||
resources.insert(Renderer::new(&device, target, compute));
|
||||
let texture = |format, usage| {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("offscreen frames"),
|
||||
size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
};
|
||||
let color = texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
let depth = texture(depth, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
Some(OffscreenFrames { device, queue, resources, color, depth, size })
|
||||
}
|
||||
|
||||
/// What the renderer can do, as the viewport is told when the window's renderer is
|
||||
/// installed (plans evaluated, order-independent transparency).
|
||||
pub(crate) fn target(&self) -> Option<GpuTarget> {
|
||||
self.resources.get::<Renderer>().map(Renderer::target)
|
||||
}
|
||||
|
||||
/// Whether the device evaluates plans (so scenes should be built with `tess`).
|
||||
pub(crate) fn tessellates(&self) -> bool {
|
||||
self.resources.get::<Renderer>().is_some_and(|r| r.target().tess)
|
||||
}
|
||||
|
||||
/// Draw one frame and wait for the GPU: milliseconds from `prepare` to the work finishing.
|
||||
pub(crate) fn frame(&mut self, frame: Frame) -> f64 {
|
||||
let started = std::time::Instant::now();
|
||||
let cb = ViewportCallback(frame);
|
||||
let mut encoder = self.device.create_command_encoder(&Default::default());
|
||||
let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: [self.size, self.size], pixels_per_point: 1.0 };
|
||||
let extra = egui_wgpu::CallbackTrait::prepare(&cb, &self.device, &self.queue, &screen, &mut encoder, &mut self.resources);
|
||||
{
|
||||
let mut pass = encoder
|
||||
.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("offscreen frames"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &self.color,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store },
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Store }),
|
||||
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Store }),
|
||||
}),
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
})
|
||||
.forget_lifetime();
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.size as f32, self.size as f32));
|
||||
let info = egui::PaintCallbackInfo { viewport: rect, clip_rect: rect, pixels_per_point: 1.0, screen_size_px: [self.size, self.size] };
|
||||
egui_wgpu::CallbackTrait::paint(&cb, info, &mut pass, &self.resources);
|
||||
}
|
||||
self.queue.submit(extra.into_iter().chain([encoder.finish()]));
|
||||
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
started.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// What the model scene's last change uploaded.
|
||||
pub(crate) fn uploads(&self) -> solidcraft_gpu::view::UploadStats {
|
||||
self.resources.get::<Renderer>().map(Renderer::uploads).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What the last frame drew.
|
||||
pub(crate) fn stats(&self) -> DrawStats {
|
||||
self.resources.get::<Renderer>().and_then(|r| r.stats().lock().ok().map(|s| *s)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The offscreen tests start the backends the app would: on Windows without `WGPU_BACKEND`
|
||||
|
||||
@@ -211,6 +211,7 @@ mod rule_editor;
|
||||
mod rule_editor_tests;
|
||||
pub mod save_job;
|
||||
pub mod scenario;
|
||||
pub(crate) mod scene_palette;
|
||||
pub mod select_other;
|
||||
pub mod selection;
|
||||
pub mod shell;
|
||||
@@ -778,6 +779,7 @@ impl SolveApp {
|
||||
depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits),
|
||||
samples: samples.max(1),
|
||||
tess: false,
|
||||
oit: false,
|
||||
};
|
||||
self.set_wgpu_targets(rs, target, target);
|
||||
}
|
||||
@@ -792,8 +794,9 @@ impl SolveApp {
|
||||
depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits),
|
||||
samples: samples.max(1),
|
||||
tess: false,
|
||||
oit: false,
|
||||
};
|
||||
let window = crate::gpu::GpuTarget { format: rs.target_format, depth: None, samples: 1, tess: false };
|
||||
let window = crate::gpu::GpuTarget { format: rs.target_format, depth: None, samples: 1, tess: false, oit: false };
|
||||
self.set_wgpu_targets(rs, scene, window);
|
||||
self.viewport.gpu.map_or(samples, |g| g.samples)
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ impl MovePreview {
|
||||
let m = rigid(translate, Vec3::ZERO, axis, angle);
|
||||
let copy = params.get("copy").and_then(Value::as_bool) == Some(true);
|
||||
let mut scene = GpuScene::default();
|
||||
let removed = scene.color(colors.removed);
|
||||
let mut bounds = Aabb3::EMPTY;
|
||||
for mesh in &cache.meshes {
|
||||
draw(&mut scene, mesh, &m, colors, &mut bounds);
|
||||
@@ -99,7 +100,7 @@ impl MovePreview {
|
||||
for t in &mesh.triangles {
|
||||
for k in t {
|
||||
if let (Some(p), Some(n)) = (mesh.positions.get(*k as usize), mesh.normals.get(*k as usize)) {
|
||||
scene.ghost_tri(p.to_f32(), n.to_f32(), colors.removed);
|
||||
scene.ghost_tri(p.to_f32(), n.to_f32(), removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,22 +121,24 @@ impl MovePreview {
|
||||
|
||||
/// `mesh` moved by `m`, in the colour of geometry the feature adds, with its shaded edges.
|
||||
fn draw(scene: &mut GpuScene, mesh: &Mesh, m: &Mat, colors: Colors, bounds: &mut Aabb3) {
|
||||
let added = scene.color(colors.added);
|
||||
for t in &mesh.triangles {
|
||||
for k in t {
|
||||
let i = *k as usize;
|
||||
if let (Some(p), Some(n)) = (mesh.positions.get(i), mesh.normals.get(i)) {
|
||||
let p = apply_point(m, *p);
|
||||
bounds.add(p);
|
||||
scene.tri(p.to_f32(), apply_vector(m, *n).to_f32(), colors.added);
|
||||
scene.tri(p.to_f32(), apply_vector(m, *n).to_f32(), added);
|
||||
}
|
||||
}
|
||||
}
|
||||
let edge = scene.color(colors.edge);
|
||||
for (ei, e) in mesh.edges.iter().enumerate() {
|
||||
if !mesh.shaded_edge_visible(ei) {
|
||||
continue;
|
||||
}
|
||||
for w in e.windows(2) {
|
||||
scene.line(apply_point(m, w[0]).to_f32(), apply_point(m, w[1]).to_f32(), colors.edge, 1.3, false);
|
||||
scene.line(apply_point(m, w[0]).to_f32(), apply_point(m, w[1]).to_f32(), edge, 1.3, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,6 +520,10 @@ fn state_bounds(st: &ModelState) -> Aabb3 {
|
||||
/// (red) and intersect.
|
||||
fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> Built {
|
||||
let mut sc = GpuScene::default();
|
||||
let removed = sc.color(c.removed);
|
||||
let intersect = sc.color([c.added[0], c.added[1], c.added[2], c.removed[3]]);
|
||||
let added = sc.color(c.added);
|
||||
let edge = if op == "cut" { sc.color([c.removed[0], c.removed[1], c.removed[2], 255]) } else { sc.color(c.edge) };
|
||||
for a in after.bodies.iter().filter(|a| before.body(&a.name).is_none()) {
|
||||
let m = a.mesh();
|
||||
for t in &m.triangles {
|
||||
@@ -527,14 +531,13 @@ fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> B
|
||||
let i = *k as usize;
|
||||
if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) {
|
||||
match op {
|
||||
"cut" => sc.xray_tri(p.to_f32(), n.to_f32(), c.removed),
|
||||
"intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), [c.added[0], c.added[1], c.added[2], c.removed[3]]),
|
||||
_ => sc.tri(p.to_f32(), n.to_f32(), c.added),
|
||||
"cut" => sc.xray_tri(p.to_f32(), n.to_f32(), removed),
|
||||
"intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), intersect),
|
||||
_ => sc.tri(p.to_f32(), n.to_f32(), added),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let edge = if op == "cut" { [c.removed[0], c.removed[1], c.removed[2], 255] } else { c.edge };
|
||||
for (ei, e) in m.edges.iter().enumerate() {
|
||||
if m.shaded_edge_visible(ei) {
|
||||
for w in e.windows(2) {
|
||||
@@ -586,6 +589,12 @@ fn same(a: &Mesh, b: &Mesh) -> bool {
|
||||
/// version of changed or removed bodies.
|
||||
pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
|
||||
let mut sc = GpuScene::default();
|
||||
let added_color = sc.color(c.added);
|
||||
let added_plane = sc.color([c.added[0], c.added[1], c.added[2], 64]);
|
||||
let body_color = sc.color(c.body);
|
||||
let new_body = sc.color(c.new_body);
|
||||
let removed = sc.color(c.removed);
|
||||
let edge = sc.color(c.edge);
|
||||
let mut replaced = Vec::new();
|
||||
for construct in &after.construct {
|
||||
if before.construct.iter().any(|old| old == construct) {
|
||||
@@ -594,14 +603,13 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
|
||||
if let solidcraft_engine::doc::construct::ConstructGeom::Plane(plane) = construct.geom {
|
||||
let (o, x, y) = (plane.origin, plane.x * 10.0, plane.y * 10.0);
|
||||
let quad = [o - x - y, o + x - y, o + x + y, o - x + y];
|
||||
let color = [c.added[0], c.added[1], c.added[2], 64];
|
||||
for triangle in [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]] {
|
||||
for p in triangle {
|
||||
sc.xray_tri(p.to_f32(), plane.normal().to_f32(), color);
|
||||
sc.xray_tri(p.to_f32(), plane.normal().to_f32(), added_plane);
|
||||
}
|
||||
}
|
||||
for (a, b) in Ring::from(quad).edges() {
|
||||
sc.line(a.to_f32(), b.to_f32(), c.added, 1.3, true);
|
||||
sc.line(a.to_f32(), b.to_f32(), added_color, 1.3, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,16 +630,16 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
|
||||
for (t, f) in am.triangles.iter().zip(&am.tri_face) {
|
||||
let new = added.get(*f as usize).copied().unwrap_or(true);
|
||||
let col = match (new, old.is_some()) {
|
||||
(false, _) => c.body,
|
||||
(true, true) => c.added,
|
||||
(true, false) => c.new_body,
|
||||
(false, _) => body_color,
|
||||
(true, true) => added_color,
|
||||
(true, false) => new_body,
|
||||
};
|
||||
for k in t {
|
||||
let i = *k as usize;
|
||||
if let (Some(p), Some(n)) = (am.positions.get(i), am.normals.get(i)) {
|
||||
sc.tri(p.to_f32(), n.to_f32(), col);
|
||||
if new && cut {
|
||||
sc.xray_tri(p.to_f32(), n.to_f32(), c.removed);
|
||||
sc.xray_tri(p.to_f32(), n.to_f32(), removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -641,7 +649,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
|
||||
continue;
|
||||
}
|
||||
for w in e.windows(2) {
|
||||
sc.line(w[0].to_f32(), w[1].to_f32(), c.edge, 1.3, false);
|
||||
sc.line(w[0].to_f32(), w[1].to_f32(), edge, 1.3, false);
|
||||
}
|
||||
}
|
||||
if old.is_some() {
|
||||
@@ -658,7 +666,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
|
||||
for k in t {
|
||||
let i = *k as usize;
|
||||
if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) {
|
||||
sc.ghost_tri(p.to_f32(), n.to_f32(), c.removed);
|
||||
sc.ghost_tri(p.to_f32(), n.to_f32(), removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1127,8 +1135,14 @@ mod tests {
|
||||
assert!((b.max.z - 18.0).abs() < 1e-6 && (b.max.y - 30.0).abs() < 1e-6, "on top, not at right angles: {b:?}");
|
||||
}
|
||||
|
||||
fn count(bytes: &[u8], stride: usize, col: [u8; 4]) -> usize {
|
||||
bytes.chunks(stride).filter(|v| v.get(24..28) == Some(&col[..])).count()
|
||||
fn count(scene: &GpuScene, bytes: &[u8], stride: usize, col: [u8; 4]) -> usize {
|
||||
bytes
|
||||
.chunks(stride)
|
||||
.filter(|v| {
|
||||
let Some(i) = v.get(24..28).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) else { return false };
|
||||
scene.palette.get(crate::gpu::PaletteIndex(i)) == Some(col)
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1138,10 +1152,11 @@ mod tests {
|
||||
let p = s.preview(&[("solid.hole".to_string(), json!({"position": [20, 15, 20], "diameter": 5, "depth": 10}))]).unwrap();
|
||||
let b = build(&p.before, &p.after, colors());
|
||||
// The hole's walls are drawn see-through in the cut colour (seen from any side).
|
||||
assert!(count(&b.scene.xray, 28, colors().removed) > 0);
|
||||
assert!(count(&b.scene, &b.scene.xray, 28, colors().removed) > 0);
|
||||
// A feature that only adds material shows no cut.
|
||||
let p = s.preview(&[("solid.box".to_string(), json!({"length": 10, "width": 10, "height": 30, "operation": "join"}))]).unwrap();
|
||||
assert_eq!(count(&build(&p.before, &p.after, colors()).scene.xray, 28, colors().removed), 0);
|
||||
let b = build(&p.before, &p.after, colors());
|
||||
assert_eq!(count(&b.scene, &b.scene.xray, 28, colors().removed), 0);
|
||||
}
|
||||
|
||||
fn plate() -> Session {
|
||||
@@ -1276,8 +1291,8 @@ mod tests {
|
||||
let (rev, undo) = (s.revision, s.undo.len());
|
||||
let b = compute(&s, &[("solid.fillet".into(), json!({"edges": [[0, 0, 10]], "radius": 3}))], colors()).unwrap();
|
||||
assert_eq!(b.replaced, vec!["Body1".to_string()]);
|
||||
let added = count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().added);
|
||||
let kept = count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().body);
|
||||
let added = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().added);
|
||||
let kept = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().body);
|
||||
assert!(added > 0 && kept > 0, "added {added} kept {kept}");
|
||||
assert!(!b.scene.ghost.is_empty());
|
||||
assert_eq!(s.revision, rev);
|
||||
@@ -1306,10 +1321,10 @@ mod tests {
|
||||
s.execute("sketch.finish", &json!({})).unwrap();
|
||||
let b = compute(&s, &[("solid.extrude".into(), json!({"distance": "15 mm"}))], colors()).unwrap();
|
||||
assert!(b.replaced.is_empty());
|
||||
assert_eq!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().body), 0);
|
||||
assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().body), 0);
|
||||
// #1805: a new body has its own colour, not a join's.
|
||||
assert!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().new_body) > 0);
|
||||
assert_eq!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().added), 0);
|
||||
assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().new_body) > 0);
|
||||
assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().added), 0);
|
||||
assert!(b.scene.ghost.is_empty());
|
||||
assert!(compute(&s, &[("solid.extrude".into(), json!({"distance": "1 +"}))], colors()).is_err());
|
||||
assert!(s.model.state().bodies.is_empty());
|
||||
@@ -1404,7 +1419,8 @@ mod tests {
|
||||
fn reset_hands_the_viewport_an_empty_scene() {
|
||||
let mut pv = PreviewState::default();
|
||||
let mut sc = GpuScene::default();
|
||||
sc.xray_tri([0.0; 3], [0.0, 0.0, 1.0], [255; 4]);
|
||||
let white = sc.color([255; 4]);
|
||||
sc.xray_tri([0.0; 3], [0.0, 0.0, 1.0], white);
|
||||
pv.set_scene(sc);
|
||||
pv.active = true;
|
||||
pv.replaced = vec!["Body1".into()];
|
||||
|
||||
@@ -1511,6 +1511,7 @@ pub fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> {
|
||||
});
|
||||
let [Some(a), Some(b), Some(c)] = vertices else { return Err("invalid product triangle".into()) };
|
||||
let rgba = [color[0], color[1], color[2], (opacity * 255.0).round() as u8];
|
||||
let index = gpu.color(rgba);
|
||||
for (p, n) in [a, b, c] {
|
||||
if let Some(surface) = surface {
|
||||
if n.iter().all(|v| *v == 0.0) {
|
||||
@@ -1518,9 +1519,9 @@ pub fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> {
|
||||
}
|
||||
gpu.pbr_tri(p, n, surface);
|
||||
} else if opacity < 0.999 {
|
||||
gpu.glass_tri(p, n, rgba);
|
||||
gpu.glass_tri(p, n, index);
|
||||
} else {
|
||||
gpu.tri(p, n, rgba);
|
||||
gpu.tri(p, n, index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +645,11 @@ fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() {
|
||||
let (key, gpu) = gpu_scene(&scene).unwrap();
|
||||
assert!(gpu.tris.is_empty());
|
||||
assert!(!gpu.glass.is_empty());
|
||||
assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| v[24..] == [51, 102, 153, 102]));
|
||||
let color = |v: &[u8]| {
|
||||
let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?;
|
||||
gpu.palette.get(crate::gpu::PaletteIndex(i))
|
||||
};
|
||||
assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102])));
|
||||
assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty());
|
||||
s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }];
|
||||
s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X));
|
||||
|
||||
@@ -71,6 +71,303 @@ fn frame_and_cheap_command_cost_by_body_count() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Times the model scene build after the edits that used to rebuild and upload everything:
|
||||
/// selection (a revision bump with no model change), an appearance colour and an opacity class
|
||||
/// change, a theme switch, and one body's geometry edit. Run with `--ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual palette measurement"]
|
||||
fn appearance_and_selection_rebuild_cost() {
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
for n in [200usize, 1000, 5000] {
|
||||
let mut h = grid(n);
|
||||
h.app.session.world_state().warm_meshes(|| true);
|
||||
h.frames(2);
|
||||
let body = h.app.session.world_state().bodies[0].name.clone();
|
||||
let cold = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let again = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let proj = crate::viewport::projection(&h.app, rect);
|
||||
let key = crate::viewport::display_scene_keys(&h.app, &proj).0;
|
||||
h.app.run("select.set", json!({"items":[{"type":"body","name":body}]})).unwrap();
|
||||
let selection_key_changed = crate::viewport::display_scene_keys(&h.app, &proj).0 != key;
|
||||
let selection = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("select.clear", json!({})).unwrap();
|
||||
h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699"})).unwrap();
|
||||
let colour = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699","opacity":0.5})).unwrap();
|
||||
let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let theme_name = if crate::theme::is_dark() { "light" } else { "dark" };
|
||||
let _ = h.call("ui.prefs", json!({"theme": theme_name}));
|
||||
let theme = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let geometry = match h.app.run("solid.move", json!({"bodies":[body.clone()], "translate":[1.0, 0.0, 0.0]})) {
|
||||
Ok(_) => ms(|| drop(crate::viewport::build_scene(&h.app))),
|
||||
Err(e) => {
|
||||
println!("MEASURE n={n} geometry edit refused: {e}");
|
||||
f64::NAN
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"MEASURE n={n} cold_ms={cold:.1} unchanged_ms={again:.1} selection_ms={selection:.1} selection_rebuilds={selection_key_changed} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} theme_ms={theme:.1} geometry_ms={geometry:.1}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same edits on a design of few, large meshes: the case where rebuilding a block rebuilt and
|
||||
/// re-uploaded a large part of the model. Run with `--ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual palette measurement"]
|
||||
fn large_body_scene_rebuild_cost() {
|
||||
for n in [20usize, 100] {
|
||||
let mut h = Harness::new();
|
||||
for k in 0..n {
|
||||
h.app
|
||||
.run("solid.torus", json!({"major": 100, "minor": 10, "center": [k as f64 * 220.0, 0.0, 0.0], "body_name": format!("T{k}")}))
|
||||
.unwrap();
|
||||
}
|
||||
h.app.session.world_state().warm_meshes(|| true);
|
||||
h.frames(2);
|
||||
let bodies = h.app.session.world_state().bodies.len();
|
||||
let triangles: usize = h.app.session.world_state().bodies.iter().map(|b| b.mesh().triangles.len()).sum();
|
||||
let body = h.app.session.world_state().bodies[0].name.clone();
|
||||
let cold = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699"})).unwrap();
|
||||
let colour = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699","opacity":0.5})).unwrap();
|
||||
let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let theme_name = if crate::theme::is_dark() { "light" } else { "dark" };
|
||||
let _ = h.call("ui.prefs", json!({"theme": theme_name}));
|
||||
let theme = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
println!(
|
||||
"LARGE n={n} bodies={bodies} triangles={triangles} cold_ms={cold:.1} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} theme_ms={theme:.1}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An assembly: `unique` detailed parts (a patterned torus, ~8,400 triangles each) and one
|
||||
/// detailed component placed `placed` times (drawn as instances). Settled, with warm meshes.
|
||||
fn assembly(unique: usize, placed: usize) -> Harness {
|
||||
let mut h = Harness::new();
|
||||
let per = |n: usize| (n as f64).sqrt().ceil().max(1.0) as usize;
|
||||
h.app.run("solid.torus", json!({"major": 40, "minor": 6, "center": [0, 0, 0], "body_name": "Part"})).unwrap();
|
||||
let (c1, c2) = (per(unique), unique.div_ceil(per(unique)));
|
||||
h.app
|
||||
.run(
|
||||
"solid.pattern.rectangular",
|
||||
json!({"bodies": ["Part"], "dir1": [1, 0, 0], "count1": c1, "spacing1": 100, "dir2": [0, 1, 0], "count2": c2, "spacing2": 100}),
|
||||
)
|
||||
.unwrap();
|
||||
h.app.run("solid.torus", json!({"major": 40, "minor": 6, "center": [0, 0, -200], "body_name": "Wheel"})).unwrap();
|
||||
h.app.run("component.from_bodies", json!({"bodies": ["Wheel"]})).unwrap();
|
||||
let (p1, p2) = (per(placed), placed.div_ceil(per(placed)));
|
||||
h.app
|
||||
.run(
|
||||
"solid.pattern.rectangular",
|
||||
json!({"components": ["Wheel"], "dir1": [1, 0, 0], "count1": p1, "spacing1": 100, "dir2": [0, 1, 0], "count2": p2, "spacing2": 100}),
|
||||
)
|
||||
.unwrap();
|
||||
h.app.session.world_state().warm_meshes(|| true);
|
||||
h.frames(3);
|
||||
h
|
||||
}
|
||||
|
||||
/// The edits made on an assembly, timed on the model scene build: selection, a part's colour and
|
||||
/// opacity, a component's colour (every placement), a theme switch, hiding a part, and moving one
|
||||
/// part. Run with `--ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual palette measurement"]
|
||||
fn assembly_scene_rebuild_cost() {
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
for (unique, placed) in [(100, 100), (300, 500)] {
|
||||
let mut h = assembly(unique, placed);
|
||||
let st = h.app.session.world_state();
|
||||
let bodies = st.bodies.len();
|
||||
let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum();
|
||||
let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap();
|
||||
drop(st);
|
||||
let cold = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let unchanged = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let proj = crate::viewport::projection(&h.app, rect);
|
||||
let key = crate::viewport::display_scene_keys(&h.app, &proj).0;
|
||||
h.app.run("select.set", json!({"items": [{"type": "body", "name": part}]})).unwrap();
|
||||
let selection_rebuilds = crate::viewport::display_scene_keys(&h.app, &proj).0 != key;
|
||||
let selection = if selection_rebuilds { ms(|| drop(crate::viewport::build_scene(&h.app))) } else { 0.0 };
|
||||
h.app.run("select.clear", json!({})).unwrap();
|
||||
// The command itself (the engine's refresh) and then the scene build.
|
||||
let colour_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [part.clone()], "color": "#336699"})).unwrap()));
|
||||
let colour = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("appearance.assign", json!({"bodies": [part.clone()], "color": "#336699", "opacity": 0.5})).unwrap();
|
||||
let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("appearance.assign", json!({"components": ["Wheel"], "color": "#cc6633"})).unwrap();
|
||||
let component_colour = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
let theme_name = if crate::theme::is_dark() { "light" } else { "dark" };
|
||||
let _ = h.call("ui.prefs", json!({"theme": theme_name}));
|
||||
let theme = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("browser.visibility", json!({"visible": false, "items": [part.clone()]})).unwrap();
|
||||
let hide = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
h.app.run("browser.visibility", json!({"visible": true, "items": [part.clone()]})).unwrap();
|
||||
let _ = crate::viewport::build_scene(&h.app);
|
||||
let geometry = match h.app.run("solid.move", json!({"bodies": [part.clone()], "translate": [1.0, 0.0, 0.0]})) {
|
||||
Ok(_) => ms(|| drop(crate::viewport::build_scene(&h.app))),
|
||||
Err(_) => f64::NAN,
|
||||
};
|
||||
println!(
|
||||
"ASSEMBLY unique={unique} placed={placed} bodies={bodies} triangles={triangles} cold_ms={cold:.1} unchanged_ms={unchanged:.1} selection_ms={selection:.1} colour_command_ms={colour_command:.1} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} component_colour_ms={component_colour:.1} theme_ms={theme:.1} hide_ms={hide:.1} geometry_ms={geometry:.1}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hovering the document tree on an assembly: the highlight scene built as the pointer moves
|
||||
/// from row to row (one part, one placement of the component, the component's every placement,
|
||||
/// the whole design), then back over rows it has lit before. Run with `--ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual highlight measurement"]
|
||||
fn assembly_tree_hover_highlight_cost() {
|
||||
for (unique, placed) in [(100, 100), (300, 500)] {
|
||||
let mut h = assembly(unique, placed);
|
||||
let _ = crate::viewport::build_scene(&h.app);
|
||||
let st = h.app.session.world_state();
|
||||
let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap();
|
||||
let wheels: Vec<String> = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect();
|
||||
let everything: Vec<String> = st.bodies.iter().map(|b| b.name.clone()).collect();
|
||||
drop(st);
|
||||
let rows = [("part", vec![part.clone()]), ("placement", wheels[..1].to_vec()), ("component", wheels.clone()), ("design", everything.clone())];
|
||||
let mut line = format!("HOVER unique={unique} placed={placed}");
|
||||
for (name, bodies) in rows.iter() {
|
||||
h.app.viewport.hover_bodies = bodies.clone();
|
||||
let first = ms(|| drop(crate::viewport::build_highlight(&h.app)));
|
||||
line.push_str(&format!(" {name}_ms={first:.2}"));
|
||||
}
|
||||
// Moving back and forth between two rows, as the pointer runs down the tree.
|
||||
let mut again = Vec::new();
|
||||
for i in 0..20 {
|
||||
h.app.viewport.hover_bodies = if i % 2 == 0 { vec![part.clone()] } else { wheels.clone() };
|
||||
again.push(ms(|| drop(crate::viewport::build_highlight(&h.app))));
|
||||
}
|
||||
again.sort_by(f64::total_cmp);
|
||||
line.push_str(&format!(" back_and_forth_median_ms={:.2}", again[again.len() / 2]));
|
||||
h.app.viewport.hover_bodies.clear();
|
||||
let none = ms(|| drop(crate::viewport::build_highlight(&h.app)));
|
||||
line.push_str(&format!(" none_ms={none:.2}"));
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame of the viewport for `app`'s camera, drawing the given model and highlight scenes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn view_frame(
|
||||
app: &crate::SolveApp,
|
||||
size: u32,
|
||||
model: (u64, &crate::gpu::SceneSlot),
|
||||
highlight: (u64, &crate::gpu::SceneSlot),
|
||||
) -> crate::gpu::Frame {
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size as f32, size as f32));
|
||||
let proj = crate::viewport::projection(app, rect);
|
||||
let e = proj.cam.eye().to_f32();
|
||||
let t = crate::theme::Tokens::get();
|
||||
let none = || std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
crate::gpu::Frame {
|
||||
product: false,
|
||||
key: model.0,
|
||||
slot: model.1.clone(),
|
||||
sketch_key: 0,
|
||||
sketch_slot: none(),
|
||||
hl_key: highlight.0,
|
||||
hl_slot: highlight.1.clone(),
|
||||
pv_key: 0,
|
||||
pv_slot: none(),
|
||||
pv_hide: false,
|
||||
view_proj: proj.vp.to_f32(),
|
||||
back: proj.cam.back().to_f32(),
|
||||
size_px: [size as f32; 2],
|
||||
clip: [0.0; 4],
|
||||
cap: [0.0; 4],
|
||||
images: Vec::new(),
|
||||
analysis: [0.0; 8],
|
||||
analysis_colors: crate::gpu::analysis_colors(&t.analysis),
|
||||
access: None,
|
||||
outline: false,
|
||||
eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }],
|
||||
ao_radius: 0.0,
|
||||
ssaa: 1.0,
|
||||
hover_tint: [f32::from(t.hover_face_lift) / 255.0; 3],
|
||||
selection_tint: [0.4, 0.6, 0.9],
|
||||
}
|
||||
}
|
||||
|
||||
/// Time hovering four rows of `h`'s tree (one part, one placement, every placement of the
|
||||
/// component, the whole design), each hover change building, uploading and drawing the highlight.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn hover_rows(h: &mut Harness, frames: &mut crate::gpu::OffscreenFrames, size: u32, model_key: u64, label: &str) -> String {
|
||||
let st = h.app.session.world_state();
|
||||
let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap();
|
||||
let wheels: Vec<String> = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect();
|
||||
let everything: Vec<String> = st.bodies.iter().map(|b| b.name.clone()).collect();
|
||||
drop(st);
|
||||
let model: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::viewport::build_scene(&h.app))));
|
||||
let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let cold = frames.frame(view_frame(&h.app, size, (model_key, &model), (model_key, &highlight)));
|
||||
let mut still = Vec::new();
|
||||
for _ in 0..5 {
|
||||
still.push(frames.frame(view_frame(&h.app, size, (model_key, &model), (model_key, &highlight))));
|
||||
}
|
||||
still.sort_by(f64::total_cmp);
|
||||
let mut line = format!("{label} cold_ms={cold:.1} still_ms={:.2} triangles={}", still[2], frames.stats().triangles);
|
||||
let rows = [("part", vec![part]), ("placement", wheels[..1].to_vec()), ("component", wheels.clone()), ("design", everything)];
|
||||
let mut key = model_key;
|
||||
for (name, bodies) in rows.iter() {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..7 {
|
||||
// Off the row and back on: each time a new highlight scene, as a sweep does.
|
||||
for hovered in [Vec::new(), bodies.clone()] {
|
||||
h.app.viewport.hover_bodies = hovered;
|
||||
key += 1;
|
||||
let built = std::time::Instant::now();
|
||||
*highlight.lock().unwrap() = Some(crate::viewport::build_highlight(&h.app));
|
||||
let build_ms = built.elapsed().as_secs_f64() * 1000.0;
|
||||
let ms = frames.frame(view_frame(&h.app, size, (model_key, &model), (key, &highlight)));
|
||||
if !h.app.viewport.hover_bodies.is_empty() {
|
||||
times.push((build_ms + ms, build_ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
times.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (total, build) = times[times.len() / 2];
|
||||
line.push_str(&format!(" {name}_ms={total:.2} {name}_build_ms={build:.2}"));
|
||||
}
|
||||
h.app.viewport.hover_bodies.clear();
|
||||
line
|
||||
}
|
||||
|
||||
/// Hovering the document tree on an assembly, as the window draws it: each hover change builds
|
||||
/// the highlight scene, uploads it and draws the frame (GPU work included), on an offscreen
|
||||
/// renderer with GPU tessellation where the device has it. Then the same with the component
|
||||
/// active (every other part faded, as when working in context) and with see-through parts.
|
||||
/// Skipped without a GPU adapter. Run with `--ignored --nocapture`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[ignore = "manual highlight measurement"]
|
||||
fn assembly_tree_hover_frame_cost() {
|
||||
const SIZE: u32 = 1024;
|
||||
let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, true) else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return;
|
||||
};
|
||||
for (design, (unique, placed)) in [(100, 100), (300, 500)].into_iter().enumerate() {
|
||||
// Keys of their own for each scene: the renderer keeps a scene while its key comes back.
|
||||
let base = 1_000_000 * (3 * design as u64 + 1);
|
||||
let mut h = assembly(unique, placed);
|
||||
h.app.viewport.gpu = frames.target();
|
||||
h.app.fit_view();
|
||||
let label = format!("HOVERFRAME unique={unique} placed={placed} tess={}", frames.tessellates());
|
||||
println!("{}", hover_rows(&mut h, &mut frames, SIZE, base, &format!("{label} mode=plain")));
|
||||
h.app.run("component.activate", json!({"component": "Wheel"})).unwrap();
|
||||
println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 1_000_000, &format!("{label} mode=component_active")));
|
||||
h.app.run("component.activate", json!({"component": 0})).unwrap();
|
||||
let parts: Vec<String> = h.app.session.world_state().bodies.iter().filter(|b| b.component == 0).map(|b| b.name.clone()).collect();
|
||||
h.app.run("appearance.assign", json!({"bodies": parts, "color": "#88aacc", "opacity": 0.5})).unwrap();
|
||||
println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 2_000_000, &format!("{label} mode=glass_parts")));
|
||||
}
|
||||
}
|
||||
|
||||
/// A design from a file (`SOLIDCRAFT_SCALE_DESIGN`), every browser folder open: the time of an
|
||||
/// idle frame and of the cheap commands, as [`frame_and_cheap_command_cost_by_body_count`].
|
||||
#[test]
|
||||
@@ -128,7 +425,105 @@ fn whole_body_highlight_cost_from_the_models_own_triangles() {
|
||||
let bodies = names.len();
|
||||
h.app.viewport.hover_bodies = names;
|
||||
let copied = ms(|| drop(crate::viewport::build_highlight(&h.app)));
|
||||
h.app.viewport.gpu = Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true });
|
||||
h.app.viewport.gpu =
|
||||
Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true, oit: false });
|
||||
let planned = ms(|| drop(crate::viewport::build_highlight(&h.app)));
|
||||
println!("HIGHLIGHT bodies={bodies} triangles={triangles} cpu_copy_ms={copied:.2} model_triangles_ms={planned:.2}");
|
||||
}
|
||||
|
||||
/// A STEP file (`SOLIDCRAFT_SCALE_STEP`), opened as the app opens one (a new design and
|
||||
/// `file.insert_step`): the time of each phase of opening it, of an idle frame with its tree, of
|
||||
/// the model scene and of appearance edits on it, and of hovering its bodies on an offscreen GPU
|
||||
/// (skipped without an adapter). Run with `--ignored --nocapture`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[ignore = "manual measurement on a STEP file"]
|
||||
fn step_file_cost() {
|
||||
let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_STEP") else { return };
|
||||
let mut h = Harness::new();
|
||||
let mut line = String::from("STEP");
|
||||
let phase = |line: &mut String, name: &str, ms: f64| {
|
||||
line.push_str(&format!(" {name}_ms={ms:.1}"));
|
||||
eprintln!("{name}: {ms:.1} ms");
|
||||
};
|
||||
let import = ms(|| drop(h.app.run("file.insert_step", json!({"path": path.to_string_lossy()})).unwrap()));
|
||||
phase(&mut line, "import", import);
|
||||
let world = ms(|| drop(h.app.session.world_state()));
|
||||
phase(&mut line, "world", world);
|
||||
let mesh = ms(|| h.app.session.world_state().warm_meshes(|| true));
|
||||
phase(&mut line, "mesh", mesh);
|
||||
let st = h.app.session.world_state();
|
||||
let bodies: Vec<String> = st.bodies.iter().map(|b| b.name.clone()).collect();
|
||||
let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum();
|
||||
let components = h.app.session.doc.components.len();
|
||||
let occurrences = h.app.session.doc.occurrences.len();
|
||||
drop(st);
|
||||
line.push_str(&format!(" bodies={} triangles={triangles} components={components} occurrences={occurrences}", bodies.len()));
|
||||
let first_frame = ms(|| h.frame());
|
||||
phase(&mut line, "first_frame", first_frame);
|
||||
let mut idle: Vec<f64> = (0..5).map(|_| ms(|| h.frame())).collect();
|
||||
idle.sort_by(f64::total_cmp);
|
||||
phase(&mut line, "idle_frame", idle[2]);
|
||||
let cold = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
phase(&mut line, "scene_cold", cold);
|
||||
let unchanged = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
phase(&mut line, "scene_unchanged", unchanged);
|
||||
let Some(part) = bodies.first().cloned() else {
|
||||
println!("{line}");
|
||||
return;
|
||||
};
|
||||
let colour_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [&part], "color": "#336699"})).unwrap()));
|
||||
phase(&mut line, "colour_command", colour_command);
|
||||
let colour = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
phase(&mut line, "colour_scene", colour);
|
||||
let opacity_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [&part], "color": "#336699", "opacity": 0.5})).unwrap()));
|
||||
phase(&mut line, "opacity_command", opacity_command);
|
||||
let opacity = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
phase(&mut line, "opacity_scene", opacity);
|
||||
let theme_name = if crate::theme::is_dark() { "light" } else { "dark" };
|
||||
let _ = h.call("ui.prefs", json!({"theme": theme_name}));
|
||||
let theme = ms(|| drop(crate::viewport::build_scene(&h.app)));
|
||||
phase(&mut line, "theme_scene", theme);
|
||||
let select = ms(|| drop(h.app.run("select.set", json!({"items": [{"type": "body", "name": &part}]})).unwrap()));
|
||||
phase(&mut line, "select_command", select);
|
||||
let selected_frame = ms(|| h.frame());
|
||||
phase(&mut line, "selected_frame", selected_frame);
|
||||
let _ = h.app.run("select.clear", json!({}));
|
||||
const SIZE: u32 = 1024;
|
||||
if let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, true) {
|
||||
h.app.viewport.gpu = frames.target();
|
||||
h.app.fit_view();
|
||||
let model: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::viewport::build_scene(&h.app))));
|
||||
let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let gpu_cold = frames.frame(view_frame(&h.app, SIZE, (1, &model), (1, &highlight)));
|
||||
phase(&mut line, "gpu_cold_frame", gpu_cold);
|
||||
let mut still: Vec<f64> = (0..5).map(|_| frames.frame(view_frame(&h.app, SIZE, (1, &model), (1, &highlight)))).collect();
|
||||
still.sort_by(f64::total_cmp);
|
||||
phase(&mut line, "gpu_still_frame", still[2]);
|
||||
line.push_str(&format!(" gpu_triangles={}", frames.stats().triangles));
|
||||
let tenth = bodies.len().div_ceil(10);
|
||||
let mut key = 1;
|
||||
for (name, hovered) in [("hover_one", vec![part.clone()]), ("hover_tenth", bodies[..tenth].to_vec()), ("hover_all", bodies.clone())] {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
for set in [Vec::new(), hovered.clone()] {
|
||||
h.app.viewport.hover_bodies = set;
|
||||
key += 1;
|
||||
let built = std::time::Instant::now();
|
||||
*highlight.lock().unwrap() = Some(crate::viewport::build_highlight(&h.app));
|
||||
let build = built.elapsed().as_secs_f64() * 1000.0;
|
||||
let frame = frames.frame(view_frame(&h.app, SIZE, (1, &model), (key, &highlight)));
|
||||
if !h.app.viewport.hover_bodies.is_empty() {
|
||||
times.push((build + frame, build));
|
||||
}
|
||||
}
|
||||
}
|
||||
times.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (total, build) = times[times.len() / 2];
|
||||
phase(&mut line, name, total);
|
||||
phase(&mut line, &format!("{name}_build"), build);
|
||||
}
|
||||
h.app.viewport.hover_bodies.clear();
|
||||
}
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Stable palette slots for the model scene.
|
||||
//!
|
||||
//! Cached block bytes index a scene palette (`solidcraft_gpu::view::Palette`). A body's faces,
|
||||
//! edges and placement keep their slots while the scene rebuilds, so an appearance or theme edit
|
||||
//! changes only palette entries — never a block's vertex bytes. Slots are append-only for the
|
||||
//! session and are reset when a different design replaces the one they belonged to.
|
||||
//!
|
||||
//! The model scene needs at most one stable slot per visible body face (plus a few per body), so
|
||||
//! the arena is capped by [`MAX_PALETTE`]. Past the cap a face falls back to its body's slot:
|
||||
//! editing such a face once rebuilds that body's block (the build still succeeds).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::gpu::{MAX_PALETTE, PaletteIndex};
|
||||
|
||||
/// The stable slots of one body: its own colour, its face range, its edges and its instances.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BodySlots {
|
||||
/// The body's own colour: the fallback for faces past the allocated range.
|
||||
pub body: PaletteIndex,
|
||||
/// The first face slot, or [`u32::MAX`] when the arena is full (every face uses `body`).
|
||||
pub faces: u32,
|
||||
pub face_capacity: u32,
|
||||
pub edge: PaletteIndex,
|
||||
pub hidden_edge: PaletteIndex,
|
||||
pub instance: PaletteIndex,
|
||||
}
|
||||
|
||||
impl BodySlots {
|
||||
/// The slot of face `face`, or the body's slot when the face has none.
|
||||
pub fn face(&self, face: usize) -> PaletteIndex {
|
||||
if self.faces == u32::MAX || face >= self.face_capacity as usize {
|
||||
return self.body;
|
||||
}
|
||||
PaletteIndex(self.faces.saturating_add(face as u32))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PaletteArena {
|
||||
entries: Vec<[u8; 4]>,
|
||||
bodies: HashMap<String, BodySlots>,
|
||||
/// Bumped when the arena is reset (a different design); cached blocks must rebuild then.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl PaletteArena {
|
||||
/// The stable entries, copied into the scene's palette.
|
||||
pub fn entries(&self) -> Vec<[u8; 4]> {
|
||||
self.entries.clone()
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
/// The slots of `name`, allocating them (and `face_count` face slots) the first time.
|
||||
pub fn body(&mut self, name: &str, face_count: usize) -> BodySlots {
|
||||
if let Some(slots) = self.bodies.get(name).copied() {
|
||||
let grown = self.grow_faces(&slots, face_count);
|
||||
// Written back only when it grew: most rebuilds find every body as it was.
|
||||
if grown != slots
|
||||
&& let Some(kept) = self.bodies.get_mut(name)
|
||||
{
|
||||
*kept = grown;
|
||||
}
|
||||
return grown;
|
||||
}
|
||||
let body = self.push();
|
||||
let edge = self.push();
|
||||
let hidden_edge = self.push();
|
||||
let instance = self.push();
|
||||
let slots = BodySlots { body, faces: u32::MAX, face_capacity: 0, edge, hidden_edge, instance };
|
||||
let slots = self.grow_faces(&slots, face_count);
|
||||
self.bodies.insert(name.to_string(), slots);
|
||||
slots
|
||||
}
|
||||
|
||||
/// Extend a body's face range when its face count grew. The range is reused when it is at the
|
||||
/// end of the arena; otherwise a new range is appended (the old one is left unused rather
|
||||
/// than moving an index cached blocks may refer to).
|
||||
fn grow_faces(&mut self, slots: &BodySlots, face_count: usize) -> BodySlots {
|
||||
let want = u32::try_from(face_count).unwrap_or(u32::MAX);
|
||||
if slots.faces != u32::MAX && slots.face_capacity >= want {
|
||||
return *slots;
|
||||
}
|
||||
let room = MAX_PALETTE.saturating_sub(self.entries.len());
|
||||
let need = usize::try_from(want).unwrap_or(usize::MAX).saturating_sub(slots.face_capacity as usize);
|
||||
let at_end = slots.faces != u32::MAX && slots.faces as usize + slots.face_capacity as usize == self.entries.len();
|
||||
if at_end && need <= room {
|
||||
self.entries.resize(self.entries.len() + need, [0; 4]);
|
||||
return BodySlots { face_capacity: want, ..*slots };
|
||||
}
|
||||
if want as usize <= room {
|
||||
let base = u32::try_from(self.entries.len()).unwrap_or(u32::MAX);
|
||||
self.entries.resize(self.entries.len() + want as usize, [0; 4]);
|
||||
return BodySlots { faces: base, face_capacity: want, ..*slots };
|
||||
}
|
||||
// Out of room: every face falls back to the body's own slot.
|
||||
BodySlots { faces: u32::MAX, face_capacity: 0, ..*slots }
|
||||
}
|
||||
|
||||
/// Append a zero entry; [`PaletteIndex(0)`] when the arena is full (never a panic).
|
||||
fn push(&mut self) -> PaletteIndex {
|
||||
if self.entries.len() >= MAX_PALETTE {
|
||||
return PaletteIndex(0);
|
||||
}
|
||||
let i = u32::try_from(self.entries.len()).unwrap_or(0);
|
||||
self.entries.push([0; 4]);
|
||||
PaletteIndex(i)
|
||||
}
|
||||
|
||||
/// The slots of `name`, if it has any (nothing is allocated).
|
||||
pub fn slots(&self, name: &str) -> Option<BodySlots> {
|
||||
self.bodies.get(name).copied()
|
||||
}
|
||||
|
||||
/// The colour at `slot`, if it is allocated.
|
||||
pub fn get(&self, slot: PaletteIndex) -> Option<[u8; 4]> {
|
||||
self.entries.get(slot.0 as usize).copied()
|
||||
}
|
||||
|
||||
/// Set a slot's colour; out-of-range slots are ignored.
|
||||
pub fn set(&mut self, slot: PaletteIndex, rgba: [u8; 4]) {
|
||||
if let Some(entry) = self.entries.get_mut(slot.0 as usize) {
|
||||
*entry = rgba;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every body when the scene belongs to a different design (no body name survives).
|
||||
/// A design that removed every body and then adds one keeps its slots (the empty set does
|
||||
/// not reset the arena).
|
||||
pub fn sync<'a>(&mut self, names: impl IntoIterator<Item = &'a str>) {
|
||||
if self.bodies.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut names = names.into_iter().peekable();
|
||||
if names.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
if !names.any(|n| self.bodies.contains_key(n)) {
|
||||
self.entries.clear();
|
||||
self.bodies.clear();
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn slots_survive_rebuilds_and_faces_fall_back_at_the_cap() {
|
||||
let mut arena = PaletteArena::default();
|
||||
let first = arena.body("A", 2);
|
||||
let again = arena.body("A", 2);
|
||||
assert_eq!(first, again);
|
||||
assert_ne!(first.face(0), first.face(1));
|
||||
assert_eq!(first.face(2), first.body);
|
||||
arena.set(first.face(0), [1, 2, 3, 4]);
|
||||
assert_eq!(arena.entries()[first.face(0).0 as usize], [1, 2, 3, 4]);
|
||||
// A grown face count reuses the range at the end of the arena.
|
||||
let grown = arena.body("A", 4);
|
||||
assert_eq!(grown.faces, first.faces);
|
||||
assert_ne!(grown.face(3), grown.body);
|
||||
// A new design with no shared names resets the slots.
|
||||
let generation = arena.generation();
|
||||
arena.sync(["B"]);
|
||||
assert_eq!(arena.generation(), generation.wrapping_add(1));
|
||||
assert!(arena.entries().is_empty());
|
||||
// An empty scene does not reset.
|
||||
let before = arena.generation();
|
||||
arena.sync([]);
|
||||
assert_eq!(arena.generation(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cap_falls_back_to_the_body_slot_without_panicking() {
|
||||
// The arena cannot allocate past MAX_PALETTE; simulate a full one by filling entries.
|
||||
let mut arena = PaletteArena { entries: vec![[0; 4]; MAX_PALETTE], ..Default::default() };
|
||||
let slots = arena.body("Big", 10);
|
||||
assert_eq!(slots.faces, u32::MAX);
|
||||
assert_eq!(slots.face(3), slots.body);
|
||||
// Every push after the cap is index 0, never an out-of-range write.
|
||||
assert_eq!(arena.push(), PaletteIndex(0));
|
||||
}
|
||||
}
|
||||
+836
-197
File diff suppressed because it is too large
Load Diff
@@ -34,12 +34,19 @@ fn a_finished_sketch_on_a_face_draws_a_halo_under_its_own_curves_only() {
|
||||
let (lines, remainder) = bytes.as_chunks::<{ crate::gpu::LINE_SIZE }>();
|
||||
assert!(remainder.is_empty());
|
||||
let halo = super::c4(tokens.sketch_halo);
|
||||
let halo_count = lines.iter().filter(|line| line[24..28] == halo).count();
|
||||
let halo_count = lines.iter().filter(|line| line_color(&scene, *line) == halo).count();
|
||||
crate::prefs::set(&mut app, &json!({"sketch_halo": false})).unwrap();
|
||||
assert_ne!(super::sketch_scene_key(&app, &projection), enabled_key, "changing the preference rebuilds the sketch scene");
|
||||
let disabled = super::build_sketch_scene(&app, &projection);
|
||||
let without_halos: Vec<u8> = lines.iter().filter(|line| line[24..28] != halo).flat_map(|line| line.iter().copied()).collect();
|
||||
assert_eq!(if finished { &disabled.lines } else { &disabled.overlay }, &without_halos, "off draws only the original curves");
|
||||
let disabled_bytes = if finished { &disabled.lines } else { &disabled.overlay };
|
||||
let (without_halos, _) = disabled_bytes.as_chunks::<{ crate::gpu::LINE_SIZE }>();
|
||||
let cores_only: Vec<&[u8]> = lines.iter().filter(|line| line_color(&scene, *line) != halo).map(|line| &line[..]).collect();
|
||||
assert_eq!(cores_only.len(), without_halos.len(), "off draws only the original curves");
|
||||
for (a, b) in cores_only.iter().zip(without_halos) {
|
||||
assert_eq!(a[..24], b[..24], "same segment");
|
||||
assert_eq!(line_color(&scene, a), line_color(&disabled, b), "same colour");
|
||||
assert_eq!(a[28..32], b[28..32], "same width");
|
||||
}
|
||||
if !finished {
|
||||
assert_eq!(halo_count, 0, "a sketch being edited has no halo");
|
||||
continue;
|
||||
@@ -49,13 +56,13 @@ fn a_finished_sketch_on_a_face_draws_a_halo_under_its_own_curves_only() {
|
||||
let projected = super::c4(tokens.sketch_projected);
|
||||
let mut cores = 0;
|
||||
let mut references = 0;
|
||||
for (index, core) in lines.iter().enumerate().filter(|(_, line)| line[24..28] != halo) {
|
||||
let rim = lines[..index].iter().find(|line| line[..24] == core[..24] && line[24..28] == halo);
|
||||
if core[24..28] == projected {
|
||||
for (index, core) in lines.iter().enumerate().filter(|(_, line)| line_color(&scene, *line) != halo) {
|
||||
let rim = lines[..index].iter().find(|line| line[..24] == core[..24] && line_color(&scene, *line) == halo);
|
||||
if line_color(&scene, core) == projected {
|
||||
assert!(rim.is_none(), "the face's projected outline has no halo");
|
||||
references += 1;
|
||||
} else {
|
||||
assert_eq!(core[24..28], super::c4(tokens.sketch_fixed));
|
||||
assert_eq!(line_color(&scene, core), super::c4(tokens.sketch_fixed));
|
||||
let rim = rim.unwrap();
|
||||
assert_eq!(width(rim), width(core) + super::SKETCH_HALO_WIDTH, "halo precedes the narrower core");
|
||||
cores += 1;
|
||||
@@ -109,17 +116,155 @@ fn placed_step_body_uses_imported_opacity_until_a_design_look_overrides_it() {
|
||||
);
|
||||
let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>();
|
||||
assert!(remainder.is_empty());
|
||||
assert!(vertices.iter().all(|v| v[27] == 102));
|
||||
assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 102));
|
||||
app.run("appearance.assign", json!({"bodies":[source],"color":"#336699","opacity":0.7})).unwrap();
|
||||
let scene = build_scene(&app);
|
||||
let scene = build_scene(&app).merged();
|
||||
let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>();
|
||||
assert!(remainder.is_empty());
|
||||
assert!(vertices.iter().all(|v| v[27] == 179));
|
||||
assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 179));
|
||||
app.run("appearance.assign", json!({"bodies":[source]})).unwrap();
|
||||
let scene = build_scene(&app);
|
||||
let scene = build_scene(&app).merged();
|
||||
let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>();
|
||||
assert!(remainder.is_empty());
|
||||
assert!(vertices.iter().all(|v| v[27] == 102));
|
||||
assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 102));
|
||||
}
|
||||
|
||||
/// The colour of a built triangle vertex: its palette index resolves through the scene.
|
||||
fn vertex_color(scene: &crate::gpu::GpuScene, v: &[u8]) -> [u8; 4] {
|
||||
let index = v.get(crate::gpu::TRI_SIZE - 4..crate::gpu::TRI_SIZE).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes);
|
||||
scene.palette.get(crate::gpu::PaletteIndex(index)).unwrap_or([0; 4])
|
||||
}
|
||||
|
||||
/// The colour of a line record: its palette index resolves through the scene.
|
||||
fn line_color(scene: &crate::gpu::GpuScene, line: &[u8]) -> [u8; 4] {
|
||||
let index = line.get(24..28).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes);
|
||||
scene.palette.get(crate::gpu::PaletteIndex(index)).unwrap_or([0; 4])
|
||||
}
|
||||
|
||||
/// The first vertex's palette index and its colour.
|
||||
fn first_vertex(scene: &crate::gpu::GpuScene, vertices: &[u8]) -> (u32, Option<[u8; 4]>) {
|
||||
let index = vertices.get(24..28).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes);
|
||||
(index, scene.palette.get(crate::gpu::PaletteIndex(index)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_does_not_rebuild_the_model_scene() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.ui.ground_shadow = false;
|
||||
h.app.set_origin_shown(false);
|
||||
h.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap();
|
||||
h.app.viewport.gpu =
|
||||
Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
|
||||
h.frame();
|
||||
let key = h.app.viewport.key;
|
||||
let highlight = h.app.viewport.hl_key;
|
||||
// Clear the scene the first frame uploaded; an untouched model must not upload another.
|
||||
let _ = h.app.viewport.slot.lock().unwrap().take();
|
||||
let name = h.app.session.world_state().bodies[0].name.clone();
|
||||
h.app.session.selection = vec![solidcraft_engine::Sel::Body { name }];
|
||||
h.frame();
|
||||
assert_eq!(h.app.viewport.key, key, "a selection does not change the model scene key");
|
||||
assert!(h.app.viewport.slot.lock().unwrap().is_none(), "and does not rebuild it");
|
||||
assert_ne!(h.app.viewport.hl_key, highlight, "the highlight scene does rebuild");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_appearance_edit_resolves_only_the_bodies_it_changes() {
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.ui.ground_shadow = false;
|
||||
app.set_origin_shown(false);
|
||||
app.run("solid.box", json!({"length": 20, "width": 15, "height": 10, "body_name": "A"})).unwrap();
|
||||
app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "body_name": "B"})).unwrap();
|
||||
let _ = build_scene(&app);
|
||||
let before = app.viewport.appearance.lock().unwrap().resolved;
|
||||
app.run("appearance.assign", json!({"bodies": ["A"], "color": "#336699"})).unwrap();
|
||||
let _ = build_scene(&app);
|
||||
let after = app.viewport.appearance.lock().unwrap().resolved;
|
||||
assert_eq!(after.saturating_sub(before), 1, "only the body whose look changed is resolved again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_edit_reuses_every_block_vertex() {
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.ui.ground_shadow = false;
|
||||
app.set_origin_shown(false);
|
||||
app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap();
|
||||
let name = app.session.world_state().bodies[0].name.clone();
|
||||
let first = build_scene(&app);
|
||||
let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block");
|
||||
let (key, vertices) = (block.key, block.bytes.vertices.clone());
|
||||
app.run("appearance.assign", json!({"bodies": [name], "color": "#336699"})).unwrap();
|
||||
let second = build_scene(&app);
|
||||
let block = second.blocks.iter().find(|b| b.key == key).expect("the block comes back");
|
||||
assert!(std::sync::Arc::ptr_eq(&vertices, &block.bytes.vertices), "a colour edit must not rebuild a vertex");
|
||||
assert_eq!(first_vertex(&second, &block.bytes.vertices).1, Some([51, 102, 153, 255]), "the palette carries the new colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opacity_class_change_keeps_vertices_and_rewrites_only_the_runs() {
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.ui.ground_shadow = false;
|
||||
app.set_origin_shown(false);
|
||||
app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap();
|
||||
let name = app.session.world_state().bodies[0].name.clone();
|
||||
let first = build_scene(&app);
|
||||
let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block");
|
||||
let (key, bytes) = (block.key, block.bytes.clone());
|
||||
app.run("appearance.assign", json!({"bodies": [name], "color": "#336699", "opacity": 0.5})).unwrap();
|
||||
let second = build_scene(&app);
|
||||
let block = second.blocks.iter().find(|b| b.key == key).expect("the block key is geometry's");
|
||||
assert!(std::sync::Arc::ptr_eq(&bytes.vertices, &block.bytes.vertices), "the class change keeps every vertex");
|
||||
assert!(!std::sync::Arc::ptr_eq(&bytes.opaque, &block.bytes.opaque), "the opaque runs change");
|
||||
assert!(block.bytes.opaque.is_empty() && !block.bytes.glass.is_empty(), "the triangles moved to the glass runs");
|
||||
let triangles: u32 = block.bytes.glass.iter().map(|r| r.len() as u32).sum::<u32>() / 3;
|
||||
assert_eq!(block.bytes.glass.len(), 1, "one body of one class is one run, drawn with no index buffer");
|
||||
assert_eq!(triangles, 12, "every triangle of the box");
|
||||
let vertex = block.bytes.glass.first().map_or(0, |r| r.start) as usize;
|
||||
let at = vertex * crate::gpu::TRI_SIZE;
|
||||
let colour = first_vertex(&second, block.bytes.vertices.get(at..).unwrap_or_default()).1;
|
||||
assert_eq!(colour.map(|c| c[3]), Some(128), "0.5 of 255");
|
||||
}
|
||||
|
||||
/// On the GPU, a colour edit writes palette rows and no geometry, also while the body is
|
||||
/// see-through (the sorted glass stream of the no-OIT path is kept).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn appearance_edits_upload_palette_rows_only() {
|
||||
const SIZE: u32 = 64;
|
||||
let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, false) else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return;
|
||||
};
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.ui.ground_shadow = false;
|
||||
app.set_origin_shown(false);
|
||||
app.viewport.gpu =
|
||||
Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
|
||||
app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap();
|
||||
app.fit_view();
|
||||
let name = app.session.world_state().bodies[0].name.clone();
|
||||
let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let mut key = 0;
|
||||
let mut draw = |app: &SolveApp| {
|
||||
key += 1;
|
||||
let slot: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(build_scene(app))));
|
||||
frames.frame(crate::scale_tests::view_frame(app, SIZE, (key, &slot), (0, &highlight)));
|
||||
frames.uploads()
|
||||
};
|
||||
let cold = draw(&app);
|
||||
assert!(cold.geometry > 0 && cold.palette > 0, "the first scene uploads its geometry and palette: {cold:?}");
|
||||
app.run("appearance.assign", json!({"bodies": [&name], "color": "#336699"})).unwrap();
|
||||
let colour = draw(&app);
|
||||
assert_eq!(colour.geometry, 0, "a colour edit uploads no geometry: {colour:?}");
|
||||
assert!(colour.palette > 0, "it writes the palette: {colour:?}");
|
||||
app.run("appearance.assign", json!({"bodies": [&name], "color": "#336699", "opacity": 0.5})).unwrap();
|
||||
let class = draw(&app);
|
||||
assert!(class.geometry <= 12 * 3 * crate::gpu::TRI_SIZE as u64, "a class change uploads at most the sorted glass stream: {class:?}");
|
||||
app.run("appearance.assign", json!({"bodies": [&name], "color": "#993366", "opacity": 0.5})).unwrap();
|
||||
let glass = draw(&app);
|
||||
assert_eq!(glass.geometry, 0, "a see-through body's colour edit uploads no geometry: {glass:?}");
|
||||
assert!(glass.palette > 0, "it writes the palette: {glass:?}");
|
||||
}
|
||||
|
||||
/// Exercise the live GPU scene slots: a fresh headless render always rebuilds and would hide
|
||||
@@ -131,7 +276,8 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() {
|
||||
h.app.ui.ground_shadow = false;
|
||||
h.app.set_origin_shown(false);
|
||||
h.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap();
|
||||
h.app.viewport.gpu = Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false });
|
||||
h.app.viewport.gpu =
|
||||
Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
|
||||
let body = h.app.session.world_state().bodies[0].name.clone();
|
||||
h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: body.clone() }];
|
||||
h.frame();
|
||||
@@ -153,7 +299,7 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() {
|
||||
let (vertices, remainder) = scene.tris.as_chunks::<{ crate::gpu::TRI_SIZE }>();
|
||||
assert!(remainder.is_empty() && !vertices.is_empty());
|
||||
let colour = super::c4(crate::theme::Tokens::get().body);
|
||||
assert!(vertices.iter().all(|v| v[24..28] == colour), "{theme}: stale body colour");
|
||||
assert!(vertices.iter().all(|v| vertex_color(&scene, v) == colour), "{theme}: stale body colour");
|
||||
assert_eq!(h.app.session.revision, revision, "theme changes must not edit the design");
|
||||
assert!(std::sync::Arc::ptr_eq(&mesh, &h.app.session.world_state().bodies[0].cached_mesh().unwrap()));
|
||||
h.frame();
|
||||
@@ -167,7 +313,7 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() {
|
||||
let scene = h.app.viewport.slot.lock().unwrap().take().unwrap().merged();
|
||||
let (vertices, _) = scene.tris.as_chunks::<{ crate::gpu::TRI_SIZE }>();
|
||||
assert!(!vertices.is_empty());
|
||||
assert!(vertices.iter().all(|v| v[24..28] == [51, 102, 153, 255]), "{theme}: explicit appearance preserved");
|
||||
assert!(vertices.iter().all(|v| vertex_color(&scene, v) == [51, 102, 153, 255]), "{theme}: explicit appearance preserved");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user