Skip to content

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

Viewport: weld a large mesh's shared vertices quicker, and ahead of its first frame (#4679) (#4680)

Jackson Oursland981d23d1d213
diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs
index 72a757301d..e7798a73f1 100644
--- a/crates/gpu/src/view.rs
+++ b/crates/gpu/src/view.rs
@@ -37,6 +37,27 @@ pub struct PlannedBody {
pub face_colors: Vec<[u8; 4]>,
}
+/// A quick hasher for welding (the keys are coordinates' bits, from the design, not chosen to
+/// collide): the standard one made welding a 2 M-triangle scan take half a second.
+#[derive(Default)]
+struct WeldHasher(u64);
+
+impl std::hash::Hasher for WeldHasher {
+ fn finish(&self) -> u64 {
+ self.0
+ }
+
+ fn write(&mut self, bytes: &[u8]) {
+ for b in bytes {
+ self.write_u32(u32::from(*b));
+ }
+ }
+
+ fn write_u32(&mut self, x: u32) {
+ self.0 = (self.0.rotate_left(5) ^ u64::from(x)).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95);
+ }
+}
+
/// A vertex of [`SharedTris`]: position and normal (3 × f32 each).
pub const SHARED_SIZE: usize = 24;
@@ -69,10 +90,11 @@ impl SharedTris {
});
let mut out = SharedTris { flat, ..Default::default() };
out.indices.reserve_exact(mesh.triangles.len() * 3);
- let mut seen: std::collections::HashMap<[u32; 6], u32> = std::collections::HashMap::with_capacity(mesh.positions.len());
+ let mut seen: std::collections::HashMap<[u32; 6], u32, std::hash::BuildHasherDefault<WeldHasher>> =
+ std::collections::HashMap::with_capacity_and_hasher(mesh.positions.len() / 2, Default::default());
for t in &mesh.triangles {
- let Some(corners) = t.iter().map(|i| corner(*i)).collect::<Option<Vec<_>>>() else { continue };
- for (p, n) in corners {
+ let [Some(a), Some(b), Some(c)] = t.map(corner) else { continue };
+ for (p, n) in [a, b, c] {
let [x, y, z] = bits(p);
let [a, b, c] = if flat { [0; 3] } else { bits(n) };
let next = u32::try_from(out.vertices.len() / SHARED_SIZE).unwrap_or(u32::MAX);
diff --git a/crates/ui-egui/src/open_meshing.rs b/crates/ui-egui/src/open_meshing.rs
index 7428e81df9..420fae03a3 100644
--- a/crates/ui-egui/src/open_meshing.rs
+++ b/crates/ui-egui/src/open_meshing.rs
@@ -52,7 +52,9 @@ pub(crate) struct Meshing {
}
impl Meshing {
- fn start(world: Arc<ModelState>, plans: bool) -> Meshing {
+ /// `plans`: the bodies are drawn from their display plans; `shared`: large meshes are drawn
+ /// from shared vertices (a GPU viewport), made here too.
+ fn start(world: Arc<ModelState>, plans: bool, shared: bool) -> Meshing {
let n = world.bodies.len();
let ready = Arc::new(Mutex::new(Vec::with_capacity(n)));
let (done, stop) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicBool::new(false)));
@@ -73,7 +75,11 @@ impl Meshing {
if let Some(b) = world.bodies.get(i) {
// What the viewport draws and picks: a placed part's shared mesh, not a
// moved copy of it (its placements are drawn as instances of it).
- let _ = b.mesh_in_place();
+ let (mesh, _) = b.mesh_in_place();
+ // A large mesh's shared vertices too, so its first frame does not weld them.
+ if shared {
+ crate::viewport::warm_shared_tris(&mesh);
+ }
if plans {
let _ = b.display_plan();
let _ = b.plan_mesh_in_place_at(solidcraft_engine::doc::display_quality::current());
@@ -120,7 +126,7 @@ impl Drop for Meshing {
pub(crate) fn start(app: &mut SolveApp, remember: Option<String>) {
app.open_meshing_next = false;
let plans = app.viewport.gpu.is_some_and(|g| g.tess);
- let mut meshing = Meshing::start(app.session.world_state(), plans);
+ let mut meshing = Meshing::start(app.session.world_state(), plans, app.viewport.gpu.is_some());
meshing.remember = remember;
app.open_meshing = Some(meshing);
app.fit_view();
@@ -180,7 +186,7 @@ pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) {
// The design changed (an edit, an undo): mesh the new world; what is made is kept.
let (framed, remember) = (m.framed, m.remember.clone());
let plans = app.viewport.gpu.is_some_and(|g| g.tess);
- let mut next = Meshing::start(world.clone(), plans);
+ let mut next = Meshing::start(world.clone(), plans, app.viewport.gpu.is_some());
(next.framed, next.remember) = (framed, remember);
app.open_meshing = Some(next);
}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index cc10249499..d565cec49e 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -571,7 +571,38 @@ type InstancedTris = std::collections::HashMap<usize, (std::sync::Arc<solidcraft
/// A body alone is drawn as an instance of its triangles (shared vertices, indexed) from this many
/// triangles: a large imported mesh. Smaller ones are drawn so only when placed more than once.
-const INSTANCE_ALONE: usize = 50_000;
+pub(crate) const INSTANCE_ALONE: usize = 50_000;
+
+/// Shared vertices made ahead, off the window thread ([`warm_shared_tris`]), by mesh address
+/// (the mesh held, so its address stays its own), until a scene takes them.
+static WARMED: std::sync::Mutex<Vec<(std::sync::Arc<solidcraft_engine::geom::Mesh>, std::sync::Arc<crate::gpu::SharedTris>)>> =
+ std::sync::Mutex::new(Vec::new());
+/// Most meshes kept warmed and not taken yet (a design opened and closed before it was drawn).
+const MAX_WARMED: usize = 8;
+
+/// Make a large mesh's shared vertices ahead of its first scene, on the caller's thread (the
+/// background mesher, after a file is opened or inserted): welding a scanned part takes a
+/// noticeable part of a second, which the window thread would otherwise spend on the first frame
+/// that shows it.
+pub(crate) fn warm_shared_tris(mesh: &std::sync::Arc<solidcraft_engine::geom::Mesh>) {
+ if mesh.triangles.len() < INSTANCE_ALONE || WARMED.lock().map_or(true, |w| w.iter().any(|(m, _)| std::sync::Arc::ptr_eq(m, mesh))) {
+ return;
+ }
+ let tris = std::sync::Arc::new(crate::gpu::SharedTris::new(mesh));
+ if let Ok(mut warmed) = WARMED.lock() {
+ if warmed.len() >= MAX_WARMED {
+ warmed.remove(0);
+ }
+ warmed.push((mesh.clone(), tris));
+ }
+}
+
+/// The shared vertices made ahead for `mesh`, taken from the warmed ones.
+fn taken_shared_tris(mesh: &std::sync::Arc<solidcraft_engine::geom::Mesh>) -> Option<std::sync::Arc<crate::gpu::SharedTris>> {
+ let mut warmed = WARMED.lock().ok()?;
+ let at = warmed.iter().position(|(m, _)| std::sync::Arc::ptr_eq(m, mesh))?;
+ Some(warmed.remove(at).1)
+}
/// One body as the model scene draws it.
struct BodyDraw {
@@ -721,7 +752,7 @@ impl Instances {
None => {
let tris = match self.kept.get(&key).filter(|(k, _)| std::sync::Arc::ptr_eq(k, &mesh)) {
Some((_, t)) => t.clone(),
- None => std::sync::Arc::new(crate::gpu::SharedTris::new(&mesh)),
+ None => taken_shared_tris(&mesh).unwrap_or_else(|| std::sync::Arc::new(crate::gpu::SharedTris::new(&mesh))),
};
self.meshes.push((mesh.clone(), crate::gpu::InstancedMesh { key: key as u64, tris, instances: Vec::new() }));
self.meshes.len() - 1
@@ -4969,6 +5000,36 @@ mod tests {
}
}
+ /// A large mesh's shared vertices made ahead (by the background mesher after a file is
+ /// opened or inserted) are the ones its first scene draws: that frame welds nothing.
+ #[test]
+ fn a_large_meshs_shared_vertices_are_made_ahead_of_its_first_scene() {
+ use solidcraft_engine::doc::{Document, FeatureKind, MeshData};
+ // A flat grid of 160 × 160 squares: 51 200 triangles, each corner its own vertex.
+ let n = 160u32;
+ let corners: Vec<[u32; 2]> =
+ (0..n).flat_map(|j| (0..n).flat_map(move |i| [[i, j], [i + 1, j], [i + 1, j + 1], [i, j], [i + 1, j + 1], [i, j + 1]])).collect();
+ let mut doc = Document::default();
+ let meshes = vec![MeshData {
+ name: "Grid".into(),
+ positions: corners.iter().flat_map(|[x, y]| [f64::from(*x), f64::from(*y), 0.0]).collect(),
+ triangles: (0..u32::try_from(corners.len()).unwrap()).collect(),
+ color: None,
+ }];
+ doc.add_feature(FeatureKind::MeshImport { file: "grid.stl".into(), meshes }, Some("Grid")).unwrap();
+ let mut app = SolveApp::new(solidcraft_engine::Session::new(doc), crate::Services::default());
+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false });
+ let (mesh, _) = app.session.world_state().bodies[0].mesh_in_place();
+ assert!(mesh.triangles.len() >= INSTANCE_ALONE);
+ warm_shared_tris(&mesh);
+ let warmed = WARMED.lock().unwrap().iter().find(|(m, _)| std::sync::Arc::ptr_eq(m, &mesh)).map(|(_, t)| t.clone()).unwrap();
+ assert_eq!(warmed.vertices.len() / crate::gpu::SHARED_SIZE, 161 * 161, "the grid's corners shared");
+ let scene = build_scene(&app);
+ assert_eq!(scene.instanced.len(), 1, "a large mesh alone is drawn from shared vertices");
+ assert!(std::sync::Arc::ptr_eq(&scene.instanced[0].tris, &warmed), "the ones made ahead");
+ assert!(!WARMED.lock().unwrap().iter().any(|(m, _)| std::sync::Arc::ptr_eq(m, &mesh)), "taken");
+ }
+
/// Each placement of a part is picked where it stands, the turned one too, from the part's
/// shared mesh: the face under the cursor names that placement's body, at the point the
/// cursor is over, and no placement makes a moved copy of the mesh to be picked.