From c914f6963df8659e60061a1a4b9c4407bc40bcce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 13:14:53 -0800 Subject: [PATCH] DXF/DWG import: keep symbols apart only where their art differs A block's symbol was looked up by its scale alone, so a placement whose art the nesting limit cut short, or that left out a block placing one of its ancestors, could hand that shortened art to a complete placement at the same scale. The symbol key now also holds the depth where the block's art reaches the nesting limit (counted under the ancestors it places) and the ancestors it places within that limit. The scale scan reuses a "yes" only while none of the blocks it went into to reach the dashes is an ancestor, and keeps up to four of them; it checks anonymous blocks with everything they inherit, as they are drawn. Inserts on hidden layers are not followed. The new shape checks have an import-wide work budget and a memory budget. --- crates/cad/src/import/build.rs | 337 +++++++++++++++++++++-- crates/cad/src/import/tests.rs | 328 ++++++++++++++++++++++ docs/mcp.md | 4 +- docs/progress/dxf-scaled-block-dashes.md | 1 + 4 files changed, 640 insertions(+), 30 deletions(-) create mode 100644 docs/progress/dxf-scaled-block-dashes.md diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index c8c6a0e2ad..11bfac399c 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -34,6 +34,13 @@ const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; /// The most scale checks kept for one block at one depth that left out a block inside itself /// under different ancestors. const MAX_SCANS_HERE: usize = 16; +/// The most blocks the checks of which blocks a block places look at in one import; past it the +/// checks take the art as different for each placement (a symbol of its own). +const MAX_SHAPE_WORK: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; +/// The most bytes of block names the shape checks keep in their sets of placed blocks. +const MAX_REACH_KEPT: usize = if cfg!(test) { 1_000_000 } else { 32_000_000 }; +/// The most "yes" scale scans kept for one block and what it inherits. +const MAX_SCALED_YES: usize = 4; /// The most path elements an import makes (blocks drawn as art are copied for every placement). pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; /// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). @@ -91,6 +98,20 @@ struct Inherit { layer: Option, } +/// A symbol's block, what it inherits, the scale slot, the depth when the nesting limit may cut +/// off its art, and its ancestors that it places (sorted). +type SymbolKey = (String, Inherit, u64, Option, Vec>); + +/// A shape check's block, its levels to the nesting limit and the ancestors it holds for. +type ShapeKey = (Rc, u32, Vec>); + +/// The blocks a block places within some levels (`None`: the shape checks' budgets ran out). +type Reach = Option>>; + +/// A kept scale scan: the shallowest and deepest depths it holds at, whether the nesting limit +/// cut off art, and the blocks it went into to reach dashes or wide polylines. +type ScaledLook = (u32, u32, bool, Rc>); + /// A scale scan of a block that left out a block inside itself: its answer, whether the nesting /// limit cut off art, the blocks it went into and the ones it left out. #[derive(Debug)] @@ -156,14 +177,34 @@ pub(crate) struct Build<'d, 'a> { blocks: HashMap>>, bounds: HashMap>, sensitive: HashMap, - /// Symbol names by block, what it inherits and the scale its art is drawn at (the bits of - /// [`symbol_scale`]'s answer, or of -1 - depth for art the nesting limit may have cut off at - /// that depth; `None`: the block has no art). - symbols: HashMap<(String, Inherit, u64), Option>, + /// Symbol names by block, what it inherits, the scale its art is drawn at (the bits of + /// [`symbol_scale`]'s answer), the depth when the nesting limit may cut off some of its art + /// there, and the ancestors it places, which are left out of its art (`None`: the block has + /// no art). + symbols: HashMap>, + /// The blocks a block places within some levels below itself (see [`Build::reach_within`]). + reaches: HashMap, + /// The blocks each block places directly (see [`Build::placed_blocks`]). + placed: HashMap>>, + /// How many levels of blocks a block draws below itself (see [`Build::height_under`]). + block_height: HashMap, + /// Whether a block placed with so many levels left before the nesting limit reaches it (see + /// [`Build::reaches_limit`]). + limit_reached: HashMap, + /// The ancestors a block places, by block, levels to the nesting limit and ancestors. + ancestors_placed: HashMap>>, + /// One shared copy of each ancestor name the keys above hold. + interned: HashSet>, + /// The steps the shape checks have taken (see [`Build::shape_step`]). + shape_work: usize, + /// How many bytes of names the kept sets of `reaches` hold. + reach_kept: usize, /// Whether a block placed with what it inherits draws dashes or wide polylines, whose - /// lengths and widths follow the insert's scale: the depths each answer holds at, and whether - /// the nesting limit cut off art (see [`Build::scaled_look`]). - scaled_looks: HashMap<(String, Inherit, bool), (u32, u32, bool)>, + /// lengths and widths follow the insert's scale: the depths each answer holds at, whether + /// the nesting limit cut off art, and for a "yes" the blocks it went into to reach the dashes + /// or wide polylines (see [`Build::scaled_look`]). + /// A "yes" keeps up to [`MAX_SCALED_YES`] answers that reached their dashes by different blocks. + scaled_looks: HashMap<(String, Inherit, bool), Vec>, /// The same answers for scans that left out a block inside itself, by depth. scaled_looks_here: HashMap<(String, Inherit, u32), Vec>>, /// The steps of the scale scan in progress. @@ -248,6 +289,14 @@ impl<'d, 'a> Build<'d, 'a> { bounds: HashMap::new(), sensitive: HashMap::new(), symbols: HashMap::new(), + reaches: HashMap::new(), + placed: HashMap::new(), + shape_work: 0, + reach_kept: 0, + limit_reached: HashMap::new(), + ancestors_placed: HashMap::new(), + interned: HashSet::new(), + block_height: HashMap::new(), scaled_looks: HashMap::new(), scaled_looks_here: HashMap::new(), scan_trail: Vec::new(), @@ -463,6 +512,185 @@ impl<'d, 'a> Build<'d, 'a> { true } + /// The blocks block `name` places directly, once each (inserts on a hidden layer other than + /// layer 0 are left out, as `art` leaves them out), or `None` when it is missing or an + /// external reference. Read once per block. + fn placed_blocks(&mut self, name: &str) -> Option>> { + if let Some(p) = self.placed.get(name) { + return Some(p.clone()); + } + if !self.blocks.contains_key(name) && self.d.blocks.get(name).is_none_or(|b| b.xref) { + return None; + } + let items = self.block(name)?; + let mut seen = HashSet::new(); + let mut placed = vec![]; + for it in items.iter() { + if let Geom::Insert(ins) = &it.geom + && !(it.props.layer != "0" && self.d.layer(&it.props.layer).is_some_and(|l| l.hidden)) + && seen.insert(ins.block.as_str()) + { + placed.push(ins.block.clone()); + } + } + let placed = Rc::new(placed); + self.placed.insert(name.to_string(), placed.clone()); + Some(placed) + } + + /// The shared copy of block name `name`. + fn intern(&mut self, name: &str) -> Rc { + if let Some(n) = self.interned.get(name) { + return n.clone(); + } + let n: Rc = Rc::from(name); + self.interned.insert(n.clone()); + n + } + + /// Counts one step of the shape checks against their import-wide budget; false once it is + /// spent, when the checks give their cautious answers. + fn shape_step(&mut self) -> bool { + self.shape_work = self.shape_work.saturating_add(1); + self.shape_work <= MAX_SHAPE_WORK + } + + /// The blocks block `name` places within `levels` levels below itself, not looking below an + /// ancestor (only blocks drawn above the nesting limit are read), or `None` when the shape + /// checks' budgets ran out. + fn reach_within(&mut self, name: &str, levels: u32) -> Option>> { + // A set that met no ancestor is kept for any ancestors that it does not hold, where it + // meets none either; one cut short at an ancestor is kept for these ancestors alone. + let open = (self.intern(name), levels, vec![]); + if let Some(r) = self.reaches.get(&open) + && r.as_ref().is_none_or(|r| !self.stack.iter().any(|s| r.contains(s))) + { + return r.clone(); + } + let stack: Vec> = self.stack.clone().iter().map(|s| self.intern(s)).collect(); + let key = (open.0.clone(), levels, stack); + if let Some(r) = self.reaches.get(&key) { + return r.clone(); + } + // Past the shape checks' budget the block is taken to place every ancestor. The kept + // entries hold at most `MAX_REACH_KEPT` bytes in all (names, with a word or so of overhead + // each, and each key's ancestors); past it a result is used without being kept. + let mut seen = HashSet::new(); + let mut size = 64usize.saturating_add(key.2.len().saturating_mul(16)); + // An ancestor is left out where it is placed, so nothing is looked at below it. + let stack = self.stack.clone(); + let mut stopped_at_ancestor = false; + let mut layer = vec![name.to_string()]; + let mut complete = true; + 'levels: for _ in 0..levels { + let mut next = vec![]; + for n in &layer { + for child in self.placed_blocks(n).unwrap_or_default().iter() { + if !self.shape_step() { + complete = false; + break 'levels; + } + if seen.contains(child) { + continue; + } + size = size.saturating_add(child.len().saturating_add(32)); + seen.insert(child.clone()); + if stack.contains(child) { + stopped_at_ancestor = true; + } else { + next.push(child.clone()); + } + } + } + if next.is_empty() { + break; + } + layer = next; + } + let r = complete.then(|| Rc::new(seen)); + if !complete { + size = 64usize.saturating_add(key.2.len().saturating_mul(16)); + } + if self.reach_kept.saturating_add(size) <= MAX_REACH_KEPT { + self.reach_kept += size; + self.reaches.insert(if stopped_at_ancestor || !complete { key } else { open }, r.clone()); + } + r + } + + /// Does block `name` placed `depth` deep draw blocks down to the nesting limit, which then + /// cuts off art? Counted under `ancestors`, the ancestors it places, which are left out, as is + /// a block inside itself. Yes when the shape checks' budget ran out. + fn reaches_limit(&mut self, name: &str, depth: u32, ancestors: &[Rc]) -> bool { + let limit = match MAX_NEST.checked_sub(depth) { + Some(limit) if limit > 0 => limit, + _ => return true, + }; + let key = (self.intern(name), limit, ancestors.to_vec()); + if let Some(r) = self.limit_reached.get(&key) { + return *r; + } + let r = self.height_under(name, limit, &mut ancestors.iter().map(|a| a.to_string()).collect()).0.is_none(); + if self.shape_work <= MAX_SHAPE_WORK { + self.limit_reached.insert(key, r); + } + r + } + + /// How many levels of blocks block `name` draws below itself under the blocks in `path`, or + /// `None` for `limit` levels or more (`limit` is at least 1); with the shallowest index in + /// `path` of a block it left out as a block inside itself (`usize::MAX`: none). Each child + /// looked at counts against the shape checks' budget. Only blocks drawn above the limit are + /// read. + fn height_under(&mut self, name: &str, limit: u32, path: &mut Vec) -> (Option, usize) { + if let Some(&h) = self.block_height.get(name) { + return ((h < limit).then_some(h), usize::MAX); + } + if !self.shape_step() { + return (None, 0); + } + path.push(name.to_string()); + let mut h = Some(0); + let mut hit = usize::MAX; + for child in self.placed_blocks(name).unwrap_or_default().iter() { + if !self.shape_step() { + (h, hit) = (None, 0); + break; + } + // A missing block draws nothing at any depth. + if !self.blocks.contains_key(child) && self.d.blocks.get(child).is_none_or(|b| b.xref) { + continue; + } + // A block inside itself is left out. + if let Some(i) = path.iter().position(|p| p == child) { + hit = hit.min(i); + continue; + } + // A child at the limit is not drawn, and is not read. + if limit == 1 { + h = None; + break; + } + let (child_h, child_hit) = self.height_under(child, limit - 1, path); + hit = hit.min(child_hit); + h = h.zip(child_h).map(|(a, b)| a.max(b.saturating_add(1))); + if h.is_none() { + break; + } + } + path.pop(); + // A count that left out a block inside itself anywhere below may count a path that is a + // loop under other ancestors, and one stopped at the limit may not have looked at every + // child, so only a complete count with neither is kept. + if let Some(h) = h + && hit == usize::MAX + && self.shape_work <= MAX_SHAPE_WORK + { + self.block_height.insert(name.to_string(), h); + } + (h, hit) + } + /// A block's bounds in its coordinates less its base point. fn block_bounds(&mut self, name: &str, depth: u32) -> Option { if let Some(b) = self.bounds.get(name) { @@ -1129,29 +1357,33 @@ impl<'d, 'a> Build<'d, 'a> { /// still within the nesting limit. A "no" that left out a block inside itself, or that the /// work budget stopped, holds nowhere. Last, whether the nesting limit cut off any of the /// block's art at this depth. `nested` is set when the scan of an enclosing block asks. - fn scaled_look(&mut self, name: &str, inh: &Inherit, depth: u32, nested: bool) -> (bool, (u32, u32), bool) { + fn scaled_look(&mut self, name: &str, inh: &Inherit, depth: u32, nested: bool) -> (bool, (u32, u32), bool, Rc>) { // A block inside itself is left out only under this chain of ancestors, so the answer // holds nowhere else. It is left out at any depth, so the nesting limit cuts off nothing. if self.stack.iter().any(|s| s == name) { self.warn(NESTED); self.scan_trail.push(Trail::LeftOut(name.to_string())); - return (false, (u32::MAX, 0), false); + return (false, (u32::MAX, 0), false, Rc::default()); } let items = self.block(name); // A placement past the nesting limit draws none of the block, so its items are not // looked at or charged for, and no answer made at a shallower depth applies. if items.is_some() && depth >= MAX_NEST { self.warn(NESTED); - return (false, (depth, u32::MAX), true); + return (false, (depth, u32::MAX), true, Rc::default()); } // A block can have a "yes" for shallow placements and a "no" for deep ones, so each answer - // is kept with its own depths. + // is kept with its own depths. A "yes" holds only while none of the blocks it went into to + // reach the dashes or wide polylines is an ancestor, which would leave them out. let key = (name.to_string(), inh.clone()); for s in [true, false] { - if let Some(&(lo, hi, cut)) = self.scaled_looks.get(&(key.0.clone(), key.1.clone(), s)) - && (lo..=hi).contains(&depth) + let stack = &self.stack; + if let Some((lo, hi, cut, via)) = self + .scaled_looks + .get(&(key.0.clone(), key.1.clone(), s)) + .and_then(|answers| answers.iter().find(|(lo, hi, _, via)| (*lo..=*hi).contains(&depth) && !via.iter().any(|v| stack.contains(v)))) { - return (s, (lo, hi), cut); + return (s, (*lo, *hi), *cut, via.clone()); } } let context = (key.0.clone(), key.1.clone(), depth); @@ -1162,14 +1394,16 @@ impl<'d, 'a> Build<'d, 'a> { answers.iter().find(|a| a.left_out.iter().all(|l| stack.contains(l)) && !stack.iter().any(|s| a.reached.contains(s))) }); if let Some(a) = here.cloned() { + // Which of the blocks it went into hold the dashes is not kept, so all of them count. + let via = Rc::new(if a.scaled { a.reached.iter().cloned().collect() } else { vec![] }); if !nested { - return (a.scaled, (u32::MAX, 0), a.cut); + return (a.scaled, (u32::MAX, 0), a.cut, via); } let (scaled, cut) = (a.scaled, a.cut); // The scan in progress keeps one reference to it, not a copy of its names (see // `keep_new_steps`). self.scan_trail.push(Trail::Reused(a)); - return (scaled, (u32::MAX, 0), cut); + return (scaled, (u32::MAX, 0), cut, via); } let trail_start = self.scan_trail.len(); // Looking at a block's items counts against the block work as placing it does, so the @@ -1177,11 +1411,11 @@ impl<'d, 'a> Build<'d, 'a> { self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); if self.visits > MAX_VISITS { self.warn(TOO_MUCH_BLOCK_WORK); - return (false, (u32::MAX, 0), false); + return (false, (u32::MAX, 0), false, Rc::default()); } - let Some(items) = items else { return (false, (0, u32::MAX), false) }; + let Some(items) = items else { return (false, (0, u32::MAX), false, Rc::default()) }; if !self.enter(name, depth) { - return (false, (depth, u32::MAX), true); + return (false, (depth, u32::MAX), true, Rc::default()); } self.scan_trail.push(Trail::Went(name.to_string())); // The steps this scan has recorded, so that each is kept once. @@ -1190,6 +1424,8 @@ impl<'d, 'a> Build<'d, 'a> { let mut s = false; let mut from = 0; let mut cut = false; + // The blocks gone into to reach the art that made `s`. + let mut via = Rc::default(); // The deepest placement at which the art that made `s` is still drawn. let mut until = MAX_NEST - 1; for it in items.iter() { @@ -1209,9 +1445,12 @@ impl<'d, 'a> Build<'d, 'a> { Geom::Shaded { .. } | Geom::Text(_) | Geom::Image(_) => false, Geom::Insert(ins) => { let child = self.inherit(&it.props, inh); - let child = if self.is_sensitive(&ins.block, depth + 1) { child } else { Inherit::default() }; + // An anonymous block is drawn with all it inherits (see `insert`); a named one + // is looked up as its symbol is. + let keep = ins.block.starts_with('*') || self.is_sensitive(&ins.block, depth + 1); + let child = if keep { child } else { Inherit::default() }; let mark = self.scan_trail.len(); - let (scaled, (child_lo, child_hi), child_cut) = self.scaled_look(&ins.block, &child, depth + 1, true); + let (scaled, (child_lo, child_hi), child_cut, child_via) = self.scaled_look(&ins.block, &child, depth + 1, true); if !self.keep_new_steps(mark, &mut seen) { stopped = true; break; @@ -1219,6 +1458,10 @@ impl<'d, 'a> Build<'d, 'a> { cut |= child_cut; if scaled { until = child_hi.saturating_sub(1); + let mut v = Vec::with_capacity(child_via.len() + 1); + v.push(ins.block.clone()); + v.extend(child_via.iter().cloned()); + via = Rc::new(v); } else { from = from.max(child_lo.saturating_sub(1)); } @@ -1231,11 +1474,18 @@ impl<'d, 'a> Build<'d, 'a> { } self.stack.pop(); if stopped { - return (false, (u32::MAX, 0), false); + return (false, (u32::MAX, 0), false, Rc::default()); } let holds = if s { (0, until) } else { (from, u32::MAX) }; if (holds.0..=holds.1).contains(&depth) { - self.scaled_looks.insert((key.0, key.1, s), (holds.0, holds.1, cut)); + let answers = self.scaled_looks.entry((key.0, key.1, s)).or_default(); + // A "no" replaces the one before; a "yes" is kept beside others, the oldest going first. + if !s { + answers.clear(); + } else if answers.len() >= MAX_SCALED_YES { + answers.remove(0); + } + answers.push((holds.0, holds.1, cut, via.clone())); } else { // An answer that left out a block inside itself holds again wherever it would leave // out the same ancestors. A block left out because the scan itself went into it @@ -1271,7 +1521,7 @@ impl<'d, 'a> Build<'d, 'a> { #[cfg(test)] SCANS_HERE_MOST.with(|n| n.set(n.get().max(answers.len()))); } - (s, holds, cut) + (s, holds, cut, via) } /// Keeps the steps recorded on the scan trail from `mark` on that the scan has not recorded @@ -1315,12 +1565,41 @@ impl<'d, 'a> Build<'d, 'a> { } let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() }; self.scan_trail.clear(); - let (scaled, _, cut) = self.scaled_look(name, &inh, depth, false); + let (scaled, ..) = self.scaled_look(name, &inh, depth, false); let scale = if scaled { scale } else { 1.0 }; - // A "no" for art the nesting limit cut off keeps its symbol apart from those drawn at - // other depths, by the depth (as -1 - depth). - let slot = if !scaled && cut { (-1.0 - f64::from(depth)).to_bits() } else { scale.to_bits() }; - let key = (name.to_string(), inh, slot); + let slot = scale.to_bits(); + // The art drawn here may also differ by the depth (the nesting limit) and by the + // ancestors it places (left out of it), whatever the scan found before it stopped. The + // depth counts only where the block's art reaches the nesting limit, under any ancestors. + // Only an ancestor it places above the nesting limit changes the art (all of them when the + // checks' budget ran out). + // Down to the nesting limit itself: an ancestor there is left out either way, and counting + // it here keeps it from looking like art the limit cuts off. The answer is kept for these + // ancestors, whether or not the set it came from could be kept. The keys share one copy + // of each ancestor's name. + let levels = MAX_NEST.saturating_sub(depth); + let context: ShapeKey = (self.intern(name), levels, self.stack.clone().iter().map(|s| self.intern(s)).collect()); + let left_out = match self.stack.is_empty() { + true => vec![], + false => match self.ancestors_placed.get(&context) { + Some(found) => found.clone(), + None => { + let reach = self.reach_within(name, levels); + let mut found: Vec> = context.2.iter().filter(|s| reach.as_ref().is_none_or(|r| r.contains(&***s))).cloned().collect(); + found.sort(); + found.dedup(); + // Charged to the same budget as the kept sets. + let size = 64usize.saturating_add(context.2.len().saturating_add(found.len()).saturating_mul(16)); + if self.reach_kept.saturating_add(size) <= MAX_REACH_KEPT { + self.reach_kept += size; + self.ancestors_placed.insert(context, found.clone()); + } + found + } + }, + }; + let deep = self.reaches_limit(name, depth, &left_out); + let key = (name.to_string(), inh, slot, deep.then_some(depth), left_out); if let Some(s) = self.symbols.get(&key) { let s = s.clone()?; if !draw || !self.empty.contains(&s) { diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 60584a839c..097cdd375c 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1805,6 +1805,332 @@ fn a_block_cut_off_by_the_nesting_limit_keeps_the_art_a_shallower_placement_draw assert_eq!(strokes.len(), 2, "{names:?}: the shallower placement draws the lines of S and D1: {strokes:?}"); } +#[test] +fn a_dashed_block_cut_off_by_the_nesting_limit_keeps_its_art_for_a_shallow_placement_at_the_same_scale() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a dashed line and places "C", which has a solid line. The anonymous chain + // *B1 > ... > *B7 places "P" at scale 10 too deep to draw "C"; the drawing places "P" at + // scale 1, the chain, then "P" at scale 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "C"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "C"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 7; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*B{i}").into_boxed_str()); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + if i == chain { + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (41, "10"), (42, "10"), (0, "ENDBLK")]); + } else { + let next: &'static str = Box::leak(format!("*B{}", i + 1).into_boxed_str()); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + } + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "*B1"), + (10, "0"), + (20, "200"), + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let [first, deep, last] = &insts[..] else { panic!("{names:?}: {insts:?}") }; + assert_eq!(instance_strokes(&doc, first).len(), 2, "{names:?}"); + assert_eq!(instance_strokes(&doc, deep).len(), 1, "{names:?}: the deep placement draws only the dashed line"); + assert_eq!(instance_strokes(&doc, last).len(), 2, "{names:?}: the shallow placement at scale 10 draws the line of C"); +} + +#[test] +fn a_dashed_block_placed_inside_its_own_child_keeps_its_art_for_a_direct_placement_at_the_same_scale() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a dashed line and places *A, which has a solid line and places "P". The drawing + // places "P" at scale 1, *A at scale 10, then "P" at scale 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*A"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "*A"), + (10, "0"), + (20, "200"), + (41, "10"), + (42, "10"), + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let last = insts.last().unwrap_or_else(|| panic!("{names:?}")); + assert_eq!(instance_strokes(&doc, last).len(), 2, "{names:?}: the direct placement at scale 10 draws the line of *A"); +} + +#[test] +fn a_block_whose_dashes_are_in_an_ancestor_shares_one_symbol_across_its_scales() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a solid line and places "D"; "D" has a dashed line and places "P". The drawing + // places "P", then "D" at scales 2 and 3, inside which "P" leaves out "D" and its dashes. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "D"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "D"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let top = [ + (0, "INSERT"), + (2, "P"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "D"), + (10, "0"), + (20, "200"), + (41, "2"), + (42, "2"), + (0, "INSERT"), + (2, "D"), + (10, "0"), + (20, "400"), + (41, "3"), + (42, "3"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + // One "P" placed directly, and one for its solid art inside "D" at either scale. + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 2, "{names:?}"); +} + +#[test] +fn a_block_reaching_dashes_by_two_ancestors_in_turn_is_scale_checked_once_for_each() { + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + // "P" has a solid line and places *A1 and *A2, each with a dashed line and an insert of "P". + // Inside *A1, "P" reaches dashes only through *A2, and inside *A2 only through *A1. The drawing + // places *A1 and *A2 in turn. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "10"), (11, "100"), (21, "10")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A2"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + for a in ["*A1", "*A2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, a), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = (0..500).flat_map(|_| [insert("*A1"), insert("*A2")]).flatten().collect(); + build::SCALED_LOOK_ITEMS.with(|n| n.set(0)); + let r = open(&drawing(&[], &tables, &blocks, &top), &points()); + let looked = build::SCALED_LOOK_ITEMS.with(std::cell::Cell::get); + assert!(looked < 100, "{looked} items looked at"); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn blocks_placing_each_other_share_one_symbol_shallow_and_near_the_nesting_limit() { + // "A" and "B" each have a solid line and place each other. The drawing places "B", then "A", + // then the anonymous chain *C1 > ... > *C6, which places "A" six levels deep: "A" and "B" + // still draw there, and the copy of "A" inside "B" is left out in both placements. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for (name, other) in [("A", "B"), ("B", "A")] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, other), (10, "0"), (20, "10"), (0, "ENDBLK")]); + } + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*C{i}").into_boxed_str()); + let next: &'static str = if i == chain { "A" } else { Box::leak(format!("*C{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("B"), insert("A"), insert("*C1")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + // One "A" inside "B", which leaves out "B", and one for both placements of "A" itself. + assert_eq!(names.iter().filter(|n| n.starts_with('A')).count(), 2, "{names:?}"); +} + +#[test] +fn a_block_placed_at_the_nesting_limit_first_leaves_its_partner_one_symbol() { + // "A" and "B" each have a solid line and place each other. The anonymous chain *D1 > ... > *D7 + // places "A" seven levels deep, where it draws only its line; *C1 > ... > *C6 places "B" six + // levels deep, where "B" draws "A", which leaves out "B". The drawing places the two chains, + // then "B", which draws the same art. + let mut blocks: Vec<(i32, &'static str)> = vec![]; + for (name, other) in [("A", "B"), ("B", "A")] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, other), (10, "0"), (20, "10"), (0, "ENDBLK")]); + } + for (prefix, chain, target) in [("D", 7, "A"), ("C", 6, "B")] { + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*{prefix}{i}").into_boxed_str()); + let next: &'static str = if i == chain { target } else { Box::leak(format!("*{prefix}{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*D1"), insert("*C1"), insert("B")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('B')).count(), 1, "{names:?}"); +} + +#[test] +fn a_block_placing_its_anonymous_parent_shares_one_symbol_at_the_nesting_limit() { + // "P" has a solid line and places *A; *A places "P". Inside *A, "P" leaves out *A at any + // depth. The drawing places *A, then the chain *C1 > ... > *C6, which places *A six levels + // deep, so "P" is seven levels deep there. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*A"), (10, "0"), (20, "10"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*A"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*C{i}").into_boxed_str()); + let next: &'static str = if i == chain { "*A" } else { Box::leak(format!("*C{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let insert = |block: &'static str| [(0, "INSERT"), (2, block), (10, "0"), (20, "0")]; + let top: Vec<(i32, &str)> = [insert("*A"), insert("*C1")].concat(); + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(leaves(&doc).len(), 2, "{names:?}"); + assert_eq!(names, ["P"]); +} + +#[test] +fn a_block_reaching_other_ancestors_only_through_a_left_out_one_shares_one_symbol() { + // "O" places "W1" and "W2", each of which places "P"; "P" has a solid line and places "O". + // Inside either wrapper, "P" leaves out "O", and with it the other wrapper. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "O"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "INSERT"), (8, "0"), (2, "W1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "W2"), (10, "0"), (20, "100"), (0, "ENDBLK")]); + for w in ["W1", "W2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, w), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "O"), (10, "0"), (20, "10"), (0, "ENDBLK")]); + let top = [(0, "INSERT"), (2, "O"), (10, "0"), (20, "0")]; + let doc = open(&drawing(&[], &[], &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 1, "{names:?}"); +} + +#[test] +fn a_block_placing_its_ancestors_only_on_a_hidden_layer_shares_one_symbol_under_each() { + let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")]; + // "P" has a solid line and places "W1" and "W2" on a hidden layer; "W1" and "W2" each place + // "P". The drawing places "W1" and "W2". + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "P"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]); + blocks.extend([(0, "INSERT"), (8, "Off"), (2, "W1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Off"), (2, "W2"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + for w in ["W1", "W2"] { + blocks.extend([(0, "BLOCK"), (8, "0"), (2, w), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [(0, "INSERT"), (2, "W1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "W2"), (10, "0"), (20, "200")]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| n.starts_with('P')).count(), 1, "{names:?}"); +} + +#[test] +fn an_anonymous_block_is_scale_checked_with_the_layer_it_is_drawn_on() { + let tables = [ + (0, "TABLE"), + (2, "LTYPE"), + (0, "LTYPE"), + (2, "DASHED"), + (73, "2"), + (40, "15"), + (49, "10"), + (49, "-5"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (2, "Dashy"), + (70, "0"), + (62, "7"), + (6, "DASHED"), + (0, "ENDTAB"), + ]; + // *D has a line on layer 0 in the layer's linetype. *P places *D on layer 0 with its own + // color, lineweight and linetype, so *P alone does not look like it follows its insert. + // "N" places *P on "Dashy", whose linetype *D's line takes. "M" places *P too, and the chain + // *B1 > ... > *B6 places "M" where *D is past the nesting limit. The drawing places the + // chain, then "N" at scales 1 and 10. + let mut blocks: Vec<(i32, &'static str)> = vec![(0, "BLOCK"), (8, "0"), (2, "*D"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "100"), (21, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "*P"), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (6, "CONTINUOUS"), (62, "1"), (370, "25"), (2, "*D"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "N"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Dashy"), (2, "*P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + blocks.extend([(0, "BLOCK"), (8, "0"), (2, "M"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, "*P"), (10, "0"), (20, "0"), (0, "ENDBLK")]); + let chain = 6; + for i in 1..=chain { + let name: &'static str = Box::leak(format!("*B{i}").into_boxed_str()); + let next: &'static str = if i == chain { "M" } else { Box::leak(format!("*B{}", i + 1).into_boxed_str()) }; + blocks.extend([(0, "BLOCK"), (8, "0"), (2, name), (70, "1"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "0"), (2, next), (10, "0"), (20, "0"), (0, "ENDBLK")]); + } + let top = [ + (0, "INSERT"), + (2, "*B1"), + (10, "0"), + (20, "0"), + (0, "INSERT"), + (2, "N"), + (10, "0"), + (20, "200"), + (0, "INSERT"), + (2, "N"), + (10, "0"), + (20, "400"), + (41, "10"), + (42, "10"), + ]; + let doc = open(&drawing(&[], &tables, &blocks, &top), &points()).document; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + let insts = leaves(&doc); + let [.., one, ten] = &insts[..] else { panic!("{names:?}: {insts:?}") }; + let dashes = |n: &Node| instance_strokes(&doc, n).first().map(|s| s.0.clone()).unwrap_or_default(); + let (a, b) = (dashes(one), dashes(ten)); + assert!(!a.is_empty(), "{names:?}: N draws *D's line dashed"); + assert_eq!(b, a.iter().map(|v| v * 10.0).collect::>(), "{names:?}: N at scale 10 scales its dashes"); +} + #[test] fn a_block_left_out_inside_itself_does_not_fix_the_scale_of_another_placement() { let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; @@ -2036,6 +2362,8 @@ fn placing_a_block_inside_itself_many_times_stays_within_the_work_budget() { let top: Vec<(i32, &str)> = (0..20_000).flat_map(|_| [(0, "INSERT"), (2, "C0"), (10, "0"), (20, "0")]).collect(); let r = open(&drawing(&[], &[], &blocks, &top), &points()); assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); + let c0 = r.document.symbols.iter().filter(|s| s.name.starts_with("C0")).count(); + assert_eq!(c0, 1, "every placement of C0 shares one symbol"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 71dc70d75e..884959bd8a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13062,7 +13062,9 @@ and dots and stroked at the lineweight without the linetype; a pattern hatch wit than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping and dash steps, or past the drawing's budget of 2,000,000 dashes or 200,000,000 clipping steps, as its boundary), text and multiline text point type, named blocks symbols -(one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface +(one per look when their art takes colour "by block"; one per insert scale when they draw dashes or wide polylines, +which scale with the insert; and one per depth or set of ancestors when the nesting limit or a block placing one of its +own ancestors changes the art they draw), anonymous blocks such as dimensions groups. 3D faces, polyface meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the lines of its visible edges (closed when every edge is visible), and a polygon mesh one path of its M and N lines (smoothed meshes draw their surface's vertices). Indexed colours diff --git a/docs/progress/dxf-scaled-block-dashes.md b/docs/progress/dxf-scaled-block-dashes.md new file mode 100644 index 0000000000..a508108dec --- /dev/null +++ b/docs/progress/dxf-scaled-block-dashes.md @@ -0,0 +1 @@ +DXF and DWG import draw a block's dashes and wide polylines at each insert's scale, with one symbol per scale for such blocks, and keep a block's art apart where the nesting limit or a block placing one of its own ancestors changes what it draws (#10930). Headline numbers unchanged.