Skip to content

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

Browser: Features folders scrolled out of view skip working out their mark (#10439)

kaltenbrunnermarkus9f37003dfa81
diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs
index 145bf4316c..59aeeee4f4 100644
--- a/crates/ui-egui/src/browser/features.rs
+++ b/crates/ui-egui/src/browser/features.rs
@@ -9,6 +9,12 @@ pub(crate) struct Reveal {
pub path: Vec<u64>,
}
+#[cfg(test)]
+thread_local! {
+ /// Folded Features folders whose mark was worked out (the tests count them).
+ static MARKS_WORKED_OUT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
/// Open the Features folder that lists this feature and scroll to its row, without changing the
/// active component or history marker. The folder is the one of the placement `body` belongs to:
/// without a body there is no telling which copy of a component was meant.
@@ -82,10 +88,14 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path:
let (key, label) =
if compact { (format!("{scope}/history"), crate::i18n::tr("ui.history_title")) } else { (format!("{scope}/features"), "Features") };
let open = is_open(app, &key, compact);
- // Folded, it carries the worst mark of what it holds.
- let ids: Vec<u64> = if open {
+ // Folded, it carries the worst mark of what it holds. A row scrolled out of view paints
+ // nothing, so its mark is not worked out: in a long tree of placements of a part with a long
+ // history, every folder's mark scanned the design's whole history on every frame (#6083).
+ let ids: Vec<u64> = if open || !ui.is_rect_visible(row_rect(ui)) {
Vec::new()
} else {
+ #[cfg(test)]
+ MARKS_WORKED_OUT.with(|n| n.set(n.get() + 1));
app.session
.doc
.features
@@ -715,6 +725,29 @@ mod tests {
}
}
+ /// #6083: in a long tree of placements, only the folded Features folders on screen work out
+ /// their mark (each scanned the design's whole history, every frame); those on screen still
+ /// show it.
+ #[test]
+ fn only_folded_features_folders_on_screen_work_out_their_mark() {
+ let mut h = Harness::new();
+ let component = h.app.run("component.create", json!({"name":"Part"})).unwrap();
+ let feature = h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap()["feature"].as_u64().unwrap();
+ h.app.run("component.activate", json!({"component":0})).unwrap();
+ let first = component["occurrence"].as_u64().unwrap();
+ for i in 1..=80 {
+ h.app.run("occurrence.copy", json!({"occurrence":first,"translate":[20.0 * f64::from(i),0,0]})).unwrap();
+ }
+ h.frames(2);
+ let result = h.app.session.model.results.iter_mut().find(|r| r.id == feature).unwrap();
+ result.error = Some("the blend is larger than the neighbouring faces".into());
+ MARKS_WORKED_OUT.with(|n| n.set(0));
+ h.frame();
+ let worked = MARKS_WORKED_OUT.with(std::cell::Cell::get);
+ assert!(worked > 0 && worked < 40, "{worked} of 81 folded Features folders worked out their mark");
+ assert!(!crate::scenario::handles("status:error:Features").is_empty(), "a folder on screen shows its mark");
+ }
+
#[test]
fn browser_find_reveals_a_placed_body_whose_row_is_off_screen() {
let mut h = Harness::new();
diff --git a/crates/ui-egui/src/frame_watch.rs b/crates/ui-egui/src/frame_watch.rs
index 0c3e742316..7224975edc 100644
--- a/crates/ui-egui/src/frame_watch.rs
+++ b/crates/ui-egui/src/frame_watch.rs
@@ -18,6 +18,14 @@ pub(crate) struct Watch {
pub slowest: (f64, &'static str),
}
+#[cfg(test)]
+impl Watch {
+ /// The last frame's named steps and their milliseconds (the scaling measurements read them).
+ pub(crate) fn steps(&self) -> &[(&'static str, f64)] {
+ &self.steps
+ }
+}
+
/// What the app is doing this frame, as far as opening a design goes.
pub(crate) fn phase(app: &SolveApp) -> &'static str {
if let Some(p) = crate::file_load::phase(app) {
diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs
index a854694048..efc1dcbe41 100644
--- a/crates/ui-egui/src/gpu.rs
+++ b/crates/ui-egui/src/gpu.rs
@@ -599,11 +599,21 @@ impl OffscreenFrames {
/// 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 [prepare, paint, wait] = self.frame_parts(frame);
+ prepare + paint + wait
+ }
+
+ /// [`Self::frame`] in its parts, in milliseconds: the renderer's `prepare` (uploads, culling),
+ /// recording the draws (`paint`), and the GPU's work until it has finished.
+ pub(crate) fn frame_parts(&mut self, frame: Frame) -> [f64; 3] {
+ let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0;
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 prepare = ms(started);
+ let painted = std::time::Instant::now();
{
let mut pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -628,9 +638,11 @@ impl OffscreenFrames {
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);
}
+ let paint = ms(painted);
+ let waited = std::time::Instant::now();
self.queue.submit(extra.into_iter().chain([encoder.finish()]));
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
- started.elapsed().as_secs_f64() * 1000.0
+ [prepare, paint, ms(waited)]
}
/// What the model scene's last change uploaded.
diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs
index 3b1a7db9a0..e0c1c8a009 100644
--- a/crates/ui-egui/src/scale_tests.rs
+++ b/crates/ui-egui/src/scale_tests.rs
@@ -745,3 +745,113 @@ fn sketch_scene_cost_while_the_camera_moves() {
}
}
}
+
+/// Orbiting a large design with the right button, as a person turns the view: per frame, the
+/// window thread's frame (the model scene built, as the app builds it once a renderer is there),
+/// its named steps, and the renderer's prepare, draw recording and GPU work on an offscreen device
+/// (skipped without an adapter, as with `WGPU_BACKEND=metal` on Linux, to time the window thread
+/// alone). The design is `SOLIDCRAFT_SCALE_STEP` (inserted as the app opens a STEP file),
+/// `SOLIDCRAFT_SCALE_DESIGN` (opened), or the generated assembly of 300 parts and 500 placements.
+/// `SOLIDCRAFT_SCALE_LOOP` frames (default 60). `painted` fingerprints the window's picture once
+/// the view rests, to compare two builds. Run with `--ignored --nocapture`.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+#[ignore = "manual measurement on a design file"]
+fn orbit_frame_cost() {
+ const SIZE: u32 = 1024;
+ let mut h = if let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_STEP") {
+ let mut h = Harness::new();
+ h.app.run("file.insert_step", json!({"path": path.to_string_lossy()})).unwrap();
+ h
+ } else if let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_DESIGN") {
+ let mut h = Harness::new();
+ h.app.run("doc.open", json!({"path": path.to_string_lossy()})).unwrap();
+ h
+ } else {
+ assembly(300, 500)
+ };
+ let st = h.app.session.world_state();
+ st.warm_meshes(|| true);
+ for b in &st.bodies {
+ let _ = b.display_plan();
+ }
+ let bodies = st.bodies.len();
+ let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum();
+ drop(st);
+ let mut frames = crate::gpu::OffscreenFrames::new(SIZE, true);
+ h.app.viewport.gpu = match &frames {
+ Some(f) => f.target(),
+ None => Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true, oit: false }),
+ };
+ h.app.fit_view();
+ h.frames(5);
+ let rect = h.app.viewport.rect.unwrap();
+ let at = rect.center();
+ let draw = |h: &Harness, frames: &mut Option<crate::gpu::OffscreenFrames>| -> [f64; 3] {
+ let Some(f) = frames.as_mut() else { return [0.0; 3] };
+ let v = &h.app.viewport;
+ f.frame_parts(view_frame(&h.app, SIZE, (v.key, &v.slot), (v.hl_key, &v.hl_slot)))
+ };
+ let cold = draw(&h, &mut frames);
+ let none = egui::Modifiers::NONE;
+ h.frame_with(vec![egui::Event::PointerMoved(at)]);
+ h.frame_with(vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: none }]);
+ let yaw = h.app.cam.yaw;
+ let n = std::env::var("SOLIDCRAFT_SCALE_LOOP").ok().and_then(|v| v.parse().ok()).unwrap_or(60usize);
+ let mut ui = Vec::new();
+ let mut parts = Vec::new();
+ let mut tess = Vec::new();
+ let mut steps: std::collections::BTreeMap<&'static str, Vec<f64>> = Default::default();
+ let mut scene_builds = 0;
+ for i in 0..n {
+ let key = h.app.viewport.key;
+ let p = at + egui::vec2(4.0 * ((i % 80) as f32 - 40.0).abs(), 0.0) - egui::vec2(160.0, 0.0);
+ ui.push(ms(|| h.frame_with(vec![egui::Event::PointerMoved(p)])));
+ let shapes = std::mem::take(&mut h.shapes);
+ tess.push(ms(|| drop(h.ctx.tessellate(shapes, 1.0))));
+ scene_builds += usize::from(h.app.viewport.key != key);
+ for (name, t) in h.app.frame_watch.steps() {
+ steps.entry(name).or_default().push(*t);
+ }
+ parts.push(draw(&h, &mut frames));
+ }
+ h.frame_with(vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: none }]);
+ assert_ne!(h.app.cam.yaw, yaw, "the right drag turned the view");
+ // What the window painted once the view rests, tessellated: positions, colours and
+ // triangles, the same between builds that only save work. Not the glyphs' places in the
+ // font atlas, which follow the order the text was first drawn in.
+ h.frames(3);
+ let painted = {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ for clipped in h.ctx.tessellate(std::mem::take(&mut h.shapes), 1.0) {
+ [clipped.clip_rect.min.x, clipped.clip_rect.min.y, clipped.clip_rect.max.x, clipped.clip_rect.max.y].map(f32::to_bits).hash(&mut hasher);
+ if let egui::epaint::Primitive::Mesh(mesh) = clipped.primitive {
+ mesh.indices.hash(&mut hasher);
+ for v in &mesh.vertices {
+ [v.pos.x.to_bits(), v.pos.y.to_bits()].hash(&mut hasher);
+ v.color.to_array().hash(&mut hasher);
+ }
+ }
+ }
+ hasher.finish()
+ };
+ let median = |mut v: Vec<f64>| {
+ v.sort_by(f64::total_cmp);
+ v.get(v.len() / 2).copied().unwrap_or(0.0)
+ };
+ let mut line = format!(
+ "ORBIT bodies={bodies} triangles={triangles} frames={n} scene_builds={scene_builds} ui_ms={:.2} egui_tessellate_ms={:.2} prepare_ms={:.2} paint_ms={:.2} gpu_ms={:.2} cold_prepare_ms={:.1} drawn_triangles={} painted={painted:016x}",
+ median(ui),
+ median(tess),
+ median(parts.iter().map(|p| p[0]).collect()),
+ median(parts.iter().map(|p| p[1]).collect()),
+ median(parts.iter().map(|p| p[2]).collect()),
+ cold[0],
+ frames.as_ref().map_or(0, |f| f.stats().triangles),
+ );
+ for (name, t) in steps {
+ line.push_str(&format!(" [{name}]={:.2}", median(t)));
+ }
+ println!("{line}");
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 57abd7ecf0..95a77fa87c 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -130,7 +130,7 @@ pub struct ViewportState {
lowered_noted: bool,
/// The graphics backend and adapter, as the frame-rate details show them.
pub(crate) adapter: String,
- slot: SceneSlot,
+ pub(crate) slot: SceneSlot,
pub(crate) key: u64,
sketch_slot: SceneSlot,
sketch_key: u64,