Skip to content

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

perf(ui): reuse assembly rendering caches during orbit (#2889)

cronos46ce12b7f05f
diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs
index 7ad8aba7f2..32649e0257 100644
--- a/crates/gpu/src/view.rs
+++ b/crates/gpu/src/view.rs
@@ -3854,6 +3854,9 @@ impl Renderer {
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
tris(pass, &res.ghost, &m.ghost);
tris(pass, &res.trans, &m.shadow);
+ pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);
+ tris(pass, &res.trans, &sk.shadow);
+ pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
if phase == Phase::BeforeSeeThrough {
return;
}
@@ -4751,18 +4754,35 @@ mod glass_tests {
scene.shadow_tri(p, shadow_color);
}
for samples in [1, 4] {
- let Some(shadow) = middle_pixel_with_samples(scene.clone(), true, samples) else {
- eprintln!("skipping: no GPU adapter");
- return;
- };
- assert!(shadow[..3].iter().all(|c| (125..=129).contains(c)), "{samples}× alpha-blended shadow: {shadow:?}");
- let mut occluded = scene.clone();
- let green = occluded.color([0, 255, 0, 255]);
- for mut p in square {
- p[2] = 5.0;
- occluded.tri(p, [0.0; 3], green);
+ for view_dependent in [false, true] {
+ let draw = |mut scene: GpuScene| {
+ let sketch = if view_dependent {
+ GpuScene { shadow: std::mem::take(&mut scene.shadow), palette: scene.palette.clone(), ..Default::default() }
+ } else {
+ GpuScene::default()
+ };
+ if view_dependent {
+ // The shadow must use its own palette, not the model's same-numbered slot.
+ assert!(Arc::make_mut(&mut scene.palette).set(shadow_color, [255, 0, 0, 255]));
+ }
+ middle_pixel_in_slots_with_samples(scene, sketch, true, samples)
+ };
+ let Some(shadow) = draw(scene.clone()) else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ assert!(
+ shadow[..3].iter().all(|c| (125..=129).contains(c)),
+ "{samples}x view-dependent={view_dependent} alpha-blended shadow: {shadow:?}"
+ );
+ let mut occluded = scene.clone();
+ let green = occluded.color([0, 255, 0, 255]);
+ for mut p in square {
+ p[2] = 5.0;
+ occluded.tri(p, [0.0; 3], green);
+ }
+ assert_eq!(draw(occluded), Some([0, 255, 0, 255]), "opaque geometry hides the ground shadow");
}
- assert_eq!(middle_pixel_with_samples(occluded, true, samples), Some([0, 255, 0, 255]), "opaque geometry hides the ground shadow");
}
}
@@ -4926,6 +4946,10 @@ mod glass_tests {
}
fn middle_pixel_with_samples(scene: GpuScene, oit: bool, samples: u32) -> Option<[u8; 4]> {
+ middle_pixel_in_slots_with_samples(scene, GpuScene::default(), oit, samples)
+ }
+
+ fn middle_pixel_in_slots_with_samples(scene: GpuScene, sketch: GpuScene, oit: bool, samples: u32) -> Option<[u8; 4]> {
const SIZE: u32 = 64;
let (_, device, queue) = crate::open_headless().ok()?;
let depth = crate::depth_format(&device, true);
@@ -4942,8 +4966,8 @@ mod glass_tests {
upload_error: None,
key: 1,
slot: Arc::new(Mutex::new(Some(scene))),
- sketch_key: 0,
- sketch_slot: none(),
+ sketch_key: 2,
+ sketch_slot: Arc::new(Mutex::new(Some(sketch))),
hl_key: 0,
hl_slot: none(),
pv_key: 0,
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index cd93dbb82e..66959144bf 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -1861,6 +1861,11 @@ pub(crate) fn timeline_joint_rows(app: &mut SolveApp, ui: &mut egui::Ui, ids: Op
for (id, name, kind, suppressed) in joints {
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), egui::Sense::click());
crate::scenario::publish_handle(&format!("timeline-joint:{name}"), rect.center());
+ // Keep the scroll extent and row IDs, but only lay out icons, text and menus for
+ // joints in the clipped viewport (an imported assembly can have thousands).
+ if !ui.is_rect_visible(rect) {
+ continue;
+ }
if app.tree.picked_joints.contains(&id) {
ui.painter().rect_filled(rect, t.radius_sm.saturating_sub(1), t.accent_soft);
} else if response.hovered() {
diff --git a/crates/ui-egui/src/view_pick.rs b/crates/ui-egui/src/view_pick.rs
index 39b4d21658..5053c3ac7f 100644
--- a/crates/ui-egui/src/view_pick.rs
+++ b/crates/ui-egui/src/view_pick.rs
@@ -130,7 +130,7 @@ pub fn pick_command(app: &mut SolveApp, p: &Value) -> Result<Value, String> {
// What the viewport shows now, and what a pick may not answer for.
let st = crate::open_meshing::shown_world(app);
let bounds = crate::viewport::body_bounds(app, &st);
- let active_bodies = app.session.active_occurrence_path.as_ref().and_then(|q| app.session.occurrence_bodies(q, true).ok());
+ let active_bodies = crate::viewport::active_body_names(app);
let replaced: &[String] = app.preview.effective_replaced();
let section = crate::viewport::section_plane(app);
let wireframe = app.ui.visual_style == 2;
@@ -215,7 +215,7 @@ fn face_candidates(
st: &solidcraft_engine::doc::ModelState,
bounds: &[(String, solidcraft_engine::geom::Aabb3)],
input: &Input,
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<crate::viewport::ActiveBodyNames>,
replaced: &[String],
include_ghosted: bool,
) -> Vec<Cand> {
@@ -312,7 +312,7 @@ fn section_cap(
first_kept: Option<f64>,
include_ghosted: bool,
replaced: &[String],
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<crate::viewport::ActiveBodyNames>,
) -> Option<(f64, String, Vec3)> {
let den = sn.dot(input.d);
if den.abs() < 1e-12 {
@@ -340,7 +340,7 @@ pub(crate) fn body_cut_at(
t_cap: f64,
include_ghosted: bool,
replaced: &[String],
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<crate::viewport::ActiveBodyNames>,
) -> Option<String> {
let walk_eps = 1e-6 * (1.0 + crate::viewport::scene_radius(app));
for (i, b) in st.bodies.iter().enumerate() {
@@ -392,7 +392,7 @@ fn near_edges(
pos: Pos2,
face_t: Option<f64>,
edge_px: f32,
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<crate::viewport::ActiveBodyNames>,
replaced: &[String],
include_ghosted: bool,
wireframe: bool,
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index e8e22c89d0..ca75607ac9 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -23,6 +23,10 @@ use crate::{SolveApp, icons};
#[path = "viewport_appearance_tests.rs"]
mod appearance_tests;
+#[cfg(test)]
+#[path = "viewport_navigation_cache_tests.rs"]
+mod navigation_cache_tests;
+
#[cfg(test)]
#[path = "viewport_overlays_tests.rs"]
mod overlays_tests;
@@ -87,6 +91,8 @@ pub struct ViewportState {
/// The sketches' box in the world of one world state (held, as `pick_bounds` is). Every
/// `projection` reads it, several times a frame, and each sketch's box samples its curves.
sketch_bounds: std::sync::Mutex<Option<(std::sync::Arc<solidcraft_engine::doc::ModelState>, solidcraft_engine::geom::Aabb3)>>,
+ /// Membership of the active assembly placement, shared by model and feedback rendering.
+ active_bodies: std::sync::Mutex<Option<ActiveBodies>>,
/// The model scene's blocks of bodies by key, from the last scene built.
pub(crate) blocks: std::sync::Mutex<std::collections::HashMap<u64, CachedBlock>>,
/// The triangles of each mesh the last scene drew as instances, by the mesh's address (the
@@ -140,6 +146,8 @@ pub struct ViewportState {
pub(crate) adapter: String,
pub(crate) slot: SceneSlot,
pub(crate) key: u64,
+ /// Ground geometry is reused independently of the camera-dependent sketch/grid scene.
+ shadow: std::sync::Mutex<Option<ShadowGeometry>>,
sketch_slot: SceneSlot,
sketch_key: u64,
physical_scale: f32,
@@ -581,7 +589,6 @@ fn scene_key(app: &SolveApp) -> u64 {
(std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h);
app.ui.visual_style.hash(&mut h);
app.preferences.vertex_markers.hash(&mut h);
- app.ui.ground_shadow.hash(&mut h);
solidcraft_engine::doc::display_quality::current().hash(&mut h);
lod_generation(app).hash(&mut h);
app.viewport.mesh_lods.generation().hash(&mut h);
@@ -591,7 +598,6 @@ fn scene_key(app: &SolveApp) -> u64 {
// The section plane (its cut outlines are part of the model scene).
section_plane(app).map(|(o, n)| [o.x, o.y, o.z, n.x, n.y, n.z].map(f64::to_bits)).hash(&mut h);
app.cam.up.hash(&mut h);
- (app.cam.pitch > 0.0).hash(&mut h);
app.session.visibility.hidden_bodies.hash(&mut h);
app.dialog.as_ref().map(|d| &d.edit_source_bodies).hash(&mut h);
app.session.visibility.hidden_occurrences.hash(&mut h);
@@ -634,6 +640,7 @@ fn scene_key(app: &SolveApp) -> u64 {
fn sketch_scene_key(app: &SolveApp, proj: &Proj) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
scene_key(app).hash(&mut h);
+ app.ui.ground_shadow.hash(&mut h);
// The grid this scene draws follows the view when the preference says so (#1470): turning it
// on or off redraws even while the camera holds still.
app.ui.show_grid.hash(&mut h);
@@ -676,8 +683,44 @@ fn sketch_color(t: &Tokens, c: Rgb) -> [u8; 4] {
}
}
+pub(crate) type ActiveBodyNames = std::sync::Arc<std::collections::HashSet<String>>;
+
+struct ActiveBodies {
+ doc: std::sync::Arc<solidcraft_engine::doc::Document>,
+ state: std::sync::Arc<solidcraft_engine::doc::ModelState>,
+ path: Vec<u64>,
+ names: ActiveBodyNames,
+}
+
+/// Expanding a nested assembly walks its placements. Camera and pointer changes do not change
+/// membership: keep it until the document, evaluated model or active placement changes. Hold
+/// both Arcs so a later allocation cannot reuse their addresses and resurrect stale names.
+pub(crate) fn active_body_names(app: &SolveApp) -> Option<ActiveBodyNames> {
+ let s = &app.session;
+ let Some(path) = s.active_occurrence_path.as_ref() else {
+ if let Ok(mut cache) = app.viewport.active_bodies.lock() {
+ *cache = None;
+ }
+ return None;
+ };
+ let state = s.model.state();
+ if let Some(names) = app.viewport.active_bodies.lock().ok().and_then(|cache| {
+ cache
+ .as_ref()
+ .filter(|c| std::sync::Arc::ptr_eq(&c.doc, &s.doc) && std::sync::Arc::ptr_eq(&c.state, &state) && c.path == *path)
+ .map(|c| c.names.clone())
+ }) {
+ return Some(names);
+ }
+ let names: ActiveBodyNames = std::sync::Arc::new(s.occurrence_bodies(path, true).ok()?.into_iter().collect());
+ if let Ok(mut cache) = app.viewport.active_bodies.lock() {
+ *cache = Some(ActiveBodies { doc: s.doc.clone(), state, path: path.clone(), names: names.clone() });
+ }
+ Some(names)
+}
+
/// With a component active, bodies outside it are drawn faded.
-pub(crate) fn body_faded(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<Vec<String>>) -> bool {
+pub(crate) fn body_faded(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<ActiveBodyNames>) -> bool {
let s = &app.session;
if let Some(names) = active_bodies {
!names.contains(&b.name)
@@ -790,7 +833,7 @@ fn lod_generation(app: &SolveApp) -> u64 {
fn shown_mesh(
app: &SolveApp,
b: &solidcraft_engine::doc::ModelBody,
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<ActiveBodyNames>,
) -> std::sync::Arc<solidcraft_engine::geom::Mesh> {
if let Some((_, mesh)) = refined(app, b) {
// Refined: faces drawn from the refined plan on the GPU or built from its mesh here.
@@ -1043,7 +1086,7 @@ fn plan_class(app: &SolveApp, faces: &[crate::gpu::TriClass]) -> Option<crate::g
/// The classes [`build_scene`] gives `b`'s faces: faded outside the active component, else
/// see-through below full opacity (the body's, or a face's own look).
-fn face_classes(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<Vec<String>>) -> Vec<crate::gpu::TriClass> {
+fn face_classes(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<ActiveBodyNames>) -> Vec<crate::gpu::TriClass> {
if body_faded(app, b, active_bodies) {
return vec![crate::gpu::TriClass::Faded; b.body.face_count()];
}
@@ -1058,7 +1101,7 @@ fn face_classes(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bo
/// Whether the model scene draws `b` from its plan's GPU-evaluated triangles (and with which
/// class), as [`build_scene`] decides: a live preview stands in for none.
-fn model_plan_class(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<Vec<String>>) -> Option<crate::gpu::TriClass> {
+fn model_plan_class(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<ActiveBodyNames>) -> Option<crate::gpu::TriClass> {
if app.preview.effective_replaced().contains(&b.name) {
return None;
}
@@ -1470,7 +1513,7 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
let s = &app.session;
// Bodies where their occurrences place them.
let st = crate::open_meshing::shown_world(app);
- let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok());
+ let active_bodies = active_body_names(app);
let (shaded, edges) = match app.ui.visual_style {
1 => (true, false),
2 => (false, true),
@@ -1670,9 +1713,6 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
*b = made;
}
sc.instanced = instances.finish(app);
- if app.ui.ground_shadow && app.ui.visual_style != 2 && app.cam.pitch > 0.0 {
- ground_shadow(&mut sc, app, &st);
- }
// Section: the outline of each body where the plane cuts it, in the view's text colour (#4146).
if let Some((o, n)) = section_plane(app) {
let col = sc.color(c4(Tokens::view().text.gamma_multiply(0.9)));
@@ -1770,12 +1810,22 @@ pub(crate) fn seam_width(order: Option<solidcraft_engine::kernel::Continuity>) -
2.6 + past_g2 as f32
}
-/// The sketch scene: the grid, the shown sketches' profile fills and curves, and the attachment guide lines.
+/// View-dependent geometry: grid, sketch feedback and the ground shadow's visibility.
pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene {
let tk = Tokens::get();
let mut sc = GpuScene::default();
let s = &app.session;
let st = crate::open_meshing::shown_world(app);
+ if app.ui.ground_shadow && app.ui.visual_style != 2 && app.cam.pitch > 0.0 {
+ let geometry = shadow_geometry(app, &st);
+ sc.shadow = geometry.bytes.as_ref().clone();
+ sc.palette = geometry.palette;
+ } else if let Ok(mut cache) = app.viewport.shadow.lock()
+ && cache.as_ref().is_some_and(|c| !std::sync::Arc::ptr_eq(&c.state, &st))
+ {
+ // A hidden shadow must not keep an earlier document's whole model alive.
+ *cache = None;
+ }
let mut fill_budget = 131_072;
// The open sketch's plane in the model this frame shows.
let sketch_plane = s.active_sketch.and_then(|id| st.sketch(id)).map(|ss| ss.plane).or_else(|| previewed_sketch_plane(app));
@@ -1915,6 +1965,32 @@ pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene {
sc
}
+#[derive(Clone)]
+struct ShadowGeometry {
+ key: u64,
+ state: std::sync::Arc<solidcraft_engine::doc::ModelState>,
+ bytes: std::sync::Arc<Vec<u8>>,
+ palette: std::sync::Arc<crate::gpu::Palette>,
+}
+
+/// Changing sides of the ground only changes whether this small shadow is drawn; it never
+/// rebuilds the model's bodies or uploads their plans and colours again.
+fn shadow_geometry(app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::ModelState>) -> ShadowGeometry {
+ let key = scene_key(app);
+ if let Some(geometry) =
+ app.viewport.shadow.lock().ok().and_then(|c| c.as_ref().filter(|c| c.key == key && std::sync::Arc::ptr_eq(&c.state, st)).cloned())
+ {
+ return geometry;
+ }
+ let mut scene = GpuScene::default();
+ ground_shadow(&mut scene, app, st);
+ let geometry = ShadowGeometry { key, state: st.clone(), bytes: std::sync::Arc::new(scene.shadow), palette: scene.palette };
+ if let Ok(mut cache) = app.viewport.shadow.lock() {
+ *cache = Some(geometry.clone());
+ }
+ geometry
+}
+
/// A soft dark ellipse on the ground under the shown bodies (darkest in the middle).
fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::ModelState>) {
// The bodies' box in the camera's Z-up frame (the ground is its XY plane).
@@ -3730,7 +3806,7 @@ struct HoverBlock {
fn highlight_plan(
app: &SolveApp,
b: &solidcraft_engine::doc::ModelBody,
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<ActiveBodyNames>,
) -> Option<std::sync::Arc<solidcraft_engine::geom::tess::TessPlan>> {
if crate::render_workspace::active(app) {
return None;
@@ -3741,7 +3817,7 @@ fn highlight_plan(
/// Whether the model draws a whole body opaque on the GPU, rather than building it on the CPU:
/// a live preview stands in for none, faded and see-through bodies stay on the CPU, and face
/// opacities matter only where faces are shaded.
-fn highlight_opaque(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<Vec<String>>) -> bool {
+fn highlight_opaque(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option<ActiveBodyNames>) -> bool {
if crate::render_workspace::active(app) || app.preview.effective_replaced().contains(&b.name) {
return false;
}
@@ -3863,7 +3939,7 @@ struct WholeBody {
fn light_whole_body(
app: &SolveApp,
b: &solidcraft_engine::doc::ModelBody,
- active_bodies: &Option<Vec<String>>,
+ active_bodies: &Option<ActiveBodyNames>,
lit: WholeBody,
body_slots: &crate::scene_palette::PaletteArena,
feedback: &mut GpuScene,
@@ -3916,7 +3992,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
let mut sc = GpuScene::with_palette(crate::gpu::Palette::with_stable(body_slots.entries()));
let st = crate::open_meshing::shown_world(app);
let s = &app.session;
- let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok());
+ let active_bodies = active_body_names(app);
// Faces lit over the model use the triangles the model shows them with.
let product = crate::render_workspace::active(app);
// Bodies a Move dialog moves are lit where they stand (as they are picked). While its triad
@@ -6256,8 +6332,7 @@ fn box_select(app: &mut SolveApp, proj: &Proj, bx: BoxSel, add: bool) {
// Keep other dialogs and Move's reference inputs free to pick across components.
let scoped_bodies =
dialog_accept.unwrap_or(BODIES) == BODIES && app.dialog.as_ref().is_none_or(|d| matches!(d.kind, crate::dialogs::Kind::Move { .. }));
- let active_bodies =
- app.session.active_occurrence_path.as_ref().filter(|_| scoped_bodies).and_then(|p| app.session.occurrence_bodies(p, true).ok());
+ let active_bodies = if scoped_bodies { active_body_names(app) } else { None };
for b in &st.bodies {
if !app.body_visible(&b.name) || (scoped_bodies && body_faded(app, b, &active_bodies)) {
continue;
diff --git a/crates/ui-egui/src/viewport_navigation_cache_tests.rs b/crates/ui-egui/src/viewport_navigation_cache_tests.rs
new file mode 100644
index 0000000000..5f7d4eeaae
--- /dev/null
+++ b/crates/ui-egui/src/viewport_navigation_cache_tests.rs
@@ -0,0 +1,188 @@
+use super::*;
+
+fn app() -> SolveApp {
+ let mut session = solidcraft_engine::Session::default();
+ session.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap();
+ let mut app = SolveApp::new(session, crate::Services::default());
+ app.home.open = false;
+ app.set_origin_shown(false);
+ app.ui.show_grid = false;
+ app.ui.ground_shadow = true;
+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
+ app.cam.pitch = 0.7;
+ app
+}
+
+fn frame(app: &mut SolveApp, ctx: &egui::Context) {
+ frame_events(app, ctx, vec![]);
+}
+
+fn frame_events(app: &mut SolveApp, ctx: &egui::Context, events: Vec<egui::Event>) {
+ let mut output = ctx
+ .run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, |ui| {
+ show(app, ui)
+ });
+ output.textures_delta.clear();
+}
+
+#[test]
+fn face_hover_and_clicks_follow_device_rotation_on_each_axis() {
+ use crate::space_mouse::{DeviceMotion, Motion};
+ for rotation in [[0.1, 0.0, 0.0], [0.0, 0.1, 0.0], [0.0, 0.0, 0.1]] {
+ let ctx = crate::fonts::test_context();
+ let mut app = app();
+ app.cam.target = Vec3::new(20.0, 15.0, 10.0);
+ frame(&mut app, &ctx);
+ let p = projection(&app, app.viewport.rect.unwrap()).to_screen(app.cam.target).unwrap();
+ let turn = |app: &mut SolveApp| {
+ app.viewport.device_motion = Some(DeviceMotion { motion: Motion { translation: [0.0; 3], rotation }, seconds: 0.016 });
+ };
+ let before = app.cam;
+ for pressed in [None, Some(true), Some(false)] {
+ turn(&mut app);
+ let mut events = vec![egui::Event::PointerMoved(p)];
+ if let Some(pressed) = pressed {
+ events.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ }
+ frame_events(&mut app, &ctx, events);
+ let proj = projection(&app, app.viewport.rect.unwrap());
+ let (expected, _) = candidate(&app, &pick(&app, &proj, p)).unwrap();
+ assert!(matches!(expected, Hit::Face { .. }));
+ assert_eq!(app.viewport.hover, Some(expected));
+ }
+ assert_ne!(app.cam, before);
+ let proj = projection(&app, app.viewport.rect.unwrap());
+ let (_, expected) = candidate(&app, &pick(&app, &proj, p)).unwrap();
+ assert_eq!(app.session.selection, vec![expected]);
+ }
+}
+
+/// Crossing the ground used to rebuild every body even with the shadow switched off.
+#[test]
+fn flips_reuse_the_model_and_only_switch_shadow_visibility() {
+ for shadow in [false, true] {
+ let ctx = crate::fonts::test_context();
+ let mut app = app();
+ app.ui.ground_shadow = shadow;
+ frame(&mut app, &ctx);
+ let model_key = app.viewport.key;
+ let above = app.viewport.sketch_slot.lock().unwrap().take().unwrap();
+ assert_eq!(!above.shadow.is_empty(), shadow);
+ let geometry = shadow_geometry(&app, &app.session.world_state().unwrap());
+ app.viewport.slot.lock().unwrap().take();
+ app.cam.pitch = -0.7;
+ frame(&mut app, &ctx);
+ assert_eq!(app.viewport.key, model_key);
+ assert!(app.viewport.slot.lock().unwrap().is_none(), "a camera flip must not rebuild or upload the model");
+ let below = app.viewport.sketch_slot.lock().unwrap().take().unwrap();
+ assert!(below.shadow.is_empty(), "the ground shadow is hidden from below");
+ app.cam.pitch = 0.7;
+ frame(&mut app, &ctx);
+ assert!(app.viewport.slot.lock().unwrap().is_none());
+ let again = app.viewport.sketch_slot.lock().unwrap().take().unwrap();
+ if shadow {
+ assert!(
+ std::sync::Arc::ptr_eq(&geometry.bytes, &shadow_geometry(&app, &app.session.world_state().unwrap()).bytes),
+ "returning above reuses the shadow geometry"
+ );
+ assert_eq!(above.shadow, again.shadow);
+ assert_eq!(above.palette.entries(), again.palette.entries(), "cached shadow indices keep their colours");
+ assert!(!again.palette.is_empty());
+ assert!(!again.shadow.is_empty());
+ assert!(again.merged().trans.is_empty(), "the shadow stays in its dedicated pass");
+ }
+ app.ui.ground_shadow = !shadow;
+ frame(&mut app, &ctx);
+ assert!(app.viewport.slot.lock().unwrap().is_none(), "toggling a shadow must not rebuild the model");
+ let toggled = app.viewport.sketch_slot.lock().unwrap().take().unwrap();
+ assert_eq!(!toggled.shadow.is_empty(), !shadow);
+ }
+}
+
+#[test]
+fn shadow_cache_follows_visibility_and_world_up() {
+ let mut app = app();
+ let st = app.session.world_state().unwrap();
+ let first = shadow_geometry(&app, &st);
+ assert!(!first.bytes.is_empty());
+ app.session.visibility.hidden_bodies.push("Body1".into());
+ let hidden = shadow_geometry(&app, &st);
+ assert_ne!(first.key, hidden.key);
+ assert!(hidden.bytes.is_empty());
+ app.session.visibility.hidden_bodies.clear();
+ app.cam.up = solidcraft_engine::render::UpAxis::Y;
+ let turned = shadow_geometry(&app, &st);
+ assert_ne!(first.key, turned.key);
+ assert_ne!(first.bytes, turned.bytes);
+}
+
+#[test]
+fn face_feedback_reuses_geometry_but_retains_fresh_pick_points() {
+ let mut app = app();
+ app.viewport.hover = Some(Hit::Face { body: "Body1".into(), index: 0, point: Vec3::new(10.0, 0.0, 5.0) });
+ let key = highlight_geometry_key(&app);
+ let first = build_highlight(&app);
+ let fresh = Vec3::new(20.0, 0.0, 5.0);
+ app.viewport.hover = Some(Hit::Face { body: "Body1".into(), index: 0, point: fresh });
+ app.cam.pitch = -0.4;
+ assert_eq!(highlight_geometry_key(&app), key);
+ let again = build_highlight(&app);
+ assert!(std::sync::Arc::ptr_eq(&first.blocks[0].bytes, &again.blocks[0].bytes));
+ assert!(
+ matches!(hit_sel(app.viewport.hover.as_ref().unwrap()),Some(Sel::Face { point,.. }) if point==fresh),
+ "clicks keep the new intersection point"
+ );
+ app.viewport.hover = Some(Hit::Face { body: "Body1".into(), index: 1, point: fresh });
+ assert_ne!(highlight_geometry_key(&app), key, "moving to another face invalidates feedback");
+ app.viewport.hover = None;
+ assert_ne!(highlight_geometry_key(&app), key, "leaving the model clears feedback");
+}
+
+/// A STEP opens with its assembly placement active. Re-expanding all descendants for every
+/// new hover used to dominate the frame; cached membership must still follow real edits.
+#[test]
+fn active_assembly_membership_is_reused_and_follows_edits_and_activation() {
+ let mut s = solidcraft_engine::Session::default();
+ let a = s.execute("component.create", &json!({"name":"A"})).unwrap()["component"].as_u64().unwrap();
+ s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap();
+ s.execute("component.create", &json!({"name":"Child"})).unwrap();
+ s.execute("solid.box", &json!({"length":5,"width":5,"height":5})).unwrap();
+ s.execute("component.activate", &json!({"component":0})).unwrap();
+ let b = s.execute("component.create", &json!({"name":"B"})).unwrap()["component"].as_u64().unwrap();
+ s.execute("solid.box", &json!({"length":4,"width":4,"height":4})).unwrap();
+ let path = s.doc.first_path(a);
+ s.execute("component.activate", &json!({"component":a,"path":path,"occurrence":path.last()})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ let first = active_body_names(&app).unwrap();
+ assert_eq!(first.len(), 2, "the child belongs to the active assembly too");
+ app.cam.pitch = -0.5;
+ let again = active_body_names(&app).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&first, &again));
+ let world = app.session.world_state().unwrap();
+ assert_eq!(world.bodies.iter().filter(|body| body_faded(&app, body, &Some(again.clone()))).count(), 1);
+ app.session.execute("solid.box", &json!({"length":3,"width":3,"height":3})).unwrap();
+ let edited = active_body_names(&app).unwrap();
+ assert_eq!(edited.len(), 3);
+ assert!(!std::sync::Arc::ptr_eq(&first, &edited));
+ let path = app.session.doc.first_path(b);
+ app.session.execute("component.activate", &json!({"component":b,"path":path,"occurrence":path.last()})).unwrap();
+ let other = active_body_names(&app).unwrap();
+ assert_eq!(other.len(), 1);
+ assert!(other.is_disjoint(&edited));
+ app.session.execute("component.activate", &json!({"component":0})).unwrap();
+ assert!(active_body_names(&app).is_none());
+ assert!(app.viewport.active_bodies.lock().unwrap().is_none());
+}
+
+/// Opening has a complete evaluated world, but only ready meshes belong to the picture.
+#[test]
+fn opening_does_not_draw_bodies_before_their_meshes_are_shown() {
+ let mut app = app();
+ assert!(!app.session.world_state().unwrap().bodies.is_empty());
+ crate::open_meshing::start(&mut app, None);
+ assert!(crate::open_meshing::shown_world(&app).bodies.is_empty());
+ // No refresh has published any body yet, even if the background worker has finished.
+ assert!(build_scene(&app).blocks.is_empty(), "the model uses the opening picture");
+ let proj = projection(&app, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)));
+ assert!(build_sketch_scene(&app, &proj).shadow.is_empty(), "the shadow uses that same picture");
+}