brep_kernel/feature_pipeline/features/sketch/loop_ids.rs
1//! Stable per-LOOP identity for a sketch's closed loops.
2//!
3//! # Why
4//!
5//! A profile-swept feature (extrude/sweep/revolve/loft/path-sweep) builds one
6//! prism per profile REGION and stamps names on the result. Sidewalls are safe:
7//! they are named from the source geometry's persistent `{sketchId}:G{gid}`. The
8//! CAPS were not — every region stamped the SAME `{cap_base}_START/_END`, so the
9//! post-union `ensure_unique_face_names` pass disambiguated them POSITIONALLY
10//! (`X[0]`, `X[1]`, …) in shell/face encounter order. Editing the sketch to add
11//! or remove a loop shifted those indices, and a fillet that referenced `X[1]`
12//! silently jumped to a different island on replay.
13//!
14//! The fix is to give every loop an identity of its own that the cap names embed.
15//! That identity must survive editing the loop itself, so it is PERSISTED: each
16//! sketch geometry carries a `loopId` in `persistentData.sketch`, written back by
17//! the editor on commit (`assign_sketch_loop_ids`).
18//!
19//! # The rule
20//!
21//! For each assembled closed loop:
22//! - if ANY member edge carries a stored `loopId`, the loop claims the LOWEST of
23//! them ("lowest number wins") and that value is written back onto every other
24//! member edge, so the loop keeps its identity as edges come and go;
25//! - otherwise the loop is new and SEEDS its id from the lowest geometry id
26//! among its edges.
27//!
28//! Both halves are computed the same way whether or not the document has ever
29//! been committed, so a sketch that has never been through the editor derives
30//! exactly the id it would have been assigned — reading and writing never
31//! disagree, and no document renames faces merely by being opened.
32//!
33//! # Resilience
34//!
35//! - ADDING an edge to a loop: the new edge carries no id and inherits the
36//! loop's — unchanged. (Minting also hands out ids above the current maximum,
37//! so a seed can only move down, never up.)
38//! - REMOVING a non-anchor edge: the id lives on the survivors — unchanged.
39//! - REMOVING the anchor edge (the one the id was seeded from): still unchanged,
40//! because the id was persisted onto the whole loop, not recomputed from the
41//! anchor. This is the case a derive-only scheme cannot handle, and the reason
42//! the id is stored at all.
43//! - Editing a DIFFERENT loop: never observed here — a loop's claim reads only
44//! its own edges. That is the reported bug, fixed.
45//!
46//! # Collisions
47//!
48//! Two loops can claim the same id: a loop that SPLIT in two (both halves carry
49//! the same stored id), or — because the editor mints `max(existing gid) + 1` and
50//! therefore REUSES the ids of deleted geometry — a freshly drawn loop whose
51//! seed collides with an older loop's stored id. Ties break in this order:
52//! 1. a loop that INHERITED the id (stored on its edges) beats one that merely
53//! seeded it from a gid, so a new loop can never steal a live loop's identity;
54//! 2. between two inheritors (the split case), the one holding the lower minimum
55//! gid keeps it — deterministic, and independent of loop order.
56//! The loser re-seeds from its own lowest gid, or, if that is taken too, from one
57//! above the highest id in play. A split therefore keeps the original id on one
58//! half and mints a fresh one for the other; if the halves are later rejoined,
59//! the survivor's id wins again.
60
61use super::geometry::Loop;
62
63/// Resolve every loop's [`Loop::loop_id`], in place.
64///
65/// `loops` is the fully assembled set (chained loops plus whole circles and
66/// ellipses) BEFORE region classification, so ids are decided over the sketch as
67/// a whole and never depend on how the loops later group into regions.
68pub(super) fn resolve(loops: &mut [Loop]) {
69 let claims: Vec<Claim> = loops.iter().map(Claim::of).collect();
70 for (loop_data, id) in loops.iter_mut().zip(settle(&claims)) {
71 loop_data.loop_id = id;
72 }
73}
74
75/// One loop's claim: the id it wants, whether it INHERITED that id from stored
76/// geometry (as opposed to seeding it from a gid), and its lowest gid — the
77/// tie-break and the re-seed source.
78struct Claim {
79 id: Option<u64>,
80 inherited: bool,
81 min_gid: Option<u64>,
82}
83
84impl Claim {
85 fn of(loop_data: &Loop) -> Self {
86 let stored = loop_data
87 .entries
88 .iter()
89 .filter_map(|(segment, _)| segment.ids.loop_id)
90 .min();
91 let min_gid = loop_data
92 .entries
93 .iter()
94 .filter_map(|(segment, _)| segment.ids.gid)
95 .min();
96 Self {
97 id: stored.or(min_gid),
98 inherited: stored.is_some(),
99 min_gid,
100 }
101 }
102}
103
104/// Award each claim a UNIQUE id, applying the tie-break rules in the module doc.
105/// Returns one id per claim, in input order.
106fn settle(claims: &[Claim]) -> Vec<Option<u64>> {
107 // Award order: inheritors first (they cannot be displaced by a seeder), then
108 // by ascending minimum gid, then by input position — a total order, so the
109 // outcome never depends on the order the loops happened to be assembled in.
110 let mut order: Vec<usize> = (0..claims.len()).collect();
111 order.sort_by_key(|&index| {
112 let claim = &claims[index];
113 (!claim.inherited, claim.min_gid.unwrap_or(u64::MAX), index)
114 });
115
116 let mut taken: Vec<u64> = Vec::with_capacity(claims.len());
117 let mut resolved = vec![None; claims.len()];
118 for index in order {
119 let claim = &claims[index];
120 let Some(wanted) = claim.id else { continue };
121 let id = if taken.contains(&wanted) {
122 // Displaced: fall back to this loop's own lowest gid, else to one
123 // above everything in play (ids are just numbers — a re-seed is free
124 // to leave the gid space).
125 let own = claim.min_gid.filter(|gid| !taken.contains(gid));
126 own.unwrap_or_else(|| next_free(claims, &taken))
127 } else {
128 wanted
129 };
130 taken.push(id);
131 resolved[index] = Some(id);
132 }
133 resolved
134}
135
136/// One above the highest id anywhere in play (awarded, claimed, or a gid) — the
137/// last-resort id for a loop displaced off both its stored id and its own gid.
138fn next_free(claims: &[Claim], taken: &[u64]) -> u64 {
139 let highest = taken
140 .iter()
141 .copied()
142 .chain(claims.iter().flat_map(|claim| claim.id.into_iter()))
143 .chain(claims.iter().flat_map(|claim| claim.min_gid.into_iter()))
144 .max()
145 .unwrap_or(0);
146 highest.saturating_add(1)
147}
148
149
150// ===========================================================================
151// Write-back — the editor side
152// ===========================================================================
153
154/// Assign every closed loop's id onto the geometries of a SOLVED sketch document,
155/// in place, and report whether anything changed.
156///
157/// This is the persistence half of the scheme: the kernel DERIVES ids the same
158/// way every run (so a document that has never been through here still names its
159/// faces correctly), and this writes the derived ids down so they survive the one
160/// edit deriving cannot: deleting the edge an id was seeded from. The editor calls
161/// it when a sketch is committed.
162///
163/// `doc` is the `persistentData.sketch` object. Geometry that is construction-only
164/// or not part of a closed loop is left untouched — only a loop has an identity.
165pub fn assign_sketch_loop_ids(doc: &mut serde_json::Value) -> bool {
166 let Some(loops) = closed_loops(doc) else {
167 return false;
168 };
169 let mut changed = false;
170 let Some(geometries) = doc
171 .get_mut("geometries")
172 .and_then(serde_json::Value::as_array_mut)
173 else {
174 return false;
175 };
176 for geometry in geometries.iter_mut() {
177 let Some(gid) = geometry.get("id").and_then(numeric) else {
178 continue;
179 };
180 let Some(loop_id) = loops.get(&gid) else {
181 continue;
182 };
183 let already = geometry.get("loopId").and_then(numeric);
184 if already == Some(*loop_id) {
185 continue;
186 }
187 if let Some(object) = geometry.as_object_mut() {
188 object.insert("loopId".into(), serde_json::json!(loop_id));
189 changed = true;
190 }
191 }
192 changed
193}
194
195/// `geometry id -> loop id` for every geometry that belongs to a closed loop,
196/// derived exactly as the sketch feature derives it: chain the segments, settle
197/// the claims, then hand each loop's awarded id to ALL of its members ("lowest
198/// number wins and updates the rest of the edges in that loop to match").
199fn closed_loops(doc: &serde_json::Value) -> Option<std::collections::HashMap<u64, u64>> {
200 let members = loop_members(doc)?;
201 let claims: Vec<Claim> = members
202 .iter()
203 .map(|edges| {
204 let stored = edges.iter().filter_map(|(_, stored)| *stored).min();
205 let min_gid = edges.iter().map(|(gid, _)| *gid).min();
206 Claim {
207 id: stored.or(min_gid),
208 inherited: stored.is_some(),
209 min_gid,
210 }
211 })
212 .collect();
213 let mut assignment = std::collections::HashMap::new();
214 for (edges, id) in members.iter().zip(settle(&claims)) {
215 let Some(id) = id else { continue };
216 for (gid, _) in edges {
217 assignment.insert(*gid, id);
218 }
219 }
220 Some(assignment)
221}
222
223/// Group the document's model geometry into closed loops, as
224/// `(geometry id, stored loop id)` per member.
225///
226/// Whole circles and ellipses are loops on their own. The rest chain end-to-end
227/// through shared POINT ids — the same adjacency the profile chainer walks, read
228/// off the document's point references rather than solved coordinates, which is
229/// exact and needs no tolerance. A chain is closed when it returns to its start.
230///
231/// At a BRANCHING junction (three or more segments meeting at one point — not a
232/// well-formed profile) this walk takes the first candidate, which may group the
233/// edges differently than the profile chainer does. That degrades safely rather
234/// than corrupting anything: the kernel resolves each loop's id from the ids
235/// stored on ITS OWN edges, so a mis-grouped stamp at worst makes two loops claim
236/// the same id, which [`settle`] then breaks apart deterministically.
237fn loop_members(doc: &serde_json::Value) -> Option<Vec<Vec<(u64, Option<u64>)>>> {
238 let geometries = doc.get("geometries")?.as_array()?;
239 let mut loops: Vec<Vec<(u64, Option<u64>)>> = Vec::new();
240 // (gid, stored, endpoint a, endpoint b) for the chainable segments.
241 let mut segments: Vec<(u64, Option<u64>, u64, u64)> = Vec::new();
242 for geometry in geometries {
243 if geometry.get("construction").and_then(serde_json::Value::as_bool) == Some(true) {
244 continue;
245 }
246 let Some(gid) = geometry.get("id").and_then(numeric) else {
247 continue;
248 };
249 let stored = geometry.get("loopId").and_then(numeric);
250 let geom_type = geometry
251 .get("type")
252 .and_then(serde_json::Value::as_str)
253 .unwrap_or("");
254 let points: Vec<u64> = geometry
255 .get("points")
256 .and_then(serde_json::Value::as_array)
257 .map(|ids| ids.iter().filter_map(numeric).collect())
258 .unwrap_or_default();
259 match geom_type {
260 // Self-contained loops.
261 "circle" | "ellipse" => loops.push(vec![(gid, stored)]),
262 // `[start, end]`.
263 "line" if points.len() == 2 => segments.push((gid, stored, points[0], points[1])),
264 // `[center, start, end]`.
265 "arc" if points.len() == 3 => segments.push((gid, stored, points[1], points[2])),
266 // `[p0, …, pn]` — the spline's endpoints are its first and last.
267 "bezier" if points.len() >= 2 => {
268 segments.push((gid, stored, points[0], points[points.len() - 1]))
269 }
270 _ => {}
271 }
272 }
273
274 // Walk each connected component; keep it only if it closes.
275 let mut visited = vec![false; segments.len()];
276 for start in 0..segments.len() {
277 if visited[start] {
278 continue;
279 }
280 let (_, _, first_point, _) = segments[start];
281 let mut chain = vec![start];
282 visited[start] = true;
283 let mut tail = segments[start].3;
284 loop {
285 if tail == first_point {
286 // Closed: a chain of one segment closes only if it is a loop on
287 // its own (a full-circle arc), which the endpoints already say.
288 loops.push(
289 chain
290 .iter()
291 .map(|&index| (segments[index].0, segments[index].1))
292 .collect(),
293 );
294 break;
295 }
296 let next = (0..segments.len()).find(|&index| {
297 !visited[index] && (segments[index].2 == tail || segments[index].3 == tail)
298 });
299 let Some(next) = next else { break };
300 visited[next] = true;
301 chain.push(next);
302 tail = if segments[next].2 == tail {
303 segments[next].3
304 } else {
305 segments[next].2
306 };
307 }
308 }
309 Some(loops)
310}
311
312/// A JSON id as a number (a numeric string counts) — the write-back's copy of the
313/// sketch pipeline's `numeric_id`, so both halves read ids identically.
314fn numeric(value: &serde_json::Value) -> Option<u64> {
315 match value {
316 serde_json::Value::Number(number) => number.as_u64(),
317 serde_json::Value::String(text) => text.parse().ok(),
318 _ => None,
319 }
320}
321