diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 5d0a1d4564..353aa0a39d 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -1,4 +1,5 @@ -//! Dynamic blocks made in another program, read from the data CADCraft keeps for them. +//! Dynamic blocks made in another program, read from the data CADCraft keeps for them, and +//! authored in CADCraft (`write`: the same objects, written). //! //! A dynamic block's behaviour lives in objects CADCraft does not write itself and keeps as //! [`Foreign`](crate::foreign::Foreign) data: the block's BLOCK_RECORD has an extension dictionary @@ -20,11 +21,17 @@ use crate::foreign::ForeignObject; use crate::{Drawing, Handle, RawTag}; mod apply; +mod copy; mod grips; +mod marks; mod reference; +mod write; pub use apply::{align_grip, drag_grip, grip_stops, set_property}; +pub use copy::{copy_definition, remap_handles, restore_definition}; pub use grips::{DynGrip, GripPart, GripShape, grips}; +pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; +pub use write::{ActionSpec, MAX_ACTION_ITEMS, ParamPoint, ParameterSpec, add_action, add_parameter, tag_elements}; /// Most objects one evaluation graph is read with. const MAX_NODES: usize = 10_000; diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs new file mode 100644 index 0000000000..6742c6f888 --- /dev/null +++ b/crates/doc/src/dynblock/copy.rs @@ -0,0 +1,225 @@ +//! Saving a dynamic block under another name (BSAVEAS): the copy gets its own evaluation graph, +//! made from the original's objects with new handles, and its own copies of the block's objects +//! (no two blocks share a handle), so references to either change as AutoCAD would change them. + +use std::collections::{HashMap, HashSet}; + +use crate::foreign::{ForeignExtra, ForeignObject}; +use crate::{Drawing, EntityKind, EntityStore, Handle, RawTag}; + +use super::write::{ETAG, dict_entry, guid, record_handle, strip_app}; +use super::{MAX_NODES, dynamic_block}; + +/// Most objects of one block's dynamic data that are copied. +const MAX_COPIED: usize = 8 * MAX_NODES; + +/// Group codes whose values are handles: the object's own (5), owners and pointers (330 to 369) +/// and 390 to 399. +fn is_handle_code(code: i32) -> bool { + code == 5 || (330..=369).contains(&code) || (390..=399).contains(&code) +} + +/// The owner of an object: its first 330 group outside the `{ACAD_REACTORS` ... `}` groups. +fn owner_of(o: &ForeignObject) -> Option { + let mut inside = false; + for t in &o.tags { + match t.code { + 102 => inside = t.value.starts_with('{'), + 330 if !inside => return Handle::parse_hex(&t.value), + _ => {} + } + } + None +} + +/// `root` and the objects it owns, directly or not (at most [`MAX_COPIED`]). +fn owned_subtree(d: &Drawing, root: Handle) -> Vec { + let mut children: HashMap> = HashMap::new(); + for o in &d.foreign.objects { + if let Some(owner) = owner_of(o) { + children.entry(owner).or_default().push(o.handle); + } + } + let mut out = vec![root]; + let mut seen: HashSet = HashSet::from([root]); + let mut at = 0; + while let Some(h) = out.get(at).copied() { + at += 1; + for c in children.get(&h).into_iter().flatten() { + if out.len() < MAX_COPIED && seen.insert(*c) { + out.push(*c); + } + } + } + out +} + +/// [`owned_subtree`], refused when it reaches [`MAX_COPIED`]: a copy of only part of it would keep +/// pointing at the original's objects. +fn whole_subtree(d: &Drawing, root: Handle) -> Result, String> { + let out = owned_subtree(d, root); + if out.len() >= MAX_COPIED { + return Err(format!("The dynamic block has {MAX_COPIED} or more objects; it can't be copied.")); + } + Ok(out) +} + +/// The handle `h` names, as `map` has it. +fn mapped(map: &HashMap, value: &str) -> Option { + Handle::parse_hex(value).and_then(|h| map.get(&h)).copied() +} + +/// Every handle in `tags` that `map` has, as the new one. +fn retarget(tags: &mut [RawTag], map: &HashMap) { + for t in tags.iter_mut().filter(|t| is_handle_code(t.code)) { + if let Some(n) = mapped(map, &t.value) { + t.value = n.hex(); + } + } +} + +/// The objects of `store` again with new handles (added to `map`). +fn rehandle(d: &mut Drawing, store: &EntityStore, map: &mut HashMap) -> EntityStore { + for e in store.iter() { + let n = d.new_handle(); + map.insert(e.handle, n); + } + remap_handles(store, map) +} + +/// The objects of `store` again with the handles `map` gives them: each one's element tag names +/// the object itself, and a hatch's sources are the new copies. +pub fn remap_handles(store: &EntityStore, map: &HashMap) -> EntityStore { + let mut out = EntityStore::new(); + for e in store.iter() { + let mut c = (**e).clone(); + c.handle = map.get(&e.handle).copied().unwrap_or(e.handle); + for t in c.common.xdata.iter_mut().filter(|t| t.code == 1005) { + if let Some(n) = mapped(map, &t.value) { + t.value = n.hex(); + } + } + if let EntityKind::Hatch(h) = &mut c.kind { + for l in &mut h.loops { + l.sources = l.sources.iter().map(|s| map.get(s).copied().unwrap_or(*s)).collect(); + } + } + out.push(c); + } + out +} + +/// The kept extras of the objects of `store` (reactors within the block; not their extension +/// dictionaries), for their new handles. +fn entity_extras(d: &Drawing, store: &EntityStore, map: &HashMap) -> Vec<(Handle, ForeignExtra)> { + store + .iter() + .filter_map(|e| { + let mut x = d.foreign.entities.get(&e.handle)?.clone(); + x.xdict = None; + x.reactors = x.reactors.iter().filter_map(|r| map.get(r).copied()).collect(); + Some((map.get(&e.handle).copied()?, x)) + }) + .collect() +} + +/// The applications whose record xdata make a block dynamic. +const DYNAMIC_APPS: [&str; 3] = ["AcDbDynamicBlockTrueName", "AcDbDynamicBlockGUID", ETAG]; + +/// Block `name`'s (upper case) dynamic data removed: the objects its extension dictionary owns +/// and its record's dynamic data. What a redefined block's old graph would point at is gone. +fn remove_definition(d: &mut Drawing, name: &str) { + let key = ("BLOCK_RECORD".to_string(), name.to_string()); + let Some(xdict) = d.foreign.records.get(&key).and_then(|x| x.xdict) else { return }; + let owned: HashSet = owned_subtree(d, xdict).into_iter().collect(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.retain(|o| !owned.contains(&o.handle)); + let empty = f.records.get_mut(&key).is_some_and(|x| { + x.xdict = None; + DYNAMIC_APPS.iter().for_each(|app| strip_app(&mut x.xdata, app)); + x.is_empty() + }); + if empty { + f.records.remove(&key); + } +} + +/// Block `name`'s dynamic data in `d` as `host` has it (BSAVEAS leaves the edited block as it +/// was: the editor's changes to its graph belong to the copy only). +pub fn restore_definition(d: &mut Drawing, host: &Drawing, name: &str) { + let name = name.trim().to_ascii_uppercase(); + remove_definition(d, &name); + let key = ("BLOCK_RECORD".to_string(), name); + let Some(record) = host.foreign.records.get(&key) else { return }; + let owned: HashSet = record.xdict.map(|x| owned_subtree(host, x)).unwrap_or_default().into_iter().collect(); + let objects: Vec = host.foreign.objects.iter().filter(|o| owned.contains(&o.handle)).cloned().collect(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.extend(objects); + f.records.insert(key, record.clone()); +} + +/// Block record xdata `xdata` with the dynamic block's true name and GUID replaced. +fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { + let mut app = String::new(); + for t in xdata { + match t.code { + 1001 => app = t.value.to_ascii_uppercase(), + 1000 if app == "ACDBDYNAMICBLOCKTRUENAME" => t.value = name.to_string(), + 1000 if app == "ACDBDYNAMICBLOCKGUID" => t.value = guid.to_string(), + _ => {} + } + } +} + +/// Make block `to` a copy of dynamic block `from` (BSAVEAS): `store`, the objects it is saved +/// with, get new handles; the copy has its own evaluation graph and objects, made from the +/// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes +/// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects +/// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`. +/// Refused, changing nothing, when `from` has too many objects to copy whole. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> Result, String> { + let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); + let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); + if from_name == to_name { + return Ok(HashMap::new()); + } + let source = d.foreign.records.get(&key(&from_name)).cloned(); + let owned = match source.as_ref().and_then(|s| s.xdict) { + Some(xdict) if dynamic_block(d, from).is_some() => Some(whole_subtree(d, xdict)?), + _ => None, + }; + remove_definition(d, &to_name); + let (Some(source), Some(owned)) = (source, owned) else { return Ok(HashMap::new()) }; + let Some(xdict) = source.xdict else { return Ok(HashMap::new()) }; + let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); + let owned_set: HashSet = owned.iter().copied().collect(); + let mut map: HashMap = owned.iter().map(|h| (*h, d.new_handle())).collect(); + let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h); + let new_record = record_handle(d, &to_name); + map.extend(old_record.map(|h| (h, new_record))); + let entities = rehandle(d, store, &mut map); + let extras = entity_extras(d, store, &map); + let copies: Vec = d + .foreign + .objects + .iter() + .filter(|o| owned_set.contains(&o.handle)) + .map(|o| { + let mut c = o.clone(); + retarget(&mut c.tags, &map); + c.handle = map.get(&o.handle).copied().unwrap_or(o.handle); + c + }) + .collect(); + let mut record = source; + record.xdict = map.get(&xdict).copied(); + let new_graph = graph.and_then(|g| map.get(&g).copied()).unwrap_or(new_record); + rename_in_xdata(&mut record.xdata, to.trim(), &guid(to.trim(), new_graph)); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.extend(copies); + f.records.insert(key(&to_name), record); + f.entities.extend(extras); + let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); + *store = entities; + Ok(made) +} diff --git a/crates/doc/src/dynblock/marks.rs b/crates/doc/src/dynblock/marks.rs new file mode 100644 index 0000000000..d969ba0367 --- /dev/null +++ b/crates/doc/src/dynblock/marks.rs @@ -0,0 +1,58 @@ +//! What the Block Editor shows of a dynamic block's parameters and actions: each one's +//! geometry and label, in block coordinates, for the editor to draw. + +use cadcraft_geom::Vec3; +use serde::Serialize; + +use super::{Cursor, ParameterKind, dynamic_block, section, sections}; +use crate::Drawing; + +/// One parameter or action as the Block Editor draws it. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum Mark { + /// A linear parameter: a dimension from `base` to `end`, its line `offset` to the left of + /// base → end, its label in the middle; arrows at the ends that have grips. + Linear { node: i32, base: Vec3, end: Vec3, offset: f64, label: String, base_grip: bool, end_grip: bool }, + /// A point parameter: a marker at `at` and its label at `label_at`. + Point { node: i32, at: Vec3, label_at: Vec3, label: String, grip: bool }, + /// Another parameter: its name at `at`. + Parameter { node: i32, at: Vec3, label: String }, + /// An action: a badge with its name at `at`. + Action { node: i32, at: Vec3, name: String }, +} + +/// Block `name`'s parameters and actions as the Block Editor draws them (empty when it has none). +pub fn marks(d: &Drawing, name: &str) -> Vec { + let Some(m) = dynamic_block(d, name) else { return Vec::new() }; + let mut out = Vec::new(); + for p in &m.parameters { + let tags = d.foreign.objects.iter().find(|o| o.handle == p.handle).map(|o| o.tags.as_slice()).unwrap_or_default(); + let secs = sections(tags); + let label = p.kind.label().unwrap_or(&p.element).to_string(); + let grip = |i: usize| p.grips.get(i).is_some_and(|g| *g != 0); + out.push(match &p.kind { + ParameterKind::Linear { base, end, .. } => { + // The label's offset (140) after its name and description (305, 306). + let mut c = Cursor::new(section(&secs, "AcDbBlockLinearParameter")); + c.next(306); + Mark::Linear { node: p.node, base: *base, end: *end, offset: c.real(140), label, base_grip: grip(0), end_grip: grip(1) } + } + ParameterKind::Point { at, .. } => { + let label_at = Cursor::new(section(&secs, "AcDbBlockPointParameter")).point(1011); + Mark::Point { node: p.node, at: *at, label_at, label, grip: grip(0) } + } + ParameterKind::Polar { base, .. } + | ParameterKind::Xy { base, .. } + | ParameterKind::Rotation { base, .. } + | ParameterKind::Alignment { base, .. } + | ParameterKind::Flip { base, .. } => Mark::Parameter { node: p.node, at: *base, label }, + ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } | ParameterKind::BasePoint { at } => { + Mark::Parameter { node: p.node, at: *at, label } + } + ParameterKind::Other { .. } => continue, + }); + } + out.extend(m.actions.iter().map(|a| Mark::Action { node: a.node, at: a.at, name: a.name.clone() })); + out +} diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs new file mode 100644 index 0000000000..847fac66cd --- /dev/null +++ b/crates/doc/src/dynblock/write.rs @@ -0,0 +1,622 @@ +//! Authoring dynamic blocks: adding parameters and actions to a block, written as the objects +//! the [reader](super::dynamic_block) reads (BPARAMETER, BACTION in the Block Editor). +//! +//! Everything lands in the block's kept [`Foreign`](crate::foreign::Foreign) data, laid out as +//! AutoCAD lays out its own (observed in files it saves): the BLOCK_RECORD's extension dictionary +//! gets an `ACAD_ENHANCEDBLOCK` evaluation graph and a purge preventer, and each parameter or +//! action is a node of the graph. A parameter brings its grips, each grip two location +//! components (its X and Y), and the graph's edges say what is evaluated after what: a +//! parameter before its location components and its actions, a grip before its parameter. +//! A graph read from a file is extended the same way. + +use cadcraft_geom::{Vec2, Vec3}; + +use crate::foreign::ForeignObject; +use crate::{Drawing, EntityStore, Handle, RawTag}; + +use super::{ParameterKind, dynamic_block}; + +/// The graph `AcDbEvalGraph` is extended only up to this many nodes. +const MAX_NODES: usize = super::MAX_NODES; + +/// Most frame points and selected objects one action is written with. +pub const MAX_ACTION_ITEMS: usize = 10_000; + +/// The application name of element tags: the xdata pairing a block's objects with their +/// copies in references. +pub(super) const ETAG: &str = "AcDbBlockRepETag"; + +/// The value AutoCAD gives a grip location component it hasn't evaluated yet (a linear +/// parameter's end grip). +const UNSET: f64 = 1.797_693_134_862_314e99; + +/// A parameter to add. +#[derive(Clone, Debug, PartialEq)] +pub enum ParameterSpec { + /// A distance from `base` to `end` (Distance1), its label `label_offset` from the line (to + /// its left, looking from base to end), with 0, 1 (end) or 2 grips. + Linear { base: Vec3, end: Vec3, label: Option, label_offset: f64, grips: u8 }, + /// A position (Position1), its label at `label_at`, with 0 or 1 grip. + Point { at: Vec3, label: Option, label_at: Vec3, grips: u8 }, +} + +/// Which point of a two-point parameter an action follows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ParamPoint { + Base, + #[default] + End, +} + +/// An action to add, following the parameter with graph id `parameter`. +#[derive(Clone, Debug, PartialEq)] +pub enum ActionSpec { + /// Moves the listed vertices of `vertices`' objects (inside `frame`, a rectangle's two corners + /// or a polygon) and the other selected objects whole. + Stretch { parameter: i32, point: ParamPoint, frame: Vec, selection: Vec, vertices: Vec<(Handle, Vec)>, at: Vec3 }, + /// Moves the selected objects. + Move { parameter: i32, point: ParamPoint, selection: Vec, at: Vec3 }, +} + +/// One node of the evaluation graph: its index, flags, graph id, object and the first and last +/// of its incoming and outgoing edges (edge indices, -1 for none). +#[derive(Clone, Debug, PartialEq)] +struct Node { + index: i32, + flags: i32, + id: i32, + handle: Handle, + links: [i32; 4], +} + +/// One edge: its index, flags, kind (1 from a parameter, 2 from a grip), the nodes it joins +/// (indices) and its neighbours in their lists: previous and next incoming of `to`, previous and +/// next outgoing of `from`, then one more link AutoCAD leaves at -1. +#[derive(Clone, Debug, PartialEq)] +struct Edge { + index: i32, + flags: i32, + kind: i32, + from: i32, + to: i32, + links: [i32; 5], +} + +/// An evaluation graph object being extended. +struct Graph { + handle: Handle, + /// Its groups before `100 AcDbEvalGraph`, as they were. + head: Vec, + nodes: Vec, + edges: Vec, +} + +fn tag(code: i32, value: impl ToString) -> RawTag { + RawTag { code, value: value.to_string() } +} + +fn real(code: i32, v: f64) -> RawTag { + tag(code, format!("{v:?}")) +} + +fn point(out: &mut Vec, code: i32, p: Vec3) { + out.extend([real(code, p.x), real(code + 10, p.y), real(code + 20, p.z)]); +} + +impl Graph { + /// The graph object `o` read back into nodes and edges, or `None` when its groups aren't + /// laid out as a graph (it is then left alone). + fn read(o: &ForeignObject) -> Option { + let at = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbEvalGraph"))?; + let head = o.tags.get(..at)?.to_vec(); + let body = o.tags.get(at + 1..)?; + let int = |t: Option<&RawTag>, code: i32| t.filter(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + let mut i = body.iter().position(|t| t.code != 96 && t.code != 97).unwrap_or(body.len()); + let (mut nodes, mut edges) = (Vec::new(), Vec::new()); + while body.get(i).is_some_and(|t| t.code == 91) { + if nodes.len() >= MAX_NODES { + return None; + } + let g = |k: usize| body.get(i + k); + let handle = g(3).filter(|t| t.code == 360).and_then(|t| Handle::parse_hex(&t.value))?; + let links = [int(g(4), 92)?, int(g(5), 92)?, int(g(6), 92)?, int(g(7), 92)?]; + nodes.push(Node { index: int(g(0), 91)?, flags: int(g(1), 93)?, id: int(g(2), 95)?, handle, links }); + i += 8; + } + while body.get(i).is_some_and(|t| t.code == 92) { + if edges.len() >= MAX_NODES.saturating_mul(16) { + return None; + } + let g = |k: usize| body.get(i + k); + let links = [int(g(5), 92)?, int(g(6), 92)?, int(g(7), 92)?, int(g(8), 92)?, int(g(9), 92)?]; + edges.push(Edge { index: int(g(0), 92)?, flags: int(g(1), 93)?, kind: int(g(2), 94)?, from: int(g(3), 91)?, to: int(g(4), 91)?, links }); + i += 10; + } + // Anything after the edges is a layout this doesn't know. + if i != body.len() { + return None; + } + Some(Graph { handle: o.handle, head, nodes, edges }) + } + + /// A new, empty graph owned by dictionary `dict`. + fn new(handle: Handle, dict: Handle) -> Graph { + let head = vec![tag(5, handle.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; + Graph { handle, head, nodes: Vec::new(), edges: Vec::new() } + } + + fn tags(&self) -> Vec { + let mut out = self.head.clone(); + out.push(tag(100, "AcDbEvalGraph")); + out.push(tag(96, self.nodes.len())); + out.push(tag(97, self.nodes.len())); + for n in &self.nodes { + out.extend([tag(91, n.index), tag(93, n.flags), tag(95, n.id), tag(360, n.handle.hex())]); + out.extend(n.links.iter().map(|l| tag(92, l))); + } + for e in &self.edges { + out.extend([tag(92, e.index), tag(93, e.flags), tag(94, e.kind), tag(91, e.from), tag(91, e.to)]); + out.extend(e.links.iter().map(|l| tag(92, l))); + } + out + } + + /// The next free graph id. + fn next_id(&self) -> i32 { + self.nodes.iter().map(|n| n.id).max().unwrap_or(0).saturating_add(1) + } + + /// Add node `id` for object `handle`; its index. + fn add_node(&mut self, id: i32, handle: Handle) -> i32 { + let index = self.nodes.iter().map(|n| n.index).max().map_or(0, |m| m.saturating_add(1)); + self.nodes.push(Node { index, flags: 32, id, handle, links: [-1; 4] }); + index + } + + fn node_mut(&mut self, index: i32) -> Option<&mut Node> { + self.nodes.iter_mut().find(|n| n.index == index) + } + + fn edge_mut(&mut self, index: i32) -> Option<&mut Edge> { + self.edges.iter_mut().find(|e| e.index == index) + } + + /// The index of the node with graph id `id`. + fn index_of(&self, id: i32) -> Option { + self.nodes.iter().find(|n| n.id == id).map(|n| n.index) + } + + /// Add an edge of `kind` from node index `from` to `to`, last in both nodes' lists. + fn link(&mut self, from: i32, to: i32, kind: i32) { + let index = self.edges.iter().map(|e| e.index).max().map_or(0, |m| m.saturating_add(1)); + let last_out = self.node_mut(from).map_or(-1, |n| n.links[3]); + let last_in = self.node_mut(to).map_or(-1, |n| n.links[1]); + self.edges.push(Edge { index, flags: 0, kind, from, to, links: [last_in, -1, last_out, -1, -1] }); + if let Some(e) = self.edge_mut(last_out) { + e.links[3] = index; + } + if let Some(e) = self.edge_mut(last_in) { + e.links[1] = index; + } + if let Some(n) = self.node_mut(from) { + if n.links[2] < 0 { + n.links[2] = index; + } + n.links[3] = index; + } + if let Some(n) = self.node_mut(to) { + if n.links[0] < 0 { + n.links[0] = index; + } + n.links[1] = index; + } + } +} + +/// The groups every node object starts with: its handle, owner and graph id. +fn node_head(h: Handle, graph: Handle, id: i32) -> Vec { + vec![tag(5, h.hex()), tag(330, graph.hex()), tag(100, "AcDbEvalExpr"), tag(90, id), tag(98, 33), tag(99, 301)] +} + +/// [`node_head`] and the block element: its name and a flag AutoCAD writes (`1071`). +fn element_head(h: Handle, graph: Handle, id: i32, name: &str, flag: i32) -> Vec { + let mut out = node_head(h, graph, id); + out.extend([tag(100, "AcDbBlockElement"), tag(300, name), tag(98, 33), tag(99, 301), tag(1071, flag)]); + out +} + +/// The block being authored: its record's kept data, graph and the objects made so far. +struct Author<'a> { + d: &'a mut Drawing, + record: String, + graph: Graph, + /// New objects to add after the graph. + new: Vec, + /// Classes the new objects need: (DXF name, C++ name). + classes: Vec<(&'static str, &'static str)>, +} + +impl<'a> Author<'a> { + /// Open block `name`'s graph for authoring, making the dictionary, graph and purge preventer + /// when it has none. + fn open(d: &'a mut Drawing, name: &str) -> Result, String> { + let record = name.trim().to_ascii_uppercase(); + if record.is_empty() || record.starts_with('*') { + return Err(format!("\"{name}\" can't have parameters or actions.")); + } + let key = ("BLOCK_RECORD".to_string(), record.clone()); + let xdict = d.foreign.records.get(&key).and_then(|x| x.xdict); + let mut new = Vec::new(); + let mut classes = Vec::new(); + let graph = match xdict.and_then(|x| dict_entry(d, x, "ACAD_ENHANCEDBLOCK")) { + Some(g) => { + let o = d.foreign.objects.iter().find(|o| o.handle == g).ok_or("The block's evaluation graph is missing.")?; + Graph::read(o).ok_or("The block's evaluation graph can't be extended.")? + } + None => { + let rec = record_handle(d, &record); + let dict = match xdict { + Some(x) if d.foreign.objects.iter().any(|o| o.handle == x) => x, + _ => { + let x = d.new_handle(); + let tags = vec![tag(5, x.hex()), tag(330, rec.hex()), tag(100, "AcDbDictionary"), tag(280, 1), tag(281, 1)]; + new.push(ForeignObject { handle: x, kind: "DICTIONARY".into(), tags }); + x + } + }; + let (g, pp) = (d.new_handle(), d.new_handle()); + let mut tags = vec![tag(5, pp.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; + tags.extend([tag(100, "AcDbDynamicBlockPurgePreventer"), tag(70, 1)]); + new.push(ForeignObject { handle: pp, kind: "ACDB_DYNAMICBLOCKPURGEPREVENTER_VERSION".into(), tags }); + classes.push(("ACAD_EVALUATION_GRAPH", "AcDbEvalGraph")); + classes.push(("ACDB_DYNAMICBLOCKPURGEPREVENTER_VERSION", "AcDbDynamicBlockPurgePreventer")); + let f = std::sync::Arc::make_mut(&mut d.foreign); + // The dictionary's entries: in the new dictionary, or added to the one it had. + let entries = + [tag(3, "ACAD_ENHANCEDBLOCK"), tag(360, g.hex()), tag(3, "AcDbDynamicBlockRoundTripPurgePreventer"), tag(360, pp.hex())]; + match new.iter_mut().find(|o| o.handle == dict) { + Some(o) => o.tags.extend(entries), + None => { + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == dict) { + o.tags.extend(entries); + } + } + } + let extra = f.records.entry(key).or_default(); + extra.xdict = Some(dict); + if !extra.xdata.iter().any(|t| t.code == 1001 && t.value.eq_ignore_ascii_case("AcDbDynamicBlockTrueName")) { + extra.xdata.extend([tag(1001, "AcDbDynamicBlockTrueName"), tag(1000, name.trim())]); + extra.xdata.extend([tag(1001, "AcDbDynamicBlockGUID"), tag(1000, guid(name.trim(), g))]); + } + Graph::new(g, dict) + } + }; + Ok(Author { d, record, graph, new, classes }) + } + + /// Write the graph and the new objects back into the drawing's kept data. + fn finish(self) { + let Author { d, graph, new, classes, .. } = self; + let f = std::sync::Arc::make_mut(&mut d.foreign); + let tags = graph.tags(); + match f.objects.iter_mut().find(|o| o.handle == graph.handle) { + Some(o) => o.tags = tags, + None => f.objects.push(ForeignObject { handle: graph.handle, kind: "ACAD_EVALUATION_GRAPH".into(), tags }), + } + f.objects.extend(new); + for (name, cpp) in classes { + if !f.classes.iter().any(|c| c.iter().any(|t| t.code == 1 && t.value.eq_ignore_ascii_case(name))) { + f.classes.push(vec![tag(1, name), tag(2, cpp), tag(3, "ObjectDBX Classes"), tag(90, 1153), tag(91, 0), tag(280, 0), tag(281, 0)]); + } + } + } + + fn class(&mut self, name: &'static str, cpp: &'static str) { + if !self.classes.iter().any(|(n, _)| *n == name) { + self.classes.push((name, cpp)); + } + } + + /// Add object `kind` with `tags` as graph node `id`; its index. + fn node(&mut self, kind: &str, h: Handle, id: i32, tags: Vec) -> i32 { + self.new.push(ForeignObject { handle: h, kind: kind.into(), tags }); + self.graph.add_node(id, h) + } + + /// A grip at `at` with its two location components (`x_name`, `y_name`, both valued + /// `value`), linked after parameter node `param`: the grip's graph id. + fn grip(&mut self, param: i32, at: Vec3, name: &str, [x_name, y_name]: [&str; 2], value: f64, linear: Option) -> i32 { + let (gh, gid) = (self.d.new_handle(), self.graph.next_id()); + let (xid, yid) = (gid.saturating_add(1), gid.saturating_add(2)); + let mut tags = element_head(gh, self.graph.handle, gid, name, 0); + tags.extend([tag(100, "AcDbBlockGrip"), tag(91, xid), tag(92, yid)]); + point(&mut tags, 1010, at); + tags.extend([tag(280, 1), tag(93, -1)]); + let kind = match linear { + Some(dir) => { + tags.extend([tag(100, "AcDbBlockLinearGrip"), real(140, dir.x), real(141, dir.y), real(142, dir.z)]); + self.class("BLOCKLINEARGRIP", "AcDbBlockLinearGrip"); + "BLOCKLINEARGRIP" + } + None => { + tags.push(tag(100, "AcDbBlockXYGrip")); + self.class("BLOCKXYGRIP", "AcDbBlockXYGrip"); + "BLOCKXYGRIP" + } + }; + let grip = self.node(kind, gh, gid, tags); + self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); + // Each component names the parameter it reads (its graph id). + let owner = self.graph.nodes.iter().find(|n| n.index == param).map_or(0, |n| n.id); + for (id, comp) in [(xid, x_name), (yid, y_name)] { + let h = self.d.new_handle(); + let mut tags = node_head(h, self.graph.handle, id); + tags.extend([tag(1, ""), tag(70, 40), real(140, value), tag(100, "AcDbBlockGripExpr"), tag(91, owner), tag(300, comp)]); + let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); + self.graph.link(param, c, 1); + } + self.graph.link(grip, param, 2); + gid + } + + /// An element name not used in the block yet: `base`, else `base` and the lowest free number. + fn element_name(&self, base: &str) -> String { + let used: Vec = dynamic_block(self.d, &self.record) + .map(|m| m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect()) + .unwrap_or_default(); + let free = |n: &str| !used.iter().any(|u| u.eq_ignore_ascii_case(n)); + if free(base) { + return base.to_string(); + } + (1..).map(|i| format!("{base}{i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) + } +} + +/// The handle the kept data uses for block `record`'s BLOCK_RECORD (a new one, registered, +/// when none refers to it yet). +pub(super) fn record_handle(d: &mut Drawing, record: &str) -> Handle { + if let Some(h) = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && n == record).map(|(h, _)| *h) { + return h; + } + let h = d.new_handle(); + std::sync::Arc::make_mut(&mut d.foreign).targets.insert(h, ("BLOCK_RECORD".to_string(), record.to_string())); + h +} + +/// A GUID for block `name`'s dynamic data, made from its name and graph (stable for a drawing). +pub(super) fn guid(name: &str, graph: Handle) -> String { + // FNV-1a over the name and handle, spread over 128 bits. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut word = || { + for b in name.bytes().chain(graph.0.to_le_bytes()) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h + }; + let (a, b) = (word(), word()); + format!("{{{:08X}-{:04X}-{:04X}-{:04X}-{:012X}}}", a >> 32, (a >> 16) & 0xFFFF, a & 0xFFFF, b >> 48, b & 0xFFFF_FFFF_FFFF) +} + +/// A property name not used by the block's parameters yet: `prefix` and the lowest number from 1. +fn free_label(d: &Drawing, record: &str, prefix: &str) -> String { + let used: Vec = + dynamic_block(d, record).map(|m| m.parameters.iter().flat_map(|p| p.kind.label().map(str::to_string)).collect()).unwrap_or_default(); + (1..).map(|i| format!("{prefix}{i}")).find(|n| !used.iter().any(|u| u.eq_ignore_ascii_case(n))).unwrap_or_else(|| format!("{prefix}1")) +} + +fn finite(p: Vec3) -> bool { + p.x.is_finite() && p.y.is_finite() && p.z.is_finite() +} + +/// Add parameter `spec` to block `name` (any case); its graph id. +pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Result { + match spec { + ParameterSpec::Linear { base, end, label, label_offset, grips } => { + // Two finite points far apart can still be infinitely far from each other, and the + // direction is written into the grips. + if !finite(*base) || !finite(*end) || !finite(*end - *base) || !label_offset.is_finite() { + return Err("Invalid point.".into()); + } + if (*end - *base).len() <= 1e-9 { + return Err("The endpoint must differ from the start point.".into()); + } + if *grips > 2 { + return Err("A linear parameter has 0, 1 or 2 grips.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Distance")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Linear"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let dir = *end - *base; + let end_grip = if *grips >= 1 { a.grip(param, *end, "End Grip", ["UpdatedEndX", "UpdatedEndY"], UNSET, Some(dir)) } else { 0 }; + let base_grip = if *grips >= 2 { a.grip(param, *base, "Base Grip", ["UpdatedBaseX", "UpdatedBaseY"], 0.0, Some(-dir)) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 2 { 32 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock2PtParameter")]); + point(&mut tags, 1010, *base); + point(&mut tags, 1011, *end); + tags.extend([tag(170, 4), tag(91, base_grip), tag(91, end_grip), tag(91, 0), tag(91, 0)]); + // Each grip's connections: a count, the grip and the value it changes. + let connections = [ + (171, 92, 301, base_grip, "DisplacementX"), + (172, 93, 302, base_grip, "DisplacementY"), + (173, 94, 303, end_grip, "DisplacementX"), + (174, 95, 304, end_grip, "DisplacementY"), + ]; + for (count, id_code, name_code, grip, value) in connections { + if grip == 0 { + tags.push(tag(count, 0)); + } else { + tags.extend([tag(count, 1), tag(id_code, grip), tag(name_code, value)]); + } + } + tags.extend([tag(177, 0), tag(100, "AcDbBlockLinearParameter"), tag(305, &label), tag(306, ""), real(140, *label_offset), tag(307, "")]); + tags.extend([tag(96, 1), real(141, 0.0), real(142, 0.0), real(143, 0.0), tag(175, 0)]); + // The parameter's object goes before its grips, as AutoCAD lists them. + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKLINEARPARAMETER".into(), tags }); + a.class("BLOCKLINEARPARAMETER", "AcDbBlockLinearParameter"); + a.finish(); + Ok(id) + } + ParameterSpec::Point { at, label, label_at, grips } => { + if !finite(*at) || !finite(*label_at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A point parameter has 0 or 1 grip.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Position")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Point"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, None) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.push(tag(93, grip)); + if grip == 0 { + tags.extend([tag(170, 0), tag(171, 0)]); + } else { + tags.extend([tag(170, 1), tag(91, grip), tag(301, "DisplacementX"), tag(171, 1), tag(92, grip), tag(302, "DisplacementY")]); + } + tags.extend([tag(100, "AcDbBlockPointParameter"), tag(303, &label), tag(304, "")]); + point(&mut tags, 1011, *label_at); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKPOINTPARAMETER".into(), tags }); + a.class("BLOCKPOINTPARAMETER", "AcDbBlockPointParameter"); + a.finish(); + Ok(id) + } + } +} + +/// Add action `spec` to block `name` (any case); its graph id. The parameter it follows must be +/// one the action can follow (a linear or point parameter for a stretch or move). +pub fn add_action(d: &mut Drawing, name: &str, spec: &ActionSpec) -> Result { + let (parameter, point_of, selection, at) = match spec { + ActionSpec::Stretch { parameter, point, selection, at, .. } | ActionSpec::Move { parameter, point, selection, at } => { + (*parameter, *point, selection, *at) + } + }; + if !finite(at) { + return Err("Invalid point.".into()); + } + if selection.is_empty() { + return Err("An action needs objects to act on.".into()); + } + if selection.len() > MAX_ACTION_ITEMS { + return Err(format!("An action acts on at most {MAX_ACTION_ITEMS} objects.")); + } + let m = dynamic_block(d, name).ok_or("The block has no parameters; add one first (BPARAMETER).")?; + let p = m.parameters.iter().find(|p| p.node == parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let connections = match (&p.kind, point_of) { + (ParameterKind::Linear { .. }, ParamPoint::End) => ["EndXDelta", "EndYDelta"], + (ParameterKind::Linear { .. }, ParamPoint::Base) => ["BaseXDelta", "BaseYDelta"], + (ParameterKind::Point { .. }, _) => ["XDelta", "YDelta"], + _ => return Err(format!("A {} can't be followed by this action yet.", p.element)), + }; + let mut a = Author::open(d, name)?; + let pindex = a.graph.index_of(parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let (kind, cpp, element) = match spec { + ActionSpec::Stretch { .. } => ("BLOCKSTRETCHACTION", "AcDbBlockStretchAction", a.element_name("Stretch")), + ActionSpec::Move { .. } => ("BLOCKMOVEACTION", "AcDbBlockMoveAction", a.element_name("Move")), + }; + let mut tags = element_head(h, a.graph.handle, id, &element, 0); + tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, selection.len())]); + tags.extend(selection.iter().map(|s| tag(330, s.hex()))); + point(&mut tags, 1010, at); + tags.push(tag(100, if kind == "BLOCKSTRETCHACTION" { "AcDbBlockStretchAction" } else { "AcDbBlockMoveAction" })); + tags.extend([tag(92, parameter), tag(301, connections[0]), tag(93, parameter), tag(302, connections[1])]); + if let ActionSpec::Stretch { frame, vertices, .. } = spec { + if frame.len() < 2 || frame.len() > MAX_ACTION_ITEMS || frame.iter().any(|p| !p.is_finite()) { + return Err("A stretch frame needs two corners or a polygon.".into()); + } + if vertices.len() > MAX_ACTION_ITEMS || vertices.iter().map(|(_, v)| v.len()).sum::() > MAX_ACTION_ITEMS.saturating_mul(16) { + return Err("Too many vertices in the stretch frame.".into()); + } + tags.push(tag(72, frame.len())); + for p in frame { + tags.extend([real(1011, p.x), real(1021, p.y)]); + } + tags.push(tag(73, vertices.len())); + for (h, idx) in vertices { + tags.extend([tag(331, h.hex()), tag(74, idx.len())]); + tags.extend(idx.iter().map(|i| tag(94, i))); + } + tags.push(tag(75, 0)); + } + tags.extend([real(140, 1.0), real(141, 0.0), tag(280, 0)]); + let node = a.node(kind, h, id, tags); + a.graph.link(pindex, node, 1); + a.class(kind, cpp); + a.finish(); + Ok(id) +} + +/// Give every object of `store`, block `name`'s objects, an element tag (`AcDbBlockRepETag` +/// xdata: `1070 1`, `1071` tag, `1005` the object itself) when it has none or has another +/// object's (a copy), and keep the next free tag on the block's record, as AutoCAD does. Only for +/// blocks with dynamic data. +pub fn tag_elements(d: &mut Drawing, name: &str, store: &mut EntityStore) { + let key = ("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()); + if dynamic_block(d, name).is_none() { + return; + } + // The tag an object carries, if it is its own. + let own = |xd: &[RawTag], h: Handle| -> Option { + let at = xd.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ETAG))?; + let app: Vec<&RawTag> = xd.iter().skip(at + 1).take_while(|t| t.code != 1001).collect(); + let mine = app.iter().find(|t| t.code == 1005).and_then(|t| Handle::parse_hex(&t.value)) == Some(h); + app.iter().find(|t| t.code == 1071).and_then(|t| t.value.trim().parse().ok()).filter(|_| mine) + }; + let mut seen = std::collections::HashSet::new(); + let mut retag = Vec::new(); + for e in store.iter() { + match own(&e.common.xdata, e.handle) { + Some(t) if seen.insert(t) => {} + _ => retag.push(e.handle), + } + } + let record_next = d.foreign.records.get(&key).and_then(|x| { + let at = x.xdata.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ETAG))?; + x.xdata.iter().skip(at + 1).take_while(|t| t.code != 1001).find(|t| t.code == 1071).and_then(|t| t.value.trim().parse::().ok()) + }); + let mut next = seen.iter().max().map_or(0, |m| m.saturating_add(1)).max(record_next.unwrap_or(0)); + for h in retag { + let t = next; + next = next.saturating_add(1); + store.modify(h, |e| { + strip_app(&mut e.common.xdata, ETAG); + e.common.xdata.extend([tag(1001, ETAG), tag(1070, 1), tag(1071, t), tag(1005, h.hex())]); + }); + } + let f = std::sync::Arc::make_mut(&mut d.foreign); + let x = f.records.entry(key).or_default(); + strip_app(&mut x.xdata, ETAG); + x.xdata.extend([tag(1001, ETAG), tag(1070, 1), tag(1071, next)]); +} + +/// Remove application `app`'s xdata from `xd`. +pub(super) fn strip_app(xd: &mut Vec, app: &str) { + let Some(at) = xd.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(app)) else { return }; + let end = xd.iter().skip(at + 1).position(|t| t.code == 1001).map_or(xd.len(), |n| at + 1 + n); + xd.drain(at..end); +} + +/// The object entry `key` of dictionary `dict` names. +pub(super) fn dict_entry(d: &Drawing, dict: Handle, key: &str) -> Option { + let o = d.foreign.objects.iter().find(|o| o.handle == dict)?; + let mut tags = o.tags.iter(); + while let Some(t) = tags.next() { + if t.code == 3 && t.value.eq_ignore_ascii_case(key) { + return tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value)); + } + } + None +} diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 0ce4ca3934..1d625ad2db 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -103,6 +103,27 @@ fn refers_to(d: &Drawing, store: &EntityStore, name: &str) -> bool { } impl BlockEdit { + /// The block's base point, which is the editor's origin. + pub fn base(&self) -> Vec2 { + self.base + } + + /// The edited block's parameters and actions as the editor draws them, in the editor's + /// coordinates (`editor` is the editor's drawing). + pub fn marks(&self, editor: &Drawing) -> Vec { + use cadcraft_doc::dynblock::Mark; + let off = self.base.to3(0.0); + let mut out = cadcraft_doc::dynblock::marks(editor, &self.name); + for m in &mut out { + match m { + Mark::Linear { base, end, .. } => (*base, *end) = (*base - off, *end - off), + Mark::Point { at, label_at, .. } => (*at, *label_at) = (*at - off, *label_at - off), + Mark::Parameter { at, .. } | Mark::Action { at, .. } => *at = *at - off, + } + } + out + } + /// The editor's objects in block coordinates, ready to be the block's: unchanged objects are /// the block's own, the others are moved back from the editor's origin to the base point. fn block_objects(&self, editor: &Drawing) -> EntityStore { @@ -132,12 +153,22 @@ impl BlockEdit { /// The drawing with the editor's objects saved into block `name` (the edited block, or a new /// name for BSAVEAS), from `editor`, the editor's drawing. pub fn compose(&self, editor: &Drawing, name: &str) -> Result { + self.compose_mapped(editor, name).map(|(d, _)| d) + } + + /// [`BlockEdit::compose`], and the handles the saved objects got when a dynamic block is saved + /// under another name (they are a copy's, with a graph of their own), by their old ones. + pub fn compose_mapped( + &self, + editor: &Drawing, + name: &str, + ) -> Result<(Drawing, std::collections::HashMap)> { // The drawing itself: the editor's drawing is the drawing. if self.current { if !name.eq_ignore_ascii_case(CURRENT_DRAWING) { return Err(EngineError::Other("The current drawing can't be saved as a block from the Block Editor; use WBLOCK or BLOCK.".into())); } - return Ok(editor.clone()); + return Ok((editor.clone(), std::collections::HashMap::new())); } if refers_to(editor, &editor.model, name) { return Err(EngineError::Other(format!("Block \"{name}\" can't contain a reference to itself."))); @@ -170,9 +201,21 @@ impl BlockEdit { } b.base.x = self.base.x; b.base.y = self.base.y; + let mut entities = entities; + // Saved under another name, a dynamic block's copy has its own graph and objects; the + // edited block stays as the drawing has it (the editor's changes to its graph are the + // copy's). + let mut remap = std::collections::HashMap::new(); + if !name.eq_ignore_ascii_case(&self.name) { + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities).map_err(EngineError::Other)?; + cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); + } + // A dynamic block's objects carry element tags, which its references' copies are paired + // with; objects added in the editor get theirs here. + cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); b.entities = entities; d.blocks.insert(key, Arc::new(b)); - Ok(d) + Ok((d, remap)) } } @@ -290,7 +333,7 @@ impl DocState { pub fn save_block_editor(&mut self, as_name: Option<&str>) -> Result<()> { let Some(be) = &self.block_edit else { return Err(EngineError::Other("The Block Editor is not open.".into())) }; let name = as_name.unwrap_or(&be.name).to_string(); - let d = be.compose(&self.doc, &name)?; + let (d, remap) = be.compose_mapped(&self.doc, &name)?; let original = d.block(&name).map(|b| b.entities.clone()).unwrap_or_default(); let name = d.block(&name).map(|b| b.name.clone()).unwrap_or(name); // When BSAVEAS saves the block under another name, the editor's drawing and each undo and @@ -305,10 +348,23 @@ impl DocState { restore_saved_definition(editor, &d, &was); editor.blocks.retain(|k, _| !k.eq_ignore_ascii_case(&name)); editor.blocks.insert(name.clone(), b.clone()); + // A dynamic block's copy: the editor edits it from here on, with its graph and + // the handles its objects got. + if !remap.is_empty() { + editor.foreign = d.foreign.clone(); + editor.model = cadcraft_doc::dynblock::remap_handles(&editor.model, &remap); + } }; reconcile(&mut self.doc); - for step in self.undo.iter_mut().chain(self.redo.iter_mut()) { - reconcile(&mut step.doc); + if remap.is_empty() { + for step in self.undo.iter_mut().chain(self.redo.iter_mut()) { + reconcile(&mut step.doc); + } + } else { + // Older steps hold the handles and graph from before the copy; they can't be + // remapped consistently, so the copy starts a new history. + self.undo.clear(); + self.redo.clear(); } } let editor = self.doc.clone(); diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 181aacd287..802a81a827 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -19,6 +19,7 @@ use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Ori mod attdef; pub(crate) mod attedit; +mod bauthor; mod burst; mod description; mod dyngrip; @@ -103,6 +104,7 @@ pub fn specs() -> Vec { .chain(refedit::specs()) .chain(xclip::specs()) .chain(bedit::specs()) + .chain(bauthor::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs new file mode 100644 index 0000000000..7de433e3b7 --- /dev/null +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -0,0 +1,662 @@ +//! BPARAMETER and BACTION: authoring a dynamic block in the Block Editor. A parameter is a +//! property references to the block can change (a distance, a position); an action is what +//! changing it does to the block's objects (stretch them, move them). Both are written into the +//! block's dynamic data ([`cadcraft_doc::dynblock::add_parameter`], [`add_action`]) as AutoCAD +//! writes its own, so the block works as a dynamic block here and in AutoCAD. Only while the +//! Block Editor is open on a block; points are in the editor's coordinates (the block's base point +//! at the origin). + +use cadcraft_doc::dynblock::{ActionSpec, Mark, ParamPoint, ParameterSpec, add_action, add_parameter, marks}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +use crate::cmd::curves::{KW, handle_value}; +use crate::cmd::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, point_param, points_param, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("bparameter", "Parameter", run_bparameter) + .alias(&["-bparameter"]) + .params( + "{type: \"linear\"|\"point\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; label?: property name (default Distance1/Position1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, default 1)} → {node, element, label} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BparameterM::default()))), + CommandSpec::new("baction", "Action", run_baction) + .alias(&["-baction"]) + .params( + "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\", point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BactionM::default()))), + ] +} + +/// The Block Editor is open on a block (parameters and actions belong to a block). +fn authoring(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Parameters and actions can be added to a block only; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The block being edited and where its base point is (the editor's origin). +fn editing(s: &Session) -> Result<(String, Vec2)> { + authoring(s).map_err(EngineError::Other)?; + let st = s.state()?; + let be = st.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + Ok((be.name.clone(), be.base())) +} + +fn to_block(p: Vec2, base: Vec2) -> Vec3 { + (p + base).to3(0.0) +} + +fn grips_param(cmd: &str, p: &Value, most: u8, default: u8) -> Result { + match p.get("grips") { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_u64().and_then(|g| u8::try_from(g).ok()).filter(|g| *g <= most).ok_or_else(|| bad(cmd, format!("`grips` is 0 to {most}"))), + } +} + +/// How far `at` is to the left of the line from `a` to `b` (negative: to its right). +fn offset_of(a: Vec2, b: Vec2, at: Vec2) -> f64 { + let d = b - a; + let len = d.len(); + if len <= 1e-12 { 0.0 } else { (d.x * (at.y - a.y) - d.y * (at.x - a.x)) / len } +} + +fn run_bparameter(s: &mut Session, p: &Value) -> Result { + let (block, base) = editing(s)?; + let label = str_param(p, "label").map(str::trim).filter(|l| !l.is_empty()).map(str::to_string); + let spec = match str_param(p, "type").map(str::to_ascii_lowercase).as_deref() { + Some("linear") => { + let start = point_param(p, "start").ok_or_else(|| bad("bparameter", "`start` ([x, y]) is required"))?; + let end = point_param(p, "end").ok_or_else(|| bad("bparameter", "`end` ([x, y]) is required"))?; + let label_offset = point_param(p, "labelAt").map_or(0.0, |at| offset_of(start, end, at)); + ParameterSpec::Linear { + base: to_block(start, base), + end: to_block(end, base), + label, + label_offset, + grips: grips_param("bparameter", p, 2, 2)?, + } + } + Some("point") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let label_at = point_param(p, "labelAt").unwrap_or(at); + ParameterSpec::Point { at: to_block(at, base), label, label_at: to_block(label_at, base), grips: grips_param("bparameter", p, 1, 1)? } + } + Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip", "visibility", "lookup"].contains(&other) => { + return Err(bad("bparameter", format!("{other} parameters are not available yet"))); + } + _ => return Err(bad("bparameter", "`type` is \"linear\" or \"point\"")), + }; + let node = add_parameter(s.doc_mut()?, &block, &spec).map_err(|e| bad("bparameter", e))?; + let m = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block); + let made = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); + Ok(json!({ "node": node, "element": made.map(|p| p.element.clone()), "label": made.and_then(|p| p.kind.label().map(str::to_string)) })) +} + +/// A parameter of the edited block as BACTION follows it, in editor coordinates. +#[derive(Clone, Debug, PartialEq)] +enum Followed { + Linear { node: i32, base: Vec2, end: Vec2 }, + Point { node: i32, at: Vec2 }, +} + +impl Followed { + fn node(&self) -> i32 { + match self { + Followed::Linear { node, .. } | Followed::Point { node, .. } => *node, + } + } +} + +/// The parameters of `block` an action can follow, in editor coordinates. +fn followable(d: &Drawing, block: &str, base: Vec2) -> Vec { + marks(d, block) + .into_iter() + .filter_map(|m| match m { + Mark::Linear { node, base: b, end, .. } => Some(Followed::Linear { node, base: b.xy() - base, end: end.xy() - base }), + Mark::Point { node, at, .. } => Some(Followed::Point { node, at: at.xy() - base }), + _ => None, + }) + .collect() +} + +/// The parameter named by `v`: its graph id, or its property name ("Distance1"). +fn parameter_named(d: &Drawing, block: &str, base: Vec2, v: &Value) -> Result { + let list = followable(d, block, base); + let m = cadcraft_doc::dynblock::dynamic_block(d, block); + let node = match v { + Value::Number(n) => n.as_i64().and_then(|n| i32::try_from(n).ok()), + Value::String(t) => t.trim().parse::().ok().or_else(|| { + m.as_ref()? + .parameters + .iter() + .find(|p| p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(t.trim())) || p.element.eq_ignore_ascii_case(t.trim())) + .map(|p| p.node) + }), + _ => None, + }; + let node = node.ok_or_else(|| bad("baction", format!("no parameter {v} in the block")))?; + match list.into_iter().find(|f| f.node() == node) { + Some(f) => Ok(f), + None if m.is_some_and(|m| m.parameters.iter().any(|p| p.node == node)) => { + Err(bad("baction", "that parameter can't have stretch or move actions yet")) + } + None => Err(bad("baction", format!("no parameter {v} in the block"))), + } +} + +/// How far `p` is from the segment from `a` to `b`. +fn segment_distance(a: Vec2, b: Vec2, p: Vec2) -> f64 { + let d = b - a; + let t = if d.len2() <= 1e-24 { 0.0 } else { ((p - a).dot(d) / d.len2()).clamp(0.0, 1.0) }; + (a + d * t).dist(p) +} + +/// Whether `p` is inside the stretch frame: a box's two corners, or a polygon. +fn in_frame(frame: &[Vec2], p: Vec2) -> bool { + match frame { + [a, b] => cadcraft_geom::Bounds2::new(*a, *b).contains(p), + poly => cadcraft_geom::point_in_polygon(poly, p), + } +} + +/// What a stretch with `frame` does to each of `handles` (editor objects): lines and polylines +/// move their vertices inside it (listed; left out with none inside), other objects move whole when their +/// first grip (a circle's centre, a text's insertion point) is inside, else not at all and they +/// are left out. Returns (selection, vertex lists). +fn stretch_lists(d: &Drawing, handles: &[Handle], frame: &[Vec2]) -> (Vec, Vec<(Handle, Vec)>) { + let (mut selection, mut vertices) = (Vec::new(), Vec::new()); + for h in handles { + let Some(e) = d.entity(*h) else { continue }; + let listed: Option> = match &e.kind { + EntityKind::Line(l) => { + Some([l.a.xy(), l.b.xy()].iter().enumerate().filter(|(_, p)| in_frame(frame, **p)).map(|(i, _)| i as i32).collect()) + } + EntityKind::LwPolyline(pl) => { + Some(pl.vertices.iter().enumerate().filter(|(_, v)| in_frame(frame, v.p)).filter_map(|(i, _)| i32::try_from(i).ok()).collect()) + } + k => { + if !k.grips().first().is_some_and(|p| in_frame(frame, *p)) { + continue; + } + None + } + }; + // A line or polyline with no vertex inside wouldn't change. + if listed.as_ref().is_some_and(Vec::is_empty) { + continue; + } + selection.push(*h); + if let Some(v) = listed { + vertices.push((*h, v)); + } + } + (selection, vertices) +} + +/// Add the action: `kind` "stretch" or "move" following `param` (at its `point`), on `handles`. +fn add( + s: &mut Session, + param: &Followed, + kind: &str, + point: ParamPoint, + handles: &[Handle], + frame: Option>, + at: Option, +) -> Result { + let (block, base) = editing(s)?; + if handles.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS { + return Err(bad("baction", "too many objects")); + } + let missing: Vec = handles.iter().filter(|h| s.doc().ok().and_then(|d| d.entity(**h)).is_none()).map(|h| h.hex()).collect(); + if !missing.is_empty() { + return Err(bad("baction", format!("no such object in the block: {}", missing.join(", ")))); + } + let shown = match param { + Followed::Linear { base: b, end, .. } => { + if point == ParamPoint::Base { + *b + } else { + *end + } + } + Followed::Point { at, .. } => *at, + }; + let at = to_block(at.unwrap_or(shown), base); + let spec = match kind { + "stretch" => { + let frame = frame.ok_or_else(|| bad("baction", "a stretch needs `frame` (two corners) or `polygon`"))?; + if frame.len() < 2 || frame.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS || frame.iter().any(|p| !p.is_finite()) { + return Err(bad("baction", "`frame` needs two corners, `polygon` three or more points")); + } + let (selection, vertices) = stretch_lists(s.doc()?, handles, &frame); + if selection.is_empty() { + return Err(bad("baction", "none of the objects is in the stretch frame")); + } + let frame = frame.iter().map(|p| *p + base).collect(); + ActionSpec::Stretch { parameter: param.node(), point, frame, selection, vertices, at } + } + "move" => ActionSpec::Move { parameter: param.node(), point, selection: handles.to_vec(), at }, + "array" | "scale" | "rotate" | "flip" | "polarstretch" | "lookup" => { + return Err(bad("baction", format!("{kind} actions are not available yet"))); + } + _ => return Err(bad("baction", "`type` is \"stretch\" or \"move\"")), + }; + let node = add_action(s.doc_mut()?, &block, &spec).map_err(|e| bad("baction", e))?; + let name = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block).and_then(|m| m.actions.into_iter().find(|a| a.node == node)).map(|a| a.name); + Ok(json!({ "node": node, "name": name })) +} + +fn run_baction(s: &mut Session, p: &Value) -> Result { + let (block, base) = editing(s)?; + let which = p.get("parameter").ok_or_else(|| bad("baction", "`parameter` (graph id or property name) is required"))?; + let param = parameter_named(s.doc()?, &block, base, which)?; + let kind = str_param(p, "type").map(|t| t.trim().to_ascii_lowercase().replace(' ', "")).ok_or_else(|| bad("baction", "`type` is required"))?; + let point = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { + None | Some("second") | Some("end") => ParamPoint::End, + Some("start") | Some("base") => ParamPoint::Base, + Some(o) => return Err(bad("baction", format!("`point` is \"start\" or \"second\", not \"{o}\""))), + }; + let handles: Vec = match p.get("handles") { + Some(Value::Array(a)) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad("baction", format!("{v} is not an object handle")))).collect::>()? + } + Some(_) => return Err(bad("baction", "`handles` is an array of object handles")), + None => s.selection(), + }; + if handles.is_empty() { + return Err(bad("baction", "`handles`: the objects the action acts on")); + } + let frame = match (points_param(p, "frame"), points_param(p, "polygon")) { + (Some(f), _) if f.len() == 2 => Some(f), + (Some(_), _) => return Err(bad("baction", "`frame` is two corners")), + (None, Some(poly)) if poly.len() >= 3 => Some(poly), + (None, Some(_)) => return Err(bad("baction", "`polygon` needs three or more points")), + (None, None) => None, + }; + add(s, ¶m, &kind, point, &handles, frame, point_param(p, "at")) +} + +/// Read keyword input: `text` (any case, an optional leading `_`) against `options`, each +/// (keyword, its shortcut). The keyword's own spelling, when one matches. +fn keyword<'a>(text: &str, options: &[(&'a str, &str)]) -> Option<&'a str> { + let t = text.trim(); + let t = t.strip_prefix('_').unwrap_or(t); + options.iter().find(|(k, short)| t.eq_ignore_ascii_case(k) || t.eq_ignore_ascii_case(short)).map(|(k, _)| *k) +} + +fn text_of(i: &Input) -> Option<&str> { + match i { + Input::Keyword(t) | Input::Text(t) => Some(t.as_str()), + _ => None, + } +} + +/// Options AutoCAD offers that are not available yet: answered with a message. +fn not_yet(s: &mut Session, what: &str) -> Result { + s.echo(format!("{what} is not available yet.")); + Ok(Step::Continue) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum PStage { + #[default] + Type, + Start, + End, + LinearLabel, + LinearGrips, + Location, + PointLabel, + PointGrips, + /// Typing the property name, then back to the stage it was asked at. + Label(&'static str), +} + +/// BPARAMETER's prompts, as AutoCAD asks them on the command line. +#[derive(Default)] +struct BparameterM { + stage: PStage, + linear: bool, + start: Vec2, + end: Vec2, + label_at: Vec2, + label: Option, +} + +const TYPES: &[(&str, &str)] = &[ + ("Alignment", "A"), + ("Base", "B"), + ("pOint", "O"), + ("Linear", "L"), + ("Polar", "P"), + ("Xy", "X"), + ("Rotation", "R"), + ("Flip", "F"), + ("Visibility", "V"), + ("looKup", "K"), +]; + +impl BparameterM { + fn make(&self, s: &mut Session, grips: u8) -> Result { + let label = self.label.clone(); + let p = if self.linear { + json!({ "type": "linear", "start": [self.start.x, self.start.y], "end": [self.end.x, self.end.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) + } else { + json!({ "type": "point", "at": [self.start.x, self.start.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) + }; + run_bparameter(s, &p).map(|_| Step::Done) + } + + /// The option keywords of the first point's prompt. + fn options(&self, i: &Input) -> Option<&'static str> { + let opts: &[(&str, &str)] = if self.linear { + &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Base", "B"), ("Palette", "P"), ("Value set", "V")] + } else { + &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Palette", "P")] + }; + text_of(i).and_then(|t| keyword(t, opts)) + } +} + +impl Interactive for BparameterM { + fn name(&self) -> &'static str { + "BPARAMETER" + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + PStage::Type => Prompt::new("Enter parameter type", KW).kw(&TYPES.iter().map(|(k, _)| *k).collect::>()), + PStage::Start => Prompt::new("Specify start point", Accept::POINT) + .kw(&["Name", "Label", "Chain", "Description", "Base", "Palette", "Value set"]) + .deferred(), + PStage::End => Prompt::new("Specify endpoint", Accept::POINT).base(self.start), + PStage::LinearLabel | PStage::PointLabel => Prompt::new("Specify label location", Accept::POINT), + PStage::LinearGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1", "2"]).default("2"), + PStage::Location => Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Chain", "Description", "Palette"]), + PStage::PointGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), + PStage::Label(what) => Prompt::new(format!("Enter {what} property label"), Accept::TEXT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + PStage::Type => { + let Some(t) = text_of(&i) else { return Ok(Step::Continue) }; + match keyword(t, TYPES) { + Some("Linear") => (self.linear, self.stage) = (true, PStage::Start), + Some("pOint") => (self.linear, self.stage) = (false, PStage::Location), + Some(other) => return Err(EngineError::Other(format!("{other} parameters are not available yet."))), + None => s.echo("Invalid option keyword."), + } + } + PStage::Start | PStage::Location => match (&i, self.options(&i)) { + (Input::Point(p), _) => { + self.start = *p; + self.stage = if self.linear { PStage::End } else { PStage::PointLabel }; + } + (_, Some("Label")) => self.stage = PStage::Label(if self.linear { "distance" } else { "position" }), + (_, Some(other)) => return not_yet(s, other), + _ => {} + }, + PStage::End => { + if let Input::Point(p) = i { + if (p - self.start).len() <= 1e-9 { + s.echo("The endpoint must differ from the start point."); + } else { + self.end = p; + self.stage = PStage::LinearLabel; + } + } + } + PStage::LinearLabel | PStage::PointLabel => { + if let Input::Point(p) = i { + self.label_at = p; + self.stage = if self.stage == PStage::LinearLabel { PStage::LinearGrips } else { PStage::PointGrips }; + } + } + PStage::LinearGrips | PStage::PointGrips => { + let most = if self.stage == PStage::LinearGrips { 2 } else { 1 }; + let grips = match &i { + Input::Enter => Some(most), + _ => text_of(&i).and_then(|t| t.trim().parse::().ok()).filter(|g| *g <= most), + }; + match grips { + Some(g) => return self.make(s, g), + None => s.echo(format!("Enter 0 to {most}.")), + } + } + PStage::Label(_) => { + match &i { + Input::Text(t) | Input::Keyword(t) if !t.trim().is_empty() => self.label = Some(t.trim().to_string()), + _ => {} + } + self.stage = if self.linear { PStage::Start } else { PStage::Location }; + } + } + Ok(Step::Continue) + } + fn preview(&self, _s: &Session, cursor: Vec2) -> Vec { + match self.stage { + PStage::End => vec![crate::cmd::helpers::line(self.start, cursor)], + PStage::LinearLabel => { + vec![crate::cmd::helpers::line(self.start, self.end), crate::cmd::helpers::line((self.start + self.end) * 0.5, cursor)] + } + PStage::PointLabel => vec![crate::cmd::helpers::line(self.start, cursor)], + _ => Vec::new(), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum AStage { + #[default] + Parameter, + Type, + Point, + Corner, + Opposite, + Polygon, + Objects, + Location, +} + +/// BACTION's prompts, as AutoCAD asks them on the command line. +#[derive(Default)] +struct BactionM { + stage: AStage, + param: Option, + kind: &'static str, + point: ParamPoint, + frame: Vec, + select: SelectPhase, + picked: Vec, +} + +impl BactionM { + /// After the parameter (and its action type): what the action asks next. + fn after_type(&mut self) { + self.stage = match (&self.param, self.kind) { + (Some(Followed::Linear { .. }), _) => AStage::Point, + (_, "stretch") => AStage::Corner, + _ => AStage::Objects, + }; + } + fn after_point(&mut self) { + self.stage = if self.kind == "stretch" { AStage::Corner } else { AStage::Objects }; + } +} + +impl Interactive for BactionM { + fn name(&self) -> &'static str { + "BACTION" + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + AStage::Parameter => Prompt::new("Select parameter", Accept::POINT), + AStage::Type => match self.param { + Some(Followed::Point { .. }) => Prompt::new("Enter action type", KW).kw(&["Move", "sTretch"]), + _ => Prompt::new("Enter action type", KW).kw(&["Array", "Move", "Scale", "sTretch"]), + }, + AStage::Point => Prompt::new("Specify parameter point to associate with action or enter", Accept::POINT) + .kw(&["sTart point", "Second point"]) + .default("Second"), + AStage::Corner => Prompt::new("Specify first corner of stretch frame", Accept::POINT).kw(&["CPolygon"]), + AStage::Opposite => match self.frame.first() { + Some(c) => Prompt::new("Specify opposite corner", Accept::POINT).corner(*c), + None => Prompt::new("Specify opposite corner", Accept::POINT), + }, + AStage::Polygon => { + Prompt::new(if self.frame.is_empty() { "Specify first polygon point" } else { "Specify endpoint of line" }, Accept::POINT) + .kw(if self.frame.is_empty() { &[] } else { &["Undo"] }) + .base_opt(self.frame.last().copied()) + } + AStage::Objects => self.select.prompt(), + AStage::Location => Prompt::new("Specify action location", Accept::POINT).kw(&["Multiplier", "Offset"]), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + AStage::Parameter => { + let (block, base) = editing(s)?; + let found = match &i { + Input::Point(p) => { + let reach = (s.pixel_size() * s.settings.pickbox.max(1.0) * 3.0).max(1e-9); + let near = |f: &Followed| match f { + Followed::Linear { base, end, .. } => segment_distance(*base, *end, *p), + Followed::Point { at, .. } => (*at - *p).len(), + }; + let list = followable(s.doc()?, &block, base); + list.into_iter().map(|f| (near(&f), f)).filter(|(d, _)| *d <= reach).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f) + } + Input::Text(t) | Input::Keyword(t) => parameter_named(s.doc()?, &block, base, &Value::String(t.clone())).ok(), + Input::Enter => return Ok(Step::Done), + _ => return Ok(Step::Continue), + }; + match found { + Some(f) => { + self.param = Some(f); + self.stage = AStage::Type; + } + None => s.echo("No linear or point parameter there."), + } + } + AStage::Type => { + let Some(t) = text_of(&i) else { return Ok(Step::Continue) }; + let opts: &[(&str, &str)] = if matches!(self.param, Some(Followed::Point { .. })) { + &[("Move", "M"), ("sTretch", "T")] + } else { + &[("Array", "A"), ("Move", "M"), ("Scale", "S"), ("sTretch", "T")] + }; + match keyword(t, opts) { + Some("Move") => self.kind = "move", + Some("sTretch") => self.kind = "stretch", + Some(other) => return Err(EngineError::Other(format!("{other} actions are not available yet."))), + None => { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + } + } + self.after_type(); + } + AStage::Point => { + match (&i, &self.param) { + (Input::Enter, _) => self.point = ParamPoint::End, + (Input::Point(p), Some(Followed::Linear { base, end, .. })) => { + self.point = if (*p - *base).len() < (*p - *end).len() { ParamPoint::Base } else { ParamPoint::End }; + } + _ => match text_of(&i) + .and_then(|t| keyword(t, &[("sTart point", "T"), ("Second point", "S"), ("Start", "Start"), ("Second", "Second")])) + { + Some("sTart point" | "Start") => self.point = ParamPoint::Base, + Some(_) => self.point = ParamPoint::End, + None => return Ok(Step::Continue), + }, + } + self.after_point(); + } + AStage::Corner => match &i { + Input::Point(p) => { + self.frame = vec![*p]; + self.stage = AStage::Opposite; + } + _ => { + if text_of(&i).and_then(|t| keyword(t, &[("CPolygon", "CP")])).is_some() { + self.frame.clear(); + self.stage = AStage::Polygon; + } + } + }, + AStage::Opposite => { + if let Input::Point(p) = i { + self.frame.push(p); + s.echo("Specify objects to stretch"); + self.stage = AStage::Objects; + } + } + AStage::Polygon => match &i { + Input::Point(p) if self.frame.len() < cadcraft_doc::dynblock::MAX_ACTION_ITEMS => self.frame.push(*p), + Input::Enter if self.frame.len() >= 3 => { + s.echo("Specify objects to stretch"); + self.stage = AStage::Objects; + } + Input::Enter => s.echo("A polygon needs three or more points."), + _ => { + if text_of(&i).and_then(|t| keyword(t, &[("Undo", "U")])).is_some() { + self.frame.pop(); + } + } + }, + AStage::Objects => match self.select.feed(s, &i)? { + SelOutcome::More => {} + SelOutcome::Empty => return Ok(Step::Done), + SelOutcome::Done(hs) => { + self.picked = hs; + self.stage = AStage::Location; + } + }, + AStage::Location => match &i { + Input::Point(p) => { + let Some(param) = self.param.clone() else { return Ok(Step::Done) }; + let frame = (self.kind == "stretch").then(|| self.frame.clone()); + return add(s, ¶m, self.kind, self.point, &self.picked, frame, Some(*p)).map(|_| Step::Done); + } + _ => { + if let Some(k) = text_of(&i).and_then(|t| keyword(t, &[("Multiplier", "M"), ("Offset", "O")])) { + return not_yet(s, k); + } + } + }, + } + Ok(Step::Continue) + } + fn preview(&self, _s: &Session, cursor: Vec2) -> Vec { + match (self.stage, self.frame.first()) { + (AStage::Opposite, Some(c)) => { + vec![crate::cmd::helpers::lwpoly(crate::cmd::helpers::rect_vertices(*c, cursor), true)] + } + (AStage::Polygon, Some(_)) => { + let mut pts = self.frame.clone(); + pts.push(cursor); + vec![crate::cmd::helpers::lwpoly(pts.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), true)] + } + _ => Vec::new(), + } + } +} diff --git a/crates/engine/src/cmd/blocks/bedit.rs b/crates/engine/src/cmd/blocks/bedit.rs index c570fa107c..dcce630039 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -159,7 +159,7 @@ fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let dynamic = |be: &crate::blockedit::BlockEdit| crate::blockedit::has_dynamic_data(&be.host.doc, if be.current { "*Model_Space" } else { &be.name }); if s.state().is_ok_and(|st| st.block_edit.as_ref().is_some_and(dynamic)) { - s.echo("This is a dynamic block: its parameters and actions are kept but can't be edited in CADCraft yet."); + s.echo("This is a dynamic block: BPARAMETER and BACTION add linear and point parameters with stretch and move actions; its other parameters and actions are kept as they are."); } Ok(json!({ "block": name, "new": new })) } diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 9afc6d02f9..c2500b5f0b 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -274,6 +274,8 @@ pub const NO_FILES: &[&str] = &[ "bsave", "bsaveas", "bclose", + "bparameter", + "baction", "erase", "oops", "move", diff --git a/crates/engine/tests/it/block_authoring.rs b/crates/engine/tests/it/block_authoring.rs new file mode 100644 index 0000000000..1775d9cfc6 --- /dev/null +++ b/crates/engine/tests/it/block_authoring.rs @@ -0,0 +1,258 @@ +//! Authoring dynamic blocks in the Block Editor (BPARAMETER, BACTION): parameters and actions +//! added to a block make its references dynamic, here and in files saved for AutoCAD. + +use cadcraft_engine::doc::dynblock::{ActionKind, Mark, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + cadcraft_engine::cmd::curves::handle_value(v).unwrap() +} + +/// Block "Box": a 10 × 5 rectangle from (5,5) and a circle on its right edge, base point (5,5), +/// and a reference at (100,0). Returns (rectangle, circle, reference): the block's objects. +fn boxed(s: &mut Session) -> (Value, Value, Value) { + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [5, 5], "p2": [15, 10] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [15, 7.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [5, 5], "handles": [r, c], "keep": "delete" })).unwrap(); + let i = s.execute("insert", &json!({ "name": "Box", "at": [100, 0] })).unwrap()["handle"].clone(); + let d = s.doc().unwrap(); + let b = d.block("Box").unwrap(); + let of = |rect: bool| json!(b.entities.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex()); + (of(true), of(false), i) +} + +/// The rectangle's corners in reference `i`'s block (block coordinates). +fn corners(s: &Session, i: &Value) -> Vec<(f64, f64)> { + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(i)).unwrap().kind else { panic!() }; + let b = d.block(&ins.block).unwrap(); + b.entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }) + .unwrap() +} + +#[test] +fn a_linear_stretch_authored_in_json_drives_references() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + assert!(s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).is_err(), "only in the Block Editor"); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + assert_eq!(p, json!({ "node": 1, "element": "Linear", "label": "Distance1" })); + let a = s + .execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + assert_eq!(a, json!({ "node": 8, "name": "Stretch" })); + + // The editor draws them where they were given. + let st = s.state().unwrap(); + let marks = st.block_edit.as_ref().unwrap().marks(&st.doc); + assert!( + matches!(&marks[0], Mark::Linear { base, end, offset, label, base_grip: true, end_grip: true, .. } + if *base == Vec3::ZERO && *end == Vec3::new(10.0, 0.0, 0.0) && *offset == -2.0 && label == "Distance1"), + "{marks:?}" + ); + assert!(matches!(&marks[1], Mark::Action { at, name, .. } if *at == Vec3::new(12.0, -2.0, 0.0) && name == "Stretch"), "{marks:?}"); + + s.execute("bclose", &json!({})).unwrap(); + // Stored in block coordinates: the base point (5,5) added back. + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { base, end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*base, *end), (Vec3::new(5.0, 5.0, 0.0), Vec3::new(15.0, 5.0, 0.0))); + let ActionKind::Stretch { frame, vertices, .. } = &m.actions[0].kind else { panic!() }; + assert_eq!(frame, &[Vec2::new(13.0, 4.0), Vec2::new(17.0, 11.0)]); + assert_eq!(vertices, &[(h(&r), vec![1, 2])], "the rectangle's right edge; the circle moves whole"); + assert_eq!(m.actions[0].selection, [h(&r), h(&c)]); + + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "15" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); +} + +/// The handles of block `name`'s objects. +fn block_handles(s: &Session, name: &str) -> Vec { + s.doc().unwrap().block(name).unwrap().entities.iter().map(|e| e.handle).collect() +} + +/// Saved under another name (BSAVEAS), a dynamic block keeps its parameters and actions in a graph +/// of its own, with objects of its own, and what was unsaved in the editor (a new object and an +/// action on it) is the copy's: the original is as the drawing had it. The editor goes on with the +/// copy, so a later BSAVE keeps its graph and handles; references to either change as before. +#[test] +fn bsaveas_gives_a_dynamic_block_its_own_graph() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + s.execute("bsave", &json!({})).unwrap(); + // Unsaved: a new circle, moved by the distance. + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let n = made(s.execute("circle", &json!({ "center": [2, 2], "radius": 0.5 })).unwrap()); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "move", "handles": [n], "at": [2, -4] })).unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2" })).unwrap(); + let check = |s: &Session| { + let d = s.doc().unwrap(); + let (a, b) = (dynamic_block(d, "Box").unwrap(), dynamic_block(d, "Box2").expect("the copy has dynamic data")); + assert_eq!((a.parameters.len(), a.actions.len()), (1, 1), "the original keeps what the drawing had"); + assert_eq!((b.parameters.len(), b.actions.len()), (1, 2), "the copy has what the editor had"); + assert_ne!(a.parameters[0].handle, b.parameters[0].handle, "its own graph objects"); + let (own, copy) = (block_handles(s, "Box"), block_handles(s, "Box2")); + assert!(own.iter().all(|h| !copy.contains(h)), "no handle in two blocks"); + assert_eq!(a.actions[0].selection, [h(&r), h(&c)], "the original's action is unchanged"); + for act in &a.actions { + assert!(act.selection.iter().all(|x| own.contains(x)), "the original's graph names only its own objects"); + } + for act in &b.actions { + assert!(act.selection.iter().all(|x| copy.contains(x)), "{:?} in {:?}", act.selection, copy); + } + }; + check(&s); + // The editor edits the copy now: saving again keeps its graph and handles. Its history from + // before the copy is gone, so an undo can't bring back handles the copy doesn't have. + let _ = s.execute("undo", &json!({})); + s.execute("bsave", &json!({})).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + check(&s); + + // A reference to the copy stretches; the original's reference does too. + let j = s.execute("insert", &json!({ "name": "Box2", "at": [200, 0] })).unwrap()["handle"].clone(); + s.execute("blocks.reference.set", &json!({ "handle": j, "name": "Distance1", "value": "15" })).unwrap(); + assert_eq!(corners(&s, &j), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "12" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (17.0, 5.0), (17.0, 10.0), (5.0, 10.0)]); +} + +/// A dynamic block replaced by BSAVEAS with a block that isn't dynamic keeps none of its old graph. +#[test] +fn bsaveas_over_a_dynamic_block_leaves_none_of_its_old_graph() { + let mut s = Session::new(); + let (r, c, _) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + s.execute("bsave", &json!({})).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + let graph_objects = s.doc().unwrap().foreign.objects.len(); + // A copy, with a graph of its own. + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2" })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(dynamic_block(s.doc().unwrap(), "Box2").is_some()); + assert!(s.doc().unwrap().foreign.objects.len() > graph_objects, "the copy's graph objects"); + // Plain block "Plain" replaces it. + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let ci = made(s.execute("circle", &json!({ "center": [50, 50], "radius": 2 })).unwrap()); + s.execute("block", &json!({ "name": "Plain", "base": [50, 50], "handles": [ci], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "Plain" })).unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2", "replace": true })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert!(dynamic_block(d, "Box2").is_none(), "Box2 is the plain block now"); + assert_eq!(d.foreign.objects.len(), graph_objects, "only Box's graph is left"); + assert!(dynamic_block(d, "Box").is_some(), "Box is untouched"); +} + +#[test] +fn bparameter_and_baction_ask_as_autocad_does() { + let mut s = Session::new(); + let (r, _, i) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.script("BPARAMETER L 0,0 10,0 5,-2\n").unwrap(); + assert_eq!(s.current_prompt().map(|p| p.message), Some("Enter number of grips".to_string())); + s.script("\n").unwrap(); + assert!(s.running.is_none(), "Enter takes the default two grips"); + s.script("BACTION 10,0\nT\n\n8,-1 12,6\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects"); + s.input(Input::Pick(vec![h(&r)])).unwrap(); + s.script("\n12,-2\n").unwrap(); + assert!(s.running.is_none()); + // A point parameter and a move of the circle, its prompts' own order. + s.script("BPARAMETER O\n10,2.5 11,3.5 1\n").unwrap(); + s.script("BACTION 10,2.5\nM\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects", "a point parameter asks no parameter point"); + let circle = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Circle(_))).unwrap().handle; + s.input(Input::Pick(vec![circle])).unwrap(); + s.script("\n12,1\n").unwrap(); + s.script("BCLOSE\n\n").unwrap(); + + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let names: Vec<_> = m.parameters.iter().map(|p| p.kind.label().unwrap_or("-")).chain(m.actions.iter().map(|a| a.name.as_str())).collect(); + assert_eq!(names, ["Distance1", "Position1", "Stretch", "Move"]); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "12" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (17.0, 5.0), (17.0, 10.0), (5.0, 10.0)]); +} + +#[test] +fn types_not_available_yet_say_so() { + let mut s = Session::new(); + boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + for t in ["polar", "xy", "rotation", "flip", "visibility", "lookup", "base", "alignment"] { + let e = s.execute("bparameter", &json!({ "type": t, "start": [0, 0], "end": [1, 0] })).unwrap_err().to_string(); + assert!(e.contains("not available yet"), "{t}: {e}"); + } + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + let e = s.execute("baction", &json!({ "parameter": 1, "type": "scale", "handles": [] })).unwrap_err().to_string(); + assert!(e.contains("handles"), "{e}"); + let any = s.doc().unwrap().model.iter().next().unwrap().handle.hex(); + let e = s.execute("baction", &json!({ "parameter": 1, "type": "scale", "handles": [any] })).unwrap_err().to_string(); + assert!(e.contains("not available yet"), "{e}"); +} + +#[test] +fn hostile_authoring_params_never_panic() { + let mut s = Session::new(); + let (r, _, _) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + for p in [ + json!(null), + json!([]), + json!({ "type": 5 }), + json!({ "type": "linear" }), + json!({ "type": "linear", "start": [0, 0], "end": [0, 0] }), + json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0], "labelAt": [1e308, 1e308] }), + json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0] }), + json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": 3 }), + json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": -1 }), + json!({ "type": "point", "at": "nan,nan" }), + json!({ "type": "point", "at": [0, 0], "grips": 2 }), + json!({ "type": "point", "at": [0, 0], "label": 7 }), + ] { + let _ = s.execute("bparameter", &p); + } + let far = s.execute("bparameter", &json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0] })); + assert!(far.is_err(), "an infinite distance between finite points is refused: {far:?}"); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + let many: Vec = (0..20_001).map(|_| r.clone()).collect(); + let poly: Vec<[f64; 2]> = (0..20_001).map(|i| [i as f64, (i % 2) as f64]).collect(); + for p in [ + json!(null), + json!({ "parameter": 99, "type": "move", "handles": [r] }), + json!({ "parameter": "Nope", "type": "move", "handles": [r] }), + json!({ "parameter": [], "type": "move", "handles": [r] }), + json!({ "parameter": 1, "type": "move", "handles": ["zz"] }), + json!({ "parameter": 1, "type": "move", "handles": ["FFFFFF"] }), + json!({ "parameter": 1, "type": "move", "handles": many }), + json!({ "parameter": 1, "type": "stretch", "handles": [r] }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "frame": [[0, 0]] }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "polygon": poly }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "frame": [[100, 100], [101, 101]] }), + json!({ "parameter": 1, "type": "move", "point": "middle", "handles": [r] }), + ] { + assert!(s.execute("baction", &p).is_err(), "{p}"); + } + // Cancelling either command midway changes nothing. + let before = s.doc().unwrap().foreign.clone(); + s.script("BPARAMETER L 0,0\n").unwrap(); + s.input(Input::Cancel).unwrap(); + s.script("BACTION 5,0\nT\n").unwrap(); + s.input(Input::Cancel).unwrap(); + assert_eq!(s.doc().unwrap().foreign, before); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3d6679d95b..ad1a21c53c 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -20,6 +20,7 @@ mod attrib_props; mod attribute_tag_matching; mod attribute_tools; mod attribute_value_baseline; +mod block_authoring; mod block_description; mod block_keep; mod block_redefine; diff --git a/crates/io/tests/it/dynblock_author.rs b/crates/io/tests/it/dynblock_author.rs new file mode 100644 index 0000000000..d48b2728ed --- /dev/null +++ b/crates/io/tests/it/dynblock_author.rs @@ -0,0 +1,346 @@ +//! Authoring dynamic blocks: parameters and actions added in CADCraft are written as the +//! evaluation graph objects the reader reads, survive a save, and drive references. +//! +//! The fixture is synthetic, written for this test: a BOX block (a 10 × 5 rectangle and a +//! circle on its right edge) with one reference. + +use cadcraft_doc::dynblock::{ + ActionKind, ActionSpec, ParamPoint, ParameterKind, ParameterSpec, add_action, add_parameter, dynamic_block, set_property, tag_elements, +}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::{Vec2, Vec3}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// DXF text from lines of `code value` (the value may be empty). +fn dxf(src: &str) -> String { + let mut out = String::new(); + for line in src.lines().map(str::trim).filter(|l| !l.is_empty()) { + let (code, value) = line.split_once(' ').unwrap_or((line, "")); + out.push_str(&format!("{code}\n{value}\n")); + } + out +} + +const BOX: &str = " +0 SECTION +2 BLOCKS +0 BLOCK +2 BOX +70 0 +10 0 +20 0 +30 0 +0 LWPOLYLINE +5 30 +8 0 +90 4 +70 1 +10 0 +20 0 +10 10 +20 0 +10 10 +20 5 +10 0 +20 5 +0 CIRCLE +5 31 +8 0 +10 10 +20 2.5 +30 0 +40 1 +0 ENDBLK +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 40 +8 0 +2 BOX +10 100 +20 0 +30 0 +0 ENDSEC +0 EOF +"; + +fn h(hex: &str) -> Handle { + Handle::parse_hex(hex).unwrap() +} + +fn box_drawing() -> Drawing { + read_dxf(dxf(BOX).as_bytes()).unwrap() +} + +fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) +} + +fn linear(grips: u8) -> ParameterSpec { + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: -2.0, grips } +} + +/// BOX with a linear parameter (2 grips) stretching the rectangle's right edge. +fn stretchy() -> (Drawing, i32, i32) { + let mut d = box_drawing(); + let p = add_parameter(&mut d, "box", &linear(2)).unwrap(); + let frame = vec![Vec2::new(8.0, -1.0), Vec2::new(12.0, 6.0)]; + let spec = ActionSpec::Stretch { + parameter: p, + point: ParamPoint::End, + frame, + selection: vec![h("30")], + vertices: vec![(h("30"), vec![1, 2])], + at: v(12.0, -2.0), + }; + let a = add_action(&mut d, "BOX", &spec).unwrap(); + (d, p, a) +} + +/// The graph's node and edge lists as written: per node (index, id, links), per edge (kind, +/// from, to, links). +fn graph(d: &Drawing) -> (Vec<(i32, i32, Vec)>, Vec<(i32, i32, i32, Vec)>) { + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let at = g.tags.iter().position(|t| t.value == "AcDbEvalGraph").unwrap(); + let ints: Vec<(i32, i32)> = g.tags[at + 1..].iter().filter(|t| t.code != 360).map(|t| (t.code, t.value.parse().unwrap())).collect(); + let mut nodes = Vec::new(); + let mut edges = Vec::new(); + let mut i = 2; + while ints.get(i).is_some_and(|t| t.0 == 91) { + nodes.push((ints[i].1, ints[i + 2].1, ints[i + 3..i + 7].iter().map(|t| t.1).collect())); + i += 7; + } + while i < ints.len() { + edges.push((ints[i + 2].1, ints[i + 3].1, ints[i + 4].1, ints[i + 5..i + 10].iter().map(|t| t.1).collect())); + i += 10; + } + (nodes, edges) +} + +#[test] +fn an_authored_linear_stretch_reads_back() { + let (d, p, a) = stretchy(); + assert_eq!((p, a), (1, 8), "parameter, 2 grips × (grip + 2 components), then the action"); + let m = dynamic_block(&d, "BOX").expect("BOX is dynamic now"); + let param = &m.parameters[0]; + assert_eq!((param.node, param.element.as_str(), param.show_properties), (1, "Linear", true)); + assert_eq!(param.grips, [5, 2], "base grip, end grip"); + let ParameterKind::Linear { base, end, label, .. } = ¶m.kind else { panic!("{param:?}") }; + assert_eq!((*base, *end, label.as_str()), (v(0.0, 0.0), v(10.0, 0.0), "Distance1")); + let act = &m.actions[0]; + assert_eq!((act.node, act.name.as_str(), act.at), (8, "Stretch", v(12.0, -2.0))); + assert_eq!(act.selection, [h("30")]); + assert_eq!(act.connections, [(1, "EndXDelta".to_string()), (1, "EndYDelta".to_string())]); + let ActionKind::Stretch { frame, vertices, multiplier, angle_offset } = &act.kind else { panic!("{act:?}") }; + assert_eq!(frame, &[Vec2::new(8.0, -1.0), Vec2::new(12.0, 6.0)]); + assert_eq!(vertices, &[(h("30"), vec![1, 2])]); + assert_eq!((*multiplier, *angle_offset), (1.0, 0.0)); + assert_eq!(m.other.len(), 6, "{:?}", m.other); + assert_eq!(m.other.iter().filter(|o| *o == "BLOCKLINEARGRIP").count(), 2); +} + +/// The graph is laid out as AutoCAD lays out the same block (nodes in creation order, each +/// edge in its from-node's outgoing list and its to-node's incoming list). +#[test] +fn the_graph_links_nodes_as_autocad_does() { + let (d, _, _) = stretchy(); + let (nodes, edges) = graph(&d); + let want_nodes = vec![ + (0, 1, vec![2, 5, 0, 6]), + (1, 2, vec![-1, -1, 2, 2]), + (2, 3, vec![0, 0, -1, -1]), + (3, 4, vec![1, 1, -1, -1]), + (4, 5, vec![-1, -1, 5, 5]), + (5, 6, vec![3, 3, -1, -1]), + (6, 7, vec![4, 4, -1, -1]), + (7, 8, vec![6, 6, -1, -1]), + ]; + assert_eq!(nodes, want_nodes); + let want_edges = vec![ + (1, 0, 2, vec![-1, -1, -1, 1, -1]), + (1, 0, 3, vec![-1, -1, 0, 3, -1]), + (2, 1, 0, vec![-1, 5, -1, -1, -1]), + (1, 0, 5, vec![-1, -1, 1, 4, -1]), + (1, 0, 6, vec![-1, -1, 3, 6, -1]), + (2, 4, 0, vec![2, -1, -1, -1, -1]), + (1, 0, 7, vec![-1, -1, 4, -1, -1]), + ]; + assert_eq!(edges, want_edges); + // The record's dictionary holds the graph and the purge preventer. + let x = d.foreign.records.get(&("BLOCK_RECORD".to_string(), "BOX".to_string())).unwrap(); + let dict = d.foreign.objects.iter().find(|o| Some(o.handle) == x.xdict).unwrap(); + let keys: Vec<&str> = dict.tags.iter().filter(|t| t.code == 3).map(|t| t.value.as_str()).collect(); + assert_eq!(keys, ["ACAD_ENHANCEDBLOCK", "AcDbDynamicBlockRoundTripPurgePreventer"]); + assert!(x.xdata.iter().any(|t| t.value == "AcDbDynamicBlockTrueName")); + for c in ["ACAD_EVALUATION_GRAPH", "BLOCKLINEARPARAMETER", "BLOCKLINEARGRIP", "BLOCKGRIPLOCATIONCOMPONENT", "BLOCKSTRETCHACTION"] { + assert!(d.foreign.classes.iter().any(|k| k.iter().any(|t| t.code == 1 && t.value == c)), "class {c}"); + } +} + +#[test] +fn an_authored_block_survives_a_save() { + let (mut d, _, _) = stretchy(); + let mut store = d.block("BOX").unwrap().entities.clone(); + tag_elements(&mut d, "BOX", &mut store); + let mut b = (**d.block("BOX").unwrap()).clone(); + b.entities = store; + d.blocks.insert("BOX".into(), std::sync::Arc::new(b)); + let before = dynamic_block(&d, "BOX").unwrap(); + let text = write_dxf(&d); + for t in ["ACAD_EVALUATION_GRAPH", "BLOCKSTRETCHACTION", "AcDbDynamicBlockRoundTripPurgePreventer", "AcDbBlockRepETag"] { + assert!(text.contains(t), "{t} written"); + } + let again = read_dxf(text.as_bytes()).unwrap(); + let after = dynamic_block(&again, "BOX").expect("still dynamic after a save"); + assert_eq!(after.parameters.len(), 1); + assert_eq!(after.parameters[0].kind, before.parameters[0].kind); + assert_eq!(after.actions[0].kind, before.actions[0].kind); + assert_eq!(after.actions[0].selection, before.actions[0].selection, "the block's objects keep their handles"); +} + +/// The rectangle's corners in reference `insert`'s block. +fn rect(d: &Drawing, insert: Handle) -> Vec<(f64, f64)> { + let EntityKind::Insert(i) = &d.entity(insert).unwrap().kind else { panic!() }; + let b = d.block(&i.block).unwrap(); + b.entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(pl) = &e.kind { Some(pl.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }) + .unwrap() +} + +#[test] +fn a_reference_to_an_authored_block_stretches() { + let (mut d, _, _) = stretchy(); + set_property(&mut d, h("40"), "Distance1", "15").unwrap(); + assert_eq!(rect(&d, h("40")), [(0.0, 0.0), (15.0, 0.0), (15.0, 5.0), (0.0, 5.0)]); +} + +#[test] +fn a_point_parameter_moves_the_circle() { + let mut d = box_drawing(); + let p = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(10.0, 2.5), label: None, label_at: v(11.0, 3.5), grips: 1 }).unwrap(); + let a = + add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![h("31")], at: v(12.0, 1.0) }).unwrap(); + assert_eq!((p, a), (1, 5)); + let m = dynamic_block(&d, "BOX").unwrap(); + let ParameterKind::Point { at, label, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*at, label.as_str()), (v(10.0, 2.5), "Position1")); + assert_eq!(m.parameters[0].grips, [2]); + assert_eq!(m.actions[0].connections, [(1, "XDelta".to_string()), (1, "YDelta".to_string())]); + assert!(matches!(m.actions[0].kind, ActionKind::Move { multiplier: 1.0, .. })); + set_property(&mut d, h("40"), "Position1 X", "13").unwrap(); + let EntityKind::Insert(i) = &d.entity(h("40")).unwrap().kind else { panic!() }; + let c = d.block(&i.block).unwrap().entities.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.center) } else { None }).unwrap(); + assert_eq!((c.x, c.y), (13.0, 2.5)); +} + +#[test] +fn names_and_labels_count_up_and_grips_follow_the_count() { + let mut d = box_drawing(); + let first = add_parameter(&mut d, "BOX", &linear(0)).unwrap(); + let second = add_parameter(&mut d, "BOX", &linear(1)).unwrap(); + let third = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(1.0, 1.0), label: Some("Hinge".into()), label_at: v(2.0, 2.0), grips: 0 }) + .unwrap(); + assert_eq!((first, second, third), (1, 2, 6), "no grips, then one grip with two components"); + let m = dynamic_block(&d, "BOX").unwrap(); + let names: Vec<_> = m.parameters.iter().map(|p| (p.element.as_str(), p.kind.label().unwrap_or("-"), p.grips.clone())).collect(); + assert_eq!(names, [("Linear", "Distance1", vec![0, 0]), ("Linear1", "Distance2", vec![0, 3]), ("Point", "Hinge", vec![0])]); + let p = second; + let a = + add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::Base, selection: vec![h("31")], at: v(0.0, 0.0) }).unwrap(); + let b = add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![h("31")], at: v(0.0, 0.0) }).unwrap(); + let m = dynamic_block(&d, "BOX").unwrap(); + let acts: Vec<_> = m.actions.iter().map(|x| (x.node, x.name.as_str(), x.connections[0].1.as_str())).collect(); + assert_eq!(acts, [(a, "Move", "BaseXDelta"), (b, "Move1", "EndXDelta")]); +} + +#[test] +fn bad_authoring_is_refused_and_changes_nothing() { + let (d0, p, _) = stretchy(); + let bad_params = [ + ParameterSpec::Linear { base: v(1.0, 1.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, + ParameterSpec::Linear { base: v(f64::NAN, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: f64::INFINITY, grips: 2 }, + ParameterSpec::Linear { base: v(1e308, 0.0), end: v(-1e308, 0.0), label: None, label_offset: 0.0, grips: 2 }, + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 3 }, + ParameterSpec::Point { at: v(0.0, 0.0), label: None, label_at: v(0.0, 0.0), grips: 2 }, + ]; + for spec in &bad_params { + let mut d = d0.clone(); + assert!(add_parameter(&mut d, "BOX", spec).is_err(), "{spec:?}"); + assert_eq!(d.foreign, d0.foreign, "{spec:?} changed the drawing"); + } + let mv = |parameter, selection: Vec| ActionSpec::Move { parameter, point: ParamPoint::End, selection, at: v(0.0, 0.0) }; + let st = |frame: Vec| ActionSpec::Stretch { + parameter: p, + point: ParamPoint::End, + frame, + selection: vec![h("30")], + vertices: vec![], + at: v(0.0, 0.0), + }; + let bad_actions = [ + mv(99, vec![h("30")]), + mv(p, vec![]), + mv(p, vec![h("30"); 20_000]), + st(vec![Vec2::new(0.0, 0.0)]), + st(vec![Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]), + ]; + for spec in &bad_actions { + let mut d = d0.clone(); + assert!(add_action(&mut d, "BOX", spec).is_err(), "{spec:?}"); + assert_eq!(d.foreign, d0.foreign, "{spec:?} changed the drawing"); + } + let mut d = box_drawing(); + assert!(add_action(&mut d, "BOX", &mv(1, vec![h("30")])).is_err(), "no parameters yet"); + assert!(add_parameter(&mut d, "*Model_Space", &linear(2)).is_err()); + assert!(add_parameter(&mut d, "", &linear(2)).is_err()); +} + +#[test] +fn element_tags_are_unique_and_the_record_keeps_the_next() { + let (mut d, _, _) = stretchy(); + let mut store = d.block("BOX").unwrap().entities.clone(); + // A copy carrying the rectangle's tag gets one of its own. + let mut copy = (**store.get(h("30")).unwrap()).clone(); + tag_elements(&mut d, "BOX", &mut store); + copy.handle = h("32"); + copy.common.xdata = store.get(h("30")).unwrap().common.xdata.clone(); + store.push(copy); + tag_elements(&mut d, "BOX", &mut store); + let tag_of = |e: &cadcraft_doc::Entity| e.common.xdata.iter().find(|t| t.code == 1071).map(|t| t.value.clone()).unwrap(); + let self_of = |e: &cadcraft_doc::Entity| e.common.xdata.iter().find(|t| t.code == 1005).map(|t| t.value.clone()).unwrap(); + let tags: Vec<_> = store.iter().map(|e| (tag_of(e), self_of(e))).collect(); + assert_eq!(tags, [("0".into(), "30".into()), ("1".into(), "31".into()), ("2".into(), "32".into())]); + let x = d.foreign.records.get(&("BLOCK_RECORD".to_string(), "BOX".to_string())).unwrap(); + assert_eq!(x.xdata.iter().rev().find(|t| t.code == 1071).map(|t| t.value.as_str()), Some("3")); +} + +/// Each grip location component names the parameter it reads (`AcDbBlockGripExpr` 91), as +/// AutoCAD writes it: a second parameter's components name it, not the first. AutoCAD evaluated +/// no parameter of a block whose later components named the first. +#[test] +fn grip_components_name_their_own_parameter() { + let mut d = box_drawing(); + let first = add_parameter(&mut d, "BOX", &linear(1)).unwrap(); + let second = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(10.0, 2.5), label: None, label_at: v(11.0, 3.5), grips: 1 }).unwrap(); + let owners: Vec<(String, i32)> = d + .foreign + .objects + .iter() + .filter(|o| o.kind == "BLOCKGRIPLOCATIONCOMPONENT") + .map(|o| { + let at = o.tags.iter().position(|t| t.value == "AcDbBlockGripExpr").unwrap(); + let owner = o.tags[at + 1..].iter().find(|t| t.code == 91).unwrap().value.parse().unwrap(); + let name = o.tags.iter().find(|t| t.code == 300).unwrap().value.clone(); + (name, owner) + }) + .collect(); + let want: Vec<(String, i32)> = [("UpdatedEndX", first), ("UpdatedEndY", first), ("UpdatedX", second), ("UpdatedY", second)] + .iter() + .map(|(n, o)| (n.to_string(), *o)) + .collect(); + assert_eq!(owners, want); + assert_eq!((first, second), (1, 5)); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index e3d58fbe8f..7ecc6c8860 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -31,6 +31,7 @@ mod dwg_roundtrip_losses; mod dwt_template; mod dxf_versions; mod dynblock_array; +mod dynblock_author; mod dynblock_params; mod dynblock_read; mod dynblock_rotate_flip; diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index e8d981b749..1720ed3757 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -1,9 +1,13 @@ //! The Block Editor on the canvas (BEDIT): a tint over the drawing area so the editor can't be -//! mistaken for the drawing, the block's base point marked at the origin, and a bar with the -//! block's name and Save Block, Save Block As and Close Block Editor. +//! mistaken for the drawing, the block's base point marked at the origin, the block's +//! parameters and actions (BPARAMETER, BACTION) drawn as the editor shows them, and a bar with +//! the block's name and Save Block, Save Block As and Close Block Editor. +use std::sync::Arc; + +use cadcraft_engine::doc::dynblock::Mark; use cadcraft_engine::geom::Vec2; -use egui::{Rect, RichText, Stroke, vec2}; +use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Shape, Stroke, vec2}; use serde_json::json; use super::Xf; @@ -39,6 +43,7 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf p.line_segment([o - vec2(12.0, 0.0), o + vec2(12.0, 0.0)], st); p.line_segment([o - vec2(0.0, 12.0), o + vec2(0.0, 12.0)], st); } + paint_marks(app, ctx, p, xf); let mut action: Option<(&str, bool)> = None; egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( ctx, @@ -75,3 +80,81 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf None => {} } } + +/// The edited block's parameters and actions, worked out once per drawing revision. +fn marks(app: &CadApp, ctx: &egui::Context) -> Arc> { + type Cache = Option<((u64, u64), Arc>)>; + let Ok(st) = app.session.state() else { return Arc::default() }; + let Some(be) = &st.block_edit else { return Arc::default() }; + let key = (st.uid, st.revision); + let cid = egui::Id::unique("cadcraft-block-editor-marks"); + if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() + && k == key + { + return m; + } + let m = Arc::new(be.marks(&st.doc)); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, m.clone())))); + m +} + +/// A filled arrow at `at` pointing along screen direction `u`, as a linear parameter's grip. +fn arrow(p: &Painter, at: Pos2, u: egui::Vec2, color: Color32) { + let n = vec2(-u.y, u.x); + let (len, half) = (9.0, 5.0); + p.add(Shape::convex_polygon(vec![at - u * (len * 0.4) + n * half, at + u * (len * 0.6), at - u * (len * 0.4) - n * half], color, Stroke::NONE)); +} + +/// Draw each parameter and action of the edited block: a linear parameter as a dimension with +/// its label and arrow grips, a point parameter as a marker with its label, other parameters by +/// name, and actions as badges. +fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { + let t = Tokens::get(); + let line = Stroke::new(1.0, t.accent); + let font = FontId::proportional(12.0); + let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); + for m in marks(app, ctx).iter() { + match m { + Mark::Linear { base, end, offset, label, base_grip, end_grip, .. } => { + let (a, b) = (base.xy(), end.xy()); + let dir = (b - a).normalized(); + let shift = Vec2::new(-dir.y, dir.x) * *offset; + let (da, db) = (xf.to_screen(a + shift), xf.to_screen(b + shift)); + let (sa, sb) = (to(*base), to(*end)); + p.line_segment([sa, da], line); + p.line_segment([sb, db], line); + p.line_segment([da, db], line); + let along = sb - sa; + let u = if along.length() > 1e-6 { along / along.length() } else { vec2(1.0, 0.0) }; + if *base_grip { + arrow(p, sa, -u, t.grip_dyn); + } + if *end_grip { + arrow(p, sb, u, t.grip_dyn); + } + p.text(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label, font.clone(), t.accent); + } + Mark::Point { at, label_at, label, grip, .. } => { + let (s, l) = (to(*at), to(*label_at)); + p.line_segment([s, l], line); + if *grip { + p.rect_filled(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, t.grip_dyn); + } else { + p.rect_stroke(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, line, egui::StrokeKind::Middle); + } + p.text(l, Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + } + Mark::Parameter { at, label, .. } => { + p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + } + Mark::Action { at, name, .. } => { + let c = to(*at); + let g = p.layout_no_wrap(name.clone(), font.clone(), t.text); + let r = Rect::from_center_size(c, g.size() + vec2(8.0, 4.0)); + p.rect_filled(r, 3.0, t.cmd_bg); + p.rect_stroke(r, 3.0, Stroke::new(1.0, t.warn), egui::StrokeKind::Middle); + p.galley(r.min + vec2(4.0, 2.0), g, t.text); + } + } + } +} diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 4935883e0b..6c7b11de7b 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1529,3 +1529,5 @@ menu View 视图 # ArtCraft feature naming Additional Tools 其他工具 + Parameter 参数 + Action 动作