diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index c074ae289..a88cbef0b 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -47,7 +47,7 @@ mod proxy; mod text; mod wipeout; -pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal}; +pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal}; pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 982f2f9bb..9d41548ea 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -1,3 +1,6 @@ +use std::cmp::Ordering; +use std::collections::BTreeMap; + use super::common::{Common, Lineweight}; use super::text::{MText, Text}; use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3}; @@ -142,6 +145,43 @@ impl AttribProps { } } +/// An attribute tag as attributes are matched to their definitions and to each other: ASCII +/// letters in either case are the same tag, other characters must be equal. As an ordered map key +/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with +/// each definition costs their product on a block with many of both (#1923). It orders, rather +/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web +/// build's `RandomState`), as in the layer and block name index. +#[derive(Clone, Copy, Debug)] +pub struct TagKey<'a>(pub &'a str); + +impl TagKey<'_> { + /// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case` + /// finds equal. + fn folded(&self) -> impl Iterator + '_ { + self.0.bytes().map(|b| b.to_ascii_lowercase()) + } +} + +impl PartialEq for TagKey<'_> { + fn eq(&self, other: &Self) -> bool { + self.0.eq_ignore_ascii_case(other.0) + } +} + +impl Eq for TagKey<'_> {} + +impl Ord for TagKey<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.folded().cmp(other.folded()) + } +} + +impl PartialOrd for TagKey<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Insert { @@ -204,4 +244,31 @@ impl Insert { .then_before(Mat3::scale(self.scale.x, self.scale.y)) .then_before(Mat3::translate(-base)) } + + /// The reference's attributes by tag: of several with one tag (in any ASCII case), the first. + /// Built once, it tells whether the reference carries a definition's tag, and its value, in + /// one lookup instead of a pass over the attributes per definition (#1923). + pub fn attribs_by_tag(&self) -> BTreeMap, &Attrib> { + let mut by_tag = BTreeMap::new(); + for a in &self.attribs { + by_tag.entry(TagKey(a.tag.as_str())).or_insert(a); + } + by_tag + } +} + +impl crate::Block { + /// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the + /// first in the block's order, the one an attribute of that tag takes its properties from. + /// Built once for all of a reference's attributes, it matches each in one lookup instead of a + /// pass over the block per attribute (#1923). + pub fn attdefs_by_tag(&self) -> BTreeMap, &crate::Entity> { + let mut by_tag = BTreeMap::new(); + for e in self.entities.iter() { + if let EntityKind::AttDef(a) = &e.kind { + by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref()); + } + } + by_tag + } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 6870a0178..ad4cdbde7 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -1,10 +1,10 @@ //! Approximate entity bounds (used for extents, zoom and selection pre-filtering). -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc}; -use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim}; +use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey}; /// Nested block references deeper than this are ignored (cyclic or hostile files). pub const MAX_BLOCK_DEPTH: usize = 16; @@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool { } /// The layer an insert's attribute draws on, as the renderer takes it: its own, else its -/// definition's (layer "0" being the insert's). -fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str { - a.props.layer.as_deref().unwrap_or_else(|| { - d.block(&ins.block) - .and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag)))) - .map_or("0", |be| be.common.layer.as_str()) - }) +/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's). +fn attrib_layer<'a>(defs: Option<&BTreeMap, &'a Entity>>, a: &'a crate::Attrib) -> &'a str { + a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str())) } /// The bounds of a block's contents, in block coordinates: its geometry, which every reference to /// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which /// only a block reference draws (a dimension's block does not), and only when the reference /// carries no attribute of that tag. They are kept apart so that the one cache serves every -/// reference, whichever asks first. +/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer +/// of an attribute that has none of its own. struct Contents<'a> { geometry: Bounds2, constants: Vec<(&'a str, Bounds2)>, + defs: BTreeMap, &'a Entity>, } impl Contents<'_> { /// What reference `ins` shows of the block: its geometry and the constant values `ins` has /// no attribute for (that attribute is drawn instead, and counted with the attributes). fn in_reference(&self, ins: &crate::Insert) -> Bounds2 { - self.constants - .iter() - .filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag))) - .fold(self.geometry, |b, (_, c)| b.union(c)) + if self.constants.is_empty() { + return self.geometry; + } + // The reference's tags are gathered once, not scanned again for each constant (#1923). + let carried = ins.attribs_by_tag(); + self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c)) } } @@ -323,7 +323,7 @@ fn contents<'a, 'm>( ) -> Option<&'m Contents<'a>> { let key = (blk.name.as_str(), depth); if !blocks.contains_key(&key) { - let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() }; + let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() }; // ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible // ones, 2 all of them. let attmode = d.header.i64("ATTMODE", 1); @@ -487,9 +487,12 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< // one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its // insertion point. Attributes below still count. let mut b = Bounds2::EMPTY; + let mut defs = None; if let Some(blk) = d.block(&ins.block) { let m = ins.transform(blk.base.xy()); - let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); + let c = contents(d, blk, depth, blocks, off_counts); + defs = c.map(|c| &c.defs); + let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) }; // XCLIP: the reference app takes the boundary's box, also where it reaches past the // block or misses it (an inverted clip can show anything, so it keeps the block's). @@ -511,7 +514,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } } for a in &ins.attribs { - if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) { + if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) { b = b.union(&match a.multiline_text() { Some(m) => mtext_box(&m), None => text_box(&a.text, a.text.value.chars().count()), diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 5c290fe6a..cab2792fd 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -891,6 +891,85 @@ fn constant_values_count_in_extents_as_attmode_shows_them() { assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one"); } +#[test] +fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() { + // Two definitions of one tag, in different case, on a frozen layer and on layer 0: an + // attribute without a layer of its own (in a third case) lies on the first one's. + let top = |defs: [(&str, &str); 2]| { + let mut d = Drawing::new_imperial(); + let mut frozen = Layer::new("AFRZ"); + frozen.frozen = true; + d.layers.push(frozen); + let mut blk = Block::new("B"); + blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1)); + for (h, (layer, tag)) in (2..).zip(defs) { + blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h)); + } + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; + let mut a = plain_attrib("Tag"); + a.text.insert = Vec3::new(0.0, 500.0, 0.0); + ins.attribs.push(a); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + extents_pair(&d).1.y + }; + assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer"); + assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0"); +} + +#[test] +fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() { + // Two constant definitions of one tag, in different case: a reference draws both values, + // unless it carries an attribute of that tag (in a third case), which stands for both. + let max = |attribs: Vec| { + let mut d = Drawing::new_imperial(); + let mut blk = Block::new("B"); + blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0)))); + for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] { + let mut a = plain_attrib(tag); + a.text.insert = at; + a.constant = true; + blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a))); + } + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; + ins.attribs = attribs; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + extents_pair(&d).1 + }; + for shown in [max(vec![]), max(vec![plain_attrib("D")])] { + assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}"); + } + let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]); + assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}"); +} + +#[test] +fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() { + // #1923: one reference with N attributes (none with a layer of its own) of a block with N + // constant definitions, the tags N long ones alike up to their last characters, no attribute's + // a definition's. Comparing each attribute with each definition, for its layer and for which + // constant values the reference carries, cost N x N comparisons of whole tags (many seconds + // here); one lookup per attribute or definition costs milliseconds. + const N: usize = 4000; + let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000)); + let mut d = Drawing::new_imperial(); + let mut blk = Block::new("B"); + blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0)))); + for (h, i) in (2..).zip(0..N) { + let mut a = plain_attrib(&tag('D', i)); + a.constant = true; + blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a))); + } + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; + ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect(); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let t = std::time::Instant::now(); + assert!(!d.extents(&Space::Model).is_empty()); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); +} + /// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N /// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924). #[test] diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index 8b51cae5d..b6d6b2d24 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -3,7 +3,7 @@ use std::sync::Arc; -use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert}; +use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey}; use serde_json::{Value, json}; use crate::cmd::curves::KW; @@ -102,17 +102,14 @@ impl Interactive for AttdispM { /// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD. pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec { let m = ins.transform(blk.base.xy()); + // The reference's attributes by tag, gathered once for all the definitions (#1923). + let carried = ins.attribs_by_tag(); defs.iter() .map(|ad| { let mut k = EntityKind::Text(ad.text.clone()); k.transform(&m); let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() }; - t.value = ins - .attribs - .iter() - .find(|a| a.tag.eq_ignore_ascii_case(&ad.tag)) - .map(|a| a.text.value.clone()) - .unwrap_or_else(|| ad.text.value.clone()); + t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); Attrib { tag: ad.tag.clone(), text: t, diff --git a/crates/engine/src/cmd/blocks/burst.rs b/crates/engine/src/cmd/blocks/burst.rs index 14a2bde87..b7bcb4b37 100644 --- a/crates/engine/src/cmd/blocks/burst.rs +++ b/crates/engine/src/cmd/blocks/burst.rs @@ -2,7 +2,7 @@ //! become text with the values they show instead of the block's attribute definitions. use cadcraft_color::Color; -use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert}; +use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey}; use serde_json::{Value, json}; use crate::cmd::machines::SelectRun; @@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result { fn burst_pieces(d: &Drawing, e: &Entity) -> Option> { let EntityKind::Insert(ins) = &e.kind else { return None }; let mut out: Vec = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect(); + // The block's definitions by tag, gathered once for all the attributes (#1923). + let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default(); for a in ins.attribs.iter().filter(|a| !a.invisible) { let kind = match a.multiline_text() { Some(m) => EntityKind::MText(m), None => EntityKind::Text(a.text.clone()), }; - out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind }); + out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind }); } Some(out) } -/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the -/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's -/// objects. -fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common { - let def = - d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag)))); +/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer +/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the +/// block's objects. +fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common { // An attribute without a definition follows the reference. let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() }); let mut c = props.over(&base); diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index 29a953aee..034eade79 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -5,7 +5,7 @@ use cadcraft_doc::color::Color; use cadcraft_doc::dynblock::{self, GripPart, GripShape}; -use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency}; +use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; @@ -111,11 +111,10 @@ fn drawn(d: &Drawing, h: Handle) -> Vec { .collect(); // An attribute draws with its definition's properties, except those set on it. let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() }; + // The block's definitions by tag, gathered once for all the attributes (#1923). + let defs = b.attdefs_by_tag(); out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| { - let def = b.entities.iter().find_map(|e| match &e.kind { - EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common), - _ => None, - }); + let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common); let common = under(&a.props.over(def.unwrap_or(&by_block)), r); let kind = match a.multiline_text() { Some(m) => EntityKind::MText(m), @@ -248,3 +247,51 @@ impl Session { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() { + // #1923: a reference with N attributes of a block with N definitions, the tags N long ones + // alike up to their last characters, no attribute's a definition's. Looking for each + // attribute's definition by comparing it with every one cost N x N comparisons of whole + // tags for each preview (many seconds here); the definitions gathered by tag once cost + // milliseconds. + const N: usize = 4000; + let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000)); + let attrib = |tag: String| cadcraft_doc::Attrib { + tag, + text: cadcraft_doc::Text { + insert: cadcraft_geom::Vec3::ZERO, + align_pt: None, + height: 1.0, + value: "v".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }, + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + let mut d = Drawing::new_metric(); + let mut blk = cadcraft_doc::Block::new("B"); + for (h, i) in (1..).zip(0..N) { + blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i))))); + } + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() }; + let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let t = std::time::Instant::now(); + assert_eq!(drawn(&d, h).len(), N); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + } +} diff --git a/crates/engine/tests/it/attribute_tag_matching.rs b/crates/engine/tests/it/attribute_tag_matching.rs new file mode 100644 index 000000000..f06cfd2b4 --- /dev/null +++ b/crates/engine/tests/it/attribute_tag_matching.rs @@ -0,0 +1,98 @@ +//! Attributes are matched to their block's definitions, and definitions to a reference's +//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both. + +use std::sync::Arc; + +use cadcraft_doc::{Attrib, EntityKind, Handle}; +use cadcraft_engine::Session; +use serde_json::json; + +/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets +/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones +/// alike up to their last characters, no attribute's a definition's. +fn reference(n: usize) -> (Session, Handle) { + let mut s = Session::new(); + s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap(); + let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap(); + let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + if n > 0 { + let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000)); + let d = s.doc_mut().unwrap(); + let handles: Vec = (0..n).map(|_| d.new_handle()).collect(); + let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap()); + let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone(); + for (i, h) in handles.into_iter().enumerate() { + let mut e = def.clone(); + e.handle = h; + if let EntityKind::AttDef(a) = &mut e.kind { + a.tag = tag('D', i); + } + blk.entities.push(e); + } + d.modify_entity(h, |e| { + if let EntityKind::Insert(ins) = &mut e.kind { + let one = ins.attribs[0].clone(); + ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect(); + } + }) + .unwrap(); + } + (s, h) +} + +fn attribs(s: &Session, h: Handle) -> Vec { + let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") }; + i.attribs.clone() +} + +/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for +/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one +/// lookup each costs milliseconds. +const N: usize = 4000; + +#[test] +fn burst_matches_many_attributes_without_comparing_every_pair() { + let (mut s, h) = reference(N); + let t = std::time::Instant::now(); + s.execute("burst", &json!({"handles": [h.hex()]})).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N); +} + +#[test] +fn attsync_matches_many_definitions_without_comparing_every_pair() { + let (mut s, h) = reference(N); + let t = std::time::Instant::now(); + s.execute("attsync", &json!({"name": "B"})).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + // An attribute for each definition (T and the N others), with its default value: the + // reference carried none of their tags. + let a = attribs(&s, h); + assert_eq!(a.len(), N + 1); + assert!(a.iter().all(|a| a.text.value == "d")); +} + +#[test] +fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() { + // A reference carrying two attributes of one tag (in different case, as a file can hold + // them) keeps the first one's value for the definition of that tag. + let (mut s, h) = reference(0); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(ins) = &mut e.kind { + let mut second = ins.attribs[0].clone(); + second.tag = "t".into(); + second.text.value = "second".into(); + ins.attribs[0].text.value = "first".into(); + ins.attribs.push(second); + } + }) + .unwrap(); + s.execute("attsync", &json!({"name": "B"})).unwrap(); + let a = attribs(&s, h); + assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::>(), [("T", "first")]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 08546a9d9..636c8e22d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -12,6 +12,7 @@ mod attdisp_attsync; mod attedit_prompts; mod attrib_modes; mod attrib_props; +mod attribute_tag_matching; mod attribute_tools; mod attribute_value_baseline; mod block_description; diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index c644eb558..1f8e6fbe5 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -617,20 +617,12 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { p(&mut t, 10, b.scale); f(&mut t, 43, b.rotation); i(&mut t, 176, 1); - // Attribute values by their ATTDEF in the block. - let defs: Vec<(Handle, &str)> = d - .block(&b.block) - .map(|blk| { - blk.entities - .iter() - .filter_map(|e| if let EntityKind::AttDef(ad) = &e.kind { Some((e.handle, ad.tag.as_str())) } else { None }) - .collect() - }) - .unwrap_or_default(); + // Attribute values by their ATTDEF in the block, the definitions gathered by tag once. + let defs = d.block(&b.block).map(|blk| blk.attdefs_by_tag()).unwrap_or_default(); let mut n = 0i64; for a in &b.attribs { - let Some((h, _)) = defs.iter().find(|(_, tag)| tag.eq_ignore_ascii_case(&a.tag)) else { continue }; - s(&mut t, 330, &h.hex()); + let Some(def) = defs.get(&cadcraft_doc::TagKey(&a.tag)) else { continue }; + s(&mut t, 330, &def.handle.hex()); i(&mut t, 177, n); f(&mut t, 44, 0.0); s(&mut t, 302, &a.text.value); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index c79a5e8ee..ee37b5f97 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet}; use cadcraft_color::Color; use cadcraft_doc::{ AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign, - HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table, + HVal, Handle, Hatch, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table, TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile, }; use cadcraft_geom::{Bounds2, Vec2, Vec3}; diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 235a23378..a8fda3257 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -1,7 +1,7 @@ use super::ctx::{AssocObj, Ctx}; use super::{ - Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, HashMap, Insert, Lineweight, Text, Transparency, - VAlign, Vec3, Version, W, dxf_ext, + Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W, + dxf_ext, }; /// `AcadAnnotative` xdata marking an annotative style. @@ -145,13 +145,11 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) { } } -/// The properties attribute `a` of block reference `e` (of `ins`) is drawn with: its own, else its -/// definition's; an attribute defined on layer 0 is on the reference's layer. Also the -/// definition's properties. -pub(super) fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, a: &Attrib) -> (Common, Common) { - let def = d - .block(&ins.block) - .and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag)))); +/// The properties attribute `a` of block reference `e` is drawn with: its own, else its +/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on +/// the reference's layer. Also the definition's properties. +pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap, &Entity>, a: &Attrib) -> (Common, Common) { + let def = defs.get(&cadcraft_doc::TagKey(&a.tag)); let base = def.map(|de| de.common.clone()).unwrap_or_default(); let mut c = a.props.over(&base); if c.layer == "0" { diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 2d24887d5..9ea3c97c8 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -372,13 +372,15 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b w.f(45, i.row_spacing); } if !i.attribs.is_empty() { + // The block's definitions by tag, gathered once for all the attributes (#1923). + let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default(); for (index, a) in i.attribs.iter().enumerate() { let ah = w.h(); w.s(0, "ATTRIB"); w.s(5, ah); w.s(330, e.handle.hex()); w.s(100, "AcDbEntity"); - let (c, base) = attrib_common(d, e, i, a); + let (c, base) = attrib_common(e, &defs, a); layer_and_props(w, &c, Some(&base)); // Hidden with its definition (a dynamic block's visibility state hides it). if !base.visible { diff --git a/crates/io/tests/it/attrib_props.rs b/crates/io/tests/it/attrib_props.rs index 3b750fa7a..4787dd8c2 100644 --- a/crates/io/tests/it/attrib_props.rs +++ b/crates/io/tests/it/attrib_props.rs @@ -109,6 +109,53 @@ fn attributes_without_properties_stay_without() { assert!(a.iter().all(|a| a.props.is_empty()), "{a:?}"); } +#[test] +fn many_attributes_are_written_without_comparing_every_pair_with_the_definitions() { + // #1923: a reference with N attributes, and a multileader's block content with N, of a block + // with N definitions, the tags N long ones alike up to their last characters, no attribute's + // a definition's. Looking for each attribute's definition by comparing it with every one (for + // the ATTRIB's properties, the multileader's attribute values) cost N x N comparisons of whole + // tags (many seconds here); the definitions gathered by tag once cost milliseconds. + const N: usize = 8000; + let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(150)); + let mut d = Drawing::new_metric(); + let mut blk = Block::new("TAGS"); + for (h, i) in (0x100..).zip(0..N) { + blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(&tag('D', i), 0.0, AttribProps::default())))); + } + d.blocks.insert(blk.name.clone(), Arc::new(blk)); + let ins = Insert { + block: "TAGS".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: (0..N).map(|i| attrib(&tag('A', i), 0.0, AttribProps::default())).collect(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins.clone())).expect("add"); + let m = MLeader { + leaders: vec![vec![Vec3::ZERO]], + landing: Vec3::new(10.0, 0.0, 0.0), + dogleg: 1.0, + text: None, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + block: Some(ins), + }; + d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).expect("add"); + // A version with native multileaders: R2000 writes one as a leader and a block reference. + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2007), binary: false }; + let t = std::time::Instant::now(); + let dxf = String::from_utf8(cadcraft_io::write_with(&d, "x.dxf", &opts).expect("write")).expect("text"); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + assert!(dxf.contains("MULTILEADER") && dxf.contains("ATTRIB")); +} + #[test] fn hostile_attrib_groups_do_not_panic() { let dxf = "0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nNOPE\n10\n0\n20\n0\n30\n0\n\ diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 028eba3fe..5fb3d6d9b 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -1,3 +1,7 @@ +use std::collections::BTreeMap; + +use cadcraft_doc::TagKey; + use super::draw::entity; use super::props::{resolve, resolve_common, transparency}; use super::text_entity::{mtext, place_text_entity}; @@ -66,6 +70,9 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: if let Some(blk) = ctx.d.block(&ins.block) { // ATTMODE (ATTDISP) for the block's constant attributes, as for its other attributes. let attmode = ctx.d.header.i64("ATTMODE", 1); + // The reference's attributes by tag, gathered at the first constant definition that asks + // and kept for the others and every copy. + let mut carried = None; let cols = ins.cols.clamp(1, 10_000); let rows = ins.rows.clamp(1, 10_000); 'copies: for r in 0..rows { @@ -91,7 +98,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: // Attribute definitions inside blocks are not drawn (the reference's attributes // are), except a constant one: its value draws with the block's geometry. if let EntityKind::AttDef(a) = &be.kind { - if let Some(text) = constant_attribute(be, a, ins, attmode) { + if let Some(text) = constant_attribute(be, a, ins, attmode, &mut carried) { entity(target, &sub, &text); } continue; @@ -123,9 +130,20 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: /// its value, with the definition's properties. A constant value isn't copied into the reference's /// attributes, so it is drawn from the definition. `None` for a variable definition (its attribute /// is drawn instead), one ATTMODE hides (0 hides all, 1 the invisible ones), and one the reference -/// carries an attribute for (that attribute is drawn, not both). -fn constant_attribute(be: &Entity, a: &cadcraft_doc::Attrib, ins: &cadcraft_doc::Insert, attmode: i64) -> Option { - if !a.constant || attmode == 0 || (a.invisible && attmode != 2) || ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(&a.tag)) { +/// carries an attribute for (that attribute is drawn, not both). `carried`: the reference's +/// attributes by tag, gathered here on first use so that each definition costs one lookup (#1923). +fn constant_attribute<'i>( + be: &Entity, + a: &cadcraft_doc::Attrib, + ins: &'i cadcraft_doc::Insert, + attmode: i64, + carried: &mut Option, &'i cadcraft_doc::Attrib>>, +) -> Option { + if !a.constant + || attmode == 0 + || (a.invisible && attmode != 2) + || carried.get_or_insert_with(|| ins.attribs_by_tag()).contains_key(&TagKey(&a.tag)) + { return None; } let kind = match a.multiline_text() { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index c75869161..1094895f4 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -940,6 +940,32 @@ fn a_constant_attribute_definition_draws_its_value_with_the_reference() { assert_eq!(drawn_above_line(constant(false), vec![own], 1, at).len(), pts.len()); } +#[test] +fn many_constant_definitions_are_matched_to_the_attributes_without_comparing_every_pair() { + // #1923: a reference with N attributes of a block with N constant definitions, the tags N long + // ones alike up to their last characters, no attribute's a definition's. Asking for each + // definition whether the reference carries its tag by comparing it with every attribute cost + // N x N comparisons of whole tags for each copy drawn (many seconds here); gathering the + // reference's tags once costs milliseconds. The values are empty and the attributes invisible, + // so drawing them costs nothing. + const N: usize = 4000; + let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000)); + let mut d = Drawing::new_imperial(); + let mut blk = cadcraft_doc::Block::new("K"); + for (h, i) in (1..).zip(0..N) { + let mut a = cadcraft_doc::Attrib { constant: true, ..attrib(&tag('D', i)) }; + a.text.value.clear(); + blk.entities.push(block_entity(h, Common::default(), EntityKind::AttDef(a))); + } + d.blocks.insert("K".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = insert_of("K") else { panic!("an insert") }; + ins.attribs = (0..N).map(|i| cadcraft_doc::Attrib { invisible: true, ..attrib(&tag('A', i)) }).collect(); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let t = std::time::Instant::now(); + build(&d, &Space::Model, &Options::default()); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); +} + #[test] fn constant_attribute_definitions_follow_attmode() { let at = Vec3::ZERO;