SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Merge upstream profile picks and flush-pad fixes with adaptive identities
bherbruck0167c358bbd2
diff --cc crates/doc/src/document.rsindex 6593252d82,58c8914e32..fc9b9e2967--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@@ -88,14 -79,11 +88,16 @@@ pub enum ProfileSelAll,/// Profiles by index in the solved sketch's profile list.Indices { indices: Vec<usize> },- /// Profiles whose outer loop is made of exactly these curves (order-insensitive); stable- /// across parameter changes.+ /// Profiles whose outer loop is made of exactly these curves, or pieces of them where other+ /// curves cut them (order and repeats don't matter; see `sketch::profile_by_curves`). Found+ /// again on every evaluation, so stable across parameter changes; no match or several is+ /// an error, never another profile.Curves { loops: Vec<Vec<String>> },+ /// Complete current boundaries of topology-aware analytic offset associations.+ /// The local association identity survives retirement and resurrection of arc roles.+ OffsetBoundaries { associations: Vec<String> },+ /// Exact whole source coverage, including holes; partial source curves do not match.+ WholeBoundaries { profiles: Vec<WholeProfileBoundary> },/// The profile containing each sketch point.Points { points: Vec<Vec2> },}diff --cc crates/doc/src/profile_refs.rsindex ff92be9096,0000000000..7359809d7fmode 100644,000000..100644--- a/crates/doc/src/profile_refs.rs+++ b/crates/doc/src/profile_refs.rs@@@ -1,501 -1,0 +1,505 @@@+//! Exact profile references through analytic offset topology transitions.+use std::collections::BTreeSet;++use crate::{DocError, ProfileSel, Result, SolvedSketch, WholeProfileBoundary};++const MAX_SELECTIONS: usize = 128;++fn whole_boundary(profile: &solvecraft_sketch::Profile) -> Option<WholeProfileBoundary> {+ let (outer, holes) = profile.whole_curve_boundaries()?;+ Some(WholeProfileBoundary { outer, holes })+}++fn validate_whole(profiles: &[WholeProfileBoundary]) -> Result<()> {+ if profiles.is_empty() || profiles.len() > MAX_SELECTIONS {+ return Err(DocError::Invalid("whole-source profile selection needs bounded unique profiles".into()));+ }+ let mut total = 0usize;+ let mut identities = BTreeSet::new();+ for profile in profiles {+ if profile.holes.len() > 128 || !identities.insert((&profile.outer, &profile.holes)) {+ return Err(DocError::Invalid("invalid whole-source profile holes or duplicate identity".into()));+ }+ let mut all = BTreeSet::new();+ for boundary in std::iter::once(&profile.outer).chain(&profile.holes) {+ total += boundary.len();+ if boundary.is_empty() || boundary.len() > 512 || total > 20_000 {+ return Err(DocError::Invalid("whole-source boundary exceeds its identity budget".into()));+ }+ let mut previous = None;+ for curve in boundary {+ if curve.is_empty()+ || curve.len() > 512+ || curve.chars().any(char::is_control)+ || previous.is_some_and(|previous| previous >= curve)+ || !all.insert(curve)+ {+ return Err(DocError::Invalid("whole-source boundary needs canonical disjoint curve identities".into()));+ }+ previous = Some(curve);+ }+ }+ if profile.holes.windows(2).any(|pair| pair[0] >= pair[1]) {+ return Err(DocError::Invalid("whole-source holes need canonical unique identities".into()));+ }+ }+ Ok(())+}++fn whole_profile_indices(ss: &SolvedSketch, profiles: &[WholeProfileBoundary]) -> Result<Vec<usize>> {+ validate_whole(profiles)?;+ let current = ss.profiles.iter().map(whole_boundary).collect::<Vec<_>>();+ profiles+ .iter()+ .map(|identity| {+ let mut matches = current.iter().enumerate().filter(|(_, candidate)| candidate.as_ref() == Some(identity));+ let (index, _) = matches.next().ok_or_else(|| DocError::Unknown(format!("complete source profile in {}", ss.name)))?;+ if matches.next().is_some() {+ return Err(DocError::Invalid(format!("ambiguous complete source profile in {}", ss.name)));+ }+ Ok(index)+ })+ .collect()+}++fn same_ids(a: &[String], b: &[String]) -> bool {+ if a.len() != b.len() {+ return false;+ }+ let (mut a, mut b) = (a.iter().collect::<Vec<_>>(), b.iter().collect::<Vec<_>>());+ a.sort();+ b.sort();+ a == b+}++fn unique_profile(ss: &SolvedSketch, curves: &[String]) -> Result<usize> {+ let mut matches = ss.profiles.iter().enumerate().filter(|(_, profile)| same_ids(curves, &profile.outer_curves));+ let (index, _) = matches.next().ok_or_else(|| DocError::Unknown(format!("profile bounded by {curves:?} in {}", ss.name)))?;+ if matches.next().is_some() {+ return Err(DocError::Invalid(format!("ambiguous profile boundary in {}", ss.name)));+ }+ Ok(index)+}++fn reserved_boundaries(ss: &SolvedSketch) -> Result<std::collections::BTreeMap<Vec<String>, String>> {+ let mut found = std::collections::BTreeMap::new();+ for offset in &ss.sketch.offsets {+ let Some(topology) = &offset.topology else { continue };+ let mut reserved = topology.roles.iter().map(|role| role.output.clone()).collect::<Vec<_>>();+ reserved.sort();+ if found.insert(reserved, topology.id.clone()).is_some() {+ return Err(DocError::Invalid("profile role set belongs to multiple offset associations".into()));+ }+ }+ Ok(found)+}++/// Resolve exact selection identities to the solved sketch's current profile indices.+/// Complete reserved role sets follow their association; partial sets never expand.+pub fn profile_selection_indices(ss: &SolvedSketch, selection: &ProfileSel) -> Result<Vec<usize>> {+ let indices = match selection {+ ProfileSel::All => (0..ss.profiles.len()).collect(),+ ProfileSel::Indices { indices } => indices.clone(),+ ProfileSel::Curves { loops } => {+ let boundaries = reserved_boundaries(ss)?;+ let mut indices = Vec::with_capacity(loops.len());+ for curves in loops {+ let mut key = curves.clone();+ key.sort();+ if let Some(id) = boundaries.get(&key) {+ if curves.len() > 512 || curves.iter().collect::<BTreeSet<_>>().len() != curves.len() {+ return Err(DocError::Invalid("offset profile has repeated or excessive curve roles".into()));+ }+ indices.push(unique_profile(ss, &ss.sketch.offset_boundary(id)?)?);+ } else {- // Preserve the historical first exact ordinary-loop match.++ // Repeated saved IDs identify exact graph spans. Their multiplicity++ // must not silently turn into a whole-source certificate on resize.++ if curves.iter().collect::<BTreeSet<_>>().len() != curves.len()++ && !ss.profiles.iter().any(|profile| same_ids(curves, &profile.outer_curves))++ {++ return Err(crate::curve_pick_error(solvecraft_sketch::CurvePick::Missing, curves, &ss.name));++ }+ indices.push(- ss.profiles- .iter()- .position(|profile| same_ids(curves, &profile.outer_curves))- .ok_or_else(|| DocError::Unknown(format!("profile bounded by {curves:?} in {}", ss.name)))?,++ solvecraft_sketch::profile_by_curves(&ss.profiles, curves)++ .map_err(|error| crate::curve_pick_error(error, curves, &ss.name))?,+ );+ }+ }+ indices+ }+ ProfileSel::OffsetBoundaries { associations } => {+ if associations.is_empty()+ || associations.len() > MAX_SELECTIONS+ || associations.iter().collect::<BTreeSet<_>>().len() != associations.len()+ {+ return Err(DocError::Invalid("offset profile selection needs unique bounded association identities".into()));+ }+ associations.iter().map(|id| unique_profile(ss, &ss.sketch.offset_boundary(id)?)).collect::<Result<Vec<_>>>()?+ }+ ProfileSel::WholeBoundaries { profiles } => whole_profile_indices(ss, profiles)?,+ ProfileSel::Points { points } => {+ let mut indices = Vec::with_capacity(points.len());+ for point in points {+ let (index, _) = ss+ .profiles+ .iter()+ .enumerate()+ .filter(|(_, profile)| profile.region.contains(*point))+ .min_by(|(_, a), (_, b)| a.area.total_cmp(&b.area))+ .ok_or_else(|| DocError::Unknown(format!("profile at {:?} in {}", [point.x, point.y], ss.name)))?;+ indices.push(index);+ }+ indices+ }+ };+ if indices.iter().any(|index| *index >= ss.profiles.len()) {+ return Err(DocError::Invalid(format!("out-of-range profile selection in {}", ss.name)));+ }+ Ok(indices)+}++/// Persist selected complete offset boundaries by association identity. Mixed selections+/// retain exact ordinary loops and the complete reserved role set of each offset boundary.+pub fn capture_profile_selection(ss: &SolvedSketch, indices: &[usize]) -> Result<ProfileSel> {+ let checked = profile_selection_indices(ss, &ProfileSel::Indices { indices: indices.to_vec() })?;+ if checked.is_empty() || checked.iter().collect::<BTreeSet<_>>().len() != checked.len() {+ return Ok(ProfileSel::Indices { indices: indices.to_vec() });+ }+ // Capture adaptive free-form boundaries only with complete source provenance,+ // including every hole. Ordinary analytic captures keep their historical form.+ let adaptive = checked.iter().any(|index| {+ ss.profiles.get(*index).is_some_and(|profile| {+ std::iter::once(&profile.outer_curves)+ .chain(&profile.hole_curves)+ .any(|curves| curves.iter().collect::<BTreeSet<_>>().len() != curves.len())+ })+ });+ if adaptive {+ let identities = checked.iter().map(|index| ss.profiles.get(*index).and_then(whole_boundary)).collect::<Option<Vec<_>>>();+ if let Some(profiles) = identities {+ // Dynamic analytic offset groups need their own association identities.+ // Do not silently flatten a mixed selection into current active curve IDs.+ let mut dynamic = false;+ for profile in &profiles {+ for boundary in std::iter::once(&profile.outer).chain(&profile.holes) {+ dynamic |= ss.sketch.offset_boundary_for_curves(boundary)?.is_some();+ }+ }+ if !dynamic && whole_profile_indices(ss, &profiles)? == checked {+ return Ok(ProfileSel::WholeBoundaries { profiles });+ }+ }+ }+ let mut associations = Vec::new();+ let mut loops = Vec::new();+ for index in checked {+ let curves = &ss.profiles.get(index).ok_or_else(|| DocError::Invalid("profile index changed during capture".into()))?.outer_curves;+ if curves.is_empty() {+ return Ok(ProfileSel::Indices { indices: indices.to_vec() });+ }+ // Ordinary free-form loops retain one curve ID per exact span. That+ // historical multiset is valid profile identity, but is not a candidate+ // for the unique reserved-role set of a topology-aware association.+ let association =+ if curves.iter().collect::<BTreeSet<_>>().len() == curves.len() { ss.sketch.offset_boundary_for_curves(curves)? } else { None };+ if let Some(id) = association {+ unique_profile(ss, curves)?;+ let offset = ss+ .sketch+ .offsets+ .iter()+ .filter_map(|offset| offset.topology.as_ref())+ .find(|topology| topology.id == id)+ .ok_or_else(|| DocError::Unknown(format!("offset association {id}")))?;+ loops.push(offset.roles.iter().map(|role| role.output.clone()).collect());+ associations.push(id);+ } else {+ if ss.profiles.iter().filter(|profile| same_ids(curves, &profile.outer_curves)).count() != 1 {+ return Ok(ProfileSel::Indices { indices: indices.to_vec() });+ }+ loops.push(curves.clone());+ }+ }+ if associations.len() > MAX_SELECTIONS {+ return Err(DocError::Invalid("too many offset association profiles".into()));+ }+ if associations.len() == loops.len() { Ok(ProfileSel::OffsetBoundaries { associations }) } else { Ok(ProfileSel::Curves { loops }) }+}++#[cfg(test)]+mod tests {+ #![allow(clippy::unwrap_used, clippy::panic)]+ use super::*;+ use solvecraft_geom::{Plane, Vec2};+ use solvecraft_sketch::{Sketch, find_profiles, solve};++ fn rounded_source(sketch: &mut Sketch, radius: f64) -> Vec<(String, bool)> {+ let endpoints = [+ Vec2::new(-37., -32. - radius),+ Vec2::new(37., -32. - radius),+ Vec2::new(37. + radius, -32.),+ Vec2::new(37. + radius, 32.),+ Vec2::new(37., 32. + radius),+ Vec2::new(-37., 32. + radius),+ Vec2::new(-37. - radius, 32.),+ Vec2::new(-37. - radius, -32.),+ ];+ let points: Vec<_> =+ endpoints.iter().enumerate().map(|(index, point)| sketch.add_point(*point, Some(&format!("source-p{index}"))).unwrap()).collect();+ let centers = [Vec2::new(37., -32.), Vec2::new(37., 32.), Vec2::new(-37., 32.), Vec2::new(-37., -32.)];+ for index in 0..8 {+ let id = format!("source-edge{index}");+ if index % 2 == 0 {+ sketch.add_line_pts(points[index], points[(index + 1) % 8], Some(&id)).unwrap();+ } else {+ let center = centers[index / 2];+ sketch+ .add_arc(+ center,+ endpoints[index],+ endpoints[(index + 1) % 8],+ [None, Some(points[index]), Some(points[(index + 1) % 8])],+ Some(&id),+ )+ .unwrap();+ }+ }+ for point in &mut sketch.points {+ point.fixed = true;+ }+ (0..8).map(|index| (format!("source-edge{index}"), true)).collect()+ }++ fn set_source_radius(sketch: &mut Sketch, radius: f64) {+ let points = [+ Vec2::new(-37., -32. - radius),+ Vec2::new(37., -32. - radius),+ Vec2::new(37. + radius, -32.),+ Vec2::new(37. + radius, 32.),+ Vec2::new(37., 32. + radius),+ Vec2::new(-37., 32. + radius),+ Vec2::new(-37. - radius, 32.),+ Vec2::new(-37. - radius, -32.),+ ];+ for (index, value) in points.into_iter().enumerate() {+ sketch.points.iter_mut().find(|point| point.id == format!("source-p{index}")).unwrap().pos = value;+ }+ }++ #[test]+ fn captured_sharp_offset_profile_survives_arc_resurrection_and_reopen() {+ let mut sketch = Sketch::new();+ let sources = rounded_source(&mut sketch, 1.);+ let created = sketch.add_convex_offset(sources, 1.4).unwrap();+ assert_eq!(created.curves.len(), 4);+ let mut document = crate::Document::new("selected logical inner boundary");+ let feature =+ document.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap();+ let mut model = crate::Model::new();+ model.evaluate(&document);+ let state = model.state();+ let solved = state.sketch(feature).unwrap();+ let index = unique_profile(solved, &created.curves).unwrap();+ let selection = capture_profile_selection(solved, &[index]).unwrap();+ assert_eq!(selection, ProfileSel::OffsetBoundaries { associations: vec![created.association.clone()] });+ let original_roles = solved.sketch.offsets[0].topology.as_ref().unwrap().roles.iter().map(|role| role.output.clone()).collect::<Vec<_>>();+ let sharp_area = crate::select_profiles(solved, &selection).unwrap()[0].area();+ assert!((sharp_area - 73.2 * 63.2).abs() < 1e-7, "{sharp_area}");+ document+ .add_feature(+ crate::FeatureKind::Extrude {+ sketch: feature,+ profiles: selection.clone(),+ extent: crate::Extent {+ distance: "2".into(),+ direction: crate::Direction::Positive,+ distance2: None,+ start_offset: None,+ through_all: false,+ taper: None,+ to: None,+ to_offset: None,+ from: None,+ },+ operation: crate::Operation::NewBody,+ targets: vec![],+ },+ None,+ )+ .unwrap();+ model.evaluate(&document);+ let volume = solvecraft_kernel::measure(&model.state().bodies[0].body).unwrap().volume;+ assert!((volume - 2. * 73.2 * 63.2).abs() < 1e-6, "{volume}");+ let reopened = crate::Document::from_json(&document.to_json()).unwrap();+ assert_eq!(reopened, document);+ let mut cold = crate::Model::new();+ cold.evaluate(&reopened);+ assert!((solvecraft_kernel::measure(&cold.state().bodies[0].body).unwrap().volume - volume).abs() < 1e-6);+ let crate::FeatureKind::Sketch { sketch, .. } = &mut document.features[0].kind else { panic!("sketch") };+ set_source_radius(sketch, 2.);+ model.evaluate(&document);+ assert!(model.results.iter().all(|result| result.error.is_none()), "{:?}", model.results);+ let state = model.state();+ let solved = state.sketch(feature).unwrap();+ let active = solved.sketch.offset_boundary(&created.association).unwrap();+ assert_eq!(active, original_roles);+ let rounded_area = 75.2 * 65.2 - (4. - std::f64::consts::PI) * 0.6 * 0.6;+ assert!((crate::select_profiles(solved, &selection).unwrap()[0].area() - rounded_area).abs() < 1e-7);+ let volume = solvecraft_kernel::measure(&model.state().bodies[0].body).unwrap().volume;+ // Kernel volume integrates the curved display mesh; the analytic region above+ // checks the exact rounded geometry independently of that tessellation.+ assert!((volume - 2. * rounded_area).abs() < 0.002, "{volume}");+ assert!(+ crate::select_profiles(solved, &ProfileSel::Curves { loops: vec![created.curves.clone()] }).is_err(),+ "partial old active set must not expand after resurrection"+ );+ assert_eq!(+ profile_selection_indices(solved, &ProfileSel::Curves { loops: vec![original_roles] }).unwrap(),+ profile_selection_indices(solved, &selection).unwrap()+ );+ let reopened = crate::Document::from_json(&document.to_json()).unwrap();+ cold.evaluate(&reopened);+ assert!((solvecraft_kernel::measure(&cold.state().bodies[0].body).unwrap().volume - volume).abs() < 1e-5);+ }++ #[test]+ fn ordinary_profile_selection_keeps_legacy_large_and_duplicate_semantics() {+ let mut sketch = Sketch::new();+ sketch.add_circle(Vec2::new(0., 0.), 3., None, Some("circle")).unwrap();+ let report = solve(&mut sketch);+ let profiles = find_profiles(&sketch);+ let ss = SolvedSketch { feature: 1, name: "ordinary circle".into(), plane: Plane::XY, sketch, report, profiles };+ assert_eq!(ss.profiles.len(), 1);+ let indices = vec![0; 600];+ let selection = ProfileSel::Indices { indices: indices.clone() };+ assert_eq!(profile_selection_indices(&ss, &selection).unwrap(), indices);+ assert_eq!(capture_profile_selection(&ss, &indices).unwrap(), selection);+ let points = ProfileSel::Points { points: vec![Vec2::new(0., 0.); 600] };+ assert_eq!(profile_selection_indices(&ss, &points).unwrap(), indices);+ let curves = ProfileSel::Curves { loops: vec![vec!["circle".into()]; 600] };+ let regions = crate::select_profiles(&ss, &curves).unwrap();+ assert_eq!(regions.len(), 600);+ assert!(regions.iter().all(|region| (region.area() - std::f64::consts::PI * 9.).abs() < 1e-9));+ assert!(profile_selection_indices(&ss, &ProfileSel::Indices { indices: vec![1] }).is_err());+ }++ #[test]+ fn periodic_offset_ring_whole_source_survives_adaptive_spans_and_reopen() {+ let mut sketch = Sketch::new();+ let major = sketch.add_point(Vec2::new(10., 0.), None).unwrap();+ let ellipse = sketch.add_curve(solvecraft_sketch::CurveKind::Ellipse { c: 0, m: major, r: 5. }, None).unwrap();+ let first = sketch.add_freeform_offset(ellipse, true, -1.).unwrap();+ sketch.add_freeform_offset(first, true, -0.5).unwrap();+ let mut document = crate::Document::new("periodic offset ring multiset");+ let feature =+ document.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap();+ let mut model = crate::Model::new();+ model.evaluate(&document);+ let state = model.state();+ let solved = state.sketch(feature).unwrap();+ assert_eq!(solved.profiles.len(), 3);+ let (index, profile) = solved.profiles.iter().enumerate().min_by(|(_, a), (_, b)| a.area.total_cmp(&b.area)).unwrap();+ assert!(profile.outer_curves.len() > 1);+ assert_eq!(profile.outer_curves.iter().collect::<BTreeSet<_>>().len(), 1);+ assert!(solved.sketch.offset_boundary_for_curves(&profile.outer_curves).is_err(), "strict association identity still refuses repeated roles");+ let selection = capture_profile_selection(solved, &[index]).unwrap();+ assert!(matches!(&selection, ProfileSel::WholeBoundaries { profiles } if profiles.len() == 1 && profiles[0].holes.len() == 1));+ let legacy_spans = ProfileSel::Curves { loops: vec![profile.outer_curves.clone()] };+ assert_eq!(profile_selection_indices(solved, &legacy_spans).unwrap(), vec![index]);+ let legacy_roundtrip: ProfileSel = serde_json::from_str(&serde_json::to_string(&legacy_spans).unwrap()).unwrap();+ assert_eq!(legacy_roundtrip, legacy_spans, "ordinary legacy span multiplicities remain serialized exactly");+ assert_eq!(profile_selection_indices(solved, &selection).unwrap(), vec![index]);+ let selected = crate::select_profiles(solved, &selection).unwrap();+ assert_eq!(selected.len(), 1);+ assert!((selected[0].area() - profile.area).abs() < 1e-10);+ assert!(selected[0].contains(Vec2::new(11.25, 0.)));+ assert!(!selected[0].contains(Vec2::new(10.5, 0.)));+ assert!(!selected[0].contains(Vec2::new(11.75, 0.)));+ let saved = serde_json::to_string(&selection).unwrap();+ let reopened: ProfileSel = serde_json::from_str(&saved).unwrap();+ let reopened_doc = crate::Document::from_json(&document.to_json()).unwrap();+ let mut cold = crate::Model::new();+ cold.evaluate(&reopened_doc);+ let cold_state = cold.state();+ let regions = crate::select_profiles(cold_state.sketch(feature).unwrap(), &reopened).unwrap();+ assert_eq!(regions, selected);++ // An identical complete identity in two profiles is ambiguous, even when+ // their boundary geometry and graph coverage certificates are identical.+ let mut ambiguous = cold_state.sketch(feature).unwrap().clone();+ ambiguous.profiles.push(ambiguous.profiles[index].clone());+ assert!(profile_selection_indices(&ambiguous, &reopened).is_err());++ document+ .add_feature(+ crate::FeatureKind::Extrude {+ sketch: feature,+ profiles: selection.clone(),+ extent: crate::Extent {+ distance: "2".into(),+ direction: crate::Direction::Positive,+ distance2: None,+ start_offset: None,+ through_all: false,+ taper: None,+ to: None,+ to_offset: None,+ from: None,+ },+ operation: crate::Operation::NewBody,+ targets: vec![],+ },+ None,+ )+ .unwrap();+ model.evaluate(&document);+ let initial_volume = solvecraft_kernel::measure(&model.state().bodies[0].body).unwrap().volume;+ // Kernel measurement integrates the curved mesh. Scale the established+ // periodic-ring tolerance (0.05 mm³ at height3) to this height2 extrusion.+ // Exact profile identity and cold/warm equality below remain strict.+ let volume_tolerance = 0.05 * 2. / 3.;+ assert!(+ (initial_volume - 2. * profile.area).abs() < volume_tolerance,+ "initial kernel volume {initial_volume}, analytic area {}",+ profile.area+ );+ let crate::FeatureKind::Sketch { sketch, .. } = &mut document.features[0].kind else { panic!("sketch") };+ sketch.points[major].pos.x = 12.;+ model.evaluate(&document);+ assert!(model.results.iter().all(|result| result.error.is_none()), "{:?}", model.results);+ let updated_state = model.state();+ let updated = updated_state.sketch(feature).unwrap();+ assert!(profile_selection_indices(updated, &legacy_spans).is_err(), "legacy tessellation-span multiplicity intentionally remains exact");+ let updated_index = profile_selection_indices(updated, &selection).unwrap()[0];+ let updated_region = &updated.profiles[updated_index].region;+ // Probe away from exact spline-span seams, using the independent analytic+ // ellipse point and unit outward gradient rather than a stored profile sample.+ let parameter = 0.2_f64;+ let source_point = Vec2::new(12. * parameter.cos(), 5. * parameter.sin());+ let normal = Vec2::new(parameter.cos() / 12., parameter.sin() / 5.).normalized().unwrap();+ let ring_point = source_point + normal * 1.25;+ assert!(updated_region.contains(ring_point));+ assert!(!updated_region.contains(source_point + normal * 0.5));+ assert!(!updated_region.contains(source_point + normal * 1.75));+ let updated_volume = solvecraft_kernel::measure(&updated_state.bodies[0].body).unwrap().volume;+ assert!(updated_volume > initial_volume);+ assert!(+ (updated_volume - 2. * updated_region.area()).abs() < volume_tolerance,+ "updated kernel volume {updated_volume}, analytic area {}",+ updated_region.area()+ );+ let reopened_document = crate::Document::from_json(&document.to_json()).unwrap();+ cold.evaluate(&reopened_document);+ assert!(cold.results.iter().all(|result| result.error.is_none()));+ assert!((solvecraft_kernel::measure(&cold.state().bodies[0].body).unwrap().volume - updated_volume).abs() < 1e-6);++ // A new hole is a semantic boundary change, not the old ring. Whole-source+ // identities include holes and must not silently absorb the new material cutout.+ let crate::FeatureKind::Sketch { sketch, .. } = &mut document.features[0].kind else { panic!("sketch") };+ sketch.add_circle(ring_point, 0.1, None, Some("new-hole")).unwrap();+ model.evaluate(&document);+ let changed = model.state();+ assert!(profile_selection_indices(changed.sketch(feature).unwrap(), &selection).is_err());+ assert!(model.results.last().unwrap().error.is_some());+ }+}diff --cc crates/engine/src/cmd/features.rsindex d9ef37b86c,fb3a8b54a9..76f6e0a9fd--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@@ -204,58 -201,51 +204,81 @@@ pub(super) fn feature_sketch(s: &Sessio.ok_or_else(|| bad(cmd, "there is no sketch to use (create one first)"))}- /// Profile indices become the curve ids of each profile's loops as the sketch is now solved.- fn stable_profiles(s: &Session, kind: &mut FeatureKind) -> Result<()> {+ /// Profiles picked by index or point are stored by the curve ids of each profile's outer loop+ /// as the sketch is now solved, so they follow the geometry when parameters move it. A pick+ /// whose curves would not find that same profile again (two profiles bounded by the same+ /// curves) stays as given. Curve picks are checked: one that names no profile, or several, is+ /// refused now rather than failing later.+ pub(super) fn stable_profiles(s: &Session, kind: &mut FeatureKind) -> Result<()> {- use solvecraft_doc::sketch::{distinct_curves, profile_at_point, profile_by_curves};++ use solvecraft_doc::sketch::profile_at_point;let st = s.model.state();-- 'sels: for (sketch, sel) in kind.profile_sels_mut() {++ for (sketch, sel) in kind.profile_sels_mut() {let Some(ss) = st.sketch(sketch) else { continue };- if !matches!(- sel,- ProfileSel::Indices { .. } | ProfileSel::Curves { .. } | ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. }- ) {- continue;- }- let indices = solvecraft_doc::profile_selection_indices(ss, sel)?;- for i in indices.iter() {- let pr = ss- .profiles- .get(*i)- .ok_or_else(|| EngineError::Other(format!("no profile {i} in sketch `{}` (it has {})", ss.name, ss.profiles.len())))?;- // Two profiles with the same outer curves (one inside the other's holes cannot be):- // keep the index then.- if !matches!(sel, ProfileSel::WholeBoundaries { .. })- && (pr.outer_curves.is_empty() || ss.profiles.iter().filter(|q| same_loop(&q.outer_curves, &pr.outer_curves)).count() != 1)- {- continue 'sels;- let picked: Vec<usize> = match sel {- ProfileSel::Indices { indices } => indices- .iter()- .map(|i| {- if *i < ss.profiles.len() {- Ok(*i)- } else {- Err(EngineError::Other(format!("no profile {i} in sketch `{}` (it has {})", ss.name, ss.profiles.len())))- }- })- .collect::<Result<_>>()?,++ let indices = match sel {++ ProfileSel::Indices { .. } => solvecraft_doc::profile_selection_indices(ss, sel)?,+ ProfileSel::Points { points } => {- let Some(v) = points.iter().map(|q| profile_at_point(&ss.profiles, *q)).collect::<Option<Vec<_>>>() else { continue };- v++ let Some(indices) = points.iter().map(|point| profile_at_point(&ss.profiles, *point)).collect::<Option<Vec<_>>>() else { continue };++ indices}- }+ ProfileSel::Curves { loops } => {- for l in loops.iter() {- profile_by_curves(&ss.profiles, l)- .map_err(|e| EngineError::Other(solvecraft_doc::curve_pick_error(e, l, &ss.name).to_string()))?;++ // The command's ordinary curve lists are sets, including repeated++ // caller IDs. Saved graph-span multisets retain their legacy meaning.++ // Reserved offset roles never use this ordinary normalization.++ let mut normalized = loops.clone();++ let reserved = ss++ .sketch++ .offsets++ .iter()++ .filter_map(|offset| offset.topology.as_ref())++ .flat_map(|topology| topology.roles.iter().map(|role| role.output.as_str()))++ .collect::<std::collections::BTreeSet<_>>();++ for curves in &mut normalized {++ let dynamic = curves.iter().any(|curve| reserved.contains(curve.as_str()));++ if !dynamic {++ let mut seen = std::collections::BTreeSet::new();++ curves.retain(|curve| seen.insert(curve.clone()));++ }+ }++ let selection = ProfileSel::Curves { loops: normalized };++ solvecraft_doc::profile_selection_indices(ss, &selection)?;++ *sel = selection;++ continue;++ }++ ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. } => {++ // Explicit identities retain the caller's semantics. Validate through the++ // same resolver as recomputation, including reserved-role precedence.++ solvecraft_doc::profile_selection_indices(ss, sel)?;+ continue;+ }+ ProfileSel::All => continue,+ };- let mut loops = Vec::with_capacity(picked.len());- for i in picked {- let Some(pr) = ss.profiles.get(i) else { continue 'sels };- let ids = distinct_curves(&pr.outer_curves);- // Keep the pick as given when its curves don't lead back to this profile.- if ids.is_empty() || profile_by_curves(&ss.profiles, &ids) != Ok(i) {- continue 'sels;+ let captured = solvecraft_doc::capture_profile_selection(ss, &indices)?;+ *sel = match captured {+ ProfileSel::OffsetBoundaries { associations }+ if associations.iter().any(|id| {+ s.doc+ .sketch(sketch)+ .is_ok_and(|raw| !raw.offsets.iter().filter_map(|offset| offset.topology.as_ref()).any(|topology| topology.id == *id))+ }) =>+ {+ // Legacy upgrade descriptors belong to the solved copy. Persist the+ // complete original role IDs instead of an unsaved association ID.+ let loops = associations+ .iter()+ .map(|id| {+ ss.sketch+ .offsets+ .iter()+ .filter_map(|offset| offset.topology.as_ref())+ .find(|topology| topology.id == *id)+ .map(|topology| topology.roles.iter().map(|role| role.output.clone()).collect())+ .ok_or_else(|| EngineError::Other(format!("offset association `{id}` changed during profile capture")))+ })+ .collect::<Result<Vec<_>>>()?;+ ProfileSel::Curves { loops }}- loops.push(ids);- }- *sel = ProfileSel::Curves { loops };+ captured => captured,+ };}Ok(())}diff --cc crates/engine/src/profile_curves_tests.rsindex 0000000000,23453ee080..dc1d6c65e6mode 000000,100644..100644--- a/crates/engine/src/profile_curves_tests.rs+++ b/crates/engine/src/profile_curves_tests.rs@@@ -1,0 -1,176 +1,206 @@@+ //! Profiles picked by the curves around them stay the same region when a parameter moves the+ //! sketch, where a pick by point can land in another region.++ use serde_json::{Value, json};++ use crate::Session;+ use solvecraft_doc::{FeatureKind, ProfileSel};++ fn run(s: &mut Session, id: &str, p: Value) -> Value {+ match s.execute(id, &p) {+ Ok(v) => v,+ Err(e) => panic!("{id} {p}: {e}"),+ }+ }++ fn volumes(s: &Session) -> Vec<f64> {+ s.model.state().bodies.iter().map(|b| b.body.tessellate(1e-2).unwrap().measure().volume).collect()+ }++ fn last_error(s: &Session) -> Option<String> {+ let id = s.doc.features.last().unwrap().id;+ s.model.result(id).and_then(|r| r.error.clone())+ }++ /// A 60 × 20 tray split in two by a divider `split` mm from its left side: the left bay is+ /// bounded by the left side, the divider and the pieces of the bottom and top the divider cuts.+ fn tray() -> Session {+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "split", "expression": "30 mm"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Tray"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [60, 0], [60, 20], [0, 20]], "closed": true, "ids": ["bottom", "right", "top", "left"]}));+ run(&mut s, "sketch.constraint.fix", json!({"entities": ["bottom", "right", "top", "left"]}));+ run(&mut s, "sketch.line", json!({"points": [[30, 0], [30, 20]], "ids": ["div"]}));+ run(&mut s, "sketch.constraint.coincident", json!({"a": "div.start", "b": "bottom"}));+ run(&mut s, "sketch.constraint.coincident", json!({"a": "div.end", "b": "top"}));+ run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "div"}));+ run(&mut s, "sketch.dimension", json!({"entities": ["left", "div"], "value": "split"}));+ run(&mut s, "sketch.finish", json!({}));+ s+ }++ fn extrude_kind(s: &Session) -> ProfileSel {+ match &s.doc.features.last().unwrap().kind {+ FeatureKind::Extrude { profiles, .. } => profiles.clone(),+ k => panic!("{k:?}"),+ }+ }++ /// The user's case: the left bay picked by its curves keeps extruding the left bay when+ /// `split` moves the divider past the old pick point; a pick by that point (as a design saved+ /// before picks were stored by curves holds it) silently extrudes the right bay instead.+ #[test]+ fn a_profile_picked_by_curves_follows_a_parameter_change() {+ let mut s = tray();+ run(&mut s, "solid.extrude", json!({"sketch": "Tray", "profiles": [{"curves": ["left", "bottom", "div", "top"]}], "distance": 10}));+ let v = volumes(&s);+ assert_eq!(v.len(), 1);+ assert!((v[0] - 30.0 * 20.0 * 10.0).abs() < 1.0, "{v:?}");+ run(&mut s, "parameters.change", json!({"name": "split", "expression": "20 mm"}));+ assert_eq!(last_error(&s), None);+ let v = volumes(&s);+ assert!((v[0] - 20.0 * 20.0 * 10.0).abs() < 1.0, "still the left bay, now 20 wide: {v:?}");++ // The same bay picked by a point (25, 10), stored as a point.+ let mut s = tray();+ run(&mut s, "solid.extrude", json!({"sketch": "Tray", "profiles": [{"point": [25, 10]}], "distance": 10}));+ let id = s.doc.features.last().unwrap().id;+ if let Some(f) = s.doc_mut().feature_mut(id)+ && let FeatureKind::Extrude { profiles, .. } = &mut f.kind+ {+ *profiles = ProfileSel::Points { points: vec![solvecraft_geom::Vec2::new(25.0, 10.0)] };+ }+ s.refresh();+ assert!((volumes(&s)[0] - 6000.0).abs() < 1.0);+ run(&mut s, "parameters.change", json!({"name": "split", "expression": "20 mm"}));+ let v = volumes(&s);+ assert!((v[0] - 40.0 * 20.0 * 10.0).abs() < 1.0, "the point now sits in the right bay: {v:?}");+ }++ /// A pick by point is stored by the curves around the picked profile, so it follows too.+ #[test]+ fn a_point_pick_is_stored_by_curves() {+ let mut s = tray();+ run(&mut s, "solid.extrude", json!({"sketch": "Tray", "profiles": [{"point": [25, 10]}], "distance": 10}));+ let ProfileSel::Curves { loops } = extrude_kind(&s) else { panic!("{:?}", extrude_kind(&s)) };+ let mut ids = loops[0].clone();+ ids.sort();+ assert_eq!(ids, ["bottom", "div", "left", "top"]);+ run(&mut s, "parameters.change", json!({"name": "split", "expression": "20 mm"}));+ assert_eq!(last_error(&s), None);+ assert!((volumes(&s)[0] - 4000.0).abs() < 1.0, "{:?}", volumes(&s));+ }+++/// New explicit API lists are sets even when reordered or repeated. Their saved++/// form must not accidentally become a legacy graph-span multiset.++#[test]++fn explicit_curve_pick_normalizes_repeats_before_save_and_parameter_edit() {++ let mut s = tray();++ run(&mut s, "solid.extrude", json!({"sketch":"Tray","profiles":[{"curves":["top","bottom","div","left","bottom","top"]}],"distance":10}));++ let ProfileSel::Curves { loops } = extrude_kind(&s) else { panic!("{:?}", extrude_kind(&s)) };++ assert_eq!(loops, vec![vec!["top", "bottom", "div", "left"]]);++ let mut reopened = Session::new(solvecraft_doc::format::read(&s.doc.to_json()).unwrap());++ run(&mut reopened, "parameters.change", json!({"name":"split","expression":"20 mm"}));++ assert_eq!(last_error(&reopened), None);++ assert!((volumes(&reopened)[0] - 4000.0).abs() < 1.0);++}++++#[test]++fn repeated_explicit_curve_ids_do_not_count_split_graph_spans() {++ let mut s = Session::default();++ run(&mut s, "sketch.create", json!({"plane":"XY","name":"S"}));++ run(&mut s, "sketch.line", json!({"points":[[0,0],[10,0],[10,10],[0,10]],"closed":true,"ids":["a","b","c","d"]}));++ run(&mut s, "sketch.line", json!({"points":[[5,-5],[5,0]],"ids":["stub"]}));++ run(&mut s, "sketch.finish", json!({}));++ assert_eq!(s.model.state().sketches[0].profiles[0].outer_curves.iter().filter(|id| *id == "a").count(), 2);++ run(&mut s, "solid.extrude", json!({"sketch":"S","profiles":[{"curves":["d","a","a","a","c","b"]}],"distance":2}));++ let ProfileSel::Curves { loops } = extrude_kind(&s) else { panic!("{:?}", extrude_kind(&s)) };++ assert_eq!(loops, vec![vec!["d", "a", "c", "b"]]);++ let reopened = Session::new(solvecraft_doc::format::read(&s.doc.to_json()).unwrap());++ assert_eq!(last_error(&reopened), None);++ assert!((volumes(&reopened)[0] - 200.0).abs() < 1e-3);++}+++ /// Curves cut into several pieces of one loop still name it: a line ending on the square's+ /// bottom from outside cuts the bottom in two, both pieces on the square's loop.+ #[test]+ fn a_curve_cut_into_pieces_still_names_its_profile() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0], [10, 10], [0, 10]], "closed": true, "ids": ["a", "b", "c", "d"]}));+ run(&mut s, "sketch.line", json!({"points": [[5, -5], [5, 0]], "ids": ["stub"]}));+ run(&mut s, "sketch.finish", json!({}));+ let ps = &s.model.state().sketches[0].profiles;+ assert_eq!(ps.len(), 1);+ assert_eq!(ps[0].outer_curves.iter().filter(|c| *c == "a").count(), 2, "the bottom is in two pieces: {:?}", ps[0].outer_curves);+ run(&mut s, "solid.extrude", json!({"sketch": "S", "profiles": [{"curves": ["a", "b", "c", "d"]}], "distance": 2}));+ assert_eq!(last_error(&s), None);+ assert!((volumes(&s)[0] - 200.0).abs() < 1e-3, "{:?}", volumes(&s));+ }++ /// Both halves of a circle cut by a line are bounded by the same two curves: an error, not one+ /// of them. A list no profile matches is an error too.+ #[test]+ fn ambiguous_and_missing_curve_picks_are_errors() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));+ run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10, "id": "ring"}));+ run(&mut s, "sketch.line", json!({"points": [[-20, 0], [20, 0]], "ids": ["cut"]}));+ run(&mut s, "sketch.circle.center", json!({"center": [40, 0], "radius": 3, "id": "dot"}));+ run(&mut s, "sketch.finish", json!({}));+ let e = s.execute("solid.extrude", &json!({"sketch": "S", "profiles": [{"curves": ["ring", "cut"]}], "distance": 2})).unwrap_err().to_string();+ assert!(e.contains("2 profiles"), "{e}");+ assert!(s.model.state().bodies.is_empty());+ let e = s.execute("solid.extrude", &json!({"sketch": "S", "profiles": [{"curves": ["ring"]}], "distance": 2})).unwrap_err().to_string();+ assert!(e.contains("no profile"), "{e}");+ let e = s.execute("solid.extrude", &json!({"sketch": "S", "profiles": [{"curves": ["dot", "cut"]}], "distance": 2})).unwrap_err().to_string();+ assert!(e.contains("no profile"), "{e}");+ // A closed curve alone.+ run(&mut s, "solid.extrude", json!({"sketch": "S", "profiles": [{"curves": ["dot"]}], "distance": 2}));+ assert!((volumes(&s)[0] - std::f64::consts::PI * 9.0 * 2.0).abs() < 0.5, "{:?}", volumes(&s));+ }++ /// An island inside the picked outline is its hole, as with a pick by point; the island is a+ /// profile of its own, picked by its curve.+ #[test]+ fn a_curve_pick_keeps_islands_as_holes() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0], [20, 20], [0, 20]], "closed": true, "ids": ["a", "b", "c", "d"]}));+ run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 5, "id": "hole"}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "S", "profiles": [{"curves": ["a", "b", "c", "d"]}], "distance": 1}));+ let disc = std::f64::consts::PI * 25.0;+ assert!((volumes(&s)[0] - (400.0 - disc)).abs() < 0.5, "{:?}", volumes(&s));+ run(&mut s, "solid.extrude", json!({"sketch": "S", "profiles": [{"curves": ["hole"]}], "distance": 1, "operation": "new"}));+ assert!((volumes(&s)[1] - disc).abs() < 0.5, "{:?}", volumes(&s));+ }++ /// Curve picks are saved in the design file and read back; timeline.edit takes the command's+ /// `profiles` form.+ #[test]+ fn curve_picks_save_load_and_edit() {+ let mut s = tray();+ run(+ &mut s,+ "solid.extrude",+ json!({"sketch": "Tray", "profiles": [{"curves": ["left", "bottom", "div", "top"]}], "distance": 10, "name": "Bay"}),+ );+ let text = serde_json::to_string(&*s.doc).unwrap();+ let doc = solvecraft_doc::format::read(&text).unwrap();+ let mut t = Session::new(doc);+ assert_eq!(extrude_kind(&t), extrude_kind(&s));+ run(&mut t, "parameters.change", json!({"name": "split", "expression": "20 mm"}));+ assert!((volumes(&t)[0] - 4000.0).abs() < 1.0, "{:?}", volumes(&t));+ // Switch to the right bay through timeline.edit.+ run(&mut t, "timeline.edit", json!({"feature": "Bay", "set": {"profiles": [{"curves": ["div", "bottom", "right", "top"]}]}}));+ assert!((volumes(&t)[0] - 8000.0).abs() < 1.0, "{:?}", volumes(&t));+ run(&mut t, "timeline.edit", json!({"feature": "Bay", "set": {"profiles": [{"point": [5, 5]}]}}));+ assert!(matches!(extrude_kind(&t), ProfileSel::Curves { .. }), "{:?}", extrude_kind(&t));+ assert!((volumes(&t)[0] - 4000.0).abs() < 1.0, "{:?}", volumes(&t));+ // An old design's point pick still loads and evaluates.+ let old = text.replace(r#"{"type":"curves","loops":[["left","bottom","div","top"]]}"#, r#"{"type":"points","points":[[25.0,10.0]]}"#);+ assert_ne!(old, text);+ let t = Session::new(solvecraft_doc::format::read(&old).unwrap());+ assert!((volumes(&t)[0] - 6000.0).abs() < 1.0, "{:?}", volumes(&t));+ }diff --cc crates/sketch/src/lib.rsindex fa909052f5,d81543de47..678840cdc0--- a/crates/sketch/src/lib.rs+++ b/crates/sketch/src/lib.rs@@@ -32,9 -31,8 +32,9 @@@ pub use freeform_offset::{FreeformOffsepub use link::{Link, LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES};pub use model::{Constraint, ConstraintKind, Curve, CurveKind, SPoint, Sketch, SketchError, SketchView};pub use offset::OffsetChain;+pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology};pub use periodic::periodic_beziers;- pub use profiles::{Profile, find_drawn_profiles, find_profiles, merge_regions};+ pub use profiles::{CurvePick, Profile, distinct_curves, find_drawn_profiles, find_profiles, merge_regions, profile_at_point, profile_by_curves};pub use shape::{Shape, intersections};pub use solver::{Hold, SolveReport, SolveStatus, measure_dimension, solve, solve_holding};pub use text::{MAX_TEXT_CHARS, text_geometry};diff --cc crates/ui-egui/src/dialogs.rsindex 590d34f531,c0fc7ec0aa..e889c74e85--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -2923,16 -2923,8 +2923,16 @@@ pub(crate) fn profile_indices(ss: &solvmatch sel {ProfileSel::All => (0..ps.len()).collect(),ProfileSel::Indices { indices } => indices.iter().copied().filter(|i| *i < ps.len()).collect(),- ProfileSel::Curves { loops } => loops.iter().filter_map(|l| solvecraft_engine::doc::sketch::profile_by_curves(ps, l).ok()).collect(),+ ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. } => {+ solvecraft_engine::doc::profile_selection_indices(ss, sel).unwrap_or_default()+ }+ ProfileSel::Curves { loops } => loops+ .iter()+ .filter_map(|l| {+ solvecraft_engine::doc::profile_selection_indices(ss, &ProfileSel::Curves { loops: vec![l.clone()] }).ok()?.first().copied()+ })+ .collect(),- ProfileSel::Points { points } => points.iter().filter_map(|q| ps.iter().position(|p| p.region.contains(*q))).collect(),+ ProfileSel::Points { points } => points.iter().filter_map(|q| solvecraft_engine::doc::sketch::profile_at_point(ps, *q)).collect(),}}