mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-29 21:59:47 +00:00
156 lines
6.6 KiB
Rust
156 lines
6.6 KiB
Rust
use super::{
|
|
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
|
|
other, targets,
|
|
};
|
|
|
|
// =====================================================================================
|
|
// ARRAYPATH (non-associative copies along a curve)
|
|
// =====================================================================================
|
|
|
|
pub(crate) fn arraypath(
|
|
s: &mut Session,
|
|
hs: &[Handle],
|
|
path: Handle,
|
|
count: Option<usize>,
|
|
spacing: Option<f64>,
|
|
align: bool,
|
|
) -> Result<Vec<Handle>> {
|
|
let pk = curves::entity(s, path)?.kind;
|
|
let c = Chain::of(&pk).ok_or_else(|| other("Select a line, arc, circle, polyline, ellipse or spline as the path."))?;
|
|
let l = c.len();
|
|
if l <= 1e-12 {
|
|
return Err(other("The path has no length."));
|
|
}
|
|
let objs: Vec<Handle> = hs.iter().copied().filter(|h| *h != path).collect();
|
|
if objs.is_empty() {
|
|
return Err(other("Select objects to array."));
|
|
}
|
|
let (n, step) = match (count, spacing) {
|
|
// As AutoCAD 2024 fills a path by distance: floor(length / spacing) items on a closed path,
|
|
// so none lands on or near the first where the path closes, and one more, at the end, on
|
|
// an open one (measured). The 1e-9 lets a length that comes out a hair short still fit.
|
|
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => {
|
|
let fit = (l / sp + 1e-9).floor() as usize;
|
|
(if c.closed { fit.max(1) } else { fit.saturating_add(1) }, sp)
|
|
}
|
|
(Some(n), _) => {
|
|
let n = n.max(1);
|
|
(n, if c.closed { l / n as f64 } else { l / (n.max(2) - 1) as f64 })
|
|
}
|
|
_ => (6, if c.closed { l / 6.0 } else { l / 5.0 }),
|
|
};
|
|
crate::cmd::array::check_size(s, n as u64, objs.len())?;
|
|
// Segment end lengths once: each sample is then a binary search, not a scan from the start.
|
|
let ends = c.end_lengths();
|
|
let Some((p0, t0)) = c.at_length_in(&ends, 0.0) else { return Ok(Vec::new()) };
|
|
let mut mats = Vec::new();
|
|
for i in 1..n {
|
|
let Some((p, t)) = c.at_length_in(&ends, step * i as f64) else { continue };
|
|
let mut m = Mat3::translate(p - p0);
|
|
if align {
|
|
m = Mat3::rotate_about(p, t.angle() - t0.angle()).then_before(m);
|
|
}
|
|
mats.push(m);
|
|
}
|
|
// Every copy is checked before the first is made: a refusal part way would leave the copies
|
|
// already added in the drawing (a failed command is not rolled back).
|
|
if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && crate::cmd::modify::holds_ole_frame(s, &objs, true)? {
|
|
return Err(crate::cmd::modify::ole_refusal());
|
|
}
|
|
let mut out = Vec::new();
|
|
for m in &mats {
|
|
out.extend(crate::cmd::modify::transform_entities(s, &objs, m, true)?);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub(super) fn run_arraypath(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let hs = targets(s, p)?;
|
|
let path = curves::handle_param(p, "path").ok_or_else(|| bad("arraypath", "`path` (handle) is required"))?;
|
|
// As in the other arrays' JSON forms, a value that isn't a whole number of at least 1 (or a
|
|
// positive spacing) is refused, not ignored; missing or null is the default.
|
|
let count = crate::cmd::array::count_or("arraypath", p, "count", 6)?;
|
|
let spacing = crate::cmd::size_param("arraypath", p, "spacing", false)?;
|
|
let r = arraypath(s, &hs, path, Some(usize::try_from(count).unwrap_or(usize::MAX)), spacing, bool_or(p, "align", true))?;
|
|
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
|
}
|
|
|
|
/// The number of items typed at ARRAYPATH's prompt: a whole number from 1 to 32767, written in
|
|
/// plain decimals. AutoCAD 2024 takes 5, +5, 05, 5., 5.0, 5.00 and +5.0 there, and refuses 4.5,
|
|
/// 1e1, 8/2, 3', 0 and 32768 (measured).
|
|
pub(super) fn item_count(t: &str) -> Option<usize> {
|
|
let t = t.trim();
|
|
let digits = t.strip_prefix('+').unwrap_or(t);
|
|
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
|
|
let plain = !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()) && fraction.bytes().all(|b| b == b'0');
|
|
whole.parse::<usize>().ok().filter(|n| plain && (1..=32_767).contains(n))
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(in crate::cmd) struct PathArrayM {
|
|
sel: SelectPhase,
|
|
objs: Vec<Handle>,
|
|
path: Option<Handle>,
|
|
}
|
|
|
|
impl PathArrayM {
|
|
/// Start at the path prompt with the objects already selected (ARRAY > PAth).
|
|
pub(in crate::cmd) fn with_objects(objs: Vec<Handle>) -> Self {
|
|
PathArrayM { sel: SelectPhase { picked: objs.clone(), done: true, ..SelectPhase::default() }, objs, path: None }
|
|
}
|
|
}
|
|
|
|
impl Interactive for PathArrayM {
|
|
fn name(&self) -> &'static str {
|
|
"ARRAYPATH"
|
|
}
|
|
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
|
self.sel = SelectPhase::begin(s);
|
|
if self.sel.done {
|
|
self.objs = self.sel.picked.clone();
|
|
}
|
|
Ok(Step::Continue)
|
|
}
|
|
fn prompt(&self, _s: &Session) -> Prompt {
|
|
if !self.sel.done {
|
|
return self.sel.prompt();
|
|
}
|
|
match self.path {
|
|
None => Prompt::new("Select path curve", Accept::POINT),
|
|
Some(_) => Prompt::new("Enter number of items along path", Accept::NUMBER).default("6"),
|
|
}
|
|
}
|
|
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
|
if !self.sel.done {
|
|
return match self.sel.feed(s, &i)? {
|
|
SelOutcome::More => Ok(Step::Continue),
|
|
SelOutcome::Empty => Ok(Step::Cancel),
|
|
SelOutcome::Done(hs) => {
|
|
self.objs = hs;
|
|
Ok(Step::Continue)
|
|
}
|
|
};
|
|
}
|
|
match (self.path, i) {
|
|
(None, Input::Point(p)) => {
|
|
let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?;
|
|
Chain::of(&curves::entity(s, h)?.kind).ok_or_else(|| other("Select a curve as the path."))?;
|
|
self.path = Some(h);
|
|
Ok(Step::Continue)
|
|
}
|
|
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
|
|
let n = match &inp {
|
|
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
|
|
_ => 6,
|
|
};
|
|
arraypath(s, &self.objs, path, Some(n), None, true)?;
|
|
s.set_selection(Vec::new());
|
|
s.echo(format!("Type = Path Associative = No ({n} items)"));
|
|
Ok(Step::Done)
|
|
}
|
|
(None, Input::Enter) => Ok(Step::Cancel),
|
|
_ => Ok(Step::Continue),
|
|
}
|
|
}
|
|
}
|