Engine: lower the per-command cost of evaluating large designs (#9615)
* claim: Engine: lower the per-command cost of evaluating large designs * Engine: lower the per-command cost of evaluating large designs - The fingerprint texts of features are kept in one store shared by every worker, not per worker: a command evaluated ahead runs on a new worker each time, where the per-worker store was always empty and every feature was written out again. Same texts, same hashes. - Pinning body names after a command keeps, per feature, the names of the bodies it made with the state they were read from, so it no longer searches every result's bodies (features x bodies per command), and finds results by their index before searching. - Pinning fingerprints the timeline again only from the first renamed feature (or a pattern or mirror of features replaying one) when the model proves its fingerprints are the design's; the fingerprints are those of the full pass. - The evaluation cache's byte count looks bodies and sketches up instead of searching them per body (bodies squared per feature). Same counts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
committed by
GitHub
parent
376c313214
commit
5b6e5815a3
+104
-26
@@ -1194,13 +1194,21 @@ impl ModelState {
|
||||
/// to the budget keep only its last few states, so setting a parameter back recomputed what
|
||||
/// had dropped out.
|
||||
fn added_bytes(&self, before: &ModelState) -> usize {
|
||||
// `before`'s bodies by solid, and its sketches by address: looked up per body and sketch,
|
||||
// not searched (every feature's result is charged, so searching was bodies² per feature).
|
||||
// Bodies sharing a solid are still told apart by `same_shape` (the mesh as well).
|
||||
let mut solids: std::collections::HashMap<usize, Vec<&Body>> = std::collections::HashMap::with_capacity(before.bodies.len());
|
||||
for o in &before.bodies {
|
||||
solids.entry(o.body.solid_id()).or_default().push(&o.body);
|
||||
}
|
||||
let bodies: usize = self
|
||||
.bodies
|
||||
.iter()
|
||||
.filter(|b| !before.bodies.iter().any(|o| o.body.same_shape(&b.body)))
|
||||
.filter(|b| !solids.get(&b.body.solid_id()).is_some_and(|os| os.iter().any(|o| o.same_shape(&b.body))))
|
||||
.map(|b| if b.bytes > 0 { b.bytes } else { b.body.retained_bytes() })
|
||||
.sum();
|
||||
let sketches: usize = self.sketches.iter().filter(|s| !before.sketches.iter().any(|o| Arc::ptr_eq(o, s))).map(|s| s.retained_bytes()).sum();
|
||||
let kept: std::collections::HashSet<*const SolvedSketch> = before.sketches.iter().map(Arc::as_ptr).collect();
|
||||
let sketches: usize = self.sketches.iter().filter(|s| !kept.contains(&Arc::as_ptr(s))).map(|s| s.retained_bytes()).sum();
|
||||
bodies + sketches + self.sheets.len() * 4096 + self.threads.len() * 192 + self.construct.len() * 192
|
||||
}
|
||||
|
||||
@@ -1299,6 +1307,10 @@ pub struct Model {
|
||||
kept: KeptSlot,
|
||||
/// The imported texts' digests the last `evaluate` fingerprinted the features with.
|
||||
step_digests: StepDigests,
|
||||
/// 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.
|
||||
fingerprinted: Option<(usize, u64)>,
|
||||
/// The document context the last `evaluate` ran in ([`context_digest`]).
|
||||
context: u64,
|
||||
/// The last active result of each feature hidden by the history marker, with its document
|
||||
@@ -1418,32 +1430,40 @@ fn quantize(sk: &mut solidcraft_sketch::Sketch) {
|
||||
/// file's text by its 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 (per thread, 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 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.
|
||||
///
|
||||
/// 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
|
||||
/// jobs), and a per-thread store started empty there, so every ahead run wrote out every
|
||||
/// 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) {
|
||||
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 { .. }) {
|
||||
feature_json(f, steps).hash(h);
|
||||
return;
|
||||
}
|
||||
thread_local! {
|
||||
static WRITTEN: std::cell::RefCell<std::collections::HashMap<u64, (Feature, String)>> = std::cell::RefCell::new(std::collections::HashMap::new());
|
||||
let seen = WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).get(&f.id).cloned();
|
||||
if let Some(seen) = seen
|
||||
&& seen.0 == *f
|
||||
{
|
||||
seen.1.hash(h);
|
||||
return;
|
||||
}
|
||||
WRITTEN.with(|written| {
|
||||
let mut written = written.borrow_mut();
|
||||
if let Some((seen, json)) = written.get(&f.id)
|
||||
&& seen == f
|
||||
{
|
||||
json.hash(h);
|
||||
return;
|
||||
}
|
||||
let json = feature_json(f, steps);
|
||||
json.hash(h);
|
||||
if written.len() >= 1 << 15 {
|
||||
written.clear();
|
||||
}
|
||||
written.insert(f.id, (f.clone(), json));
|
||||
});
|
||||
#[cfg(test)]
|
||||
cost_tests::count_written();
|
||||
let json = feature_json(f, steps);
|
||||
json.hash(h);
|
||||
let entry = Arc::new((f.clone(), json));
|
||||
let mut written = WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if written.len() >= 1 << 15 {
|
||||
written.clear();
|
||||
}
|
||||
written.insert(f.id, entry);
|
||||
}
|
||||
|
||||
fn feature_json(f: &Feature, steps: &StepDigests) -> String {
|
||||
@@ -2131,6 +2151,7 @@ impl Model {
|
||||
/// Re-evaluate the document, reusing results up to the first changed feature.
|
||||
pub fn evaluate(&mut self, doc: &Document) {
|
||||
self.placement_inputs = None;
|
||||
self.fingerprinted = None;
|
||||
self.placement_local = true;
|
||||
let (vals, perr) = evaluation_values(doc);
|
||||
self.param_errors = perr;
|
||||
@@ -2532,19 +2553,76 @@ impl Model {
|
||||
/// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result
|
||||
/// (after a change that builds nothing differently).
|
||||
pub fn refingerprint(&mut self, doc: &Document) {
|
||||
self.refingerprint_from(doc, 0);
|
||||
}
|
||||
|
||||
/// How many leading results keep their fingerprints when `doc` has the body names of the
|
||||
/// features `renamed` pinned, and nothing else changed (see [`Model::refingerprint_shared`]).
|
||||
/// Every command pins, and fingerprinting the whole timeline again for it cost as much as
|
||||
/// the fingerprinting of the evaluation itself. When the results hold `doc`'s fingerprints
|
||||
/// (the address and digest kept when they were given prove it), those before the first
|
||||
/// renamed feature stand, since nothing they read changes, unless a pattern or mirror of
|
||||
/// features among them replays a renamed one (it fingerprints its sources' definitions
|
||||
/// wherever they are). Without that proof: none.
|
||||
pub fn pinned_prefix(&self, doc: &Arc<Document>, renamed: &[u64]) -> usize {
|
||||
let proven = self.fingerprinted.is_some_and(|(of, digest)| of == Arc::as_ptr(doc) as usize && digest == fingerprints_digest(&self.results));
|
||||
if !proven {
|
||||
return 0;
|
||||
}
|
||||
let Some(first) = doc.features.iter().position(|f| renamed.contains(&f.id)) else { return doc.features.len() };
|
||||
let replays_renamed = |f: &Feature| match &f.kind {
|
||||
FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } => {
|
||||
bodies.is_empty() && !features.is_empty() && replayed_sources(doc, features).iter().any(|g| renamed.contains(&g.id))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
doc.features.iter().take(first).position(replays_renamed).unwrap_or(first)
|
||||
}
|
||||
|
||||
/// Drop the proof [`Model::pinned_prefix`] reads: the document at that address is about to
|
||||
/// change in place.
|
||||
pub fn forget_fingerprints(&mut self) {
|
||||
self.fingerprinted = None;
|
||||
}
|
||||
|
||||
/// Fingerprint the results from `start` on for `doc`, chained onto the fingerprint before.
|
||||
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);
|
||||
let start = start.min(self.results.len()).min(doc.features.len());
|
||||
if start == self.results.len().min(doc.features.len()) {
|
||||
return;
|
||||
}
|
||||
let (vals, _) = evaluation_values(doc);
|
||||
let marker = doc.marker.unwrap_or(usize::MAX);
|
||||
self.step_digests = StepDigests::of(doc, &self.step_digests);
|
||||
let mut prev = 0;
|
||||
let last = start.checked_sub(1).and_then(|i| self.results.get(i));
|
||||
let mut prev = last.map_or(0, |r| r.fingerprint);
|
||||
// Each feature's fingerprint reads the model it starts from, as evaluating does.
|
||||
let mut before = Arc::new(ModelState::default());
|
||||
for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate() {
|
||||
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));
|
||||
r.fingerprint = prev;
|
||||
before = r.state.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that the results now hold `doc`'s fingerprints (for [`Model::pinned_prefix`]).
|
||||
pub(crate) fn mark_fingerprinted(&mut self, doc: &Arc<Document>) {
|
||||
self.fingerprinted = Some((Arc::as_ptr(doc) as usize, fingerprints_digest(&self.results)));
|
||||
}
|
||||
}
|
||||
|
||||
/// A digest of the results' features and fingerprints, which proves they are still the ones
|
||||
/// [`Model::mark_fingerprinted`] saw (whatever changed them since).
|
||||
fn fingerprints_digest(results: &[FeatureResult]) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
results.len().hash(&mut h);
|
||||
for r in results {
|
||||
r.id.hash(&mut h);
|
||||
r.fingerprint.hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Key of the design's length unit (mm per unit) among the values (no parameter can be named
|
||||
|
||||
@@ -36,6 +36,22 @@ pub(super) fn count(f: impl FnOnce(&mut Counts)) {
|
||||
});
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WRITTEN: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A feature written out on this thread to be fingerprinted.
|
||||
pub(super) fn count_written() {
|
||||
WRITTEN.with(|c| c.set(c.get() + 1));
|
||||
}
|
||||
|
||||
/// The features `f` writes out on this thread to fingerprint them.
|
||||
fn written(f: impl FnOnce()) -> usize {
|
||||
WRITTEN.with(|c| c.set(0));
|
||||
f();
|
||||
WRITTEN.with(Cell::get)
|
||||
}
|
||||
|
||||
/// The work `f` does on this thread.
|
||||
fn counted(f: impl FnOnce()) -> Counts {
|
||||
COUNTS.with(|c| c.set(Counts::default()));
|
||||
@@ -358,6 +374,132 @@ fn an_imported_file_is_fingerprinted_by_its_text() {
|
||||
assert_eq!(model.state().bodies.len(), 3);
|
||||
}
|
||||
|
||||
/// Pinning body names fingerprints the timeline again only from the first renamed feature on
|
||||
/// (`Model::pinned_prefix`), and gives the fingerprints the full pass gives: random pins
|
||||
/// on a timeline of boxes, cuts, patterns of features (one placed before its source, as one made
|
||||
/// with the timeline rolled back is), a suppressed feature and a history marker, after an
|
||||
/// evaluation and after earlier pins.
|
||||
#[test]
|
||||
fn pinning_body_names_fingerprints_as_the_full_pass_does() {
|
||||
let kind = |v: serde_json::Value| serde_json::from_value::<FeatureKind>(v).unwrap();
|
||||
let mut doc = Document::new("pins");
|
||||
let mut ids = Vec::new();
|
||||
for i in 0..10 {
|
||||
let x = 20.0 * i as f64;
|
||||
let b =
|
||||
kind(serde_json::json!({"type": "box", "corner": [x, 0.0, 0.0], "length": "10", "width": "10", "height": "10", "operation": "new_body"}));
|
||||
ids.push(doc.add_feature(b, None).unwrap());
|
||||
if i % 3 == 1 {
|
||||
let c = kind(
|
||||
serde_json::json!({"type": "cylinder", "axis": [0.0, 0.0, 1.0], "base": [x + 5.0, 5.0, -1.0], "height": "12", "radius": "2", "operation": "cut"}),
|
||||
);
|
||||
ids.push(doc.add_feature(c, None).unwrap());
|
||||
}
|
||||
}
|
||||
let circular = |features: Vec<u64>| {
|
||||
kind(serde_json::json!({"type": "pattern", "features": features, "bodies": [],
|
||||
"pattern": {"type": "circular", "angle": "360 deg", "axis": [0.0, 0.0, 1.0], "count": "3", "origin": [0.0, -40.0, 0.0]}}))
|
||||
};
|
||||
ids.push(doc.add_feature(circular(vec![ids[2]]), None).unwrap());
|
||||
// A pattern of a later feature, placed early in the timeline.
|
||||
let early = doc.add_feature(circular(vec![ids[9]]), None).unwrap();
|
||||
let at = doc.features.iter().position(|f| f.id == early).unwrap();
|
||||
let f = doc.features.remove(at);
|
||||
doc.features.insert(3, f);
|
||||
ids.push(early);
|
||||
doc.feature_mut(ids[5]).unwrap().suppressed = true;
|
||||
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = |n: usize| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % n as u64) as usize
|
||||
};
|
||||
let fps = |m: &Model| m.results.iter().map(|r| (r.id, r.fingerprint)).collect::<Vec<_>>();
|
||||
let mut old = Arc::new(doc);
|
||||
let mut model = Model::new();
|
||||
model.evaluate_shared(&old);
|
||||
let (mut proven, mut kept) = (0, 0);
|
||||
for round in 0..60 {
|
||||
if round % 20 == 10 {
|
||||
// From an evaluation's fingerprints again, with the marker in some rounds.
|
||||
let mut d = (*old).clone();
|
||||
d.marker = (round == 30).then_some(d.features.len() - 2);
|
||||
old = Arc::new(d);
|
||||
model.evaluate_shared(&old);
|
||||
}
|
||||
let mut new = (*old).clone();
|
||||
let mut renamed = Vec::new();
|
||||
for _ in 0..1 + next(3) {
|
||||
let f = &mut new.features[next(old.features.len())];
|
||||
let slot = next(3);
|
||||
f.body_names.resize(f.body_names.len().max(slot + 1), String::new());
|
||||
f.body_names[slot] = format!("Pinned {round} {slot}");
|
||||
renamed.push(f.id);
|
||||
}
|
||||
new.reserved_body_names.insert(format!("Body{}", 100 + round));
|
||||
let new = Arc::new(new);
|
||||
let start = model.pinned_prefix(&old, &renamed);
|
||||
let first = new.features.iter().position(|f| renamed.contains(&f.id)).unwrap();
|
||||
assert!(start <= first, "round {round}: kept {start} past the first renamed feature {first}");
|
||||
proven += usize::from(start > 0);
|
||||
kept += start;
|
||||
let mut partial = model.clone();
|
||||
partial.refingerprint_shared(&new, start);
|
||||
let mut full = model.clone();
|
||||
full.refingerprint_shared(&new, 0);
|
||||
assert_eq!(fps(&partial), fps(&full), "round {round}");
|
||||
assert_ne!(fps(&partial), fps(&model), "round {round}: the names are fingerprinted");
|
||||
// The pinned fingerprints prove themselves for the next pin, as the full pass's do.
|
||||
assert_eq!(partial.fingerprinted.as_ref().map(|(_, d)| *d), full.fingerprinted.as_ref().map(|(_, d)| *d));
|
||||
model = partial;
|
||||
old = new;
|
||||
}
|
||||
assert!(proven > 40 && kept > 0, "the stored fingerprints were reused: {proven} rounds, {kept} results");
|
||||
|
||||
// No proof, no reuse: results changed since, another design, or the design about to change
|
||||
// in place.
|
||||
let last = [*ids.last().unwrap()];
|
||||
assert!(model.pinned_prefix(&old, &last) > 0);
|
||||
let mut changed = model.clone();
|
||||
changed.results[0].fingerprint ^= 1;
|
||||
assert_eq!(changed.pinned_prefix(&old, &last), 0);
|
||||
assert_eq!(model.pinned_prefix(&Arc::new((*old).clone()), &last), 0);
|
||||
let mut forgot = model.clone();
|
||||
forgot.forget_fingerprints();
|
||||
assert_eq!(forgot.pinned_prefix(&old, &last), 0);
|
||||
}
|
||||
|
||||
/// A design evaluated ahead, on a worker thread of its own, fingerprints its features from the
|
||||
/// texts the window's evaluation wrote: none is written out again there (the store was per
|
||||
/// thread, and every ahead run started it empty), and the fingerprints are the same.
|
||||
#[test]
|
||||
fn an_evaluation_on_another_thread_reuses_the_written_features() {
|
||||
let mut doc = Document::new("ahead");
|
||||
// Ids no other test's design uses: the store is shared by the tests running beside this one.
|
||||
doc.next_id = 0x0007_e57a_4ead_0000;
|
||||
for i in 0..40 {
|
||||
let x = 20.0 * i as f64;
|
||||
let b = serde_json::json!({"type": "box", "corner": [x, 0.0, 0.0], "length": "10", "width": "10", "height": "10", "operation": "new_body"});
|
||||
doc.add_feature(serde_json::from_value(b).unwrap(), None).unwrap();
|
||||
}
|
||||
let mut window = Model::new();
|
||||
let first = written(|| window.evaluate(&doc));
|
||||
assert!(first >= doc.features.len(), "{first} written");
|
||||
let fps = |m: &Model| m.results.iter().map(|r| r.fingerprint).collect::<Vec<_>>();
|
||||
let (doc2, mut ahead) = (doc.clone(), window.clone());
|
||||
ahead.no_cache = true;
|
||||
let (work, ahead_fps) = std::thread::spawn(move || {
|
||||
let work = written(|| ahead.evaluate(&doc2));
|
||||
(work, fps(&ahead))
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert_eq!(work, 0, "features written out again");
|
||||
assert_eq!(ahead_fps, fps(&window));
|
||||
}
|
||||
|
||||
/// A 10 mm square plate per hole along X, 4 mm thick, in component `comp`, with `holes` square
|
||||
/// holes cut through it by boxes drawn in component `tools` (the plate's own, usually). The
|
||||
/// plate's body name.
|
||||
|
||||
@@ -31,6 +31,7 @@ impl Model {
|
||||
return false;
|
||||
}
|
||||
self.evaluate(doc);
|
||||
self.mark_fingerprinted(doc);
|
||||
if !self.no_cache && self.primed.is_none() && self.placement_local {
|
||||
self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) });
|
||||
}
|
||||
@@ -38,13 +39,16 @@ impl Model {
|
||||
}
|
||||
|
||||
/// [`Model::refingerprint`] for a shared document: a proof that held for the results before
|
||||
/// is kept for `doc`, since nothing was built differently (pinned body names, say).
|
||||
pub fn refingerprint_shared(&mut self, doc: &Arc<Document>) {
|
||||
/// is kept for `doc`, since nothing was built differently (pinned body names, say). The
|
||||
/// first `keep` results keep their fingerprints: [`Model::pinned_prefix`] of the document
|
||||
/// before the pins, or 0.
|
||||
pub fn refingerprint_shared(&mut self, doc: &Arc<Document>, keep: usize) {
|
||||
let proven = !self.no_cache
|
||||
&& self.primed.is_none()
|
||||
&& self.placement_inputs.as_ref().is_some_and(|inputs| inputs.state.upgrade().is_some_and(|state| Arc::ptr_eq(&state, &self.state())))
|
||||
&& !self.is_stale();
|
||||
self.refingerprint(doc);
|
||||
self.refingerprint_from(doc, keep);
|
||||
self.mark_fingerprinted(doc);
|
||||
if proven && self.placement_local {
|
||||
self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) });
|
||||
}
|
||||
|
||||
@@ -1108,6 +1108,57 @@ fn counted_body_names_stay_when_the_timeline_changes() {
|
||||
assert_eq!(bodies(&s), named(&[("Body2", "B"), ("Body3", "C"), ("Body4", "E")]));
|
||||
}
|
||||
|
||||
/// Pinning reads each feature's bodies once and keeps them with the state it read them from;
|
||||
/// the names it pins and reserves, and the fingerprints it leaves, are those of reading every
|
||||
/// feature's bodies again: random boxes (named and counted), moves, suppressions, deletions,
|
||||
/// reorders, undo and redo, against a session that forgets what it read before every command and
|
||||
/// against fingerprinting the whole timeline again.
|
||||
#[test]
|
||||
fn pinning_with_the_bodies_it_read_before_pins_as_reading_them_again() {
|
||||
let (mut kept, mut fresh) = (Session::default(), Session::default());
|
||||
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||
let mut next = |n: usize| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % n as u64) as usize
|
||||
};
|
||||
for step in 0..60 {
|
||||
let features: Vec<String> = kept.doc.features.iter().map(|f| f.name.clone()).collect();
|
||||
let counted: Vec<String> = kept.model.state().bodies.iter().map(|b| b.name.clone()).collect();
|
||||
let pick = |names: &[String], k: usize| names.get(k % names.len().max(1)).cloned().unwrap_or_default();
|
||||
let x = 15 * step;
|
||||
let (id, params) = match next(9) {
|
||||
_ if features.len() < 3 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})),
|
||||
0 | 1 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})),
|
||||
2 => ("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "body_name": format!("Named {step}")})),
|
||||
3 => ("solid.move", json!({"bodies": [pick(&counted, next(64))], "translate": [0, 5, 0]})),
|
||||
4 => ("timeline.suppress", json!({"feature": pick(&features, next(64)), "suppressed": next(2) == 0})),
|
||||
5 => ("timeline.delete", json!({"feature": pick(&features, next(64))})),
|
||||
6 => ("timeline.reorder", json!({"feature": pick(&features, next(64)), "position": next(features.len()), "active": true})),
|
||||
7 => ("edit.undo", json!({})),
|
||||
_ => ("edit.redo", json!({})),
|
||||
};
|
||||
fresh.made_bodies.clear();
|
||||
let (a, b) = (kept.execute(id, ¶ms), fresh.execute(id, ¶ms));
|
||||
assert_eq!(a.is_ok(), b.is_ok(), "step {step}: {id} {params}");
|
||||
assert_eq!(kept.doc.to_json(), fresh.doc.to_json(), "step {step}: {id} {params}");
|
||||
// The fingerprints match the design as fingerprinting the whole timeline again makes them
|
||||
// match it: evaluating it again reuses the same results (all, as a rule; the others are
|
||||
// computed or taken from the cache the copies share).
|
||||
let again = |model: &solidcraft_doc::Model| {
|
||||
let mut m = model.clone();
|
||||
m.evaluate(&kept.doc);
|
||||
m.last_recomputed + m.last_restored
|
||||
};
|
||||
let mut full = kept.model.clone();
|
||||
full.refingerprint(&kept.doc);
|
||||
assert_eq!(again(&kept.model), again(&full), "step {step}: {id} {params}");
|
||||
assert_eq!(again(&kept.model), again(&fresh.model), "step {step}: {id} {params}");
|
||||
}
|
||||
assert!(kept.doc.features.len() > 5 && !kept.doc.reserved_body_names.is_empty());
|
||||
}
|
||||
|
||||
/// The value at a dotted path of a definition.
|
||||
fn dotted<'a>(def: &'a Value, path: &str) -> &'a Value {
|
||||
path.split('.').fold(def, |v, k| &v[k])
|
||||
|
||||
@@ -424,6 +424,9 @@ impl ComputedCommands {
|
||||
/// reports how it went and opens the answer itself. `Err`: it couldn't start.
|
||||
pub type EasyPrintUpload = Arc<dyn Fn(&str, Vec<u8>) -> std::result::Result<(), String> + Send + Sync>;
|
||||
|
||||
/// See [`Session::made_bodies`].
|
||||
type MadeBodies = std::collections::HashMap<u64, (std::sync::Weak<ModelState>, Vec<String>)>;
|
||||
|
||||
pub struct Session {
|
||||
pub doc: Arc<Document>,
|
||||
pub model: Model,
|
||||
@@ -492,6 +495,9 @@ pub struct Session {
|
||||
/// of the design on every frame (#3892), and an answer that walked the hidden lists made a
|
||||
/// frame cost grow with the size of the design.
|
||||
visibility_index_cache: std::sync::Mutex<Option<occurrences::VisibilityIndex>>,
|
||||
/// The bodies each feature made, by name, with the state they were read from
|
||||
/// ([`Session::pin_body_names`]).
|
||||
made_bodies: MadeBodies,
|
||||
removed_later_cache: std::sync::Mutex<Option<occurrences::RemovedLaterCache>>,
|
||||
occurrence_bodies_cache: std::sync::Mutex<Option<occurrences::OccurrenceBodiesCache>>,
|
||||
placement_index_cache: std::sync::Mutex<Option<occurrences::PlacementIndex>>,
|
||||
@@ -700,6 +706,7 @@ impl Session {
|
||||
joints_settled: None,
|
||||
occurrence_visibility_cache: Default::default(),
|
||||
visibility_index_cache: Default::default(),
|
||||
made_bodies: MadeBodies::new(),
|
||||
removed_later_cache: Default::default(),
|
||||
occurrence_bodies_cache: Default::default(),
|
||||
placement_index_cache: Default::default(),
|
||||
@@ -903,6 +910,7 @@ impl Session {
|
||||
*index = None;
|
||||
}
|
||||
self.forget_dirty_answer();
|
||||
self.model.forget_fingerprints();
|
||||
Arc::make_mut(&mut self.doc)
|
||||
}
|
||||
|
||||
@@ -1128,12 +1136,34 @@ impl Session {
|
||||
}
|
||||
let mut pins: Vec<(u64, Vec<String>)> = Vec::new();
|
||||
let mut reserve: Vec<String> = Vec::new();
|
||||
for f in self.doc.features.iter().filter(|f| !matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. })) {
|
||||
let Some(r) = self.model.result(f.id).filter(|r| r.error.is_none() && !r.skipped && !r.stale) else { continue };
|
||||
let made: Vec<&str> = r.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.as_str()).collect();
|
||||
// The names of the bodies each feature made, kept with the state they were read from:
|
||||
// every command pins, and reading them again searched every result's bodies (features ×
|
||||
// bodies per command). A state is the same while it is the same allocation (the weak
|
||||
// reference keeps that address from being reused), and its bodies never change in place.
|
||||
let mut known = std::mem::take(&mut self.made_bodies);
|
||||
let mut made_bodies = MadeBodies::with_capacity(known.len());
|
||||
for (i, f) in self.doc.features.iter().enumerate() {
|
||||
if matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. }) {
|
||||
continue;
|
||||
}
|
||||
// Results are in timeline order: the feature's own index first, the search only when not.
|
||||
let r = self.model.results.get(i).filter(|r| r.id == f.id).or_else(|| self.model.result(f.id));
|
||||
let Some(r) = r.filter(|r| r.error.is_none() && !r.skipped && !r.stale) else { continue };
|
||||
let made = match known.remove(&f.id).filter(|(state, _)| std::sync::Weak::as_ptr(state) == Arc::as_ptr(&r.state)) {
|
||||
Some(entry) => made_bodies.entry(f.id).or_insert(entry),
|
||||
None => made_bodies.entry(f.id).or_insert_with(|| {
|
||||
let names = r.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.clone()).collect();
|
||||
(Arc::downgrade(&r.state), names)
|
||||
}),
|
||||
};
|
||||
let made: Vec<&str> = made.1.iter().map(String::as_str).collect();
|
||||
reserve.extend(
|
||||
made.iter().filter(|n| solidcraft_doc::is_counted_body_name(n) && !self.doc.reserved_body_names.contains(**n)).map(|n| n.to_string()),
|
||||
);
|
||||
// Nothing to pin when every slot the bodies take already holds a name.
|
||||
if made.len() <= f.body_names.len() && f.body_names.iter().take(made.len()).all(|slot| !slot.trim().is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let mut names = f.body_names.clone();
|
||||
names.resize(names.len().max(made.len()), String::new());
|
||||
for (slot, name) in names.iter_mut().zip(&made) {
|
||||
@@ -1145,9 +1175,13 @@ impl Session {
|
||||
pins.push((f.id, names));
|
||||
}
|
||||
}
|
||||
self.made_bodies = made_bodies;
|
||||
if pins.is_empty() && reserve.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The fingerprints that stand: taken before the pins change the design.
|
||||
let renamed: Vec<u64> = pins.iter().map(|(id, _)| *id).collect();
|
||||
let keep = self.model.pinned_prefix(&self.doc, &renamed);
|
||||
let doc = self.doc_mut();
|
||||
for (id, names) in pins {
|
||||
if let Some(f) = doc.feature_mut(id) {
|
||||
@@ -1156,7 +1190,7 @@ impl Session {
|
||||
}
|
||||
doc.reserved_body_names.extend(reserve);
|
||||
// The pinned names are the ones the bodies have: no result changes, so none is evaluated.
|
||||
self.model.refingerprint_shared(&self.doc);
|
||||
self.model.refingerprint_shared(&self.doc, keep);
|
||||
}
|
||||
|
||||
/// A hidden construction plane stays hidden when the design renames it, or undo or redo
|
||||
@@ -1632,6 +1666,9 @@ impl Session {
|
||||
pending_moves: self.pending_moves.clone(),
|
||||
world_cache: std::sync::Mutex::new(self.world_cache.lock().ok().and_then(|cache| cache.clone())),
|
||||
joints_settled: self.joints_settled.clone(),
|
||||
// Read again by the copy: handing it these references measured more peak memory on a
|
||||
// large design (the rover, evaluated ahead) for no change in what it pins.
|
||||
made_bodies: MadeBodies::new(),
|
||||
occurrence_visibility_cache: Default::default(),
|
||||
visibility_index_cache: Default::default(),
|
||||
removed_later_cache: Default::default(),
|
||||
|
||||
Reference in New Issue
Block a user