diff --git a/assets/locales/pending/align-components.json b/assets/locales/pending/align-components.json new file mode 100644 index 000000000..34b8aba5e --- /dev/null +++ b/assets/locales/pending/align-components.json @@ -0,0 +1,32 @@ +{ + "ar": { + "cmd.occurrence_align": "محاذاة النسخة", + "select components first": "حدد المكوّنات أولًا", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "هذا المكوّن داخل تجميع فرعي موضوع أكثر من مرة: محاذاته تحرّكه في كل موضع." + }, + "en": { + "cmd.occurrence_align": "Align Occurrence", + "select components first": "select components first", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "This component is inside a subassembly placed more than once: aligning it moves it in every placement." + }, + "he": { + "cmd.occurrence_align": "יישור מופע", + "select components first": "יש לבחור רכיבים תחילה", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "רכיב זה נמצא בתוך תת-הרכבה שהוצבה יותר מפעם אחת: יישורו יזיז אותו בכל הצבה." + }, + "ja": { + "cmd.occurrence_align": "オカレンスを整列", + "select components first": "コンポーネントを先に選択してください", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "このコンポーネントは複数配置されたサブアセンブリ内にあります。整列すると、すべての配置で移動します。" + }, + "vi": { + "cmd.occurrence_align": "Căn chỉnh bản thể", + "select components first": "hãy chọn các thành phần trước", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "Thành phần này nằm trong một cụm lắp phụ được đặt nhiều lần: căn chỉnh nó sẽ làm nó di chuyển ở mọi vị trí đặt." + }, + "zh": { + "cmd.occurrence_align": "对齐实例", + "select components first": "请先选择组件", + "This component is inside a subassembly placed more than once: aligning it moves it in every placement.": "此组件位于多次放置的子装配体中:对齐它会使其在每个放置位置中都移动。" + } +} diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index 04145baa8..ce2b3f31f 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -11,13 +11,17 @@ use solidcraft_geom::Vec3; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; -use crate::schema::component::{EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult}; +use crate::schema::component::{ + EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, OccurrenceAlignParams, OccurrenceAlignResult, +}; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; const EDIT_IN_PLACE_CONTRACT: TypedContract = TypedContract::new(); const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new(); +#[path = "component_align.rs"] +mod align; #[path = "component_drag.rs"] mod drag; #[path = "component_matrix.rs"] @@ -110,6 +114,16 @@ pub static COMMANDS: &[CommandSpec] = &[ point - at (with any chain of joints it is in that is joined to nothing grounded) and captures its position; other pending \ moves stay pending. Shared definitions move in all placements. Grounded parts and parts joints hold to something fixed are refused (joint.reach moves those)", ), + CommandSpec::new("occurrence.align", "Align Occurrence", crate::checked!("occurrence.align", align::align)) + .icon("align") + .contract(&ALIGN_CONTRACT) + .output(output_schema_for::) + .params( + "occurrence?, occurrences?, path?, paths?: placements to move together; from | from_face | from_plane; to | to_face | to_plane; \ + flip?: bool; capture?: bool (default true); move_grounded?: bool (default false). Moves only the chosen occurrence placements in \ + world coordinates without changing shared component geometry; a placement inside a component placed more than once moves in \ + every placement of it, and the reply's `shared` lists those paths", + ), CommandSpec::new("occurrence.ground", "Ground", ground).icon("ground").params("occurrence; grounded?: bool (default toggles)"), CommandSpec::new("occurrence.reparent", "Move to Component", reparent::reparent).icon("move").params( "occurrence; path?: exact placement; parent: component id or name (0 or \"root\" for the design); parent_path?: the parent's \ @@ -120,6 +134,8 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.revert_position", "Revert Position", revert).at("SOLID", "POSITION").icon("revert").noundo().params("occurrences?: [ids] (default all); drops selected pending occurrence moves"), ]; +const ALIGN_CONTRACT: TypedContract = TypedContract::new(); + fn key(v: Option<&Value>) -> Option { match v { Some(Value::Number(n)) => Some(n.to_string()), diff --git a/crates/engine/src/cmd/component_align.rs b/crates/engine/src/cmd/component_align.rs new file mode 100644 index 000000000..b8371b6db --- /dev/null +++ b/crates/engine/src/cmd/component_align.rs @@ -0,0 +1,244 @@ +//! Aligning component occurrences (`occurrence.align`): moves only the chosen occurrence +//! placements in world coordinates using the same `from` / `to` / `flip` rules as `solid.align`, +//! without modifying shared component geometry across other instances. + +use serde_json::{Value, json}; +use solidcraft_doc::{IDENTITY, mat_inverse, mat_mul, rigid}; +use solidcraft_geom::Vec3; + +use super::{occurrence, occurrence_path, valid_position}; +use crate::params::{bad, vec3}; +use crate::{Result, Session}; + +const MAX_ALIGNED: usize = 64; + +fn opt_bool(p: &Value, key: &str, default: bool, cmd: &str) -> Result { + match p.get(key) { + None => Ok(default), + Some(Value::Bool(b)) => Ok(*b), + _ => Err(bad(cmd, format!("`{key}` must be a boolean"))), + } +} + +fn parse_path(v: &Value, key: &str, cmd: &str) -> Result> { + v.as_array() + .filter(|a| !a.is_empty() && a.len() <= 64) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .ok_or_else(|| bad(cmd, format!("`{key}` must list 1..64 occurrence ids"))) +} + +fn resolve_paths(s: &Session, p: &Value, cmd: &str) -> Result>> { + let raw: Vec> = if let Some(v) = p.get("paths") { + if ["occurrences", "occurrence", "path"].into_iter().any(|k| p.get(k).is_some()) { + return Err(bad(cmd, "give `paths`, `occurrences`, or `occurrence`/`path`, not more than one")); + } + let items = v + .as_array() + .filter(|a| !a.is_empty() && a.len() <= MAX_ALIGNED) + .ok_or_else(|| bad(cmd, format!("`paths` must list 1..{MAX_ALIGNED} occurrence paths")))?; + let mut out = Vec::with_capacity(items.len()); + for item in items { + let path = parse_path(item, "paths", cmd)?; + s.occurrence_placement(&path).map_err(|e| bad(cmd, e.to_string()))?; + out.push(path); + } + out + } else if let Some(v) = p.get("occurrences") { + if p.get("occurrence").is_some() || p.get("path").is_some() { + return Err(bad(cmd, "give `occurrences` or `occurrence`/`path`, not both")); + } + let items: Vec<&Value> = match v { + Value::Number(_) | Value::String(_) => vec![v], + Value::Array(a) if !a.is_empty() && a.len() <= MAX_ALIGNED => a.iter().collect(), + _ => return Err(bad(cmd, format!("`occurrences` must be an occurrence id/name or a list of 1..{MAX_ALIGNED} ids/names"))), + }; + let mut out = Vec::with_capacity(items.len()); + for item in items { + let q = json!({ "occurrence": item }); + let id = occurrence(s, &q, cmd)?; + out.push(occurrence_path(s, &json!({}), id, cmd)?); + } + out + } else if p.get("occurrence").is_some() { + let id = occurrence(s, p, cmd)?; + vec![occurrence_path(s, p, id, cmd)?] + } else if let Some(v) = p.get("path") { + let path = parse_path(v, "path", cmd)?; + s.occurrence_placement(&path).map_err(|e| bad(cmd, e.to_string()))?; + vec![path] + } else { + return Err(bad(cmd, "give `occurrence`, `occurrences`, `path` or `paths`")); + }; + + let mut deduped: Vec> = Vec::with_capacity(raw.len()); + for path in raw { + if !deduped.contains(&path) { + deduped.push(path); + } + } + + // If both an ancestor placement and a placement under it were selected, moving the ancestor + // already carries the descendant along; skip the descendant so it moves once. Only a path + // prefix means "under it": another placement of the same component does not carry it. + let all = deduped.clone(); + deduped.retain(|cand| !all.iter().any(|other| other.len() < cand.len() && cand.starts_with(other))); + + // Two distinct paths ending in the same nested occurrence id share one definition transform. + for (i, a) in deduped.iter().enumerate() { + if deduped[..i].iter().any(|b| b.last() == a.last()) { + return Err(bad(cmd, "cannot align two placements of the same shared child occurrence at once; align their parent occurrences instead")); + } + } + Ok(deduped) +} + +fn world_pick( + s: &Session, + p: &Value, + pk: &str, + fk: &str, + plane: &Option, + vals: &std::collections::BTreeMap, + cmd: &str, +) -> Result<(Vec3, Option)> { + if let Some(pl_ref) = plane { + if p.get(pk).is_some() || p.get(fk).is_some() { + return Err(bad(cmd, format!("give `{pk}_plane` or `{pk}`/`{fk}`, not both"))); + } + let world = s.world_state(); + let pl = s.placed_document().resolve_plane_in(vals, pl_ref, 0, Some(&*world)).map_err(|e| bad(cmd, e.to_string()))?; + return Ok((pl.origin, Some(pl.normal()))); + } + if let Some(fv) = p.get(fk) { + if p.get(pk).is_some() { + return Err(bad(cmd, format!("give `{pk}` or `{fk}`, not both"))); + } + let fp = vec3(fv).ok_or_else(|| bad(cmd, format!("`{fk}` must be [x, y, z]")))?; + let n = super::super::face::face_normal_world(s, fp).ok_or_else(|| bad(cmd, format!("`{fk}` must be on a planar face")))?; + return Ok((fp, Some(n))); + } + if p.get(pk).and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("origin")) { + return Ok((Vec3::ZERO, None)); + } + if let Some(o) = p.get(pk).and_then(Value::as_object) + && (o.contains_key("at") || o.contains_key("snap")) + { + let at = o.get("at").and_then(vec3).ok_or_else(|| bad(cmd, format!("`{pk}.at` must be [x, y, z]")))?; + let kind = match o.get("snap") { + None => "vertex", + Some(Value::String(k)) if matches!(k.as_str(), "vertex" | "edge_mid" | "face_center" | "circle_center") => k.as_str(), + _ => return Err(bad(cmd, format!("`{pk}.snap` must be vertex, edge_mid, face_center or circle_center"))), + }; + return super::super::features_more::snap_point(s, kind, at) + .map(|q| (q, None)) + .ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); + } + p.get(pk) + .and_then(vec3) + .map(|v| (v, None)) + .ok_or_else(|| bad(cmd, format!("give `{pk}`, `{fk}` or `{pk}_plane` ([x, y, z], \"origin\", or a plane)"))) +} + +pub(super) fn align(s: &mut Session, p: &Value) -> Result { + let cmd = "occurrence.align"; + let paths = resolve_paths(s, p, cmd)?; + let flip = opt_bool(p, "flip", false, cmd)?; + let capture = opt_bool(p, "capture", true, cmd)?; + let move_grounded = opt_bool(p, "move_grounded", false, cmd)?; + + for path in &paths { + let Some(&id) = path.last() else { + return Err(bad(cmd, "occurrence path is empty")); + }; + let o = s.doc.occurrences.iter().find(|o| o.id == id).ok_or_else(|| bad(cmd, "no occurrence"))?; + if o.grounded && !move_grounded { + return Err(bad( + cmd, + format!("{} is grounded: unground it first (occurrence.ground; a design's first part is grounded when it is made)", o.name), + )); + } + if let Some(mut group) = s.held_by_rigid_group(id) { + for _ in 0..64 { + match s.doc.occurrence_of(group).and_then(|occ| s.held_by_rigid_group(occ.id)) { + Some(up) => group = up, + None => break, + } + } + let name = s.doc.components.iter().find(|c| c.id == group).map(|c| c.name.clone()).unwrap_or_default(); + return Err(bad(cmd, format!("{} is held in {name} by a rigid group: move {name}, or Unlock Contents (component.unlock) first", o.name))); + } + } + + let plane = |key: &str| -> Result> { + p.get(key).map(|v| super::super::features::plane_param(s, Some(v), cmd)).transpose() + }; + let (from_plane, to_plane) = (plane("from_plane")?, plane("to_plane")?); + let (vals, _) = s.doc.param_values(); + let (from, from_normal) = world_pick(s, p, "from", "from_face", &from_plane, &vals, cmd)?; + let (to, to_normal) = world_pick(s, p, "to", "to_face", &to_plane, &vals, cmd)?; + + let (mut axis, mut ang) = (Vec3::Z, 0.0); + if let (Some(a), Some(b)) = (from_normal.and_then(Vec3::normalized), to_normal.and_then(Vec3::normalized)) { + let want = if flip { b } else { b * -1.0 }; + let cross = a.cross(want); + let theta = cross.len().atan2(a.dot(want)); + if theta.abs() > 1e-12 { + axis = cross.normalized().unwrap_or_else(|| a.any_perp()); + ang = theta; + } + } + let d = match (&to_plane, to_normal.and_then(Vec3::normalized)) { + (Some(_), Some(n)) => n * (to - from).dot(n), + _ => to - from, + }; + if !(d.is_finite() && from.is_finite() && axis.is_finite() && ang.is_finite()) { + return Err(bad(cmd, "non-finite alignment transform")); + } + let world_move = rigid(d, from, axis, ang); + + // Compute every new local placement from the current placements before mutating anything. + let mut updates = Vec::with_capacity(paths.len()); + for path in &paths { + let placement = s.occurrence_placement(path).map_err(|e| bad(cmd, e.to_string()))?; + let inverse = mat_inverse(&placement.parent_world).ok_or_else(|| bad(cmd, "parent frame is singular"))?; + let local_delta = mat_mul(&mat_mul(&inverse, &world_move), &placement.parent_world); + let next = mat_mul(&local_delta, &placement.local); + if !valid_position(&next) { + return Err(bad(cmd, "alignment transform exceeds supported numeric range")); + } + updates.push((placement.occurrence, next)); + } + + let moved: Vec = updates.iter().map(|(id, _)| *id).collect(); + // Placements inside a component placed more than once move in every placement of it: the + // command still runs (as occurrence.move does), and says so for the dialog's warning. + let shared: Vec<&Vec> = paths.iter().filter(|path| s.occurrence_shared(path)).collect(); + if capture { + if world_move != IDENTITY || updates.iter().any(|(id, _)| s.pending_moves.contains_key(id)) { + for (id, next) in updates { + s.pending_moves.remove(&id); + if let Some(x) = s.doc_mut().occurrences.iter_mut().find(|x| x.id == id) { + x.transform = next; + } + } + } + } else { + for (id, next) in updates { + s.pending_moves.insert(id, next); + } + s.revision += 1; + } + + let mut reply = json!({ + "occurrences": moved, + "paths": paths, + "world_transform": world_move, + "pending": !capture, + }); + if !shared.is_empty() + && let Some(o) = reply.as_object_mut() + { + o.insert("shared".into(), json!(shared)); + } + Ok(reply) +} diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index 6b5f1404b..77b80fe35 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -506,7 +506,7 @@ mod tests; /// A snap point near `at` on the model: the nearest vertex, edge midpoint, planar face's centre /// or circular edge's centre (the end of a cylindrical face). -pub(super) fn snap_point(s: &Session, kind: &str, at: Vec3) -> Option { +pub(crate) fn snap_point(s: &Session, kind: &str, at: Vec3) -> Option { let st = s.world_state(); let near = |pts: Vec| pts.into_iter().min_by(|a, b| a.dist(at).total_cmp(&b.dist(at))); match kind { diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 702d8c9b5..42503da4c 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -1507,3 +1507,134 @@ fn a_pattern_of_another_components_body_follows_its_own_component_when_moved() { fresh.evaluate(&s.doc); assert_eq!(boxes(&s.model.state()), boxes(&fresh.state()), "the kept model against a fresh evaluation"); } + +#[test] +fn occurrence_align_moves_only_selected_instance_including_90_degree_face_mate() { + let mut s = Session::default(); + let c = run(&mut s, "component.create", json!({"name": "Extrusion"})); + let (comp, first) = (c["component"].as_u64().unwrap(), c["occurrence"].as_u64().unwrap()); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 60, "body_name": "Beam"})); + run(&mut s, "component.activate", json!({"component": "root"})); + let second = run(&mut s, "occurrence.copy", json!({"component": comp, "translate": [40, 0, 0]}))["occurrence"].as_u64().unwrap(); + + // Activate the second instance (the user's exact workflow) and align its bottom face (-Z at + // [45, 5, 0]) onto the first instance's +X side face ([10, 5, 30]): instance 2 turns 90 deg + // to extend along +X, while instance 1 remains untouched. + run(&mut s, "component.activate", json!({"component": comp, "occurrence": second, "path": [second]})); + let features_before = s.doc.features.len(); + run( + &mut s, + "occurrence.align", + json!({ + "occurrence": second, + "path": [second], + "from_face": [45, 5, 0], + "to_face": [10, 5, 30] + }), + ); + assert_eq!(s.doc.features.len(), features_before, "aligning an occurrence must not add a body feature to the shared component"); + + let st = s.world_state(); + let b1 = st.body("Beam").unwrap().mesh().bounds(); + assert!((b1.min.x - 0.0).abs() < 1e-5 && (b1.max.x - 10.0).abs() < 1e-5, "{b1:?}"); + assert!((b1.min.y - 0.0).abs() < 1e-5 && (b1.max.y - 10.0).abs() < 1e-5, "{b1:?}"); + assert!((b1.min.z - 0.0).abs() < 1e-5 && (b1.max.z - 60.0).abs() < 1e-5, "{b1:?}"); + + let b2 = st.body("Beam (Extrusion:2)").unwrap().mesh().bounds(); + assert!((b2.min.x - 10.0).abs() < 1e-5 && (b2.max.x - 70.0).abs() < 1e-5, "{b2:?}"); + assert!((b2.min.y - 0.0).abs() < 1e-5 && (b2.max.y - 10.0).abs() < 1e-5, "{b2:?}"); + assert!((b2.min.z - 25.0).abs() < 1e-5 && (b2.max.z - 35.0).abs() < 1e-5, "{b2:?}"); + + // Grounded first part refuses without move_grounded, leaving both placements untouched. + let doc_before = s.doc.clone(); + let err = s.execute("occurrence.align", &json!({"occurrence": first, "from": [0, 0, 0], "to": [5, 0, 0]})).unwrap_err().to_string(); + assert!(err.contains("grounded"), "{err}"); + assert_eq!(s.doc, doc_before); +} + +#[test] +fn occurrence_align_supports_snaps_planes_flip_nested_paths_and_pending_capture() { + let mut s = Session::default(); + let (_, parent) = created(&mut s, "Frame"); + run(&mut s, "occurrence.move", json!({"occurrence": parent, "axis": [0, 0, 1], "angle": "90 deg"})); + let (_, child) = created(&mut s, "Bracket"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 4, "corner": [5, 5, 10], "body_name": "Plate"})); + run(&mut s, "component.activate", json!({"component": "root"})); + + // Align the child under a 90-deg rotated parent onto XY plane along plane normal only (capture: false). + let before = s.world_state().body("Plate").unwrap().mesh().bounds(); + run( + &mut s, + "occurrence.align", + json!({ + "paths": [[parent, child]], + "from_face": [before.center().x, before.center().y, 10.0], + "to_plane": "XY", + "capture": false + }), + ); + let moved = s.world_state().body("Plate").unwrap().mesh().bounds(); + assert!((moved.min.z - 0.0).abs() < 1e-5 && (moved.max.z - 4.0).abs() < 1e-5, "{moved:?}"); + assert!((moved.center().x - before.center().x).abs() < 1e-5 && (moved.center().y - before.center().y).abs() < 1e-5, "{moved:?}"); + + // Revert drops the pending alignment; re-align with capture: true and vertex snap to origin. + run(&mut s, "component.revert_position", json!({})); + assert!((s.world_state().body("Plate").unwrap().mesh().bounds().min.z - 10.0).abs() < 1e-5); + + run( + &mut s, + "occurrence.align", + json!({ + "occurrence": child, + "path": [parent, child], + "from": {"snap": "vertex", "at": [before.min.x, before.min.y, before.min.z]}, + "to": "origin" + }), + ); + let at_origin = s.world_state().body("Plate").unwrap().mesh().bounds(); + assert!(at_origin.min.dist(solidcraft_geom::Vec3::ZERO) < 1e-5, "{at_origin:?}"); + + // Hostile / invalid parameters never panic. + for bad_params in [ + json!({}), + json!({"occurrence": 999999, "from": [0, 0, 0], "to": [1, 0, 0]}), + json!({"paths": [], "from": [0, 0, 0], "to": [1, 0, 0]}), + json!({"occurrence": child, "path": [parent, child], "from": [1e12, 0, 0], "to": [0, 0, 0]}), + json!({"occurrence": child, "path": [parent, child], "from": {"snap": "bogus", "at": [0, 0, 0]}, "to": [0, 0, 0]}), + json!({"occurrence": child, "path": [parent, child], "from_plane": "XY", "from": [0, 0, 0], "to": [0, 0, 1]}), + ] { + assert!(s.execute("occurrence.align", &bad_params).is_err(), "{bad_params}"); + } +} + +#[test] +fn occurrence_align_keeps_every_pick_and_reports_shared_definitions() { + // Frame holds Bracket and is placed twice (A and B). Aligning [A, Bracket] together with B + // must move both picks: B is another placement of Frame, not an ancestor of [A, Bracket]. + let mut s = Session::default(); + let (frame, a) = created(&mut s, "Frame"); + let (_, bracket) = created(&mut s, "Bracket"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 4, "body_name": "Plate"})); + run(&mut s, "component.activate", json!({"component": "root"})); + let b = run(&mut s, "occurrence.copy", json!({"component": frame, "translate": [0, 50, 0]}))["occurrence"].as_u64().unwrap(); + let origin = |s: &Session, path: &[u64]| solidcraft_doc::apply_point(&s.occurrence_placement(path).unwrap().world, solidcraft_geom::Vec3::ZERO); + let (a0, ab0, b0, bb0) = (origin(&s, &[a]), origin(&s, &[a, bracket]), origin(&s, &[b]), origin(&s, &[b, bracket])); + + assert!(!s.occurrence_shared(&[a]) && !s.occurrence_shared(&[b]), "top-level placements are their own"); + assert!(s.occurrence_shared(&[a, bracket]) && s.occurrence_shared(&[b, bracket]), "Bracket's placement lives in Frame, placed twice"); + + let r = run(&mut s, "occurrence.align", json!({"paths": [[a, bracket], [b]], "from": [0, 0, 0], "to": [5, 0, 0]})); + assert_eq!(r["paths"], json!([[a, bracket], [b]]), "{r}"); + assert_eq!(r["shared"], json!([[a, bracket]]), "{r}"); + + let shift = solidcraft_geom::Vec3::new(5.0, 0.0, 0.0); + assert!(origin(&s, &[a]).dist(a0) < 1e-9, "A itself stays"); + assert!(origin(&s, &[a, bracket]).dist(ab0 + shift) < 1e-9, "the picked Bracket moves"); + assert!(origin(&s, &[b]).dist(b0 + shift) < 1e-9, "B moves"); + // B's Bracket moves with B and, sharing Frame's definition, with the other pick too. + assert!(origin(&s, &[b, bracket]).dist(bb0 + shift + shift) < 1e-9); + + // A top-level-only alignment reports nothing shared. + let r = run(&mut s, "occurrence.align", json!({"paths": [[b]], "from": [0, 0, 0], "to": [1, 0, 0]})); + assert!(r.get("shared").is_none(), "{r}"); +} diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs index 987a2c0e8..ec6a34d1b 100644 --- a/crates/engine/src/occurrences.rs +++ b/crates/engine/src/occurrences.rs @@ -326,6 +326,20 @@ impl Session { }) } + /// Is the leaf of `path` placed inside a component that has more than one placement? Its + /// transform lives in that shared definition, so moving it moves it in every placement. + /// Top-level placements and unknown ids are never shared. + pub fn occurrence_shared(&self, path: &[u64]) -> bool { + let Some((_, ancestors)) = path.split_last() else { return false }; + ancestors.iter().take(64).any(|id| { + self.doc + .occurrences + .iter() + .find(|o| o.id == *id) + .is_some_and(|a| self.doc.occurrences.iter().filter(|o| o.component == a.component).nth(1).is_some()) + }) + } + /// Children are definitions shared by every placement of the parent component. pub fn occurrence_children(&self, path: &[u64]) -> Result> { let component = if path.is_empty() { 0 } else { self.occurrence_placement(path)?.component }; diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs index 8129a0fac..ef918bb65 100644 --- a/crates/engine/src/schema/component.rs +++ b/crates/engine/src/schema/component.rs @@ -1,9 +1,14 @@ //! Contracts and result types for the commands in `cmd/component.rs`. -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; +use std::borrow::Cow; -use super::types::{IdOrName, present}; +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Value, json}; + +use super::types::{IdOrName, Point3, PointExpr3, not_blank_pattern, present}; +use crate::params; /// Edit a linked component's design in place. In the app window: open the design it links in a /// tab of its own, with the rest of the assembly drawn faded around it as the placement `path` @@ -60,6 +65,290 @@ pub struct FinishEditResult { pub param_warnings: Vec, } +/// One exact occurrence placement path (`1..=64` occurrence ids, root-first). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OccurrencePath(pub Vec); + +impl<'de> Deserialize<'de> for OccurrencePath { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + v.as_array() + .filter(|a| !a.is_empty() && a.len() <= 64) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .map(OccurrencePath) + .ok_or_else(|| D::Error::custom("must list 1..64 occurrence ids")) + } +} + +impl JsonSchema for OccurrencePath { + fn schema_name() -> Cow<'static, str> { + "OccurrencePath".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "An exact placement path: 1 to 64 occurrence ids from the root down.", + "type": "array", + "items": {"type": "integer", "minimum": 0, "maximum": u64::MAX}, + "minItems": 1, + "maxItems": 64 + }) + } +} + +/// A list of `1..=64` exact occurrence placement paths. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OccurrencePaths(pub Vec>); + +impl<'de> Deserialize<'de> for OccurrencePaths { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let items = v.as_array().filter(|a| !a.is_empty() && a.len() <= 64).ok_or_else(|| D::Error::custom("must list 1..64 occurrence paths"))?; + items + .iter() + .map(|item| OccurrencePath::deserialize(item).map(|p| p.0).map_err(D::Error::custom)) + .collect::, _>>() + .map(OccurrencePaths) + } +} + +impl JsonSchema for OccurrencePaths { + fn schema_name() -> Cow<'static, str> { + "OccurrencePaths".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let path = generator.subschema_for::(); + json_schema!({ + "description": "1 to 64 exact occurrence placement paths.", + "type": "array", + "items": path, + "minItems": 1, + "maxItems": 64 + }) + } +} + +/// One occurrence or a list of `1..=64` occurrences, each by id or name. +#[derive(Clone, Debug, PartialEq)] +pub struct OccurrenceList(pub Vec); + +impl<'de> Deserialize<'de> for OccurrenceList { + fn deserialize>(d: D) -> Result { + let fail = || D::Error::custom("must be an occurrence id/name or a list of 1..64 ids/names"); + match Value::deserialize(d)? { + v @ (Value::Number(_) | Value::String(_)) => IdOrName::deserialize(v).map(|x| OccurrenceList(vec![x.0])).map_err(|_| fail()), + Value::Array(a) if !a.is_empty() && a.len() <= 64 => { + a.into_iter().map(|v| IdOrName::deserialize(v).ok().map(|x| x.0)).collect::>>().map(OccurrenceList).ok_or_else(fail) + } + _ => Err(fail()), + } + } +} + +impl JsonSchema for OccurrenceList { + fn schema_name() -> Cow<'static, str> { + "OccurrenceList".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let item = generator.subschema_for::(); + json_schema!({ + "description": "An occurrence id/name, or 1 to 64 occurrence ids/names.", + "anyOf": [ + item.clone(), + {"type": "array", "items": item, "minItems": 1, "maxItems": 64} + ] + }) + } +} + +const SNAPS: [&str; 4] = ["vertex", "edge_mid", "face_center", "circle_center"]; + +/// An alignment point: `[x, y, z]`, `"origin"`, or `{snap?: vertex|edge_mid|face_center|circle_center, at: [x, y, z]}`. +#[derive(Clone, Debug, PartialEq)] +pub struct AlignPickParam(pub Value); + +impl<'de> Deserialize<'de> for AlignPickParam { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + if v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("origin")) { + return Ok(AlignPickParam(v)); + } + if let Some(o) = v.as_object() + && (o.contains_key("at") || o.contains_key("snap")) + { + if o.get("at").and_then(params::vec3).is_none() { + return Err(D::Error::custom("`.at` must be [x, y, z]")); + } + if let Some(snap) = o.get("snap") { + let Some(s) = snap.as_str() else { + return Err(D::Error::custom("`.snap` must be vertex, edge_mid, face_center or circle_center")); + }; + if !SNAPS.contains(&s) { + return Err(D::Error::custom("`.snap` must be vertex, edge_mid, face_center or circle_center")); + } + } + return Ok(AlignPickParam(v)); + } + if params::vec3(&v).is_some() { + return Ok(AlignPickParam(v)); + } + Err(D::Error::custom("must be [x, y, z], \"origin\", or {snap, at: [x, y, z]}")) + } +} + +impl JsonSchema for AlignPickParam { + fn schema_name() -> Cow<'static, str> { + "AlignPick".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + json_schema!({ + "description": "A world point [x, y, z], \"origin\", or a snap point {\"snap\": \"vertex\"|\"edge_mid\"|\"face_center\"|\"circle_center\", \"at\": [x, y, z]}.", + "anyOf": [ + point.clone(), + {"type": "string", "pattern": "^[Oo][Rr][Ii][Gg][Ii][Nn]$"}, + { + "type": "object", + "properties": { + "snap": {"type": "string", "enum": SNAPS}, + "at": point + }, + "required": ["at"] + } + ] + }) + } +} + +/// A plane parameter as `features::plane_param` reads it: `"XY" | "XZ" | "YZ"`, a construction +/// plane name or feature id, or `{origin?, normal}` / `{origin?, x_dir, y_dir}`. +#[derive(Clone, Debug, PartialEq)] +pub struct AlignPlaneParam(pub Value); + +impl<'de> Deserialize<'de> for AlignPlaneParam { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + match &v { + Value::String(s) if !s.trim().is_empty() && s.len() <= 4096 => Ok(AlignPlaneParam(v)), + Value::Number(n) if n.as_u64().is_some() => Ok(AlignPlaneParam(v)), + Value::Object(o) => { + if let Some(origin) = o.get("origin") { + PointExpr3::deserialize(origin).map_err(|_| D::Error::custom("plane `origin` must be [x, y, z]"))?; + } + let has_xy = o.get("x_dir").and_then(params::vec3).is_some() && o.get("y_dir").and_then(params::vec3).is_some(); + let has_n = o.get("normal").and_then(params::vec3).is_some(); + if has_xy || has_n { Ok(AlignPlaneParam(v)) } else { Err(D::Error::custom("plane needs x_dir and y_dir, or normal")) } + } + _ => Err(D::Error::custom("must be XY, XZ, YZ, a construction plane name or id, or {origin, normal}")), + } + } +} + +impl JsonSchema for AlignPlaneParam { + fn schema_name() -> Cow<'static, str> { + "AlignPlane".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let expr_point = generator.subschema_for::(); + json_schema!({ + "description": "XY, XZ, YZ, a construction plane name or feature id, or an explicit plane {origin?, normal} / {origin?, x_dir, y_dir}.", + "anyOf": [ + {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": not_blank_pattern()}, + {"type": "integer", "minimum": 0, "maximum": u64::MAX}, + json!({ + "type": "object", + "properties": {"origin": expr_point.clone(), "normal": point.clone()}, + "required": ["normal"] + }), + json!({ + "type": "object", + "properties": {"origin": expr_point, "x_dir": point.clone(), "y_dir": point}, + "required": ["x_dir", "y_dir"] + }) + ] + }) + } +} + +/// Align one or more component occurrence placements in world coordinates without modifying +/// shared component geometry. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct OccurrenceAlignParams { + /// A single occurrence to align, by id or name (optionally disambiguated by `path`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "IdOrName")] + pub occurrence: Option, + /// One or more occurrences to align together, by id or name. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "OccurrenceList")] + pub occurrences: Option, + /// Exact placement path `[occ_id, ...]` of a single occurrence. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "OccurrencePath")] + pub path: Option, + /// Exact placement paths `[[occ_id, ...], ...]` of one or more occurrences to align together. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "OccurrencePaths")] + pub paths: Option, + /// Source point (`[x, y, z]`, `"origin"`, or `{snap, at}`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "AlignPickParam")] + pub from: Option, + /// Point on a planar source face in world coordinates (turns to meet `to_face` or `to_plane`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "Point3")] + pub from_face: Option, + /// Source plane (`XY`, `XZ`, `YZ`, a construction plane, or `{origin, normal}`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "AlignPlaneParam")] + pub from_plane: Option, + /// Destination point (`[x, y, z]`, `"origin"`, or `{snap, at}`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "AlignPickParam")] + pub to: Option, + /// Point on a planar destination face in world coordinates. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "Point3")] + pub to_face: Option, + /// Destination plane (`XY`, `XZ`, `YZ`, a construction plane, or `{origin, normal}`). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "AlignPlaneParam")] + pub to_plane: Option, + /// Flip face/plane normal alignment so normals point the same way instead of meeting opposite. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub flip: Option, + /// Capture the aligned position immediately (default: `true`); `false` leaves it pending. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub capture: Option, + /// Allow aligning a grounded occurrence while keeping it grounded (default: `false`). + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub move_grounded: Option, +} + +/// Result of `occurrence.align`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OccurrenceAlignResult { + /// Occurrence ids whose placements were updated, in order. + pub occurrences: Vec, + /// Exact placement paths aligned, in order. + pub paths: Vec>, + /// World-space rigid transform applied (column-major 4×4 matrix). + pub world_transform: [[f64; 4]; 4], + /// True when `capture: false` kept the aligned positions as pending moves. + pub pending: bool, + /// Aligned paths that sit inside a component placed more than once: they moved in every + /// placement of it. Left out when there are none. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub shared: Vec>, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + #[cfg(test)] #[path = "component_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs index 08ae137a8..0ef2d0171 100644 --- a/crates/engine/src/schema/component_tests.rs +++ b/crates/engine/src/schema/component_tests.rs @@ -1,16 +1,34 @@ use std::sync::Arc; -use serde_json::json; +use serde_json::{Value, json}; -use super::{EditInPlaceParams, FinishEditParams}; +use super::{EditInPlaceParams, FinishEditParams, OccurrenceAlignParams, OccurrenceAlignResult}; use crate::Session; -use crate::schema::input_schema_for; -use crate::schema::tests::assert_keys; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["component", "path"]); assert_keys(input_schema_for::(), &[]); + assert_keys( + input_schema_for::(), + &[ + "capture", + "flip", + "from", + "from_face", + "from_plane", + "move_grounded", + "occurrence", + "occurrences", + "path", + "paths", + "to", + "to_face", + "to_plane", + ], + ); } #[test] @@ -32,3 +50,30 @@ fn finishing_an_edit_outside_the_window_changes_nothing() { assert!(r.as_object().is_some_and(serde_json::Map::is_empty), "{r}"); assert!(Arc::ptr_eq(&doc, &s.doc) && s.undo.len() == undo); } + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); + assert!(!required.contains(&"shared"), "`shared` is left out when nothing shared moved"); + + let mut s = Session::default(); + let comp = s.execute("component.create", &json!({"name": "Extrusion"})).unwrap_or_else(|e| panic!("{e}")); + let comp_id = comp["component"].as_u64().unwrap_or(0); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 40})).unwrap_or_else(|e| panic!("{e}")); + s.execute("component.activate", &json!({"component": "root"})).unwrap_or_else(|e| panic!("{e}")); + let copy = s.execute("occurrence.copy", &json!({"component": comp_id, "translate": [30, 0, 0]})).unwrap_or_else(|e| panic!("{e}")); + let second = copy["occurrence"].as_u64().unwrap_or(0); + + s.param_check = ParamCheck::Warn; + let r1 = s.execute("occurrence.align", &json!({"occurrence": second, "from": [30, 0, 0], "to": [10, 0, 0]})).unwrap_or_else(|e| panic!("{e}")); + assert!(conforms(schema, schema, &r1), "{r1} doesn't match {schema}"); + + let r2 = s + .execute("occurrence.align", &json!({"paths": [[second]], "from": [10, 0, 0], "to": [20, 0, 0], "unknown_extra": 1})) + .unwrap_or_else(|e| panic!("{e}")); + assert!(r2.get("param_warnings").is_some(), "{r2}"); + assert!(conforms(schema, schema, &r2), "{r2} doesn't match {schema}"); +} diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index e5be74595..fe2a4acc4 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -271,7 +271,7 @@ enum Take { /// ([`pick_from_browser`]). Returns false when that input does not take bodies, so the click /// keeps its ordinary meaning. A Shift range only adds; a group or component toggles. fn offer_bodies(app: &mut SolveApp, names: &[String], take: Take) -> bool { - if !dialog_takes_body(app) { + if !dialog_takes_body(app) || app.dialog.as_ref().is_some_and(|d| d.takes_components()) { return false; } let world = app.session.world_state(); @@ -1502,16 +1502,22 @@ fn occurrence_rows_inner( if r.eye { let _ = app.run("browser.visibility", json!({"visible": app.session.occurrence_hidden(path), "paths": [path]})); } + let takes_components = app.dialog.as_ref().is_some_and(|d| d.takes_components()); let params = json!({"component": placement.component, "occurrence": placement.occurrence, "path": path}); if r.radio { let _ = app.run("component.activate", params); - } else if r.double && !app.session.doc.parts.contains_key(&placement.component) { + } else if r.double && !takes_components && !app.session.doc.parts.contains_key(&placement.component) { crate::edit_in_place::double_click_component(app, params); } - if r.double && app.session.doc.parts.contains_key(&placement.component) { + if r.double && !takes_components && app.session.doc.parts.contains_key(&placement.component) { crate::dialogs_part_size::open(app, placement.component); } - if r.clicked && !r.double { + if r.clicked && takes_components { + if let Some(mut d) = app.dialog.take() { + d.pick(&app.session, Sel::Occurrence { path: path.to_vec() }); + app.dialog = Some(d); + } + } else if r.clicked && !r.double { let names = app.session.occurrence_bodies(path, true).unwrap_or_default(); if !offer_bodies(app, &names, Take::Toggle) { click_select(app, ui, key.clone(), Some(Sel::Occurrence { path: path.to_vec() })); @@ -2013,11 +2019,18 @@ fn dialog_takes_body(app: &SolveApp) -> bool { /// Browser picks go only into compatible active dialog inputs. Outside a dialog, planes and /// axes become the selection; body rows use the ordinary Ctrl/Shift-aware selection path. fn pick_from_browser(app: &mut SolveApp, x: Sel) { - if let Sel::Body { .. } = &x + if let Sel::Body { name } = &x && dialog_takes_body(app) && let Some(mut d) = app.dialog.take() { - d.pick(&app.session, x); + let pick = if d.takes_components() { + crate::dialogs::occurrence_path_of_body(&app.session, name).map(|path| Sel::Occurrence { path }) + } else { + Some(x) + }; + if let Some(pick) = pick { + d.pick(&app.session, pick); + } app.dialog = Some(d); return; } @@ -2915,7 +2928,13 @@ pub fn needs_capture(app: &SolveApp, what: &str) -> bool { !app.session.pending_moves.is_empty() && !matches!( what, - "component.capture_position" | "component.revert_position" | "occurrence.move" | "occurrence.drag" | "edit.undo" | "edit.redo" + "component.capture_position" + | "component.revert_position" + | "occurrence.move" + | "occurrence.align" + | "occurrence.drag" + | "edit.undo" + | "edit.redo" ) && app.tree.capture_prompt.is_none() } diff --git a/crates/ui-egui/src/browser_card_tests.rs b/crates/ui-egui/src/browser_card_tests.rs index 39bcd43bd..2bf76a96c 100644 --- a/crates/ui-egui/src/browser_card_tests.rs +++ b/crates/ui-egui/src/browser_card_tests.rs @@ -481,3 +481,31 @@ fn mesh_and_solid_body_rows_have_different_icons_and_tooltips() { assert_ne!(icon.master, crate::icon_svg::resolve("body").master); assert_eq!(icon.accent, crate::icon_svg::accent_index("mesh")); } + +#[test] +fn browser_occurrence_clicks_fill_align_components_input() { + let mut h = Harness::new(); + let comp = h.app.run("component.create", json!({"name": "Extrusion", "grounded": false})).unwrap()["component"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 40, "body_name": "Beam"})).unwrap(); + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"component": comp, "translate": [30, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap(); + + h.app.start("solid.align"); + { + let d = h.app.dialog.as_mut().unwrap(); + d.kind = crate::dialogs::Kind::Align { flip: false, components: true }; + d.inputs[0].label = "Components"; + d.active = 0; + } + h.settle(); + + let handle = format!("row:occurrence:{second}"); + h.step(&json!({"click": {"handle": &handle}})).unwrap(); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![second] }]); + assert!(h.app.session.selection.is_empty(), "dialog picks do not change global selection"); + + // Clicking the same occurrence row again toggles it off in the multi-select Components input. + h.step(&json!({"click": {"handle": &handle}})).unwrap(); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c7246c166..4737b92c1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -268,9 +268,10 @@ crate::dialog_descriptor::dialog_descriptors! { cells: Vec<(Vec3, String, bool)>, of: Vec, }, - /// Move bodies so a face or point meets another. + /// Move bodies or component occurrences so a face or point meets another. Align { flip: bool, + components: bool, }, /// Remove bodies from here on in the timeline. Remove, @@ -844,14 +845,17 @@ impl Dialog { "solid.boundary_fill" => { Dialog::new(Kind::BoundaryFill { operation: 0, cells: Vec::new(), of: Vec::new() }, vec![SelInput::new("Tools", BODIES, true)]) } - "solid.align" => Dialog::new( - Kind::Align { flip: false }, - vec![ - SelInput::new("Bodies", BODIES, true), - SelInput::new("From", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), - SelInput::new("To", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), - ], - ), + "solid.align" => { + let components = s.selection.iter().any(|x| matches!(x, Sel::Occurrence { .. })); + Dialog::new( + Kind::Align { flip: false, components }, + vec![ + SelInput::new(if components { "Components" } else { "Bodies" }, BODIES, true), + SelInput::new("From", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), + SelInput::new("To", FACES | EDGES | selection::VERTICES | PLANES | selection::ORIGIN, false), + ], + ) + } "solid.remove" => Dialog::new(Kind::Remove, vec![SelInput::new("Bodies", BODIES, true)]), "solid.pattern.path" => Dialog::new( Kind::PathPattern { count: "4".into(), spacing: length_default(s, "20") }, @@ -1045,6 +1049,24 @@ impl Dialog { // text it edits, not its path.) let preselection: &[Sel] = if matches!(d.kind, Kind::Text(_)) { &[] } else { &s.selection }; for sel in preselection { + if matches!(d.kind, Kind::Align { components: true, .. }) { + let occ = match sel { + Sel::Occurrence { path } if !path.is_empty() => Some(Sel::Occurrence { path: path.clone() }), + Sel::Body { name } => occurrence_path_of_body(s, name).map(|path| Sel::Occurrence { path }), + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => { + occurrence_path_of_body(s, body).map(|path| Sel::Occurrence { path }) + } + _ => None, + }; + if let Some(occ) = occ { + if let Some(inp) = d.inputs.first_mut() + && !inp.items.contains(&occ) + { + inp.items.push(occ); + } + continue; + } + } let as_body = match sel { Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.to_string() }), _ => None, @@ -1330,6 +1352,11 @@ impl Dialog { && (matches!(self.kind, Kind::Move { .. }) || (matches!(self.kind, Kind::Construct { .. }) && inp.accept & selection::VERTICES != 0)) } + /// Does the active input pick component occurrences rather than bodies? + pub(crate) fn takes_components(&self) -> bool { + matches!(self.kind, Kind::Align { components: true, .. }) && self.active == 0 + } + /// Everything the inputs hold (for highlighting). pub fn items(&self) -> Vec { self.inputs.iter().flat_map(|i| i.items.iter().cloned()).collect() @@ -1422,6 +1449,12 @@ impl Dialog { return Some(target); } let inp = self.active_input()?; + if self.takes_components() { + return match h { + Hit::Face { body, .. } => occurrence_path_of_body(s, body).map(|path| Sel::Occurrence { path }), + _ => None, + }; + } // Features are also picked on the canvas: a face stands for the feature that made it. if inp.accept == selection::FEATURES { return match h { @@ -1609,6 +1642,7 @@ impl Dialog { self.profile_selection_changed = true; } let measure = matches!(self.kind, Kind::Measure { .. }); + let takes_components = self.takes_components(); let is_fillet = matches!(self.kind, Kind::Fillet { .. }) && self.active == 0; let chain = matches!(self.kind, Kind::Fillet { chain: true, .. }); if is_fillet && !add { @@ -1619,6 +1653,19 @@ impl Dialog { inp.items.clear(); } for x in sels { + if takes_components { + let occ = match x { + Sel::Occurrence { path } if !path.is_empty() => Some(Sel::Occurrence { path }), + Sel::Body { name } => occurrence_path_of_body(s, &name).map(|path| Sel::Occurrence { path }), + _ => None, + }; + if let Some(occ) = occ + && !inp.items.contains(&occ) + { + inp.items.push(occ); + } + continue; + } let x = if measure { crate::viewport::measurement_selection(s, &x) } else { x }; if !fits(inp.accept, &x) { continue; @@ -2153,6 +2200,8 @@ fn hint(inp: &SelInput) -> &'static str { "click sketch curves" } else if a & (selection::POINTS | selection::SKETCH_POINTS) != 0 { "click sketch points" + } else if inp.label == "Components" { + "click components" } else if a & BODIES != 0 { "click bodies" } else { @@ -2248,6 +2297,22 @@ fn object_type_row(d: &mut Dialog, ui: &mut egui::Ui) { } } +fn align_object_type_row(d: &mut Dialog, ui: &mut egui::Ui) { + let Kind::Align { components, .. } = &mut d.kind else { return }; + let Some(inp) = d.inputs.first_mut() else { return }; + let cur = usize::from(*components); + let mut ty = cur; + choice_row(ui, "Object Type", "align_obj", &mut ty, &["Bodies", "Components"]); + if ty != cur { + *components = ty == 1; + inp.label = if *components { "Components" } else { "Bodies" }; + let back = std::mem::take(&mut d.other_objects); + d.other_objects = std::mem::replace(&mut inp.items, back); + d.active = 0; + d.error = None; + } +} + /// Rows above the selection inputs: the pattern type and object type, the Hole placement (one /// face point, or sketch points). fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, app: &SolveApp) { @@ -2256,6 +2321,10 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, app: &SolveApp) { object_type_row(d, ui); return; } + if matches!(d.kind, Kind::Align { .. }) { + align_object_type_row(d, ui); + return; + } if matches!(d.kind, Kind::Move { .. }) { crate::dialogs_move::type_row(app, d, ui); return; @@ -2320,6 +2389,65 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, app: &SolveApp) { } } +/// The placement a click on a placed component's world body picks (`None` for root-component +/// bodies): the one directly under the active component, as the browser shows it. With the design +/// active a part inside a subassembly picks the subassembly; with the subassembly (or the part) +/// active it picks the part. A body outside the active component picks its top-level placement. +pub(crate) fn occurrence_path_of_body(s: &Session, body: &str) -> Option> { + let st = s.world_state(); + let b = st.body(body)?; + if s.doc.model_body_component(b) == 0 { + return None; + } + let model = s.model.state(); + let (_, _, _, path, _) = s.placed_document().body_frames_with_source(&model).into_iter().find(|(world, ..)| world == body)?; + let depth = pick_depth(s, &path); + let path: Vec = path.into_iter().take(depth).collect(); + (!path.is_empty()).then_some(path) +} + +/// How many ids of a body's full placement `path` a component pick keeps (see +/// [`occurrence_path_of_body`]). +fn pick_depth(s: &Session, path: &[u64]) -> usize { + let context = match &s.active_occurrence_path { + Some(active) => Some(active.len()), + // An active component without an exact placement: the placement of it on this path. + None if s.active_component != 0 => { + path.iter().position(|id| s.doc.occurrences.iter().any(|o| o.id == *id && o.component == s.active_component)).map(|i| i + 1) + } + None => Some(0), + }; + match context { + Some(n) if s.active_occurrence_path.as_deref().is_none_or(|active| path.starts_with(active)) => (n + 1).min(path.len()), + _ => 1, + } +} + +/// The note Align shows when a picked component sits inside a subassembly placed more than once. +const ALIGN_SHARED_WARNING: &str = "This component is inside a subassembly placed more than once: aligning it moves it in every placement."; + +/// Does aligning these Components picks move a placement shared by several subassembly copies? +fn align_moves_shared(s: &Session, items: &[Sel]) -> bool { + occurrence_paths(s, items).iter().any(|path| s.occurrence_shared(path)) +} + +fn occurrence_paths(s: &Session, items: &[Sel]) -> Vec> { + let mut out = Vec::new(); + for item in items { + let path = match item { + Sel::Occurrence { path } if !path.is_empty() => Some(path.clone()), + Sel::Body { name } => occurrence_path_of_body(s, name), + _ => None, + }; + if let Some(p) = path + && !out.contains(&p) + { + out.push(p); + } + } + out +} + /// A picked item as its chip shows it. A round edge or face says what it stands for in `inp`: /// its axis in an axis input, a circle's centre in a point input. An origin plane goes by /// the name the preferences give it. @@ -2340,6 +2468,7 @@ pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames // A point of the model: a vertex, or the centre a round edge stands for. Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), + Sel::Occurrence { path } => s.occurrence_placement(path).map(|p| p.name).unwrap_or_else(|_| "Component".into()), Sel::Vertex { body, point } if body.is_empty() => { let state = s.world_state(); let p = s.active_sketch.and_then(|id| state.sketch(id)).map(|sk| sk.plane.to_local(*point)).unwrap_or_default(); @@ -4313,11 +4442,19 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, "faces")?; ("face.delete", json!({"faces": face_points(0)})) } - Kind::Align { flip } => { - need(0, "bodies")?; + Kind::Align { flip, components } => { + need(0, if *components { "components" } else { "bodies" })?; need(1, "what to move from")?; need(2, "where to move it to")?; - let mut p = json!({"bodies": sels(d, 0).body_names(), "flip": flip}); + let mut p = if *components { + let paths = occurrence_paths(s, sels(d, 0)); + if paths.is_empty() { + return Err("select components first".into()); + } + json!({"paths": paths, "flip": flip}) + } else { + json!({"bodies": sels(d, 0).body_names(), "flip": flip}) + }; for (i, key) in [(1, "from"), (2, "to")] { let snap = d.extra.get(&format!("{key}_snap")).and_then(Value::as_str).unwrap_or("picked"); match (sels(d, i).first(), snap) { @@ -4335,7 +4472,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S _ => return Err("pick faces, edges, vertices or planes".into()), } } - ("solid.align", p) + (if *components { "occurrence.align" } else { "solid.align" }, p) } Kind::Remove => { need(0, "bodies")?; diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 9edb12c54..69f4c3ebb 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -398,7 +398,53 @@ form_case!(web, "solid.web", ["Direction", "Thickness", "Depth"]); form_case!(emboss, "solid.emboss", ["Depth", "Type"]); form_case!(replace_face, "solid.replace_face", []); form_case!(boundary_fill, "solid.boundary_fill", ["Cells", "Operation"]); -form_case!(align, "solid.align", ["From Snap", "To Snap"]); +form_case!(align, "solid.align", ["Object Type", "From Snap", "To Snap"]); + +#[test] +fn align_components_mode_switches_and_aligns_only_selected_instance() { + let mut h = Harness::new(); + let comp = h.app.run("component.create", json!({"name": "Extrusion"})).unwrap()["component"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 60, "body_name": "Beam"})).unwrap(); + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"component": comp, "translate": [40, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap(); + + // Preselecting an occurrence opens Align in Components mode and advances to From. + let picked = vec![Sel::Occurrence { path: vec![second] }]; + h.app.session.selection = picked.clone(); + h.app.start("solid.align"); + h.frames(4); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].label, "Components"); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, picked); + assert_eq!(h.app.dialog.as_ref().unwrap().active, 1); + + // Switching Object Type to Bodies and back restores the preselected occurrence. + mirror_object_type(&mut h, "Bodies"); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].label, "Bodies"); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); + mirror_object_type(&mut h, "Components"); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].label, "Components"); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, picked); + + let from = face_sel(&h.app.session, Vec3::new(45.0, 5.0, 0.0)).unwrap(); + let to = face_sel(&h.app.session, Vec3::new(10.0, 5.0, 30.0)).unwrap(); + { + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[1].items = vec![from]; + d.inputs[2].items = vec![to]; + } + let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].0, "occurrence.align"); + assert_eq!(commands[0].1["paths"], json!([[second]])); + for (command, params) in commands { + h.app.run(&command, params).unwrap(); + } + + let st = h.app.session.world_state(); + let b1 = st.body("Beam").unwrap().mesh().bounds(); + assert!((b1.min.x - 0.0).abs() < 1e-5 && (b1.max.x - 10.0).abs() < 1e-5, "{b1:?}"); + let b2 = st.body("Beam (Extrusion:2)").unwrap().mesh().bounds(); + assert!((b2.min.x - 10.0).abs() < 1e-5 && (b2.max.x - 70.0).abs() < 1e-5, "{b2:?}"); +} form_case!(remove, "solid.remove", []); form_case!(path_pattern, "solid.pattern.path", ["Type", "Object Type", "Quantity", "Spacing"]); form_case!(pipe, "solid.pipe", ["Diameter", "Wall", "Operation"]); @@ -1061,3 +1107,35 @@ fn every_selection_field_label_is_translated() { } assert!(missing.is_empty(), "selection fields without a message: {missing:#?}"); } + +#[test] +fn align_components_picks_the_placement_under_the_active_component_and_warns_when_shared() { + let mut h = Harness::new(); + let made = h.app.run("component.create", json!({"name": "Frame", "grounded": false})).unwrap(); + let (frame, a) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap()); + let bracket = h.app.run("component.create", json!({"name": "Bracket", "grounded": false})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 4, "body_name": "Plate"})).unwrap(); + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + let plate = h.app.session.world_state().bodies.first().map(|b| b.name.clone()).unwrap(); + + // With the design active, a click on the part inside Frame picks the Frame placement. + assert_eq!(occurrence_path_of_body(&h.app.session, &plate), Some(vec![a])); + // With that Frame placement active, the same click picks the part inside it. + h.app.run("component.activate", json!({"component": frame, "occurrence": a, "path": [a]})).unwrap(); + assert_eq!(occurrence_path_of_body(&h.app.session, &plate), Some(vec![a, bracket])); + assert!(!align_moves_shared(&h.app.session, &[Sel::Occurrence { path: vec![a, bracket] }]), "Frame is placed once"); + + // Once Frame is placed twice, the part's placement inside it is shared: the dialog says so. + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + h.app.run("occurrence.copy", json!({"component": frame, "translate": [0, 50, 0]})).unwrap(); + assert!(align_moves_shared(&h.app.session, &[Sel::Occurrence { path: vec![a, bracket] }])); + assert!(!align_moves_shared(&h.app.session, &[Sel::Occurrence { path: vec![a] }]), "a top-level placement is its own"); + + h.app.session.selection = vec![Sel::Occurrence { path: vec![a] }]; + h.app.start("solid.align"); + h.frames(4); + assert!(h.widget(ALIGN_SHARED_WARNING).is_none(), "no warning for a top-level pick"); + h.app.dialog.as_mut().unwrap().inputs[0].items = vec![Sel::Occurrence { path: vec![a, bracket] }]; + h.frames(4); + assert!(h.widget(ALIGN_SHARED_WARNING).is_some(), "the shared pick is called out"); +} diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 91d9df3cf..8e35dd277 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -83,6 +83,7 @@ const MOVES: &[&str] = &[ "joint.rack_pinion", "joint.screw", "joint.cam", + "occurrence.align", "parts.insert", "parts.fastener", ]; diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 744121ae1..793933d79 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -731,7 +731,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo }); ui.add(egui::Label::new(crate::i18n::tr("ui.emboss_wrap_note")).wrap()); } - Kind::Align { flip } => { + Kind::Align { flip, components } => { // Where on the picked face or edge to snap: as picked (a face turns to meet // the other, an edge at its middle), its centre, or a round one's centre. for (label, key) in [("From Snap", "from_snap"), ("To Snap", "to_snap")] { @@ -740,6 +740,12 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo }); } ui_kit::options(ui, "feature_options", &mut [("Flip", flip)]); + // A part inside a subassembly placed more than once sits where that shared + // definition says: aligning it moves it in every placement. + if *components && align_moves_shared(&app.session, d.inputs.first().map_or(&[], |i| i.items.as_slice())) { + let t = Tokens::get(); + ui.add(egui::Label::new(RichText::new(tr(ALIGN_SHARED_WARNING)).color(t.warning).size(t.font_small)).wrap()); + } } Kind::BoundaryFill { operation, cells, .. } => { form_row(ui, "Cells", |_| {}); diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index de6423aac..87cbe1357 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1901,6 +1901,32 @@ fn align_accepts_a_plane_click() { assert_eq!(p["to"], json!("origin")); } +#[test] +fn align_components_input_picks_occurrence_from_viewport_body_and_skips_root_body() { + let mut app = app_with(json!([])); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "RootBody"})).unwrap(); + let comp = app.run("component.create", json!({"name": "Extrusion", "grounded": false})).unwrap()["component"].as_u64().unwrap(); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 40, "corner": [20, 0, 0], "body_name": "Beam"})).unwrap(); + app.run("component.activate", json!({"component": "root"})).unwrap(); + let second = app.run("occurrence.copy", json!({"component": comp, "translate": [30, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap(); + + let mut d = start(&mut app, vec![], "solid.align"); + d.kind = Kind::Align { flip: false, components: true }; + d.inputs[0].label = "Components"; + d.active = 0; + + // Root-component bodies are not components. + let root_hit = crate::viewport::Hit::Face { body: "RootBody".into(), index: 0, point: Vec3::new(5.0, 5.0, 10.0) }; + assert_eq!(d.candidate(&app.session, &root_hit), None); + + // Clicking the second instance's body picks its exact occurrence path. + let inst_hit = crate::viewport::Hit::Face { body: "Beam (Extrusion:2)".into(), index: 0, point: Vec3::new(55.0, 5.0, 20.0) }; + let cand = d.candidate(&app.session, &inst_hit); + assert_eq!(cand, Some(Sel::Occurrence { path: vec![second] })); + d.pick(&app.session, cand.unwrap()); + assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![second] }]); +} + #[test] fn surface_dialogs_make_their_commands() { // A planar patch of a sketch's rectangle, then thickened; Edit Feature brings both back.