Skip to content
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/hatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub(crate) use assoc::detach;
mod edit;
mod pick;
use super::has_doc;
pub(crate) use assoc::update as refill_associative;
pub(crate) use assoc::{remap_sources as remap_copied_sources, update as refill_associative};
pub use pick::{HatchPicks, PickMode};

pub fn specs() -> Vec<CommandSpec> {
Expand Down
22 changes: 21 additions & 1 deletion crates/engine/src/cmd/hatch/assoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
//! stops being associative (with a message).
//! - The hatch moved or reshaped without its boundary: it stops being associative.
//! - A new hatch (COPY, paste, EXPLODE) whose loops aren't where its objects are: it stops being
//! associative.
//! associative. COPY, MIRROR, ROTATE and SCALE that copy a hatch together with all of its
//! objects point the copy at the copied objects first ([`remap_sources`]), so it follows them.
//!
//! Only hatches whose own objects changed are traced again, so a command costs a scan of the
//! hatches plus the work on the ones it touched.

use std::collections::HashMap;
use std::sync::Arc;

use cadcraft_doc::{Drawing, EntityKind, Handle, Hatch, HatchLoop, entity_bounds};
Expand Down Expand Up @@ -126,6 +128,24 @@ pub(crate) fn detach(h: &mut Hatch) {
h.loops.iter_mut().for_each(|l| l.sources.clear());
}

/// Point the loops of a copied hatch at the copies of its objects, when every object of every
/// loop was copied with it (`map`: original handle to copy). Returns whether it did; a hatch
/// copied without all of its objects keeps its sources, and [`update`] ends its link.
pub(crate) fn remap_sources(h: &mut Hatch, map: &HashMap<Handle, Handle>) -> bool {
let srcs = || h.loops.iter().flat_map(|l| &l.sources);
if !h.associative || srcs().next().is_none() || !srcs().all(|s| map.contains_key(s)) {
return false;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
for l in &mut h.loops {
for s in &mut l.sources {
if let Some(&c) = map.get(s) {
*s = c;
}
}
}
true
}

/// Loops of `h` that aren't loops of `prev` (a hatch split by HATCHEDIT, or one that lost an
/// island, keeps the rest unchanged).
fn reshaped(prev: &Hatch, h: &Hatch) -> bool {
Expand Down
17 changes: 17 additions & 0 deletions crates/engine/src/cmd/modify/transform.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::collections::HashMap;

use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec3;

use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets};
Expand Down Expand Up @@ -30,16 +33,24 @@ pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 {
fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Entity)) -> Result<Vec<Handle>> {
let d = s.doc_mut()?;
let mut out = Vec::new();
// Copies: original handle to copy, and the copied hatches, so a hatch copied together with
// its boundary follows the copied boundary.
let mut copies: HashMap<Handle, Handle> = HashMap::new();
let mut hatches = Vec::new();
for h in hs {
let Some(sp) = d.space_of(*h) else { continue };
if copy {
let Some(e) = d.entity(*h).map(|e| (**e).clone()) else { continue };
let nh = d.new_handle();
let mut ne = Entity { handle: nh, ..e };
edit(&mut ne);
if matches!(ne.kind, EntityKind::Hatch(_)) {
hatches.push(nh);
}
if let Some(st) = d.space_mut(&sp) {
st.push(ne);
out.push(nh);
copies.insert(*h, nh);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
} else {
let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked);
Expand All @@ -50,6 +61,12 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
out.push(*h);
}
}
for h in hatches {
let Some(EntityKind::Hatch(mut x)) = d.entity(h).map(|e| e.kind.clone()) else { continue };
if crate::cmd::hatch::remap_copied_sources(&mut x, &copies) {
d.modify_entity(h, |e| e.kind = EntityKind::Hatch(x))?;
}
}
Ok(out)
}

Expand Down
110 changes: 110 additions & 0 deletions crates/engine/tests/it/hatch_assoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,116 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
assert!(!hatch(&s, &h).associative);
}

/// The handles a command returned, in order.
fn handles(v: &Value) -> Vec<String> {
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
}

fn sorted_sources(h: &Hatch) -> Vec<String> {
let mut v: Vec<String> = h.loops.iter().flat_map(|l| &l.sources).map(|h| h.hex()).collect();
v.sort();
v
}

#[test]
fn copying_the_hatch_with_its_boundary_keeps_the_copy_associative() {
let mut s = Session::new();
let (mut ls, h) = square_of_lines(&mut s);
ls.push(h.clone());
let out = handles(&s.execute("copy", &json!({ "handles": ls, "delta": [30, 0] })).unwrap());
assert_eq!(out.len(), 5);
let (copied_lines, copy) = (out[..4].to_vec(), out[4].clone());
let ch = hatch(&s, &copy);
assert!(ch.associative, "the copy follows its own boundary");
let mut want = copied_lines.clone();
want.sort();
assert_eq!(sorted_sources(&ch), want, "the copy's loop names the copied lines");
assert!(bounds(&ch).min.dist(Vec2::new(30.0, 0.0)) < 1e-6);
// Stretch the copied right edge out by 5: the copy fills 15 x 10, the original stays 10 x 10.
s.execute("stretch", &json!({ "window": [[38, -1], [42, 11]], "delta": [5, 0] })).unwrap();
let ch = hatch(&s, &copy);
assert!(ch.associative);
assert!(close(area(&ch), 150.0), "copy area {}", area(&ch));
let oh = hatch(&s, &h);
assert!(oh.associative);
assert!(close(area(&oh), 100.0), "original area {}", area(&oh));
}

#[test]
fn copying_the_hatch_with_part_of_its_boundary_ends_the_copys_link() {
let mut s = Session::new();
let (ls, h) = square_of_lines(&mut s);
let sel = vec![ls[0].clone(), ls[1].clone(), ls[2].clone(), h.clone()];
let out = handles(&s.execute("copy", &json!({ "handles": sel, "delta": [30, 0] })).unwrap());
let ch = hatch(&s, &out[3]);
assert!(!ch.associative, "three of four lines don't enclose the copy");
assert!(hatch(&s, &h).associative);
}

#[test]
fn copying_the_hatch_with_its_boundary_twice_links_each_copy_to_its_own_lines() {
let mut s = Session::new();
let (mut ls, h) = square_of_lines(&mut s);
ls.push(h);
let out = handles(&s.execute("copy", &json!({ "handles": ls, "delta": [30, 0], "count": 2 })).unwrap());
assert_eq!(out.len(), 10);
for set in out.chunks(5) {
let ch = hatch(&s, &set[4]);
assert!(ch.associative);
let mut want = set[..4].to_vec();
want.sort();
assert_eq!(sorted_sources(&ch), want);
}
}

#[test]
fn mirroring_the_hatch_with_its_boundary_keeps_the_copy_associative() {
let mut s = Session::new();
let (mut ls, h) = square_of_lines(&mut s);
ls.push(h.clone());
let out = handles(&s.execute("mirror", &json!({ "handles": ls, "p1": [20, 0], "p2": [20, 10] })).unwrap());
let ch = hatch(&s, &out[4]);
assert!(ch.associative, "the mirrored copy follows its own boundary");
let mut want = out[..4].to_vec();
want.sort();
assert_eq!(sorted_sources(&ch), want);
assert!(bounds(&ch).min.dist(Vec2::new(30.0, 0.0)) < 1e-6);
assert!(hatch(&s, &h).associative);
}

/// ROTATE and SCALE with the copy option copy a hatch together with its boundary; the copy names
/// the copied lines and the original keeps its own.
fn assert_copy_follows_copied_lines(s: &Session, out: &[String], original: &str) {
assert_eq!(out.len(), 5);
let ch = hatch(s, &out[4]);
assert!(ch.associative, "the copy follows its own boundary");
let mut want = out[..4].to_vec();
want.sort();
assert_eq!(sorted_sources(&ch), want, "the copy's loop names the copied lines");
assert!(hatch(s, original).associative);
}

#[test]
fn rotating_a_copy_of_the_hatch_with_its_boundary_keeps_the_copy_associative() {
let mut s = Session::new();
let (mut ls, h) = square_of_lines(&mut s);
ls.push(h.clone());
let out = handles(&s.execute("rotate", &json!({ "handles": ls, "base": [20, 0], "angle": 90, "copy": true })).unwrap());
assert_copy_follows_copied_lines(&s, &out, &h);
assert!(close(area(&hatch(&s, &out[4])), 100.0));
}

#[test]
fn scaling_a_copy_of_the_hatch_with_its_boundary_keeps_the_copy_associative() {
let mut s = Session::new();
let (mut ls, h) = square_of_lines(&mut s);
ls.push(h.clone());
let out = handles(&s.execute("scale", &json!({ "handles": ls, "base": [30, 0], "factor": 2, "copy": true })).unwrap());
assert_copy_follows_copied_lines(&s, &out, &h);
assert!(close(area(&hatch(&s, &out[4])), 400.0));
assert!(close(area(&hatch(&s, &h)), 100.0));
}

#[test]
fn non_associative_hatch_keeps_no_sources() {
let mut s = Session::new();
Expand Down
Loading