diff --git a/crates/doc/src/body_transfer.rs b/crates/doc/src/body_transfer.rs index 1226ea1d0..3f1fa843a 100644 --- a/crates/doc/src/body_transfer.rs +++ b/crates/doc/src/body_transfer.rs @@ -2,6 +2,46 @@ use crate::{DocError, Document, Mat, ModelBody, ModelState, Result}; use std::collections::BTreeSet; +/// A profile moved into the component receiving its own body is read through the recorded +/// transfer frame. Reading its live placement would move the source geometry when that +/// component moves, then move the transferred body a second time. All outputs of a constructor +/// must reach the sketch's component through the same frame; independent cross-component +/// references retain their ordinary live placement. +pub(crate) fn profile_frame(doc: &Document, feature: &crate::Feature, sketch: u64) -> Option { + if !matches!( + feature.kind, + crate::FeatureKind::Extrude { operation: crate::Operation::NewBody, .. } + | crate::FeatureKind::Revolve { operation: crate::Operation::NewBody, .. } + ) || feature.body_names.is_empty() + { + return None; + } + let owner = doc.feature(sketch)?.component; + if owner == feature.component { + return None; + } + let mut frames: std::collections::BTreeMap<&str, (u64, Mat)> = + feature.body_names.iter().map(|name| (name.as_str(), (feature.component, crate::IDENTITY))).collect(); + let start = doc.feature_index(feature.id)?.saturating_add(1); + for step in doc.features.iter().take(doc.marker.unwrap_or(usize::MAX)).skip(start).filter(|step| !step.suppressed) { + let crate::FeatureKind::BodyTransfer { bodies, from, to, transform } = &step.kind else { continue }; + for name in bodies { + if let Some((component, frame)) = frames.get_mut(name.as_ref()) { + if *component != *from || !valid_transfer_matrix(transform) { + return None; + } + *component = *to; + *frame = crate::mat_mul(transform, frame); + } + } + if frames.values().all(|(component, _)| *component == owner) { + let (_, first) = frames.values().next()?; + return frames.values().all(|(_, frame)| frame == first).then(|| crate::mat_inverse(first)).flatten(); + } + } + None +} + pub fn valid_transfer_matrix(m: &Mat) -> bool { crate::is_placement(m) } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 1e1cd90d6..1b76fe734 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1650,6 +1650,13 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 for (sketch, _) in f.kind.profile_sels() { if doc.feature(sketch).is_some_and(|s| s.component != f.component) { reads.sketch(doc, sketch); + // A later transfer can preserve this profile's historical frame. Changes to that + // boundary (including suppression and rollback) must invalidate the constructor. + if let Some(relative) = crate::body_transfer::profile_frame(doc, f, sketch) { + "transferred profile".hash(&mut h); + sketch.hash(&mut h); + hash_placement(&relative, &mut h); + } } } let path = match &f.kind { @@ -5051,10 +5058,10 @@ fn feature_tools_with_constructor( let unnamed = |bodies: Vec| -> Vec { bodies.into_iter().map(Traced::unnamed).collect() }; match &f.kind { FeatureKind::Extrude { sketch, profiles, extent, operation, targets, thin } => { - let ss = sketch_in_feature_frame( + let ss = constructor_profile_in_frame( doc, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, - f.component, + f, )?; let regions = match thin { Some(thin) => thin_regions(vals, &ss, thin)?, @@ -5278,10 +5285,10 @@ fn feature_tools_with_constructor( Ok(tools) } FeatureKind::Revolve { sketch, profiles, axis, angle, angle2, symmetric, convention, to, .. } => { - let ss = sketch_in_feature_frame( + let ss = constructor_profile_in_frame( doc, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, - f.component, + f, )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); let (o, d) = @@ -5686,16 +5693,27 @@ fn sketch_in_feature_frame(doc: &Document, sketch: &SolvedSketch, consumer: u64) profile_in_frame(doc, sketch, consumer) } +fn constructor_profile_in_frame(doc: &Document, sketch: &SolvedSketch, feature: &Feature) -> Result { + match crate::body_transfer::profile_frame(doc, feature, sketch.feature) { + Some(relative) => profile_with_transform(sketch, &relative), + None => sketch_in_feature_frame(doc, sketch, feature.component), + } +} + fn profile_in_frame(doc: &Document, sketch: &SolvedSketch, consumer: u64) -> Result { let owner = doc.feature(sketch.feature).map(|feature| feature.component).unwrap_or(0); let inverse = crate::mat_inverse(&doc.component_transform(consumer)).ok_or_else(|| DocError::Invalid("profile consumer frame is invalid".into()))?; let relative = crate::mat_mul(&inverse, &doc.component_transform(owner)); + profile_with_transform(sketch, &relative) +} + +fn profile_with_transform(sketch: &SolvedSketch, relative: &Mat) -> Result { let mut mapped = sketch.clone(); mapped.plane = Plane::new( - crate::apply_point(&relative, sketch.plane.origin), - crate::apply_vector(&relative, sketch.plane.x), - crate::apply_vector(&relative, sketch.plane.y), + crate::apply_point(relative, sketch.plane.origin), + crate::apply_vector(relative, sketch.plane.x), + crate::apply_vector(relative, sketch.plane.y), ) .ok_or_else(|| DocError::Invalid("profile sketch frame is invalid".into()))?; Ok(mapped) diff --git a/crates/doc/src/format/pending/transferred-profile-frame.rs b/crates/doc/src/format/pending/transferred-profile-frame.rs new file mode 100644 index 000000000..0058834cd --- /dev/null +++ b/crates/doc/src/format/pending/transferred-profile-frame.rs @@ -0,0 +1,6 @@ +//! A new-body extrusion or revolve whose outputs transfer into its source sketch's component +//! reads the profile through the recorded transfer frame. Capturing that component's position +//! therefore moves the body once, as the pending preview does. Existing designs use their +//! saved transfer transforms without rewriting fields; independent cross-component references +//! keep their live placement. The last release refuses the newer design-format number rather +//! than reopening the design with the former double-placement behavior. diff --git a/crates/engine/src/cmd/component_transfer_tests.rs b/crates/engine/src/cmd/component_transfer_tests.rs index 03cff0885..9bebd5faa 100644 --- a/crates/engine/src/cmd/component_transfer_tests.rs +++ b/crates/engine/src/cmd/component_transfer_tests.rs @@ -4,6 +4,136 @@ fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap() } +fn transferred_profile(revolve: bool) -> (Session, u64, u64, solidcraft_kernel::Body) { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":if revolve { "XZ" } else { "XY" },"name":"Profile"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[20,0],"p1":[30,5]})); + run(&mut s, "sketch.finish", json!({})); + if revolve { + run(&mut s, "solid.revolve", json!({"axis":"y","angle":"360 deg","body_name":"Part"})); + } else { + run(&mut s, "solid.extrude", json!({"distance":10,"body_name":"Part"})); + } + let original = s.world_state().unwrap().body("Part").unwrap().body.clone(); + let created = run(&mut s, "component.from_bodies", json!({"bodies":["Part"]})); + let component = created["components"][0]["component"].as_u64().unwrap(); + let occurrence = s.doc.occurrences.iter().find(|o| o.component == component).unwrap().id; + run(&mut s, "component.move_sketches", json!({"sketches":["Profile"],"component":component})); + run(&mut s, "occurrence.ground", json!({"occurrence":occurrence,"grounded":false})); + (s, component, occurrence, original) +} + +fn check_captured_profile_transfer(revolve: bool) { + let (mut s, _, occurrence, original) = transferred_profile(revolve); + let before = s.doc.to_json(); + let matrix = solidcraft_doc::rigid(Vec3::new(40.0, 0.0, 0.0), Vec3::ZERO, Vec3::X, std::f64::consts::FRAC_PI_4); + let expected = solidcraft_kernel::transform_matrix(&original, matrix).unwrap(); + let expected_bounds = expected.exact_bounds().unwrap(); + let assert_pose = |s: &Session| { + let state = s.world_state().unwrap(); + let body = &state.body("Part").unwrap().body; + let bounds = body.exact_bounds().unwrap(); + assert!(bounds.min.dist(expected_bounds.min) < 0.002, "minimum: {bounds:?}, expected {expected_bounds:?}"); + assert!(bounds.max.dist(expected_bounds.max) < 0.002, "maximum: {bounds:?}, expected {expected_bounds:?}"); + let measured = solidcraft_kernel::measure(body).unwrap(); + let expected_measure = solidcraft_kernel::measure(&expected).unwrap(); + assert!((measured.volume - expected_measure.volume).abs() < 1e-5); + assert!(measured.centroid.dist(expected_measure.centroid) < 1e-5); + }; + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[40,0,0],"axis":[1,0,0],"angle":"45 deg","capture":false})); + assert_pose(&s); + let undo = s.undo.len(); + run(&mut s, "component.capture_position", json!({})); + assert_eq!(s.undo.len(), undo + 1); + assert!(s.pending_moves.is_empty()); + assert_pose(&s); + let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; + reopened.refresh(); + assert_pose(&reopened); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_pose(&s); +} + +#[test] +fn capture_transferred_extrusion_with_its_source_sketch_moves_once() { + check_captured_profile_transfer(false); +} + +#[test] +fn capture_transferred_revolve_with_its_source_sketch_moves_once() { + check_captured_profile_transfer(true); +} + +#[test] +fn transferred_profile_frame_follows_transfer_edits_suppression_and_rollback() { + let (mut s, component, occurrence, _) = transferred_profile(false); + let creator = s.model.state().body("Part").unwrap().feature; + let transfer = s.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::BodyTransfer { .. })).unwrap().id; + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[40,0,0]})); + let assert_x = |s: &Session, local: f64, owner: u64| { + let source = s.model.result(creator).unwrap().state.body("Part").unwrap().body.exact_bounds().unwrap(); + assert!((source.min.x - local).abs() < 1e-6, "source frame: {source:?}"); + let state = s.world_state().unwrap(); + let body = state.body("Part").unwrap(); + assert_eq!(body.component, owner); + assert!((body.body.exact_bounds().unwrap().min.x - 60.0).abs() < 1e-6); + }; + assert_x(&s, 20.0, component); + s.doc_mut().feature_mut(transfer).unwrap().suppressed = true; + s.refresh(); + assert_x(&s, 60.0, 0); + s.doc_mut().feature_mut(transfer).unwrap().suppressed = false; + s.refresh(); + assert_x(&s, 20.0, component); + let boundary = s.doc.feature_index(transfer); + s.doc_mut().marker = boundary; + s.refresh(); + assert_x(&s, 60.0, 0); + s.doc_mut().marker = None; + s.refresh(); + assert_x(&s, 20.0, component); + if let FeatureKind::BodyTransfer { transform, .. } = &mut s.doc_mut().feature_mut(transfer).unwrap().kind { + *transform = solidcraft_doc::rigid(Vec3::new(-7.0, 0.0, 0.0), Vec3::ZERO, Vec3::Z, 0.0); + } + s.refresh(); + assert_x(&s, 27.0, component); + let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; + reopened.refresh(); + assert_x(&reopened, 27.0, component); +} + +#[test] +fn capturing_one_transferred_profile_instance_keeps_its_peer_in_place() { + let (mut s, _, occurrence, _) = transferred_profile(false); + run(&mut s, "occurrence.copy", json!({"occurrence":occurrence,"translate":[100,0,0]})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[40,0,0],"capture":false})); + run(&mut s, "component.capture_position", json!({})); + let state = s.world_state().unwrap(); + let mut xs: Vec = state.bodies.iter().map(|body| body.body.exact_bounds().unwrap().min.x).collect(); + xs.sort_by(f64::total_cmp); + assert_eq!(xs.len(), 2); + assert!((xs[0] - 60.0).abs() < 1e-6 && (xs[1] - 120.0).abs() < 1e-6, "{xs:?}"); +} + +#[test] +fn a_profile_without_a_body_transfer_keeps_its_live_component_frame() { + let mut s = Session::default(); + let created = run(&mut s, "component.create", json!({"name":"Source","grounded":false})); + let occurrence = created["occurrence"].as_u64().unwrap(); + run(&mut s, "sketch.create", json!({"plane":"XY","name":"Profile"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,20]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "component.activate", json!({"component":0})); + run(&mut s, "solid.extrude", json!({"sketch":"Profile","distance":5,"body_name":"Part"})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[40,0,0]})); + let state = s.world_state().unwrap(); + let body = state.body("Part").unwrap(); + assert_eq!(body.component, 0); + assert!((body.body.exact_bounds().unwrap().min.x - 40.0).abs() < 1e-6); +} + #[test] fn recorded_assignment_preserves_sample_joined_material_and_timeline() { let mut s = Session::default(); diff --git a/docs/occurrence-workflows.md b/docs/occurrence-workflows.md index 32aade1dc..e81d32e43 100644 --- a/docs/occurrence-workflows.md +++ b/docs/occurrence-workflows.md @@ -58,6 +58,8 @@ Create Components from Bodies and Move Bodies to Component now add ownership-tra Transfers preserve the body's world pose through rotated or translated parents. Pending positions on the involved source and destination paths are captured atomically with the transfer so save/reopen retains that pose; unrelated pending positions remain pending. Undo and checkpoint restoration recover the original pending positions as well as the feature history; redo restores the captured transfer. The operation requires one source and one destination placement. Shared instance definitions with several placements are rejected because a single ownership change cannot preserve several different world poses. A component that supplies transfer history outside its subtree cannot be deleted until that dependent history is removed. +When the bodies of a new-body Extrude or Revolve are transferred into their source sketch's component through the same frame, the profile uses that recorded frame. Moving the component and capturing its position then moves the bodies once, matching the preview, even when the source sketch was moved into the component separately. Other cross-component sketch references continue to follow their live placements. + Older files without transfer features keep their saved assignment and offset behavior. No transfer timestamp is inferred from their final ownership map. Paste New freezes externally authored geometry after its successful entry transfer and remaps internal transfers, then replays later modifiers once. All transfer commands validate and evaluate on a scratch document before adoption. New face-attached sketches capture the selected body's producer, certified face and exact occurrence path, together with the sketch's authoring placement. A supported face follows source edits; a missing or incompatible source reports a lost attachment rather than choosing another nearby face. Opening Edit restores the saved authoring occurrence as view context without creating an undo entry. Older saved point-only face references retain their legacy behavior.