From b600293cfa7388b93efa52fa0718cf56d70bd603 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 22:42:36 +0100 Subject: [PATCH] arrays: the Key point option of a base point (F5) ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and REPlace) offered Key point but only said it was not available. It now asks for a key point on the source (or replacement) objects and takes their key point nearest the pick (an end point, midpoint, centre, quadrant, vertex or insertion point) as the base point; in ARRAYEDIT the source objects are searched as placed at the item picked. The JSON forms take `keyPoint`. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/array.rs | 71 ++++++++-- crates/engine/src/cmd/array/edit.rs | 49 ++++++- crates/engine/tests/it/array_key_point.rs | 155 ++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + docs/gaps.md | 5 +- docs/target-app-parity.md | 5 +- 6 files changed, 264 insertions(+), 22 deletions(-) create mode 100644 crates/engine/tests/it/array_key_point.rs diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 479b7873a..dbc845d57 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -25,6 +25,10 @@ mod edit; /// Most preview entities drawn while the array is edited. const PREVIEW_LIMIT: usize = 2000; +/// Most objects whose key points are searched for a Key point base point. +const MAX_KEY_OBJECTS: usize = 10_000; +/// The prompt after the Key point option of a base point. +const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point"; /// Keyword-only prompts: each typed token is matched on its own (no free text). const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true }; @@ -39,13 +43,13 @@ pub fn specs() -> Vec { CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect) .menu(&["Modify", "Array", "Rectangular Array"]) .params( - "{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", + "{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", ) .interactive(|_| Ok(Box::new(RectM::default()))), CommandSpec::new("arraypolar", "Polar Array", run_arraypolar) .menu(&["Modify", "Array", "Polar Array"]) .params( - "{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", + "{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", ) .interactive(|_| Ok(Box::new(PolarM::default()))), ] @@ -219,6 +223,32 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 { } /// The centre of the first object (the point a non-rotated polar copy is moved by). +/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points, +/// midpoints, centres, vertices, insertion points). `None` when they have none. +pub(crate) fn nearest_key_point<'a>(ents: impl Iterator, m: &Mat3, at: Vec2) -> Option { + if !at.is_finite() { + return None; + } + let mut best: Option<(Vec2, f64)> = None; + for e in ents.take(MAX_KEY_OBJECTS) { + let mut k = e.kind.clone(); + k.transform(m); + for g in k.grips().into_iter().filter(|g| g.is_finite()) { + let d = g.dist(at); + if best.is_none_or(|(_, bd)| d < bd) { + best = Some((g, d)); + } + } + } + best.map(|b| b.0) +} + +/// The key point of objects `hs` in the drawing nearest `at`. +pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result { + nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at) + .ok_or_else(|| other("The objects have no key point; specify a point.")) +} + fn first_center(d: &Drawing, hs: &[Handle]) -> Option { hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite()) } @@ -348,9 +378,10 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result { row_elevation: f64_or(p, "rowElevation", 0.0), }); let rs = f64_or(p, "rowSpacing", 1.0); - let base = match point_param(p, "base") { - Some(b) => b, - None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(), + let base = match (point_param(p, "keyPoint"), point_param(p, "base")) { + (Some(k), _) => key_point_of(s.doc()?, &hs, k)?, + (None, Some(b)) => b, + (None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(), }; let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs)); let associative = bool_or(p, "associative", assoc_default(s)); @@ -364,7 +395,10 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result { let rows = count_or(p, "rows", 1); let levels = count_or(p, "levels", 1); check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?; - let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c); + let base = match point_param(p, "keyPoint") { + Some(k) => key_point_of(s.doc()?, &hs, k)?, + None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c), + }; let row_spacing = f64_or(p, "rowSpacing", 1.0); let kind = ArrayKind::Polar(PolarArray { center: c - base, @@ -461,6 +495,8 @@ enum RStage { Main, Assoc, Base, + /// Base point: Key point (a grip of the source objects). + BaseKey, /// COUnt: columns, then rows. CountCols, CountRows, @@ -621,6 +657,7 @@ impl Interactive for RectM { .default("eXit"), Assoc => assoc_prompt(self.assoc), Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), CountCols | ColsCount => cols(), CountRows | RowsCount => rows(), SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]), @@ -670,10 +707,12 @@ impl Interactive for RectM { self.base = self.centroid; Main } - (Base, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - Base + (Base, Input::Keyword(_)) => BaseKey, + (BaseKey, Input::Point(p)) => { + self.base = key_point_of(s.doc()?, &self.objs, *p)?; + Main } + (BaseKey, Input::Enter) => Base, (CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? { Some(c) => { self.cols = c; @@ -816,6 +855,9 @@ enum PStage { Main, Assoc, Base, + /// Key point of the base point asked from the center prompt, or from the main prompt. + CenterBaseKey, + BaseKey, Items, Between, Fill, @@ -992,6 +1034,7 @@ impl Interactive for PolarM { match self.stage { Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]), CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), Main => Prompt::new("Select grip to edit array", Accept::POINT) .kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"]) .default("eXit"), @@ -1050,10 +1093,14 @@ impl Interactive for PolarM { self.base = None; if stage == CenterBase { Center } else { Main } } - (CenterBase | Base, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - stage + (CenterBase, Input::Keyword(_)) => CenterBaseKey, + (Base, Input::Keyword(_)) => BaseKey, + (CenterBaseKey | BaseKey, Input::Point(p)) => { + self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?); + if stage == CenterBaseKey { Center } else { Main } } + (CenterBaseKey, Input::Enter) => CenterBase, + (BaseKey, Input::Enter) => Base, (Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? { Some(c) => { self.items = c; diff --git a/crates/engine/src/cmd/array/edit.rs b/crates/engine/src/cmd/array/edit.rs index 21bf6b132..1708aeb21 100644 --- a/crates/engine/src/cmd/array/edit.rs +++ b/crates/engine/src/cmd/array/edit.rs @@ -18,7 +18,7 @@ use super::super::helpers::v3; use super::super::machines::{SelOutcome, SelectPhase, number}; use super::super::{CommandSpec, bad, bool_or, point_param, targets}; -use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no}; +use super::{KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, nearest_key_point, nesting, other, yes, yes_no}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub(super) fn specs() -> Vec { @@ -26,7 +26,7 @@ pub(super) fn specs() -> Vec { CommandSpec::new("arrayedit", "Edit Array", run_arrayedit) .menu(&["Modify", "Object", "Array"]) .params( - "{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}", + "{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}", ) .interactive(|_| Ok(Box::new(EditM::default()))), CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose) @@ -214,6 +214,16 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32) best.map(|b| b.0) } +/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as +/// placed at the item under `at` (within `tol`). +fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result { + let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?; + let (ins, blk, p) = array_of(d, h)?; + let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?; + let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy())); + nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at).ok_or_else(|| other("The source objects have no key point; specify a point.")) +} + /// Move the base point of array `h` to world point `base` without moving the items. fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> { let d = s.doc()?; @@ -342,6 +352,9 @@ fn close_source(s: &mut Session, save: bool) -> Result { // ---------------- JSON ---------------- +/// How far outside an item's extents a JSON `keyPoint` may be. +const KEY_POINT_TOLERANCE: f64 = 1e-6; + fn item_param(v: &Value) -> Option<(u32, u32, u32)> { let a = v.as_array()?; let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok()); @@ -458,7 +471,10 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { } if let Some(r) = p.get("replace").filter(|v| !v.is_null()) { let hs = targets(s, r)?; - let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()); + let base = match point_param(r, "keyPoint") { + Some(k) => key_point_of(s.doc()?, &hs, k)?, + None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()), + }; let name = block_from(s, h, &hs, base)?; let (_, _, mut a) = array_of(s.doc()?, h)?; match r.get("items") { @@ -476,6 +492,10 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { if let Some(b) = point_param(p, "base") { rebase(s, h, b)?; } + if let Some(k) = point_param(p, "keyPoint") { + let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?; + rebase(s, h, at)?; + } let (_, _, mut a) = array_of(s.doc()?, h)?; let before = a.clone(); apply_params(&mut a, p, &to_local)?; @@ -506,6 +526,8 @@ enum Stage { Select, Main, Base, + /// Base point: Key point (of the source objects). + BaseKey, ColsCount, ColsSpace, ColsTotal, @@ -523,6 +545,8 @@ enum Stage { /// REPlace: objects, their base point, then the items to replace. RepSelect, RepBase, + /// REPlace base point: Key point (of the replacement objects). + RepKey, RepItems, /// Source: the item whose objects are placed for editing. SourceItem, @@ -658,6 +682,7 @@ impl Interactive for EditM { .kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"]) .default("eXit"), Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()), ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]), ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)), @@ -686,6 +711,7 @@ impl Interactive for EditM { Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))), RepSelect => Prompt::new("Select replacement objects", Accept::SELECT), RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"), + RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT), RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]), SourceItem => Prompt::new("Select item in array", Accept::POINT), } @@ -745,10 +771,21 @@ impl Interactive for EditM { } Main } - (Base | RepBase, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - stage + (Base, Input::Keyword(_)) => BaseKey, + (RepBase, Input::Keyword(_)) => RepKey, + (BaseKey, Input::Point(p)) => { + let tol = s.pixel_size() * s.settings.pickbox; + let at = source_key_point(s.doc()?, h, *p, tol)?; + rebase(s, h, at)?; + Main } + (BaseKey, Input::Enter) => Base, + (RepKey, Input::Point(p)) => { + let base = key_point_of(s.doc()?, &self.rep_objs, *p)?; + self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?); + RepItems + } + (RepKey, Input::Enter) => RepBase, (ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? { Some(n) => { let n = super::count32(n); diff --git a/crates/engine/tests/it/array_key_point.rs b/crates/engine/tests/it/array_key_point.rs new file mode 100644 index 000000000..d903fd5a8 --- /dev/null +++ b/crates/engine/tests/it/array_key_point.rs @@ -0,0 +1,155 @@ +//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and +//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the +//! picked point as the base point; the JSON forms take `keyPoint`. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle}; +use cadcraft_engine::geom::Vec2; +use serde_json::json; + +fn source_line(s: &mut Session) -> String { + let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap(); + r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string() +} + +fn handle(v: &serde_json::Value) -> Handle { + Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap() +} + +/// The array's insertion point (its base point) and parameters. +fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) { + let d = s.doc().unwrap(); + let e = d.entity(h).unwrap(); + let EntityKind::Insert(i) = &e.kind else { panic!("not an array") }; + (i.insert.xy(), d.array_params(e).unwrap()) +} + +fn only_array(s: &Session) -> Handle { + let d = s.doc().unwrap(); + let arrays: Vec = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect(); + assert_eq!(arrays.len(), 1); + arrays[0] +} + +fn typed(s: &mut Session, inputs: &[&str]) { + for t in inputs { + s.cmdline(t).unwrap(); + } +} + +#[test] +fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() { + let mut s = Session::new(); + let l = source_line(&mut s); + let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap(); + assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9)); + let mut s = Session::new(); + let l = source_line(&mut s); + let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap(); + assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint"); +} + +#[test] +fn typed_key_points_at_arrayrect_and_arraypolar() { + let mut s = Session::new(); + source_line(&mut s); + typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]); + assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9)); + // Enter at the key point prompt goes back to the base point prompt. + let mut s = Session::new(); + source_line(&mut s); + typed(&mut s, &["arraypolar", "l", "", "b", "k"]); + assert!(s.current_prompt().unwrap().message.contains("key point")); + typed(&mut s, &[""]); + assert!(s.current_prompt().unwrap().message.contains("base point")); + typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]); + assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9)); +} + +#[test] +fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() { + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + // Near the start of the third item: the base point goes to (10, 0), the items stay. + s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap(); + let (at, p) = array(&s, h); + assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}"); + assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0)); + let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap(); + assert!(items.to_string().len() > 2); + let d = s.doc().unwrap(); + let mut starts: Vec<(i64, i64)> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)), + _ => None, + }) + .collect(); + starts.sort(); + assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]); + // Not on an item: refused. + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err()); + assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9)); + // Typed: Base point, Key point, a point on the second item near its end. + s.set_selection(vec![h]); + typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]); + assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9)); +} + +#[test] +fn replacement_objects_take_a_key_point_as_their_base_point() { + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone(); + // The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4. + s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap(); + s.execute("explode", &json!({"handles": [h.hex()]})).unwrap(); + let d = s.doc().unwrap(); + // The replaced item stays a reference to the replacement block. + let centres: Vec = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)), + _ => None, + }) + .flat_map(|(m, b)| { + b.entities + .iter() + .filter_map(move |e| match &e.kind { + EntityKind::Circle(c) => Some(m.apply(c.center.xy())), + _ => None, + }) + .collect::>() + }) + .collect(); + assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}"); +} + +#[test] +fn hostile_key_points_never_panic() { + let mut s = Session::new(); + let l = source_line(&mut s); + for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] { + let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp})); + let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp})); + } + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] { + let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp})); + let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}})); + } + // Typed key points far away or on nothing are refused without leaving the command broken. + s.set_selection(vec![h]); + typed(&mut s, &["arrayedit", "b", "k"]); + assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some()); + s.cancel(); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..3964c7249 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod annotate_options; mod annotative; mod arc_ctrl_direction; mod array_commands; +mod array_key_point; mod assoc_array; mod attdisp_attsync; mod attedit_prompts; diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..974579942 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (Key point base points: F5 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -28,7 +28,7 @@ do them first. | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | | F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | -| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | +| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click), levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | | F8 | TOLERANCE leftovers (feature control frames landed, #420: model, our own symbol drawing, DXF, command-line prompts, explode, grips): no Geometric Tolerance dialog, no LEADER/QLEADER tolerance annotation, no in-place editing of a frame's contents | `cmd/tolerance.rs` | Low-medium (mechanical) | 2–4 | | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | F5: the Key point option of a base point works in ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point, REPlace): the source (or replacement) objects' key point nearest the pick becomes the base point; JSON `keyPoint` | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..6947678a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (array Key point base points; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -147,7 +147,7 @@ presence: an option that prints "not available yet" doesn't count. | Area | Weight | Parity | Remaining (Opus 5.5 h) | Evidence and main gaps | Doc | |---|---:|---:|---|---|---| | Draw (2D) | 13% | 60% | 15–25 | ARC 11/11 methods, CIRCLE 6/6, RECTANG all options plus a centre construction mode (#1127), REVCLOUD, WIPEOUT, XLINE; PLINE arc options and SPLINE options done (#397, #408); MLINE, REGION and HELIX are objects (#510); isometric drafting (#556) | [gaps](gaps.md#features) | -| Modify | 15% | 50% | 40–60 | TRIM/EXTEND, OFFSET, ROTATE, PEDIT and SPLINEDIT options done (#397, #558, #559); associative arrays with ARRAYEDIT (#448), no array grips; MATCHPROP picker and Settings (#439) | [gaps](gaps.md#features) | +| Modify | 15% | 50% | 40–60 | TRIM/EXTEND, OFFSET, ROTATE, PEDIT and SPLINEDIT options done (#397, #558, #559); associative arrays with ARRAYEDIT (#448) and Key point base points, no array grips; MATCHPROP picker and Settings (#439) | [gaps](gaps.md#features) | | Geometry precision | 10% | 40% | 70–110 | exact for lines/arcs/circles; ellipse and spline intersections, offsets, closest points tessellated; absolute tolerances; polyline offset doesn't recompute bulges | [geometry-parity](geometry-parity.md) | | Layers and properties | 7% | 70% | 10–15 | Layer Properties Manager with filters, states, VP overrides; QSELECT; Quick Properties; transparency; linetype manager thin; 19 linetypes of ~45 | [gaps](gaps.md#features) | | Dimensions | 9% | 45% | 25–35 | all core DIM types and associativity; style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT, QDIM modes (#507) and TOLERANCE (#420); no DIMSTYLE manager dialog or smart DIM | [gaps](gaps.md#features) | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Modify row: array base points take a Key point of the source objects (ARRAYRECT, ARRAYPOLAR, ARRAYEDIT); parity percentages and hours not re-measured | | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured |