SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Reuse unchanged imported meshes during joint motion (#5476) (#5480)
takuto-NA61ada529849e
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 1b76fe7345..25a49daf7e 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -1084,8 +1084,8 @@ pub struct Model {pub no_cache: bool,/// Results kept besides the cache ([`Model::keep`]).kept: KeptSlot,- /// The imported texts' digests the last `evaluate` fingerprinted the features with.- step_digests: StepDigests,+ /// Embedded imports' content digests from the last evaluation.+ import_digests: ImportDigests,/// The address of the shared document whose fingerprints the results were last given in/// full, with [`fingerprints_digest`] of them then ([`Model::pinned_prefix`]). Only an/// address: a reference to the document would make every in-place edit of it a copy.@@ -1124,7 +1124,7 @@ fn param_names(f: &Feature) -> Vec<String> {names}-fn fingerprint(doc: &Document, prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_back: bool, steps: &StepDigests) -> u64 {+fn fingerprint(doc: &Document, prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_back: bool, steps: &ImportDigests) -> u64 {let mut h = std::collections::hash_map::DefaultHasher::new();prev.hash(&mut h);rolled_back.hash(&mut h);@@ -1145,34 +1145,73 @@ fn fingerprint(doc: &Document, prev: u64, f: &Feature, vals: &BTreeMap<String, Vh.finish()}-/// The digests of the Import features' STEP texts, by feature id, with the text each was taken-/// from. Every evaluation fingerprints every feature, and writing out a design's imported files-/// each time made every command as slow as the files are large: a text is shared (`Arc`), so-/// its digest is taken once and kept while the feature holds that same text.+/// Content digests for embedded imports. Shared, unchanged arrays/text are read once;+/// feature metadata is still fingerprinted on every evaluation. Rebuilding this map prunes+/// removed features and never trusts an address without retaining and checking its Arc.#[derive(Clone, Debug, Default)]-struct StepDigests(std::collections::HashMap<u64, (Arc<str>, u64)>);+struct ImportDigests {+ steps: std::collections::HashMap<u64, (Arc<str>, u64)>,+ meshes: std::collections::HashMap<u64, Vec<MeshDigest>>,+}-impl StepDigests {- /// The digests of `doc`'s imported texts, reusing `known` for texts it has seen.- fn of(doc: &Document, known: &StepDigests) -> StepDigests {- let texts = doc.features.iter().filter_map(|f| match &f.kind {- FeatureKind::Import { step, .. } => Some((f.id, step)),- _ => None,- });- StepDigests(- texts- .map(|(id, step)| {- let digest = known.get(id, step).unwrap_or_else(|| step_text_digest(step));- (id, (step.clone(), digest))- })- .collect(),- )+#[derive(Clone, Debug)]+struct MeshDigest {+ positions: Arc<[f64]>,+ triangles: Arc<[u32]>,+ digest: u64,+}++impl MeshDigest {+ fn matches(&self, mesh: &crate::MeshData) -> bool {+ Arc::ptr_eq(&self.positions, &mesh.positions) && Arc::ptr_eq(&self.triangles, &mesh.triangles)+ }+}++impl ImportDigests {+ fn of(doc: &Document, known: &ImportDigests) -> ImportDigests {+ let mut out = ImportDigests::default();+ for f in &doc.features {+ match &f.kind {+ FeatureKind::Import { step, .. } => {+ let digest = known.get(f.id, step).unwrap_or_else(|| step_text_digest(step));+ out.steps.insert(f.id, (step.clone(), digest));+ }+ FeatureKind::MeshImport { meshes, .. } => {+ let digests = meshes+ .iter()+ .enumerate()+ .map(|(index, mesh)| {+ let digest = known.mesh(f.id, index, mesh).unwrap_or_else(|| mesh_content_digest(mesh));+ MeshDigest { positions: mesh.positions.clone(), triangles: mesh.triangles.clone(), digest }+ })+ .collect();+ out.meshes.insert(f.id, digests);+ }+ _ => {}+ }+ }+ out}- /// The digest of `step`, when it is the text feature `id` was last seen with.fn get(&self, id: u64, step: &Arc<str>) -> Option<u64> {- self.0.get(&id).filter(|(text, _)| Arc::ptr_eq(text, step)).map(|(_, digest)| *digest)+ self.steps.get(&id).filter(|(text, _)| Arc::ptr_eq(text, step)).map(|(_, digest)| *digest)+ }++ fn mesh(&self, id: u64, index: usize, mesh: &crate::MeshData) -> Option<u64> {+ self.meshes.get(&id)?.get(index).filter(|cached| cached.matches(mesh)).map(|cached| cached.digest)+ }+}++fn mesh_content_digest(mesh: &crate::MeshData) -> u64 {+ #[cfg(test)]+ cost_tests::count(|c| c.mesh_digested += 1);+ let mut h = std::collections::hash_map::DefaultHasher::new();+ mesh.positions.len().hash(&mut h);+ for coordinate in mesh.positions.iter() {+ coordinate.to_bits().hash(&mut h);}+ mesh.triangles.hash(&mut h);+ h.finish()}fn step_text_digest(text: &str) -> u64 {@@ -1208,12 +1247,12 @@ fn quantize(sk: &mut solidcraft_sketch::Sketch) {}/// A feature as fingerprinted: its definition, a sketch's stored solve quantized, an imported-/// file's text by its digest.+/// file's text or mesh payload by its content digest./// Hash [`feature_json`] of `f` into `h`. Every evaluation fingerprints every feature, and in a/// design built command by command almost all of them are the same as last time: the text of a/// feature is kept (by id) with the feature it was written from, and written again only when the-/// feature differs. An Import's text also depends on its STEP digest, so it is written each time-/// as before.+/// feature differs. Embedded imports also depend on their content digests, so their small+/// metadata-and-digest representation is written each time without comparing large arrays.////// The texts are shared by every thread: a command evaluated ahead runs on a new worker thread/// each time (the desktop's deferred commands and delete checks, the control channel's ahead@@ -1221,10 +1260,10 @@ fn quantize(sk: &mut solidcraft_sketch::Sketch) {/// feature again. The lock is held only to look up or store an entry, never while a feature is/// compared or written; an entry is the same whichever thread wrote it, since the text is a/// function of the feature alone.-fn hash_feature_json(f: &Feature, steps: &StepDigests, h: &mut impl Hasher) {+fn hash_feature_json(f: &Feature, steps: &ImportDigests, h: &mut impl Hasher) {type Written = std::collections::HashMap<u64, Arc<(Feature, String)>>;static WRITTEN: std::sync::LazyLock<std::sync::Mutex<Written>> = std::sync::LazyLock::new(Default::default);- if matches!(f.kind, FeatureKind::Import { .. }) {+ if matches!(f.kind, FeatureKind::Import { .. } | FeatureKind::MeshImport { .. }) {feature_json(f, steps).hash(h);return;}@@ -1247,7 +1286,21 @@ fn hash_feature_json(f: &Feature, steps: &StepDigests, h: &mut impl Hasher) {written.insert(f.id, entry);}-fn feature_json(f: &Feature, steps: &StepDigests) -> String {+fn feature_json(f: &Feature, steps: &ImportDigests) -> String {+ if matches!(&f.kind, FeatureKind::MeshImport { .. }) {+ let mut g = f.clone();+ let mut digests = Vec::new();+ if let FeatureKind::MeshImport { meshes, .. } = &mut g.kind {+ for (index, mesh) in meshes.iter_mut().enumerate() {+ digests.push(steps.mesh(f.id, index, mesh).unwrap_or_else(|| mesh_content_digest(mesh)));+ mesh.positions = Arc::from([]);+ mesh.triangles = Arc::from([]);+ }+ }+ // Keep the complete definition (including mesh order, names and colors) without+ // writing the large numeric arrays out again. Equal content in fresh Arcs hashes alike.+ return serde_json::to_string(&(g, digests)).unwrap_or_default();+ }if let FeatureKind::Import { step, .. } = &f.kind {let mut g = f.clone();if let FeatureKind::Import { step: text, .. } = &mut g.kind {@@ -1344,7 +1397,7 @@ fn chain_fingerprint(f: &Feature,prev: u64,rolled_back: bool,- steps: &StepDigests,+ steps: &ImportDigests,st: Option<&ModelState>,) -> u64 {let mut fp = fingerprint(doc, prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f, st);@@ -1422,7 +1475,7 @@ fn context_digest(doc: &Document, vals: &BTreeMap<String, Value>) -> u64 {for f in doc.features.iter().filter(|f| {matches!(f.kind, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. })}) {- fingerprint(doc, 0, f, vals, false, &StepDigests::default()).hash(&mut h);+ fingerprint(doc, 0, f, vals, false, &ImportDigests::default()).hash(&mut h);}doc.units.hash(&mut h);serde_json::to_string(&doc.sheet).unwrap_or_default().hash(&mut h);@@ -1922,7 +1975,7 @@ impl Model {}// The fingerprints from the first stored sketch on.let vals = evaluation_values(doc).0;- let steps = StepDigests::of(doc, &self.step_digests);+ let steps = ImportDigests::of(doc, &self.import_digests);let marker = doc.marker.unwrap_or(usize::MAX);let mut prev_fp = first.checked_sub(1).and_then(|i| self.results.get(i)).map_or(0, |r| r.fingerprint);for (i, f) in doc.features.iter().enumerate().skip(first) {@@ -1972,7 +2025,7 @@ impl Model {return false;}let vals = evaluation_values(doc).0;- let steps = StepDigests::of(doc, &self.step_digests);+ let steps = ImportDigests::of(doc, &self.import_digests);let marker = doc.marker.unwrap_or(usize::MAX);let mut prev = 0;// The model each feature starts from (which components the bodies it names are in).@@ -2037,7 +2090,7 @@ impl Model {let previous_context = self.context;let mut rolled_results = std::mem::take(&mut self.rolled_results);self.context = ctx;- self.step_digests = StepDigests::of(doc, &self.step_digests);+ self.import_digests = ImportDigests::of(doc, &self.import_digests);let primed = self.primed.as_ref().filter(|(context, _)| !self.no_cache && *context == ctx).map(|(_, results)| results.clone());// Each feature's component, for `Document::legacy_body_component` on every body after// every feature without searching the timeline for each (the first feature with an id).@@ -2072,7 +2125,7 @@ impl Model {};// Opening was cancelled: the rest is skipped and the result discarded.let cancelled = watched.step(i);- let fp = chain_fingerprint(doc, &vals, f, prev_fp, rolled_back, &self.step_digests, Some(&state));+ let fp = chain_fingerprint(doc, &vals, f, prev_fp, rolled_back, &self.import_digests, Some(&state));prev_fp = fp;let current = |old: &&FeatureResult| old.id == f.id && old.fingerprint == fp && !old.stale;// A state the saved model did not keep is evaluated again from the one before it; the@@ -2148,7 +2201,7 @@ impl Model {}// The same feature on the same inputs: its earlier result.let key =- cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);+ cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.import_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);let kept = self.kept.0.as_ref().filter(|_| !self.no_cache);if !self.no_cache&& let Some(c) = self@@ -2502,7 +2555,7 @@ impl Model {pub(crate) fn refingerprint_from(&mut self, doc: &Document, start: usize) {self.placement_inputs = None;self.fingerprinted = None;- self.step_digests = StepDigests::of(doc, &self.step_digests);+ self.import_digests = ImportDigests::of(doc, &self.import_digests);let start = start.min(self.results.len()).min(doc.features.len());if start == self.results.len().min(doc.features.len()) {return;@@ -2514,7 +2567,7 @@ impl Model {// Each feature's fingerprint reads the model it starts from, as evaluating does.let mut before = last.map_or_else(|| Arc::new(ModelState::default()), |r| r.state.clone());for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate().skip(start) {- prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests, Some(&before));+ prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.import_digests, Some(&before));r.fingerprint = prev;before = r.state.clone();}diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rsindex 30996921ac..0ae6fa90a1 100644--- a/crates/doc/src/eval_cost_tests.rs+++ b/crates/doc/src/eval_cost_tests.rs@@ -16,7 +16,7 @@ use solidcraft_sketch::Sketch;use crate::eval::{PlacementReads, body_world, hash_placement, placement_digest};use crate::*;-/// Work counted on this thread: bodies moved, STEP texts digested, joint faces and bodies+/// Work counted on this thread: bodies moved, STEP/mesh contents digested, joint faces and bodies/// measured, bodies searched for by name, features searched for by id, bodies a cut (or/// intersect) ran its booleans on, bodies searched for the cylinder a tap marking lies on,/// bodies whose faces a tapped hole read for its wall, intersects run to find a pattern's copies@@ -26,6 +26,7 @@ use crate::*;pub(super) struct Counts {pub moved: usize,pub digested: usize,+ pub mesh_digested: usize,pub joint_faces: usize,pub measures: usize,pub body_searches: usize,@@ -42,6 +43,7 @@ thread_local! {Cell::new(Counts {moved: 0,digested: 0,+ mesh_digested: 0,joint_faces: 0,measures: 0,body_searches: 0,@@ -1637,3 +1639,123 @@ fn tools_are_apart_only_when_they_neither_meet_nor_nest() {// A rod in the tube's bore, clear of its wall, is apart from it.assert!(super::tools_clearly_apart(&[tube, rod(0.0, 0.0, 3.0)]));}++fn imported_meshes() -> Document {+ let mut doc = Document::new("reference meshes");+ let comp = doc.add_component(Some("Part"), 0).unwrap();+ let meshes = (0..2)+ .map(|i| MeshData {+ name: format!("Mesh{i}"),+ positions: [0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 4.0].into(),+ triangles: [0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3].into(),+ color: Some([0.2, 0.4, 0.6]),+ })+ .collect();+ let id = doc.add_feature(FeatureKind::MeshImport { file: "tetrahedra.stl".into(), meshes }, Some("Meshes")).unwrap();+ doc.feature_mut(id).unwrap().component = comp;+ doc+}++fn meshes_mut(doc: &mut Document) -> &mut Vec<MeshData> {+ let FeatureKind::MeshImport { meshes, .. } = &mut doc.features[0].kind else { panic!("mesh fixture") };+ meshes+}++fn same_as_fresh(doc: &Document, model: &Model) {+ let mut fresh = Model::new();+ fresh.no_cache = true;+ fresh.evaluate(doc);+ assert_eq!(model.results.iter().map(|r| r.fingerprint).collect::<Vec<_>>(), fresh.results.iter().map(|r| r.fingerprint).collect::<Vec<_>>());+ let (actual, expected) = (model.state(), fresh.state());+ assert_eq!(actual.bodies.len(), expected.bodies.len());+ for (a, b) in actual.bodies.iter().zip(&expected.bodies) {+ assert_eq!(a.name, b.name);+ assert_eq!(a.mesh().positions, b.mesh().positions);+ assert_eq!(a.mesh().triangles, b.mesh().triangles);+ assert_eq!(a.body.color(), b.body.color());+ }+ assert!(model.results.iter().all(|r| r.error.is_none()));+}++#[test]+fn unchanged_mesh_payloads_are_not_read_again_for_rigid_motion() {+ let mut doc = imported_meshes();+ let mut model = Model::new();+ assert_eq!(counted(|| model.evaluate(&doc)).mesh_digested, 2);+ for k in 1..5 {+ doc = doc.clone(); // Undo/preview copies share the arrays, not the document itself.+ doc.occurrences[0].transform = rigid(Vec3::new(f64::from(k), 2.0, 3.0), Vec3::ZERO, Vec3::Z, 0.1 * f64::from(k));+ assert_eq!(+ counted(|| {+ model.evaluate(&doc);+ assert!(model.is_current(&doc));+ })+ .mesh_digested,+ 0+ );+ assert_eq!(model.last_recomputed, 0);+ same_as_fresh(&doc, &model);+ }+ let saved = serde_json::to_string(&doc).unwrap();+ let reopened: Document = serde_json::from_str(&saved).unwrap();+ assert_eq!(counted(|| model.evaluate(&reopened)).mesh_digested, 2, "new array identities must be checked");+ assert_eq!(model.last_recomputed, 0, "equal content has equal fingerprints");+ same_as_fresh(&reopened, &model);+}++#[test]+fn mesh_payload_edits_invalidate_the_cache_and_undo_restores_the_geometry() {+ let mut doc = imported_meshes();+ let original = doc.clone();+ let mut model = Model::new();+ model.evaluate(&doc);+ let fingerprint = model.results[0].fingerprint;+ Arc::make_mut(&mut meshes_mut(&mut doc)[0].positions)[3] = 5.0;+ assert!(!model.is_current(&doc));+ assert_eq!(counted(|| model.evaluate(&doc)).mesh_digested, 1);+ assert_ne!(model.results[0].fingerprint, fingerprint);+ same_as_fresh(&doc, &model);+ let edited = doc.clone();+ Arc::make_mut(&mut meshes_mut(&mut doc)[0].triangles).swap(0, 1);+ assert_eq!(counted(|| model.evaluate(&doc)).mesh_digested, 1);+ same_as_fresh(&doc, &model);+ for restored in [&original, &edited, &original] {+ model.evaluate(restored);+ same_as_fresh(restored, &model);+ }+ assert_eq!(model.results[0].fingerprint, fingerprint);+}++#[test]+fn mesh_metadata_and_order_remain_part_of_the_fingerprint() {+ let mut doc = imported_meshes();+ let mut model = Model::new();+ model.evaluate(&doc);+ for edit in 0..7 {+ let before = model.results[0].fingerprint;+ match edit {+ 0 => meshes_mut(&mut doc)[0].name = "Renamed".into(),+ 1 => meshes_mut(&mut doc)[0].color = Some([0.8, 0.1, 0.3]),+ 2 => doc.features[0].name = "Renamed feature".into(),+ 3 => meshes_mut(&mut doc).swap(0, 1),+ 4 => {+ meshes_mut(&mut doc).pop();+ }+ 5 => {+ let mesh = meshes_mut(&mut doc)[0].clone();+ meshes_mut(&mut doc).push(MeshData { name: "Added".into(), ..mesh });+ }+ _ => {+ let FeatureKind::MeshImport { file, .. } = &mut doc.features[0].kind else { panic!("mesh fixture") };+ *file = "renamed.stl".into();+ }+ }+ assert!(!model.is_current(&doc));+ let work = counted(|| model.evaluate(&doc));+ if edit < 3 || edit == 6 {+ assert_eq!(work.mesh_digested, 0, "metadata alone: {edit}");+ }+ assert_ne!(model.results[0].fingerprint, before, "edit {edit}");+ same_as_fresh(&doc, &model);+ }+}diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rsindex d06f546eb5..6301061540 100644--- a/crates/doc/src/model_cache.rs+++ b/crates/doc/src/model_cache.rs@@ -760,7 +760,7 @@ impl Model {return Err(bad("saved model: features"));}let (vals, param_errors) = evaluation_values(doc);- let step_digests = StepDigests::of(doc, &StepDigests::default());+ let import_digests = ImportDigests::of(doc, &ImportDigests::default());let marker = doc.marker.unwrap_or(usize::MAX);// As `evaluate` digests the context under the mode, so the next evaluation reuses these.let ctx = context_digest(doc, &vals) ^ validation_digest(validation);@@ -776,7 +776,7 @@ impl Model {// A fingerprint reads the state before its feature (where the bodies it takes lie).// After a state the file left out, the saved one is taken: `evaluate` works that state// out, checks the fingerprints after it, and evaluates again from one that differs.- prev = if exact { chain_fingerprint(doc, &vals, f, prev, i >= marker, &step_digests, Some(&before)) } else { saved };+ prev = if exact { chain_fingerprint(doc, &vals, f, prev, i >= marker, &import_digests, Some(&before)) } else { saved };if r.get("id").and_then(Json::as_u64) != Some(f.id) || saved != prev {return Err(bad("saved model: the document changed"));}@@ -826,7 +826,7 @@ impl Model {}results.push(result);}- let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, validation, ..Model::default() };+ let mut model = Model { results, param_errors, import_digests, context: ctx, frame_bodies, validation, ..Model::default() };let unkept = model.results.iter().filter(|r| r.unkept).count();if unkept > 0 {// The features whose state the file did not keep, each evaluated again from the state@@ -844,7 +844,7 @@ impl Model {let mut before = Arc::new(ModelState::default());if let Ok(mut cache) = model.cache.lock() {for (f, r) in doc.features.iter().zip(&model.results).filter(|(_, r)| !r.skipped && r.error.is_none()) {- let local = fingerprint(doc, 0, f, &vals, false, &model.step_digests) ^ placement_digest(doc, f, Some(&before));+ let local = fingerprint(doc, 0, f, &vals, false, &model.import_digests) ^ placement_digest(doc, f, Some(&before));cache.put(cache_key(f, r.fingerprint, local, ctx, &before),CachedEval {diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex f26f84cd9b..aa818af2ef 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -1416,11 +1416,11 @@ fn reindex_block(block: CachedBlock, draws: &[BodyDraw]) -> CachedBlock {CachedBlock { bytes, meshes: draws.iter().map(|d| d.mesh.clone()).collect(), ranges }}-/// The model scene's instanced meshes: the shared triangles drawn more than once among the shown-/// bodies (or large: [`INSTANCE_ALONE`]), and each body placed from them.+/// The model scene's instanced meshes: imported reference meshes, shared triangles drawn more+/// than once, and large bodies ([`INSTANCE_ALONE`]), with each body's placement.struct Instances {- /// Each candidate body's shared mesh and placement, by body name.- candidates: std::collections::HashMap<String, (std::sync::Arc<solidcraft_engine::geom::Mesh>, solidcraft_engine::doc::Mat)>,+ /// Each candidate body's shared mesh, placement and eligibility for existing LODs, by name.+ candidates: std::collections::HashMap<String, (std::sync::Arc<solidcraft_engine::geom::Mesh>, solidcraft_engine::doc::Mat, bool)>,/// The meshes drawn as instances, in the order their first placement came, by address.meshes: Vec<(std::sync::Arc<solidcraft_engine::geom::Mesh>, crate::gpu::InstancedMesh)>,/// Where a mesh's look already is in `meshes`, so placing a body is a lookup, not a scan.@@ -1430,20 +1430,24 @@ struct Instances {}impl Instances {- /// The shown bodies' shared meshes, keeping those more than one body is drawn from and large- /// ones.+ /// Keep reference meshes at every size: their triangles do not change when a joint moves.+ /// Other bodies share triangles when repeated or large enough to warrant a separate draw.fn new(app: &SolveApp, shown: &[&solidcraft_engine::doc::ModelBody], shaded: bool) -> Instances {let kept = app.viewport.instanced_tris.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();let mut candidates = std::collections::HashMap::new();if shaded {let mut uses: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();- let placed: Vec<_> = shown.iter().filter_map(|b| Some((b.name.clone(), shared_mesh(app, b)?))).collect();- for (_, (mesh, _)) in &placed {+ let placed: Vec<_> = shown.iter().filter_map(|b| Some((b.name.clone(), b.body.is_mesh(), shared_mesh(app, b)?))).collect();+ for (_, _, (mesh, _)) in &placed {*uses.entry(std::sync::Arc::as_ptr(mesh) as usize).or_default() += 1;}candidates = placed.into_iter()- .filter(|(_, (m, _))| m.triangles.len() >= INSTANCE_ALONE || uses.get(&(std::sync::Arc::as_ptr(m) as usize)).is_some_and(|n| *n > 1))+ .filter_map(|(name, reference, (mesh, placement))| {+ let lod_eligible =+ mesh.triangles.len() >= INSTANCE_ALONE || uses.get(&(std::sync::Arc::as_ptr(&mesh) as usize)).is_some_and(|n| *n > 1);+ (reference || lod_eligible).then_some((name, (mesh, placement, lod_eligible)))+ }).collect();}Instances { candidates, meshes: Vec::new(), by_mesh: std::collections::HashMap::new(), kept, lods: app.viewport.mesh_lods.clone() }@@ -1456,8 +1460,13 @@ impl Instances {b: &solidcraft_engine::doc::ModelBody,col: crate::gpu::PaletteIndex,look: crate::gpu::InstanceLook,+ oit: bool,) -> Option<(std::sync::Arc<solidcraft_engine::geom::Mesh>, solidcraft_engine::doc::Mat)> {- let (mesh, m) = self.candidates.get(&b.name)?.clone();+ let (mesh, m, lod_eligible) = self.candidates.get(&b.name)?.clone();+ // A smaller single reference mesh formerly used the sorted CPU glass stream.+ if !lod_eligible && matches!(look, crate::gpu::InstanceLook::Glass | crate::gpu::InstanceLook::Faded) && !oit {+ return None;+ }let rows = [0, 1, 2].map(|r| [m[0][r] as f32, m[1][r] as f32, m[2][r] as f32, m[3][r] as f32]);let key = std::sync::Arc::as_ptr(&mesh) as usize;let at = match self.by_mesh.get(&(key, look)).copied() {@@ -1472,8 +1481,8 @@ impl Instances {Some((_, t)) => t.clone(),None => taken_shared_tris(&mesh).unwrap_or_else(|| std::sync::Arc::new(crate::gpu::SharedTris::new(&mesh))),},- // A large mesh's levels of detail, once made (until then, drawn in full).- self.lods.levels(&mesh).map(|l| l.as_ref().clone()).unwrap_or_default(),+ // Keep the existing detail of newly instanced single reference meshes.+ if lod_eligible { self.lods.levels(&mesh).map(|l| l.as_ref().clone()).unwrap_or_default() } else { Vec::new() },),};self.meshes.push((@@ -1650,7 +1659,8 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {crate::gpu::InstanceLook::Opaque => 255,};set_palette_color(&mut arena, &mut sc.palette, slots.instance, [col[0], col[1], col[2], alpha]);- let instanced = (!on_gpu && face_looks.is_empty()).then(|| instances.place(b, slots.instance, look)).flatten();+ let instanced =+ (!on_gpu && face_looks.is_empty()).then(|| instances.place(b, slots.instance, look, app.viewport.gpu.is_some_and(|g| g.oit))).flatten();let name = b.name.clone();let body = match instanced {Some((mesh, place)) => BodyDraw {@@ -8799,6 +8809,107 @@ mod tests {}}+ #[test]+ fn small_reference_meshes_reuse_display_triangles_when_their_occurrence_moves() {+ use solidcraft_engine::doc::{Document, FeatureKind, MeshData};+ let mut doc = Document::default();+ let component = doc.add_component(Some("Part"), 0).unwrap();+ let occurrence = doc.occurrences.iter_mut().find(|o| o.component == component).unwrap();+ occurrence.grounded = false;+ let occurrence = occurrence.id;+ let meshes = vec![MeshData {+ name: "Small mesh".into(),+ positions: [0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 4.0].into(),+ triangles: [0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3].into(),+ color: Some([0.8, 0.3, 0.1]),+ }];+ let id = doc.add_feature(FeatureKind::MeshImport { file: "small.stl".into(), meshes }, Some("Mesh")).unwrap();+ doc.feature_mut(id).unwrap().component = component;+ let mut app = SolveApp::new(solidcraft_engine::Session::new(doc), crate::Services::default());+ app.ui.ground_shadow = false;+ app.ui.visual_style = 1;+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });+ let first = build_scene(&app);+ assert_eq!(first.instanced.len(), 1, "a single reference mesh below the large-mesh threshold shares its triangles");+ assert!(first.blocks.iter().all(|b| b.bytes.vertices.is_empty()));+ app.run("occurrence.move", json!({"occurrence":occurrence, "translate":[7,11,13], "axis":[1,1,0], "angle":"30 deg"})).unwrap();+ let moved = build_scene(&app);+ assert_eq!(moved.instanced.len(), 1);+ assert!(std::sync::Arc::ptr_eq(&first.instanced[0].tris, &moved.instanced[0].tris));+ assert!(moved.blocks.iter().all(|b| b.bytes.vertices.is_empty()));+ let expected = app.session.world_state().unwrap().bodies[0].mesh();+ let merged = moved.merged();+ assert_ne!(first.merged().tris, merged.tris, "the placement changed");+ let actual: Vec<[f32; 3]> = merged+ .tris+ .as_chunks::<{ crate::gpu::TRI_SIZE }>()+ .0+ .iter()+ .map(|v| std::array::from_fn(|i| f32::from_le_bytes(v[4 * i..4 * i + 4].try_into().unwrap())))+ .collect();+ let expected: Vec<[f32; 3]> = expected.triangles.iter().flatten().map(|i| expected.positions[*i as usize].to_f32()).collect();+ assert_eq!(actual.len(), expected.len());+ for (a, b) in actual.iter().zip(expected) {+ assert!(a.iter().zip(b).all(|(a, b)| (*a - b).abs() < 1e-4));+ }+ }++ fn single_reference_grid(n: u32) -> SolveApp {+ use solidcraft_engine::doc::{Document, FeatureKind, MeshData};+ let mut doc = Document::default();+ let positions = (0..=n).flat_map(|y| (0..=n).flat_map(move |x| [f64::from(x), f64::from(y), 0.0])).collect();+ let triangles = (0..n)+ .flat_map(|y| {+ (0..n).flat_map(move |x| {+ let a = y * (n + 1) + x;+ [a, a + 1, a + n + 2, a, a + n + 2, a + n + 1]+ })+ })+ .collect();+ let meshes = vec![MeshData { name: "Grid".into(), positions, triangles, 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.ui.ground_shadow = false;+ app.ui.visual_style = 1;+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });+ app+ }++ #[test]+ fn a_single_reference_mesh_below_the_former_instance_threshold_keeps_full_detail() {+ let app = single_reference_grid(100);+ let scene = build_scene(&app);+ let instance = scene.instanced.first().unwrap();+ assert_eq!(scene.instanced.len(), 1);+ assert_eq!(instance.tris.indices.len(), 20_000 * 3);+ assert!(instance.levels.is_empty());+ assert!(!app.viewport.mesh_lods.busy(), "no simplification job is started");+ assert_eq!(app.viewport.mesh_lods.generation(), 0);+ }++ #[test]+ fn a_small_translucent_reference_mesh_keeps_the_sorted_fallback_without_oit() {+ let mut app = single_reference_grid(2);+ app.run("appearance.assign", json!({"bodies":["Grid"],"color":"#3366cc","opacity":0.4})).unwrap();+ let sorted = build_scene(&app);+ assert!(sorted.instanced.is_empty(), "the non-OIT path sorts individual glass triangles");+ assert!(!sorted.merged().glass.is_empty());+ app.viewport.gpu.as_mut().unwrap().oit = true;+ let instanced = build_scene(&app);+ assert_eq!(instanced.instanced.len(), 1);+ assert_eq!(instanced.instanced[0].look, crate::gpu::InstanceLook::Glass);+ app.run("appearance.assign", json!({"bodies":["Grid"],"color":"#3366cc","opacity":1.0})).unwrap();+ app.run("component.create", json!({"name":"Editing"})).unwrap();+ app.viewport.gpu.as_mut().unwrap().oit = false;+ let faded = build_scene(&app);+ assert!(faded.instanced.is_empty(), "faded reference meshes retain the old non-OIT block ordering");+ assert!(!faded.merged().trans.is_empty());+ app.viewport.gpu.as_mut().unwrap().oit = true;+ let instanced = build_scene(&app);+ assert_eq!(instanced.instanced.len(), 1);+ assert_eq!(instanced.instanced[0].look, crate::gpu::InstanceLook::Faded);+ }+/// 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]diff --git a/xtask/src/mesh_decisions.rs b/xtask/src/mesh_decisions.rsindex 64fa82c4d5..123e7334bc 100644--- a/xtask/src/mesh_decisions.rs+++ b/xtask/src/mesh_decisions.rs@@ -61,6 +61,8 @@ pub const SKIPPED_MODULES: &[(&str, &str)] = &[/// Functions, in modules that also decide geometry, whose job is the display mesh itself, a/// preview, or a mesh body.pub const SKIPPED_FUNCTIONS: &[(&str, &str)] = &[+ ("crates/doc/src/eval.rs:ImportDigests::of", "mesh-body imports: retained content identities, not tessellated-solid decisions"),+ ("crates/doc/src/eval.rs:MeshDigest::matches", "mesh-body imports: compares retained source-array identities"),("crates/doc/src/eval.rs:ModelBody::display_plan", "the display plan"),("crates/doc/src/eval.rs:ModelBody::mesh", "the display mesh"),("crates/doc/src/eval.rs:ModelBody::mesh_in_place", "the display mesh where the body stands"),@@ -72,7 +74,9 @@ pub const SKIPPED_FUNCTIONS: &[(&str, &str)] = &[("crates/doc/src/eval.rs:ModelState::warm_display", "display meshes made ahead"),("crates/doc/src/eval.rs:ModelState::warm_display_at", "display meshes made ahead"),("crates/doc/src/eval.rs:ModelState::warm_meshes", "display meshes made ahead"),+ ("crates/doc/src/eval.rs:feature_json", "fingerprints feature inputs; triangles are only embedded mesh-body source data"),("crates/doc/src/eval.rs:mesh_bodies", "mesh bodies: a mesh import's triangles"),+ ("crates/doc/src/eval.rs:mesh_content_digest", "mesh-body imports: hashes source arrays without geometric classification"),("crates/engine/src/cmd/file.rs:saved_preview", "the preview picture saved in a design"),("crates/kernel/src/body.rs:Body::classify_point", "mesh bodies: its mesh-body branch (a B-rep is classified by SMLib)"),("crates/kernel/src/body.rs:Body::mesh_untimed", "the mesher: a body's tessellation"),