A renamed body keeps its number: the next body does not take the freed name (#4957) (#5053)

* A renamed body keeps its number (#4957)

The design's body counter starts over at every evaluation, so a body
renamed after a join (the join changed it, so the rename cannot be
followed without evaluating the design again) gave its number back: the
next body took the name the rename freed, and a script that names a body
found another one.

The design now saves the names a rename freed, and the counter skips
them.

* A renamed body keeps its number (#4957)

The design's body counter starts over at every evaluation, so a body
renamed after a join (the join changed it, so the rename cannot be
followed without evaluating the design again) gave its number back: the
next body took the name the rename freed, and a script that names a body
found another one.

The design now saves the names a rename freed, and the counter skips
them.

* Format
This commit is contained in:
vdirienzo
2026-10-23 13:43:28 +00:00
committed by GitHub
parent 01bbc0aa9f
commit 92d1331978
5 changed files with 71 additions and 2 deletions
+14
View File
@@ -2419,6 +2419,12 @@ pub struct Document {
pub marker: Option<usize>,
#[serde(default)]
pub next_id: u64,
/// Body names the design used and must not use again: a name a `body.rename` freed (#4957).
/// The design's own counter starts over at every evaluation, so without these a design that
/// is evaluated again after a rename hands the freed name to the next body, and a script
/// that names a body finds another one.
#[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
pub reserved_body_names: std::collections::BTreeSet<String>,
/// Components below the root, as a tree (by parent).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub components: Vec<Component>,
@@ -2665,6 +2671,7 @@ impl Document {
features: Vec::new(),
marker: None,
next_id: 1,
reserved_body_names: Default::default(),
components: Vec::new(),
occurrences: Vec::new(),
assembly: Default::default(),
@@ -2692,7 +2699,14 @@ impl Document {
/// Rename body `old` to `new` where the design keeps things by body name outside its
/// features: materials, appearances, configuration columns, offsets, components and the
/// browser's groups and order. (The features are the rename command's to change.)
///
/// A name the design numbered (`Body1`) is not used again after the rename: the design's
/// counter starts over at every evaluation, so without this a design that is evaluated
/// again hands the freed name to the next body (#4957).
pub fn rename_body_keys(&mut self, old: &str, new: &str) {
if old.strip_prefix("Body").and_then(|n| n.parse::<usize>().ok()).is_some() {
self.reserved_body_names.insert(old.to_string());
}
if let Some(m) = self.materials.remove(old) {
self.materials.insert(new.to_string(), m);
}
+16 -2
View File
@@ -716,6 +716,10 @@ pub struct ModelState {
/// Shared between states: a feature that does not change a sketch keeps it as it was.
pub sketches: Vec<Arc<SolvedSketch>>,
pub body_counter: usize,
/// Body names the design used and must not use again (a name a `body.rename` freed, #4957).
/// The counter starts over at every evaluation, so without these a design that is evaluated
/// again after a rename hands the freed name to the next body.
pub reserved_body_names: std::collections::BTreeSet<String>,
/// Sheet metal bodies (by body name) and their flat patterns.
pub sheets: Vec<crate::sheet::SheetBody>,
/// Construction planes, axes and points as evaluated (by feature).
@@ -751,6 +755,9 @@ impl ModelState {
self.sketch_keys.get(&s.feature).hash(&mut h);
}
self.body_counter.hash(&mut h);
for n in &self.reserved_body_names {
n.hash(&mut h);
}
for (feature, points) in &self.blend_edges {
feature.hash(&mut h);
for p in points {
@@ -1761,7 +1768,8 @@ impl Model {
let (vals, perr) = evaluation_values(doc);
self.param_errors = perr;
let mut prev_fp = 0u64;
let mut state = self.empty.clone();
// The names the design must not use again travel with the state (#4957).
let mut state = std::sync::Arc::new(ModelState { reserved_body_names: doc.reserved_body_names.clone(), ..(*self.empty).clone() });
let mut out: Vec<FeatureResult> = Vec::with_capacity(doc.features.len());
let mut reuse = !self.no_cache;
let mut recomputed = 0;
@@ -1851,6 +1859,9 @@ impl Model {
recomputed += 1;
let t0 = now();
let mut next = (*state).clone();
// The names the design must not use again travel with the state (#4957): a state
// taken from an earlier evaluation may have been made before a rename freed one.
next.reserved_body_names = doc.reserved_body_names.clone();
for b in &mut next.bodies {
b.made = crate::lineage::Made::Before;
}
@@ -2028,6 +2039,8 @@ impl Model {
b.name = new.to_string();
b.names = b.names.renamed();
}
// The names the design must not use again travel with the state (#4957).
st.reserved_body_names = doc.reserved_body_names.clone();
Arc::new(st)
})
.clone();
@@ -2210,7 +2223,8 @@ fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String {
loop {
state.body_counter += 1;
let n = format!("Body{}", state.body_counter);
if state.body(&n).is_none() {
// A name a rename freed is not handed out again (#4957).
if state.body(&n).is_none() && !state.reserved_body_names.contains(&n) {
return n;
}
}
@@ -0,0 +1,5 @@
//! The design saves the body names a `body.rename` freed (`Body1` after the body it named was
//! renamed), so a name the design used is not used again.
//!
//! A design saved before this has no such names: it keeps the names it has, and the next body
//! it makes may take a name an earlier rename freed.
+6
View File
@@ -181,6 +181,7 @@ impl Writer {
let sketches = st.sketches.iter().map(|s| self.sketch(s)).collect::<Option<Vec<_>>>()?;
let r = json!({
"bodies": runs(&bodies), "sketches": runs(&sketches), "body_counter": st.body_counter,
"reserved_body_names": st.reserved_body_names.iter().collect::<Vec<_>>(),
"sheets": serde_json::to_value(&st.sheets).ok()?, "construct": serde_json::to_value(&st.construct).ok()?,
"threads": serde_json::to_value(&st.threads).ok()?,
"sketch_keys": st.sketch_keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::<Vec<_>>(),
@@ -320,6 +321,11 @@ impl SavedModel {
bodies: ids("bodies", model_bodies.len())?.into_iter().filter_map(|i| model_bodies.get(i).cloned()).collect(),
sketches: ids("sketches", sketches.len())?.into_iter().filter_map(|i| sketches.get(i).cloned()).collect(),
body_counter: index(s.get("body_counter"), usize::MAX)?,
reserved_body_names: s
.get("reserved_body_names")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|n| n.as_str().map(str::to_string)).collect())
.unwrap_or_default(),
sheets: serde_json::from_value(field("sheets")?).map_err(invalid)?,
construct: serde_json::from_value(field("construct")?).map_err(invalid)?,
threads: serde_json::from_value(field("threads")?).map_err(invalid)?,
+30
View File
@@ -3587,6 +3587,36 @@ fn a_pattern_repeats_a_fillet_on_the_edges_it_found() {
assert!(rel(volume(&mut s), expect) < 1e-5, "{} vs {expect}", volume(&mut s));
}
/// A body renamed after a join: the next new body does not take the name the rename freed
/// (#4957). The join changed the body, so the rename is followed by a full evaluation of the
/// design; the numbers the design handed out must not go back with it, or a script that names
/// a body finds another one.
#[test]
fn a_renamed_body_keeps_its_number_from_the_next_body() {
for join in [false, true] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new"}));
if join {
// A second box joined to the first: the join changes the body, so the rename
// cannot be followed without evaluating the design again.
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 0], "p1": [15, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"}));
}
run(&mut s, "body.rename", json!({"body": "Body1", "name": "First"}));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [30, 10]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new"}));
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(names, ["First", "Body2"], "with a join: {join}");
}
}
/// A copy added by raising the count after a rename takes the next number, not the freed one (#372).
#[test]
fn raising_a_pattern_count_after_a_rename_numbers_the_new_copy_after_the_others() {