From 2827d420b127f3e7b7fc106f88ed6c06182fbb5b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:23:43 -0600 Subject: [PATCH 01/15] DXF: a block record keeps its annotative flag and uniform scaling A BLOCK_RECORD's AcadAnnotative xdata (references to the block are annotative) was dropped on reading, AcadAnnotative being among the applications CADCraft writes itself, and never written: a saved drawing's annotative blocks came back plain, and AutoCAD then scaled their references by units instead of the annotation scale (a metre block showed Unit factor 1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are now read into the block (`Block::annotative`, `Block::scale_uniformly`) and written back. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/tables.rs | 4 ++++ crates/io/src/dxf_read.rs | 14 ++++++++++++-- crates/io/src/dxf_read/document.rs | 4 ++-- crates/io/src/dxf_read/tables.rs | 10 ++++++++-- crates/io/src/dxf_write/common.rs | 2 +- crates/io/src/dxf_write/sections.rs | 8 +++++++- 6 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index a2c63ca6a..100d58f08 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -716,6 +716,9 @@ pub struct Block { pub explodable: bool, #[serde(default)] pub units: u8, + /// References to this block scale uniformly (the BLOCK_RECORD's group 281). + #[serde(default)] + pub scale_uniformly: bool, /// The parameters of an associative array when this is an array block. #[serde(default, skip_serializing_if = "Option::is_none")] pub array: Option, @@ -764,6 +767,7 @@ impl Block { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, } } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..e34e9588d 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -34,6 +34,15 @@ use tables::{header, tables}; pub(crate) mod mtext_dxf; +/// A block record's properties (see [`Rx::block_props`]). +#[derive(Clone, Copy, Default)] +struct BlockProps { + units: u8, + explodable: bool, + scale_uniformly: bool, + annotative: bool, +} + /// Handle maps and references gathered while reading. #[derive(Default)] struct Rx { @@ -43,8 +52,9 @@ struct Rx { brs: HashMap, /// LTYPE record handle (upper case) → linetype name (DIMLTYPE, DIMLTEX1, DIMLTEX2). ltypes: HashMap, - /// Upper-case block name → (insertion units, explodable) from its BLOCK_RECORD. - block_props: HashMap, + /// Upper-case block name → its BLOCK_RECORD's properties: units (70), explodable (280), + /// scale uniformly (281) and annotative (`AcadAnnotative` xdata). + block_props: HashMap, /// Upper-case names of anonymous `*T` blocks drawn by ACAD_TABLE entities. table_blocks: std::collections::HashSet, /// Upper-case block names used by INSERTs. diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index d732f4450..48110d9a7 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -204,8 +204,8 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, let mut b = Block::new(&name); b.base = base; b.description = description; - if let Some(&(units, explodable)) = rx.block_props.get(&up) { - (b.units, b.explodable) = (units, explodable); + if let Some(p) = rx.block_props.get(&up) { + (b.units, b.explodable, b.scale_uniformly, b.annotative) = (p.units, p.explodable, p.scale_uniformly, p.annotative); } if xref & 4 != 0 { b.xref_path = Some(String::new()); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e..c750ee3ff 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -1,7 +1,7 @@ use super::common::T; use super::objects::MAX_OBJECTS; use super::{ - Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, + BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, VportConfig, VportTile, records, }; @@ -290,7 +290,13 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { } "BLOCK_RECORD" => { let units = table.i(70).and_then(|units| u8::try_from(units).ok()).unwrap_or(0); - rx.block_props.insert(name.to_ascii_uppercase(), (units, table.i(280).unwrap_or(1) != 0)); + let props = BlockProps { + units, + explodable: table.i(280).unwrap_or(1) != 0, + scale_uniformly: table.i(281).unwrap_or(0) != 0, + annotative: annotative(tags), + }; + rx.block_props.insert(name.to_ascii_uppercase(), props); if let Some(array) = crate::dxf_ext::read_array(tags) { rx.block_arrays.insert(name.to_ascii_uppercase(), array); } diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index b09d90410..88ad71566 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -4,7 +4,7 @@ use super::{ VAlign, Vec3, Version, W, dxf_ext, }; -/// `AcadAnnotative` xdata marking an annotative style. +/// `AcadAnnotative` xdata marking an annotative style or block. pub(super) fn annotative_xdata(w: &mut W) { w.s(1001, "AcadAnnotative"); w.s(1000, "AnnotativeData"); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 9a21ef7a9..48979755a 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -996,10 +996,16 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec Date: Wed, 14 Oct 2026 10:32:18 -0600 Subject: [PATCH 02/15] DXF: a block reference keeps its annotation scale contexts, following the reference A reference to an annotative block holds its scale at each annotation scale in its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES). CADCraft dropped it with the other annotation contexts it means to write from its model, but it models none for references: with the block's annotative flag kept, AutoCAD then scaled the reference once more by the current annotation scale (5 became 25). A reference's contexts are now kept, and refreshed on writing: each moves, turns and scales by what the reference did since the file was read (its default context was the reference then), so a reference left alone keeps them as read. The scales they name are found by name (SCALE group 300), as the scale list is written again from the model. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 114 +++++++- crates/io/tests/annotative_block_contexts.rs | 287 +++++++++++++++++++ 2 files changed, 392 insertions(+), 9 deletions(-) create mode 100644 crates/io/tests/annotative_block_contexts.rs diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9b755f80f..89557979c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -41,6 +41,19 @@ const MODELLED_KEYS: &[&str] = &[ /// changes that model them; stale copies would contradict the drawing). const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"]; +/// The annotation scale contexts of a block reference are kept, though: CADCraft doesn't model a +/// reference's scale at each annotation scale, and without them AutoCAD scales an annotative +/// reference once more by the current annotation scale. They are refreshed from the reference +/// when written ([`block_contexts`]). +const CONTEXTS_KEY: &str = "ACDBCONTEXTDATAMANAGER"; + +/// Whether extension dictionary entry `key` is left to CADCraft's model, in the extension +/// dictionary of a block reference (`of_insert`) or of something else. +fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { + let k = up(key); + MODELLED_XDICT_KEYS.contains(&k.as_str()) && !(of_insert && k == CONTEXTS_KEY) +} + /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides /// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; @@ -204,6 +217,13 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap {} } } + // Annotation scales by name (written again from the model, maybe under other keys): what + // annotation scale contexts refer to. + for (kind, _, t) in objects.iter().filter(|(k, _, _)| k.eq_ignore_ascii_case("SCALE")) { + if let Some(name) = val(t, 300).filter(|n| !n.trim().is_empty()) { + put(head(t).handle, (kind.to_ascii_uppercase(), up(&name))); + } + } let Some((_, _, root)) = objects.first().filter(|(k, _, _)| is_dictionary(k)) else { return out }; put(head(root).handle, ("NOD".into(), String::new())); let by_handle: HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect(); @@ -347,7 +367,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) }; - let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of); + // Block references (their extension dictionaries keep annotation scale contexts). + let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); + let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o)); + let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); for (i, (kind, _, t)) in objects.iter().enumerate() { @@ -357,7 +380,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue }; let mut tags: Vec = t.iter().map(raw).collect(); if is_xdict(i) { - strip_entries(&mut tags); + strip_entries(&mut tags, of_insert(t)); } if head(t).owner == root && let Some(key) = root_key(&h.hex()) @@ -488,10 +511,11 @@ fn retained_objects( entities: &HashMap, records: &HashMap, by_handle: &HashMap, - root: Option<&str>, - root_entries: &[(String, String)], + (root, root_entries): (Option<&str>, &[(String, String)]), xdict_of: &HashMap, + inserts: &HashSet, ) -> HashMap { + let of_insert = |tags: &[Tag]| head(tags).owner.is_some_and(|owner| inserts.contains(&owner)); let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -500,7 +524,7 @@ fn retained_objects( !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { - entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str())) + entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags))) }; let mut retained = HashMap::new(); for index in 0..objects.len() { @@ -531,7 +555,7 @@ fn retained_objects( continue; } if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags))); } break entities.get(&owner) == Some(&true); }; @@ -619,12 +643,81 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } -/// Drop a dictionary's modelled entries (key and handle) from its groups. -fn strip_entries(tags: &mut Vec) { +/// The kept annotation scale contexts of block references, brought up to date with each +/// reference (see [`CONTEXTS_KEY`]). A context holds the reference's insertion point, rotation +/// (degrees) and scale at one annotation scale; the default context (group 290 = 1) was the +/// reference itself when the file was read, so each context moves, turns and scales by what the +/// reference did since. Only the contexts of references that changed are returned (by handle). +fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> HashMap { + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The entity a kept object belongs to: the owner past the kept dictionaries. + let owner_entity = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Handle::parse_hex(o), + None => return None, + } + } + None + }; + // The contexts of each reference, together (they share their dictionary). + let mut by_parent: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + if let Some(p) = owners.get(&o.handle.hex()) { + by_parent.entry(p.clone()).or_default().push(o); + } + } + let mut out = HashMap::new(); + for list in by_parent.values() { + let Some(first) = list.first() else { continue }; + let Some(EntityKind::Insert(ins)) = owner_entity(&first.handle.hex()).and_then(|h| d.entity(h)).map(|e| &e.kind) else { continue }; + let def = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let turn = (ins.rotation.to_degrees() - num(def, 50).unwrap_or(0.0)).to_radians(); + let at0 = cadcraft_doc::geom::Vec2::new(x0, y0); + let ratio = |code: i32, now: f64| num(def, code).filter(|s| s.abs() > 1e-12).map_or(1.0, |s| now / s); + let ratios = [(41, ratio(41, ins.scale.x)), (42, ratio(42, ins.scale.y)), (43, ratio(43, ins.scale.z))]; + let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); + if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { + continue; + } + for c in list { + let mut o = (*c).clone(); + // Its offset from the default context turns with the reference. + let at = match (num(c, 10), num(c, 20)) { + (Some(x), Some(y)) => ins.insert.xy() + (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(turn), + _ => ins.insert.xy(), + }; + for t in &mut o.tags { + let v = match t.code { + 10 => Some(at.x), + 20 => Some(at.y), + 30 => Some(ins.insert.z), + 50 => num(c, 50).map(|r| r + turn.to_degrees()), + 41..=43 => ratios.iter().find(|(k, _)| *k == t.code).and_then(|(k, r)| num(c, *k).map(|s| s * r)), + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) { + t.value = v.to_string(); + } + } + out.insert(o.handle.hex(), o); + } + } + out +} + +/// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: +/// it is a block reference's). +fn strip_entries(tags: &mut Vec, of_insert: bool) { let mut out = Vec::with_capacity(tags.len()); let mut i = 0; while let Some(t) = tags.get(i) { - if t.code == 3 && MODELLED_XDICT_KEYS.contains(&up(&t.value).as_str()) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { + if t.code == 3 && modelled_xdict_key(&t.value, of_insert) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { i += 2; continue; } @@ -921,6 +1014,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); + // Block references' annotation scale contexts, up to date with the references. + let contexts = block_contexts(f, d, &owners); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); @@ -977,6 +1072,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { } if r.kind == "ENDSEC" && r.sec == "OBJECTS" { for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { + let o = contexts.get(&o.handle.hex()).unwrap_or(o); let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten(); match number { Some(n) => { diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs new file mode 100644 index 000000000..da3931651 --- /dev/null +++ b/crates/io/tests/annotative_block_contexts.rs @@ -0,0 +1,287 @@ +//! An annotative block survives a save: its BLOCK_RECORD keeps the `AcadAnnotative` xdata and +//! uniform scaling (281), and a reference keeps its annotation scale contexts (the reference's +//! scale at each annotation scale), pointing at the same scales and following the reference when +//! it is moved, turned or scaled. Without them AutoCAD scales the reference by its units, or once +//! more by the current annotation scale. +//! +//! The fixture is synthetic: block SIGN (metres) with one line, a reference at (10, 20) scaled 5, +//! and its contexts for 1:5 (default, scale 5) and 1:1 (scale 1). + +use cadcraft_doc::geom::Vec2; +use cadcraft_doc::{Drawing, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +const FIXTURE: &str = " +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $INSUNITS +70 6 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 1 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 SIGN +70 6 +280 1 +281 1 +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 SIGN +70 0 +10 0 +20 0 +30 0 +3 SIGN +1 +0 LINE +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbLine +10 0 +20 0 +30 0 +11 1 +21 0 +31 0 +0 ENDBLK +5 22 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 40 +102 {ACAD_XDICTIONARY +360 41 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockReference +2 SIGN +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +50 0 +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +3 ACAD_SCALELIST +350 50 +0 DICTIONARY +5 50 +330 C +100 AcDbDictionary +281 1 +3 A0 +350 51 +3 A1 +350 52 +0 SCALE +5 51 +330 50 +100 AcDbScale +70 0 +300 1:1 +140 1 +141 1 +290 0 +0 SCALE +5 52 +330 50 +100 AcDbScale +70 0 +300 1:5 +140 1 +141 5 +290 0 +0 DICTIONARY +5 41 +330 40 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 42 +0 DICTIONARY +5 42 +330 41 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 43 +0 DICTIONARY +5 43 +330 42 +100 AcDbDictionary +281 1 +3 *A1 +350 44 +3 *A2 +350 45 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 44 +330 43 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +50 0 +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 45 +330 43 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +50 0 +10 10 +20 20 +30 0 +41 1 +42 1 +43 1 +0 ENDSEC +0 EOF +"; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// A written file's records: (type, groups). +fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec<(String, Vec<(i32, String)>)> = Vec::new(); + for pair in lines.chunks(2) { + let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::().ok()), pair.get(1)) else { continue }; + if code == 0 { + out.push((value.to_string(), Vec::new())); + } else if let Some((_, tags)) = out.last_mut() { + tags.push((code, value.to_string())); + } + } + out +} + +fn get<'a>(tags: &'a [(i32, String)], code: i32) -> Option<&'a str> { + tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) +} + +/// The written block reference contexts: (scale name, default, insertion, rotation, x scale). +fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| { + let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(); + (scale, get(t, 290) == Some("1"), Vec2::new(num(t, 10), num(t, 20)), num(t, 50), num(t, 41)) + }) + .collect() +} + +fn read() -> Drawing { + read_dxf(dxf(FIXTURE).as_bytes()).unwrap() +} + +#[test] +fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() { + let d = read(); + let b = d.block("SIGN").unwrap(); + assert!(b.annotative && b.scale_uniformly && b.units == 6); + let text = write_dxf(&d); + // The record: units, uniform scaling and the annotative flag. + let recs = records(&text); + let (_, rec) = recs.iter().find(|(k, t)| k == "BLOCK_RECORD" && get(t, 2) == Some("SIGN")).unwrap(); + assert_eq!((get(rec, 70), get(rec, 281)), (Some("6"), Some("1"))); + assert!(rec.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{rec:?}"); + // The contexts, as read, at the same scales. + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), false, 1.0), ("1:5".to_string(), true, 5.0)]); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0)); + // Read back: still annotative. + assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative); +} + +#[test] +fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() { + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.rotation = 30f64.to_radians(); + i.scale = i.scale * 2.0; + } + }) + .unwrap(); + let mut ctx = contexts(&write_dxf(&d)); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + for (scale, _, at, rot, sx) in &ctx { + assert!((at.x - 15.0).abs() < 1e-9 && (at.y - 20.0).abs() < 1e-9, "{scale}: {at:?}"); + assert!((rot - 30.0).abs() < 1e-9, "{scale}: {rot}"); + // Each context doubles: 1 → 2 at 1:1, 5 → 10 at 1:5. + let want = if scale == "1:1" { 2.0 } else { 10.0 }; + assert!((sx - want).abs() < 1e-9, "{scale}: {sx}"); + } + assert_eq!(ctx.len(), 2); +} From 425054a9624895214beb66575bcb82a9e09b0b1e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:42:55 -0600 Subject: [PATCH 03/15] Block literals in tests take scale_uniformly; a test helper's lifetime is elided Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/spatial.rs | 1 + crates/engine/tests/it/pick_text.rs | 1 + crates/io/tests/annotative_block_contexts.rs | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index dd2e0d593..2341bec2d 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -308,6 +308,7 @@ mod tests { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, }; blk.entities diff --git a/crates/engine/tests/it/pick_text.rs b/crates/engine/tests/it/pick_text.rs index b0df6d8a3..0341e8761 100644 --- a/crates/engine/tests/it/pick_text.rs +++ b/crates/engine/tests/it/pick_text.rs @@ -103,6 +103,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, }; d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index da3931651..74d33c097 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -218,7 +218,7 @@ fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> { out } -fn get<'a>(tags: &'a [(i32, String)], code: i32) -> Option<&'a str> { +fn get(tags: &[(i32, String)], code: i32) -> Option<&str> { tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) } From f344a13e63e4539f0f1f441cb95d8f1bb660514f Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:44:39 -0600 Subject: [PATCH 04/15] DXF: a block reference's attributes keep their annotation scale contexts The attributes of an annotative reference hold their own contexts (insertion and alignment points and rotation at each annotation scale, under the ATTRIB's extension dictionary), dropped like the reference's were. CADCraft writes attributes with new handles, so their extension dictionaries are now kept by attribute, as its reference's handle and tag, and put back on the attribute written with that reference and tag. On writing each context keeps its own place in the block at its scale, moves by what the attribute did in the block since (its default context then, the attribute now), and is placed by the reference's context for that scale as it is now: a reference left alone keeps them as read; one moved, turned or scaled carries them exactly. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 161 ++++++++++++++++++- crates/io/tests/annotative_block_contexts.rs | 123 ++++++++++++++ 2 files changed, 276 insertions(+), 8 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 89557979c..d8aaa1689 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -193,13 +193,17 @@ fn modelled_key(key: &str) -> bool { /// The roles of a file's handles (see [`ForeignKey`]): table records and tables by type and /// name, blocks by name, the named object dictionary, its entries, and their entries. -fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap { +fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> HashMap { let mut out: HashMap = HashMap::new(); let mut put = |h: Option, k: ForeignKey| { if let Some(h) = h { out.entry(h).or_insert(k); } }; + // Attributes (written with new handles each time) by their reference and tag. + for (kind, _, t) in blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB") { + put(head(t).handle, (kind.clone(), attrib_key(t))); + } for (kind, _, t) in tables { let name = up(&val(t, 2).unwrap_or_default()); if kind == "TABLE" || !name.is_empty() { @@ -347,7 +351,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (classes, tables, blocks, entities, objects) = (get("CLASSES"), get("TABLES"), get("BLOCKS"), get("ENTITIES"), get("OBJECTS")); // The drawing's entities by handle: whether each is of a type CADCraft doesn't model. let ents = entity_types(d); - let ids = identities(&tables, &blocks, &objects); + let ids = identities(&tables, &blocks, &entities, &objects); // Extension dictionaries of entities and records: owner → dictionary. let xdict_of = extension_dictionaries(&tables, &blocks, &entities); // Objects by handle: the first of each, and none that has an entity's handle. @@ -367,9 +371,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) }; - // Block references (their extension dictionaries keep annotation scale contexts). + // Block references and their attributes (their extension dictionaries keep annotation scale + // contexts). let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); - let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o)); + let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")); let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); @@ -410,6 +415,12 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } put_xdata(d, xdata_of); + // Attributes' extension dictionaries (their annotation scale contexts), by attribute. + for (kind, _, t) in blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB") { + if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { + f.records.entry((kind.clone(), attrib_key(t))).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + } + } for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; let x = extra(kind, t, kind == "BLOCK", false, &kept); @@ -515,7 +526,9 @@ fn retained_objects( xdict_of: &HashMap, inserts: &HashSet, ) -> HashMap { - let of_insert = |tags: &[Tag]| head(tags).owner.is_some_and(|owner| inserts.contains(&owner)); + let of_insert = |tags: &[Tag]| { + head(tags).owner.is_some_and(|owner| inserts.contains(&owner) || records.get(&owner).is_some_and(|key| key.0 == "ATTRIB")) + }; let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -643,6 +656,12 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } +/// An attribute's identity across saves (its handle is new each time): its reference's handle +/// and its tag. +fn attrib_key(tags: &[Tag]) -> String { + format!("{}/{}", head(tags).owner.unwrap_or_default(), up(&val(tags, 2).unwrap_or_default())) +} + /// The kept annotation scale contexts of block references, brought up to date with each /// reference (see [`CONTEXTS_KEY`]). A context holds the reference's insertion point, rotation /// (degrees) and scale at one annotation scale; the default context (group 290 = 1) was the @@ -711,6 +730,128 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> out } +/// The kept annotation scale contexts of block references' attributes, brought up to date. A +/// context holds the attribute's insertion and alignment points (10, 11) and rotation (50) at one +/// annotation scale. It keeps its own place in the block at that scale (as read, through the +/// reference's context for the same scale), moved by what the attribute did in the block since +/// (seen in its default context, 290 = 1), and is placed by the reference's context as it is now +/// (`block`: the reference contexts [`block_contexts`] refreshed). Only changed contexts are +/// returned (by handle). +fn attribute_contexts( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + block: &HashMap, +) -> HashMap { + use cadcraft_doc::geom::{Mat3, Vec2}; + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + let text = |o: &ForeignObject, code: i32| o.tags.iter().find(|t| t.code == code).map(|t| norm(&t.value)); + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + // Attributes' extension dictionaries: (reference, tag). + let attribs: HashMap = f + .records + .iter() + .filter(|(k, _)| k.0 == "ATTRIB") + .filter_map(|(k, x)| { + let (ins, tag) = k.1.split_once('/')?; + Some((x.xdict?.hex(), (Handle::parse_hex(ins)?, tag.to_string()))) + }) + .collect(); + // A reference's context at each scale, as read and as written: (insertion, degrees, scale). + type Place = (Vec2, f64, (f64, f64)); + let place = + |o: &ForeignObject| -> Option { Some((Vec2::new(num(o, 10)?, num(o, 20)?), num(o, 50).unwrap_or(0.0), (num(o, 41)?, num(o, 42)?))) }; + let mut read: HashMap<(Handle, String), Place> = HashMap::new(); + let mut now: HashMap<(Handle, String), Place> = HashMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + let (Some((_, r)), Some(s)) = (top(&o.handle.hex()), text(o, 340)) else { continue }; + let Some(r) = Handle::parse_hex(&r) else { continue }; + if let Some(p) = place(o) { + read.insert((r, s.clone()), p); + } + if let Some(p) = place(block.get(&o.handle.hex()).unwrap_or(o)) { + now.insert((r, s), p); + } + } + // The block-to-drawing transform of a reference placed at `p` (its block's base `base`). + let matrix = |ins: &cadcraft_doc::Insert, base: Vec2, p: Place| { + let mut i = ins.clone(); + i.insert = p.0.to3(ins.insert.z); + i.rotation = p.1.to_radians(); + i.scale = cadcraft_doc::geom::Vec3::new(p.2.0, p.2.1, ins.scale.z); + i.transform(base) + }; + // Each attribute's contexts, together. + let mut by_attrib: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| up(&o.kind).contains("ATTRIBUTEOBJECTCONTEXTDATA")) { + if let Some((xd, _)) = top(&o.handle.hex()) { + by_attrib.entry(xd).or_default().push(o); + } + } + let mut out = HashMap::new(); + for (xd, list) in &by_attrib { + let Some((r, tag)) = attribs.get(xd) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; + let Some(a) = ins.attribs.iter().find(|a| up(&a.tag) == *tag) else { continue }; + let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); + let Some(to_block_now) = ins.transform(base).inverse() else { continue }; + let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; + let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); + // What the attribute did in the block since: its default context then, the attribute now. + let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; + let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; + let now_ins = to_block_now.apply(a.text.insert.xy()); + let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); + let (Some(then_ins), Some(then_align)) = (at(def, 10).map(|p| to_block_then.apply(p)), at(def, 11).map(|p| to_block_then.apply(p))) else { + continue; + }; + let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); + for c in list { + let Some(s) = text(c, 340) else { continue }; + let (Some(was), Some(is)) = (read.get(&(*r, s.clone())).copied(), now.get(&(*r, s)).copied()) else { continue }; + let (Some(from), to): (Option, Mat3) = (matrix(ins, base, was).inverse(), matrix(ins, base, is)) else { continue }; + let moved = |x: i32, delta: Vec2| at(c, x).map(|p| to.apply(from.apply(p) + delta)); + let (new_ins, new_align) = (moved(10, now_ins - then_ins), moved(11, now_align - then_align)); + let rot = num(c, 50).map(|v| v + (is.1 - was.1) + turn); + let mut o = (*c).clone(); + let mut changed = false; + for t in &mut o.tags { + let v = match t.code { + 10 => new_ins.map(|p| p.x), + 20 => new_ins.map(|p| p.y), + 11 => new_align.map(|p| p.x), + 21 => new_align.map(|p| p.y), + 50 => rot, + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) + && t.value.trim().parse::().map_or(true, |old| (old - v).abs() > 1e-9) + { + t.value = v.to_string(); + changed = true; + } + } + if changed { + out.insert(o.handle.hex(), o); + } + } + } + out +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -908,6 +1049,8 @@ fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: & match (rec.sec.as_str(), rec.kind.as_str()) { ("BLOCKS", "BLOCK") => f.records.get(&("BLOCK".to_string(), block.to_string())).map(Cow::Borrowed), ("BLOCKS", "ENDBLK") => None, + // An attribute by its reference and tag (its handle is new). + ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attrib_key(body))).map(Cow::Borrowed), ("ENTITIES" | "BLOCKS", _) => entity_extra(f, xd, handle(&head(body).handle?)?), ("TABLES", kind) => { let name = up(&val(body, 2).unwrap_or_default()); @@ -951,9 +1094,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let by_sec = |name: &str| -> Recs { recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() }; - let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); + let (tables, blocks, entities, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("ENTITIES"), by_sec("OBJECTS")); let mut roles: HashMap = HashMap::new(); - for (h, k) in identities(&tables, &blocks, &objects) { + for (h, k) in identities(&tables, &blocks, &entities, &objects) { roles.entry(k).or_insert(h); } let mut written: HashSet = recs.iter().filter_map(|r| head(body(r)).handle).collect(); @@ -1015,7 +1158,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); // Block references' annotation scale contexts, up to date with the references. - let contexts = block_contexts(f, d, &owners); + let mut contexts = block_contexts(f, d, &owners); + let attribute = attribute_contexts(f, d, &owners, &contexts); + contexts.extend(attribute); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 74d33c097..ad5cca0b7 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -97,6 +97,29 @@ const FIXTURE: &str = " 42 5 43 5 50 0 +66 1 +0 ATTRIB +5 70 +102 {ACAD_XDICTIONARY +360 71 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 15 +20 30 +30 0 +40 1 +1 X +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND +5 77 +330 40 +100 AcDbEntity +8 0 0 ENDSEC 0 SECTION 2 OBJECTS @@ -188,6 +211,60 @@ const FIXTURE: &str = " 41 1 42 1 43 1 +0 DICTIONARY +5 71 +330 70 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 73 +0 DICTIONARY +5 73 +330 71 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 74 +0 DICTIONARY +5 74 +330 73 +100 AcDbDictionary +281 1 +3 *A1 +350 75 +3 *A2 +350 76 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 75 +330 74 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +70 0 +50 0 +10 15 +20 30 +11 15 +21 30 +290 0 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 76 +330 74 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +70 0 +50 0 +10 11 +20 22 +11 11 +21 22 +290 0 0 ENDSEC 0 EOF "; @@ -237,6 +314,19 @@ fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> { .collect() } +/// The written attribute contexts: (scale name, insertion point), and the ATTRIB they hang on +/// (its tag, through its extension dictionary). +fn attribute_contexts(text: &str) -> Vec<(String, Vec2)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| (get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), Vec2::new(num(t, 10), num(t, 20)))) + .collect() +} + fn read() -> Drawing { read_dxf(dxf(FIXTURE).as_bytes()).unwrap() } @@ -260,6 +350,39 @@ fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() { assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0)); // Read back: still annotative. assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative); + // The attribute's contexts, on the written attribute (its handle is new), as read. + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); + let recs = records(&text); + let (_, attrib) = recs.iter().find(|(k, t)| k == "ATTRIB" && get(t, 2) == Some("TAG")).unwrap(); + assert!(attrib.iter().any(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY"), "{attrib:?}"); +} + +#[test] +fn an_attribute_s_contexts_follow_its_reference() { + // Moved 5 along x and scaled 2 (the attribute with it, as MOVE and SCALE move it): at 1:5 + // the attribute goes to (15 + 10, 20 + 20); at 1:1, through the reference's 1:1 context (now + // at (15, 20), scale 2), to (15 + 2, 20 + 4). + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.scale = i.scale * 2.0; + for a in &mut i.attribs { + a.text.insert = cadcraft_doc::geom::Vec3::new(25.0, 40.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + assert_eq!(actx.len(), 2); + assert!(near(actx[0].1, 17.0, 24.0), "1:1 {:?}", actx[0]); + assert!(near(actx[1].1, 25.0, 40.0), "1:5 {:?}", actx[1]); } #[test] From 6aa64a13c90ed3948e1e494d7a3bcb3509d9581b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:08:05 -0600 Subject: [PATCH 05/15] DWG: block reference annotation contexts keep their rotation, insertion and scales AutoCAD's DXF has a block reference context's rotation (50, degrees), insertion point and scales straight after its scale (340). acadrust 0.6.4 reads them after an AcDbBlkRefObjectContextData marker, with the rotation in radians, and without the marker read zeros: a drawing saved as DWG had every annotative reference at scale 0 at its other annotation scales, where AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its way (marker, radians) and turns its DXF back into AutoCAD's (no marker, degrees). Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 60 +++++++++++++++++++- crates/io/tests/annotative_block_contexts.rs | 32 +++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 037aa26b5..39d1f27fa 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -121,7 +121,7 @@ mod native { )); } written.map_err(|e| format!("DWG→DXF: {e}"))?; - Ok((add_header_vars(out.buf, &doc.header), notes)) + Ok((add_header_vars(blkref_contexts(&out.buf, false), &doc.header), notes)) } /// Most record types named in the skipped-records note. @@ -574,6 +574,62 @@ mod native { } } + /// Block reference annotation contexts (`ACDB_BLKREFOBJECTCONTEXTDATA_CLASS`) as acadrust + /// reads and writes them (`to_acadrust`), or back as AutoCAD writes them. AutoCAD's DXF has + /// the rotation (50, degrees), insertion point and scales straight after the context's scale + /// (340); acadrust 0.6.4 looks for them after an `AcDbBlkRefObjectContextData` marker, with + /// the rotation in radians (as DWG holds it), and without the marker reads zeros (an + /// annotative reference at scale 0 draws nothing in AutoCAD). Text that isn't UTF-8, or has + /// no such context, is returned as it is. + pub(crate) fn blkref_contexts(dxf: &[u8], to_acadrust: bool) -> Vec { + const KIND: &str = "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS"; + const MARKER: &str = "AcDbBlkRefObjectContextData"; + let Ok(text) = std::str::from_utf8(dxf) else { return dxf.to_vec() }; + if !text.contains(KIND) { + return dxf.to_vec(); + } + let lines: Vec<&str> = text.split('\n').collect(); + let eol = |l: &str| if l.ends_with('\r') { "\r" } else { "" }; + let mut out: Vec = Vec::with_capacity(lines.len() + 16); + let (mut inside, mut marked) = (false, false); + let mut i = 0; + while let (Some(&code_line), Some(&value_line)) = (lines.get(i), lines.get(i + 1)) { + let (code, value) = (code_line.trim(), value_line.trim_end_matches('\r')); + if code == "0" { + inside = value.trim() == KIND; + marked = false; + } + let mut value = value.to_string(); + if inside { + if code == "100" && value.trim() == MARKER { + marked = true; + i += 2; + if !to_acadrust { + continue; + } + out.push(code_line.to_string()); + out.push(value_line.to_string()); + continue; + } + if code == "50" { + if to_acadrust && !marked { + out.push(format!("100{}", eol(code_line))); + out.push(format!("{MARKER}{}", eol(value_line))); + marked = true; + } + if let Ok(a) = value.trim().parse::() { + value = if to_acadrust { a.to_radians() } else { a.to_degrees() }.to_string(); + } + } + } + out.push(code_line.to_string()); + out.push(format!("{value}{}", eol(value_line))); + i += 2; + } + out.extend(lines.get(i..).unwrap_or(&[]).iter().map(|l| (*l).to_string())); + out.join("\n").into_bytes() + } + fn convert(dxf: &[u8], version: Option) -> Result, String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which // allocates tables and section buffers from the input's declared sizes and cannot be @@ -586,7 +642,7 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let data = dxf.to_vec(); + let data = blkref_contexts(dxf, true); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index ad5cca0b7..6c3cff476 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -408,3 +408,35 @@ fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() { } assert_eq!(ctx.len(), 2); } + +/// A reference's annotation contexts as CADCraft's model keeps them: (scale's SCALE handle, +/// rotation, x scale) of each, by the order kept. +fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> { + let num = |o: &cadcraft_doc::foreign::ForeignObject, c: i32| { + o.tags.iter().find(|t| t.code == c).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(f64::NAN) + }; + d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_reference_s_contexts_survive_dwg() { + // Turned 30° first, so the rotation's unit shows (DXF degrees, DWG radians). + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.rotation = 30f64.to_radians(); + } + }) + .unwrap(); + let back = + cadcraft_io::read(&cadcraft_io::read_dxf(write_dxf(&d).as_bytes()).map(|d| cadcraft_io::write(&d, "x.dwg").unwrap()).unwrap(), "x.dwg") + .unwrap(); + let mut ctx = kept_contexts(&back); + ctx.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(ctx.len(), 2, "{ctx:?}"); + for ((rot, sx), want) in ctx.iter().zip([1.0, 5.0]) { + assert!((rot - 30.0).abs() < 1e-9 && (sx - want).abs() < 1e-9, "{ctx:?}"); + } +} From 8a0ca4da379c5220fcb346e543bdf75d4e453e6c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:29:04 -0600 Subject: [PATCH 06/15] DXF: kept reference contexts follow the drawing's and the reference's scales A kept block reference or attribute context whose SCALE is no longer in the drawing's list is not written (its dictionary entry goes with it), so no context points at a null scale. A reference CADCraft's model keeps annotative has a context for exactly the scales it supports: contexts of scales it dropped go, and one per new scale is made from the default context, scaled by the ratio of the scales about the reference's insertion point. One context stays the default. Attributes are identified by reference, tag and their place among the reference's attributes with that tag, so two attributes with one tag keep their own extension dictionaries and contexts. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 302 +++++++++++++++++-- crates/io/tests/annotative_block_contexts.rs | 122 ++++++++ 2 files changed, 392 insertions(+), 32 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d8aaa1689..5a6d291c4 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -201,8 +201,9 @@ fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> } }; // Attributes (written with new handles each time) by their reference and tag. - for (kind, _, t) in blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB") { - put(head(t).handle, (kind.clone(), attrib_key(t))); + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + put(head(t).handle, ("ATTRIB".into(), key)); } for (kind, _, t) in tables { let name = up(&val(t, 2).unwrap_or_default()); @@ -416,9 +417,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } put_xdata(d, xdata_of); // Attributes' extension dictionaries (their annotation scale contexts), by attribute. - for (kind, _, t) in blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB") { + let attribs: Vec<&[Tag]> = blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { - f.records.entry((kind.clone(), attrib_key(t))).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); } } for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { @@ -656,10 +658,29 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } -/// An attribute's identity across saves (its handle is new each time): its reference's handle -/// and its tag. -fn attrib_key(tags: &[Tag]) -> String { - format!("{}/{}", head(tags).owner.unwrap_or_default(), up(&val(tags, 2).unwrap_or_default())) +/// The identities across saves (an attribute's handle is new each time) of ATTRIB records, in +/// order: the reference's handle, the tag and the attribute's place among the reference's +/// attributes with that tag (a block can have two attributes with one tag; reading and writing +/// keep their order). +fn attrib_keys<'a>(attribs: impl Iterator) -> Vec { + let mut seen: HashMap = HashMap::new(); + attribs + .map(|t| { + let base = format!("{}/{}", head(t).owner.unwrap_or_default(), up(&val(t, 2).unwrap_or_default())); + let n = seen.entry(base.clone()).or_insert(0); + let key = format!("{base}/{n}"); + *n += 1; + key + }) + .collect() +} + +/// An attribute's identity ([`attrib_keys`]) split: its reference, tag and place among the +/// reference's attributes with that tag. +fn split_attrib_key(key: &str) -> Option<(Handle, &str, usize)> { + let (ins, rest) = key.split_once('/')?; + let (tag, nth) = rest.rsplit_once('/')?; + Some((Handle::parse_hex(ins)?, tag, nth.parse().ok()?)) } /// The kept annotation scale contexts of block references, brought up to date with each @@ -760,16 +781,7 @@ fn attribute_contexts( } None }; - // Attributes' extension dictionaries: (reference, tag). - let attribs: HashMap = f - .records - .iter() - .filter(|(k, _)| k.0 == "ATTRIB") - .filter_map(|(k, x)| { - let (ins, tag) = k.1.split_once('/')?; - Some((x.xdict?.hex(), (Handle::parse_hex(ins)?, tag.to_string()))) - }) - .collect(); + let attribs = attribute_xdicts(f); // A reference's context at each scale, as read and as written: (insertion, degrees, scale). type Place = (Vec2, f64, (f64, f64)); let place = @@ -803,9 +815,9 @@ fn attribute_contexts( } let mut out = HashMap::new(); for (xd, list) in &by_attrib { - let Some((r, tag)) = attribs.get(xd) else { continue }; + let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some(a) = ins.attribs.iter().find(|a| up(&a.tag) == *tag) else { continue }; + let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; @@ -852,6 +864,206 @@ fn attribute_contexts( out } +fn is_blkref_context(kind: &str) -> bool { + kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") +} + +fn is_attribute_context(kind: &str) -> bool { + up(kind).contains("ATTRIBUTEOBJECTCONTEXTDATA") +} + +/// Attributes' kept extension dictionaries: (reference, tag, place among the reference's +/// attributes with that tag), by dictionary handle. +fn attribute_xdicts(f: &Foreign) -> HashMap { + f.records + .iter() + .filter(|(k, _)| k.0 == "ATTRIB") + .filter_map(|(k, x)| { + let (ins, tag, nth) = split_attrib_key(&k.1)?; + Some((x.xdict?.hex(), (ins, tag.to_string(), nth))) + }) + .collect() +} + +/// The kept contexts of block references and their attributes, in line with the drawing's +/// scales ([`reconcile`]). +#[derive(Default)] +struct Reconciled { + /// Contexts not written: their scale is gone from the drawing's scale list, or their + /// reference is annotative in CADCraft's model and no longer supports it. + dropped: HashSet, + /// New contexts for the scales such a reference supports without a context, with handles + /// above every file handle ([`MAX_HANDLE`]); their dictionaries list them. + added: Vec, + /// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role. + scales: HashMap, +} + +/// Bring the kept contexts of block references and their attributes (`contexts`: those already +/// refreshed, by handle) in line with the scales: a context whose SCALE is not written (deleted +/// from the drawing's list) goes. A reference CADCraft's model keeps annotative (it supports +/// scales, [`cadcraft_doc::Common::anno_scales`]) has a context for exactly the scales it +/// supports: one per new scale is made from its default context, scaled by the ratio of the two +/// scales about the reference's insertion point (as AutoCAD adds a scale). One context of each +/// reference stays the default (290 = 1). Changed dictionaries and contexts go into `contexts`. +fn reconcile( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + roles: &HashMap, + contexts: &mut HashMap, +) -> Reconciled { + use cadcraft_doc::geom::Vec2; + let mut out = Reconciled::default(); + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The written scale a context names (upper case), if its SCALE is written. + let scale_of = |o: &ForeignObject| -> Option { + let v = o.tags.iter().find(|t| t.code == 340)?; + let k = f.targets.get(&handle(&norm(&v.value))?)?; + (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) + }; + let is_default = |o: &ForeignObject| o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1"); + let set_default = |o: &mut ForeignObject, on: bool| { + if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { + t.value = if on { "1" } else { "0" }.into(); + } + }; + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + let attribs = attribute_xdicts(f); + // The contexts (as refreshed) by their dictionary, with the reference they belong to and + // whether they are an attribute's. + let mut groups: BTreeMap)> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| is_blkref_context(&o.kind) || is_attribute_context(&o.kind)) { + let h = o.handle.hex(); + let (Some(parent), Some((xd, owner))) = (owners.get(&h), top(&h)) else { continue }; + let attribute = is_attribute_context(&o.kind); + let reference = if attribute { attribs.get(&xd).map(|a| a.0) } else { Handle::parse_hex(&owner) }; + let Some(reference) = reference else { continue }; + groups.entry(parent.clone()).or_insert((reference, attribute, Vec::new())).2.push(contexts.get(&h).unwrap_or(o).clone()); + } + let mut next = MAX_HANDLE; + let mut fresh = || { + next = next.saturating_add(1); + format!("{next:X}") + }; + // Each annotative reference's default context: (scale, insertion point). + let mut ref_default: HashMap = HashMap::new(); + for (r, attribute, list) in groups.values() { + if let (false, Some(def)) = (attribute, list.iter().find(|o| is_default(o)).or(list.first())) + && let (Some(s), Some(x), Some(y)) = (scale_of(def), num(def, 10), num(def, 20)) + { + ref_default.insert(*r, (s, Vec2::new(x, y))); + } + } + let current = up(&d.current_anno_scale().name); + for (dict, (r, attribute, list)) in &groups { + let e = d.entity(*r).filter(|e| matches!(e.kind, EntityKind::Insert(_)) && cadcraft_doc::is_annotative(e)); + // The scales the reference supports, when CADCraft's model says (each written once). + let mut wanted: Vec = Vec::new(); + for s in e.map(|e| e.common.anno_scales.as_slice()).unwrap_or_default() { + let n = up(&s.name); + if s.is_valid() && roles.contains_key(&("SCALE".to_string(), n.clone())) && !wanted.contains(&n) { + wanted.push(n); + } + } + let mut have: Vec<(String, ForeignObject)> = Vec::new(); + for c in list { + match scale_of(c) { + Some(s) if e.is_none() || (wanted.contains(&s) && !have.iter().any(|(x, _)| *x == s)) => have.push((s, c.clone())), + _ => { + out.dropped.insert(c.handle.hex()); + } + } + } + // New contexts, from the context at the reference's default scale. + let mut added: Vec<(String, ForeignObject)> = Vec::new(); + if let Some(e) = e + && let Some((def_scale, at)) = ref_default.get(r) + && let Some(template) = list.iter().find(|c| scale_of(c).as_ref() == Some(def_scale)) + { + let factor = |name: &str| { + d.scales + .iter() + .chain(&e.common.anno_scales) + .find(|s| up(&s.name) == name) + .map(cadcraft_doc::AnnoScale::factor) + .filter(|f| f.is_finite() && *f > 0.0) + }; + for s in wanted.iter().filter(|s| !have.iter().any(|(x, _)| x == *s)) { + let (Some(to), Some(from)) = (factor(s), factor(def_scale)) else { continue }; + let k = to / from; + let (h, scale) = (fresh(), fresh()); + let mut o = template.clone(); + o.handle = Handle::parse_hex(&h).unwrap_or(o.handle); + for t in &mut o.tags { + let v = t.value.trim().parse::().ok().filter(|v| v.is_finite()); + let new = match (t.code, v) { + (5, _) => Some(h.clone()), + (340, _) => Some(scale.clone()), + (41..=43, Some(v)) if !attribute => Some((v * k).to_string()), + // An attribute's points scale about the reference's insertion point. + (10 | 11, Some(v)) if *attribute => Some((at.x + (v - at.x) * k).to_string()), + (20 | 21, Some(v)) if *attribute => Some((at.y + (v - at.y) * k).to_string()), + _ => None, + }; + if let Some(new) = new { + t.value = new; + } + } + set_default(&mut o, false); + out.scales.insert(scale, ("SCALE".into(), s.clone())); + added.push((s.clone(), o)); + } + } + // One default: the one kept, else the current scale's, else the first. + if !have.iter().chain(&added).any(|(_, o)| is_default(o)) { + let pick = have.iter().chain(&added).position(|(s, _)| *s == current).unwrap_or(0); + if let Some((_, o)) = have.get_mut(pick) { + set_default(o, true); + contexts.insert(o.handle.hex(), o.clone()); + } else if let Some((_, o)) = added.get_mut(pick.saturating_sub(have.len())) { + set_default(o, true); + } + } + if added.is_empty() { + continue; + } + // The dictionary lists the new contexts (as `*A`, after its own). + let Some(mut dobj) = contexts.get(dict).or_else(|| f.objects.iter().find(|o| o.handle.hex() == *dict)).cloned() else { continue }; + let mut n = dobj + .tags + .iter() + .filter(|t| t.code == 3) + .filter_map(|t| t.value.trim().strip_prefix("*A").and_then(|n| n.parse::().ok())) + .max() + .unwrap_or(0); + let at = dobj.tags.iter().position(|t| t.code >= 1000).unwrap_or(dobj.tags.len()); + let mut entries = Vec::new(); + for (_, o) in &added { + n = n.saturating_add(1); + entries.push(RawTag { code: 3, value: format!("*A{n}") }); + entries.push(RawTag { code: 350, value: o.handle.hex() }); + } + dobj.tags.splice(at..at, entries); + contexts.insert(dict.clone(), dobj); + out.added.extend(added.into_iter().map(|(_, o)| o)); + } + out +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -952,6 +1164,8 @@ struct Map<'a> { roles: HashMap, /// Entities in the written file. entities: HashSet, + /// Stand-in handles of the scales new contexts name ([`Reconciled::scales`]). + scales: &'a HashMap, } impl Map<'_> { @@ -965,6 +1179,9 @@ impl Map<'_> { if self.raw.contains(&v) { return self.alive.get(&v).cloned(); } + if let Some(role) = self.scales.get(&v) { + return self.roles.get(role).cloned(); + } let h = handle(&v)?; if let Some(role) = self.f.targets.get(&h) { return self.roles.get(role).cloned(); @@ -1045,12 +1262,19 @@ impl Map<'_> { } /// The extras of a written record, if the drawing keeps any for it. -fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: &str) -> Option> { +fn extra_for<'a>( + f: &'a Foreign, + xd: &XdataOf, + attribs: &HashMap, + rec: &Rec, + body: &[Tag], + block: &str, +) -> Option> { match (rec.sec.as_str(), rec.kind.as_str()) { ("BLOCKS", "BLOCK") => f.records.get(&("BLOCK".to_string(), block.to_string())).map(Cow::Borrowed), ("BLOCKS", "ENDBLK") => None, // An attribute by its reference and tag (its handle is new). - ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attrib_key(body))).map(Cow::Borrowed), + ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attribs.get(&rec.start)?.clone())).map(Cow::Borrowed), ("ENTITIES" | "BLOCKS", _) => entity_extra(f, xd, handle(&head(body).handle?)?), ("TABLES", kind) => { let name = up(&val(body, 2).unwrap_or_default()); @@ -1130,6 +1354,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s); let root_keys: HashSet = objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default(); + // The written attributes' identities, by record. + let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); + let attribs: HashMap = attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect(); // Extension dictionaries that go on a written record (one without its own). let mut block = String::new(); let mut attached: HashSet = HashSet::new(); @@ -1137,7 +1364,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { if r.kind == "BLOCK" { block = up(&val(body(r), 2).unwrap_or_default()); } - if let Some(x) = extra_for(f, &xd, r, body(r), &block) + if let Some(x) = extra_for(f, &xd, &attribs, r, body(r), &block) && let Some(xd) = x.xdict && head(body(r)).xdict.is_none() { @@ -1148,11 +1375,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h)); attached.extend(x.and_then(|x| x.xdict).map(Handle::hex)); } - // Which kept objects are written: those whose owner chain ends at a written owner. - let objs: HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); - let owners: HashMap = f + let mut owners: HashMap = f .objects .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) @@ -1161,11 +1386,21 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let mut contexts = block_contexts(f, d, &owners); let attribute = attribute_contexts(f, d, &owners, &contexts); contexts.extend(attribute); + // In line with the drawing's scales and each reference's. + let rec = reconcile(f, d, &owners, &roles, &mut contexts); + let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); + for o in &rec.added { + if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { + owners.insert(o.handle.hex(), norm(&parent.value)); + } + } + // Which kept objects are written: those whose owner chain ends at a written owner. + let objs: HashMap = all.iter().map(|o| (o.handle.hex(), *o)).collect(); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); } - for o in &f.objects { + for o in &all { let mut path: Vec = Vec::new(); let mut cur = o.handle.hex(); let verdict = loop { @@ -1193,15 +1428,18 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { alive_memo.insert(p, verdict); } } + for h in &rec.dropped { + alive_memo.insert(h.clone(), false); + } // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); - for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { + for o in all.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { alive.insert(o.handle.hex(), format!("{next:X}")); next = next.saturating_add(1); } let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); - let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities }; + let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities, scales: &rec.scales }; let mut out: Vec = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::()); let mut block = String::new(); for r in &recs { @@ -1216,8 +1454,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { } } if r.kind == "ENDSEC" && r.sec == "OBJECTS" { - for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { - let o = contexts.get(&o.handle.hex()).unwrap_or(o); + for o in all.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { + let o = contexts.get(&o.handle.hex()).unwrap_or(*o); let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten(); match number { Some(n) => { @@ -1238,7 +1476,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { record(&map, &ur, ub, x.as_deref(), true, false, &mut out); } out.extend(tags.get(r.start).cloned()); - let x = extra_for(f, &xd, r, b, &block); + let x = extra_for(f, &xd, &attribs, r, b, &block); if x.is_none() && Some(r.start) != root { out.extend(b.iter().cloned()); continue; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 6c3cff476..56f502db4 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -440,3 +440,125 @@ fn a_reference_s_contexts_survive_dwg() { assert!((rot - 30.0).abs() < 1e-9 && (sx - want).abs() < 1e-9, "{ctx:?}"); } } + +/// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every +/// written context is listed once. +fn listed_contexts(text: &str) -> usize { + let recs = records(text); + let handles: std::collections::HashSet<&str> = + recs.iter().filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")).filter_map(|(_, t)| get(t, 5)).collect(); + let mut listed = 0; + for (_, t) in recs.iter().filter(|(k, _)| k == "DICTIONARY") { + for (c, v) in t { + if *c == 350 && handles.contains(v.as_str()) { + listed += 1; + } + } + } + assert_eq!(listed, handles.len(), "contexts listed in their dictionaries"); + listed +} + +#[test] +fn a_context_whose_scale_was_deleted_is_not_written() { + let mut d = read(); + d.scales.retain(|s| s.name != "1:1"); + let text = write_dxf(&d); + let ctx = contexts(&text); + assert_eq!(ctx.iter().map(|c| (c.0.as_str(), c.1)).collect::>(), [("1:5", true)]); + let actx = attribute_contexts(&text); + assert_eq!(actx.iter().map(|c| c.0.as_str()).collect::>(), ["1:5"]); + assert_eq!(listed_contexts(&text), 2); +} + +#[test] +fn an_annotative_reference_s_contexts_follow_its_scales() { + // CADCraft's model makes the reference annotative at 1:5 and a new 1:2 (1:1 no longer): + // the 1:1 contexts go, 1:2 ones are made from the default 1:5 ones, scaled 2/5 about the + // reference's insertion point. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!((got[0].0.as_str(), got[0].1), ("1:2", false)); + assert!((got[0].2 - 2.0).abs() < 1e-9, "{got:?}"); + assert_eq!(got[1], ("1:5".to_string(), true, 5.0)); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0))); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0].0, "1:2"); + assert!((actx[0].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(actx[1], ("1:5".to_string(), Vec2::new(15.0, 30.0))); + assert_eq!(listed_contexts(&text), 4); + // Read back, the reference keeps them (and nothing points at a missing scale). + let back = read_dxf(text.as_bytes()).unwrap(); + assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?")); +} + +#[test] +fn two_attributes_with_one_tag_keep_their_own_contexts() { + // A second attribute TAG on the reference, with its own extension dictionary (no contexts + // in it): each written ATTRIB gets its own dictionary, the first keeps the contexts. + let second = " +0 ATTRIB +5 80 +102 {ACAD_XDICTIONARY +360 81 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 1 +20 2 +30 0 +40 1 +1 Y +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND"; + let objs = " +0 DICTIONARY +5 81 +330 80 +100 AcDbDictionary +280 1 +281 1 +3 OTHER +360 82 +0 XRECORD +5 82 +330 81 +100 AcDbXrecord +1 kept +0 ENDSEC +0 EOF"; + let src = FIXTURE.replacen("0 SEQEND", second, 1); + let at = src.rfind("0 ENDSEC").unwrap(); + let src = format!("{}{objs}", &src[..at]); + let d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let xdict = |t: &[(i32, String)]| { + let i = t.iter().position(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY")?; + t.get(i + 1).map(|(_, v)| v.clone()) + }; + let attribs: Vec<(String, Option)> = + recs.iter().filter(|(k, _)| k == "ATTRIB").map(|(_, t)| (get(t, 1).unwrap_or_default().to_string(), xdict(t))).collect(); + assert_eq!(attribs.len(), 2, "{attribs:?}"); + let (x, y) = (attribs[0].1.clone().unwrap(), attribs[1].1.clone().unwrap()); + assert_ne!(x, y, "{attribs:?}"); + // The first attribute's dictionary leads to its contexts, the second's to the xrecord. + let owner_of = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).and_then(|(_, t)| get(t, 330)).map(str::to_string); + let xrec = recs.iter().find(|(k, t)| k == "XRECORD" && get(t, 1) == Some("kept")).map(|(_, t)| get(t, 5).unwrap().to_string()).unwrap(); + assert_eq!(owner_of(&xrec), Some(y)); + assert_eq!(attribute_contexts(&text).len(), 2); +} From 97e225f324570ad33a2893b1b9db5c22fdeb1524 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:12:07 -0600 Subject: [PATCH 07/15] DXF: new reference contexts come from one whose scale is still written When the default context's scale had been deleted from the drawing's list, a reference CADCraft keeps annotative got no new contexts for its added scales; the template is now its default context, else its first, among those whose SCALE is written. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 6 +++-- crates/io/tests/annotative_block_contexts.rs | 25 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 5a6d291c4..f52cd9d07 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -959,10 +959,12 @@ fn reconcile( next = next.saturating_add(1); format!("{next:X}") }; - // Each annotative reference's default context: (scale, insertion point). + // Each reference's template for new contexts: (scale, insertion point) of its default + // context, else of its first, among those whose scale is still written. let mut ref_default: HashMap = HashMap::new(); for (r, attribute, list) in groups.values() { - if let (false, Some(def)) = (attribute, list.iter().find(|o| is_default(o)).or(list.first())) + let written: Vec<&ForeignObject> = list.iter().filter(|o| scale_of(o).is_some()).collect(); + if let (false, Some(def)) = (attribute, written.iter().find(|o| is_default(o)).or(written.first())) && let (Some(s), Some(x), Some(y)) = (scale_of(def), num(def, 10), num(def, 20)) { ref_default.insert(*r, (s, Vec2::new(x, y))); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 56f502db4..f3c740d97 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -562,3 +562,28 @@ fn two_attributes_with_one_tag_keep_their_own_contexts() { assert_eq!(owner_of(&xrec), Some(y)); assert_eq!(attribute_contexts(&text).len(), 2); } + +#[test] +fn new_contexts_come_from_one_whose_scale_remains() { + // The default context's scale (1:5) is deleted, and the reference is annotative at 1:1 and a + // new 1:2: the 1:2 contexts are made from the 1:1 ones (scale 1 → 2 about the insertion + // point), and 1:1 becomes the default. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.retain(|s| s.name != "1:5"); + d.scales.push(half.clone()); + let one = d.scales.iter().find(|s| s.name == "1:1").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![one, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), true, 1.0), ("1:2".to_string(), false, 2.0)]); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0], ("1:1".to_string(), Vec2::new(11.0, 22.0))); + assert_eq!(actx[1].0, "1:2"); + assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(listed_contexts(&text), 4); +} From 37bf128ffde672f64f0945f7ce8dd3aa38ab9bdc Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:01:39 -0600 Subject: [PATCH 08/15] DXF: kept reference contexts follow the reference as read; one default rule A kept context is brought up to date by what its block reference did since the file was read. That baseline was the default context, which needn't be where the reference was (an unchanged save then moved every context); the reference and its attributes as read are now kept (`Foreign::placements`) and used, the default context only for data without them. A context's own offset from the reference now scales and mirrors with it (back into the reference's frame then, scaled, turned to its frame now), not only turns. The default context is the one whose first 290 group is 1 everywhere (an attribute context has a later 290 of its own). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/foreign.rs | 15 ++++ crates/io/src/dxf_raw.rs | 66 ++++++++++++---- crates/io/tests/annotative_block_contexts.rs | 81 ++++++++++++++++++++ 3 files changed, 147 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..84ca2031b 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -75,6 +75,20 @@ pub struct Foreign { /// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD` /// names its entity with a 320 handle (see [`Foreign::data_store_entities`]). pub data_store: Vec, + /// Block references with kept annotation scale contexts, as they were read: what a context + /// is brought up to date from (see [`KeptPlacement`]), by handle. + pub placements: BTreeMap, +} + +/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its +/// attributes' insertion and alignment points, in order. Its kept contexts were written for it +/// then; what it did since moves them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptPlacement { + pub insert: crate::geom::Vec3, + pub rotation: f64, + pub scale: crate::geom::Vec3, + pub attribs: Vec<(crate::geom::Vec3, crate::geom::Vec3)>, } impl Foreign { @@ -87,6 +101,7 @@ impl Foreign { && self.targets.is_empty() && self.class_order.is_empty() && self.data_store.is_empty() + && self.placements.is_empty() } /// The entities the data store has records for (their 320 handles). diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index f52cd9d07..d25aac64e 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -430,6 +430,17 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.records.entry(key).or_insert(x); } } + // Block references whose extension dictionaries are kept (their annotation scale contexts), + // as read. + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins.attribs.iter().map(|a| (a.text.insert, a.text.align_pt.unwrap_or(a.text.insert))).collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -714,22 +725,36 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> let mut out = HashMap::new(); for list in by_parent.values() { let Some(first) = list.first() else { continue }; - let Some(EntityKind::Insert(ins)) = owner_entity(&first.handle.hex()).and_then(|h| d.entity(h)).map(|e| &e.kind) else { continue }; - let def = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).unwrap_or(first); - let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; - let turn = (ins.rotation.to_degrees() - num(def, 50).unwrap_or(0.0)).to_radians(); - let at0 = cadcraft_doc::geom::Vec2::new(x0, y0); - let ratio = |code: i32, now: f64| num(def, code).filter(|s| s.abs() > 1e-12).map_or(1.0, |s| now / s); - let ratios = [(41, ratio(41, ins.scale.x)), (42, ratio(42, ins.scale.y)), (43, ratio(43, ins.scale.z))]; + let Some(h) = owner_entity(&first.handle.hex()) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { continue }; + // The reference as read: kept when it was read, else (data made before that was kept) + // its default context. + let (at0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.rotation, [p.scale.x, p.scale.y, p.scale.z]), + None => { + let def = list.iter().find(|o| is_default(o)).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let s = |code: i32, now: f64| num(def, code).unwrap_or(now); + let rot = num(def, 50).unwrap_or(0.0).to_radians(); + (cadcraft_doc::geom::Vec2::new(x0, y0), rot, [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)]) + } + }; + let turn = ins.rotation - rot0; + let ratio = |then: f64, now: f64| if then.abs() > 1e-12 { now / then } else { 1.0 }; + let ratios = [(41, ratio(scale0[0], ins.scale.x)), (42, ratio(scale0[1], ins.scale.y)), (43, ratio(scale0[2], ins.scale.z))]; let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { continue; } for c in list { let mut o = (*c).clone(); - // Its offset from the default context turns with the reference. + // Its offset from where the reference was moves as the reference did: back into the + // reference's frame then, scaled (a mirror flips it), turned to its frame now. let at = match (num(c, 10), num(c, 20)) { - (Some(x), Some(y)) => ins.insert.xy() + (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(turn), + (Some(x), Some(y)) => { + let off = (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(-rot0); + ins.insert.xy() + cadcraft_doc::geom::Vec2::new(off.x * ratios[0].1, off.y * ratios[1].1).rotate(ins.rotation) + } _ => ins.insert.xy(), }; for t in &mut o.tags { @@ -817,19 +842,25 @@ fn attribute_contexts( for (xd, list) in &by_attrib { let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; + let Some((index, a)) = ins.attribs.iter().enumerate().filter(|(_, a)| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; - let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; + let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); // What the attribute did in the block since: its default context then, the attribute now. let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; let now_ins = to_block_now.apply(a.text.insert.xy()); let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); - let (Some(then_ins), Some(then_align)) = (at(def, 10).map(|p| to_block_then.apply(p)), at(def, 11).map(|p| to_block_then.apply(p))) else { - continue; - }; + // The attribute as read, in its reference as read, when that was kept; else its default + // context in the reference's. + let kept = f.placements.get(r).and_then(|p| { + let (ins_then, align_then) = p.attribs.get(index)?; + let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; + Some((then.apply(ins_then.xy()), then.apply(align_then.xy()))) + }); + let then = kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?)))); + let Some((then_ins, then_align)) = then else { continue }; let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); for c in list { let Some(s) = text(c, 340) else { continue }; @@ -864,6 +895,12 @@ fn attribute_contexts( out } +/// Whether a kept context is its object's default one: its first 290 group (of +/// AcDbObjectContextData) is 1. An attribute context has a later 290 group of its own. +fn is_default(o: &ForeignObject) -> bool { + o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1") +} + fn is_blkref_context(kind: &str) -> bool { kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") } @@ -924,7 +961,6 @@ fn reconcile( let k = f.targets.get(&handle(&norm(&v.value))?)?; (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) }; - let is_default = |o: &ForeignObject| o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1"); let set_default = |o: &mut ForeignObject, on: bool| { if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { t.value = if on { "1" } else { "0" }.into(); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index f3c740d97..0a9746735 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -587,3 +587,84 @@ fn new_contexts_come_from_one_whose_scale_remains() { assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); assert_eq!(listed_contexts(&text), 4); } + +/// The written context of the block reference at scale `name`: (insertion, rotation). +fn context_at(text: &str, name: &str) -> (Vec2, f64) { + contexts(text).into_iter().find(|c| c.0 == name).map(|c| (c.2, c.3)).unwrap() +} + +#[test] +fn an_unchanged_reference_keeps_its_contexts_when_its_default_one_is_elsewhere() { + // The reference sits at (11, 20) while its default context says (10, 20): saved unchanged, + // every context is written as read (what moves them is what the reference did since). + let d = read_dxf(dxf(&FIXTURE.replace("2 SIGN\n10 10\n20 20\n30 0\n41 5", "2 SIGN\n10 11\n20 20\n30 0\n41 5")).as_bytes()).unwrap(); + let text = write_dxf(&d); + for scale in ["1:1", "1:5"] { + assert_eq!(context_at(&text, scale).0, Vec2::new(10.0, 20.0), "{scale}"); + } + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} + +#[test] +fn a_context_s_own_offset_scales_turns_and_mirrors_with_the_reference() { + // The 1:1 context sits 2 to the right of the reference. Scaled 2 and turned 90°, it is 4 + // above; mirrored (x scale -5), 2 to the left. + let src = FIXTURE.replace("340 51\n50 0\n10 10", "340 51\n50 0\n10 12"); + let edit = |f: &dyn Fn(&mut cadcraft_doc::Insert)| { + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + f(i); + } + }) + .unwrap(); + write_dxf(&d) + }; + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let text = edit(&|i| { + i.scale = i.scale * 2.0; + i.rotation = 90f64.to_radians(); + }); + let (at, rot) = context_at(&text, "1:1"); + assert!(near(at, 10.0, 24.0) && (rot - 90.0).abs() < 1e-9, "{at:?} {rot}"); + let text = edit(&|i| i.scale.x = -i.scale.x); + let (at, _) = context_at(&text, "1:1"); + assert!(near(at, 8.0, 20.0), "{at:?}"); +} + +#[test] +fn the_default_context_is_the_one_whose_first_290_is_1() { + // The 1:1 attribute context comes first, turned 10° in its reference, with its own later + // 290 set: the 1:5 one is still the default, so an unchanged save keeps the 10°. + let at = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 76").unwrap(); + let end = FIXTURE.find("0 ENDSEC\n0 EOF").unwrap(); + let second = FIXTURE[at..end].replace("50 0\n10 11", "50 10\n10 11").replace("21 22\n290 0", "21 22\n290 1"); + let first = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 75").unwrap(); + let src = format!("{}{second}{}{}", &FIXTURE[..first], &FIXTURE[first..at], &FIXTURE[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + // Moved, so the attribute contexts are brought up to date. + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + for a in &mut i.attribs { + a.text.insert = a.text.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let rot = recs + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .find(|(_, t)| get(t, 340).and_then(|h| scales.get(h)) == Some(&"1:1")) + .and_then(|(_, t)| get(t, 50)) + .and_then(|v| v.parse::().ok()) + .unwrap(); + assert!((rot - 10.0).abs() < 1e-9, "{rot}"); +} From 345b5bc7d6131a3574144cd7fa2e128518c693a9 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:20:00 -0600 Subject: [PATCH 09/15] DXF: new reference contexts take handles above every handle in use Upstream now believes handles above 2^48 (AutoCAD writes them), so new annotation contexts can no longer take stand-in handles from 2^48 up: they start above the written handles, $HANDSEED, the kept objects and their targets. Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every written handle stays unique (red with the old 2^48 base). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 11 ++++-- crates/io/tests/annotative_block_contexts.rs | 39 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d25aac64e..2aaed0276 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -929,8 +929,8 @@ struct Reconciled { /// Contexts not written: their scale is gone from the drawing's scale list, or their /// reference is annotative in CADCraft's model and no longer supports it. dropped: HashSet, - /// New contexts for the scales such a reference supports without a context, with handles - /// above every file handle ([`MAX_HANDLE`]); their dictionaries list them. + /// New contexts for the scales such a reference supports without a context, with stand-in + /// handles above every handle in use (`above`); their dictionaries list them. added: Vec, /// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role. scales: HashMap, @@ -943,12 +943,15 @@ struct Reconciled { /// supports: one per new scale is made from its default context, scaled by the ratio of the two /// scales about the reference's insertion point (as AutoCAD adds a scale). One context of each /// reference stays the default (290 = 1). Changed dictionaries and contexts go into `contexts`. +/// New objects take stand-in handles above `above` and the kept objects' and targets' handles +/// (AutoCAD writes handles above 2^48, so no range is free by itself). fn reconcile( f: &Foreign, d: &Drawing, owners: &HashMap, roles: &HashMap, contexts: &mut HashMap, + above: u64, ) -> Reconciled { use cadcraft_doc::geom::Vec2; let mut out = Reconciled::default(); @@ -990,7 +993,7 @@ fn reconcile( let Some(reference) = reference else { continue }; groups.entry(parent.clone()).or_insert((reference, attribute, Vec::new())).2.push(contexts.get(&h).unwrap_or(o).clone()); } - let mut next = MAX_HANDLE; + let mut next = f.objects.iter().map(|o| o.handle.0).chain(f.targets.keys().map(|h| h.0)).fold(above, u64::max); let mut fresh = || { next = next.saturating_add(1); format!("{next:X}") @@ -1425,7 +1428,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let attribute = attribute_contexts(f, d, &owners, &contexts); contexts.extend(attribute); // In line with the drawing's scales and each reference's. - let rec = reconcile(f, d, &owners, &roles, &mut contexts); + let rec = reconcile(f, d, &owners, &roles, &mut contexts, seed(tags).max(max_handle(tags))); let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); for o in &rec.added { if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 0a9746735..fc5d944fe 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -502,6 +502,45 @@ fn an_annotative_reference_s_contexts_follow_its_scales() { assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?")); } +/// The fixture with every handle moved up to just past 2^48 (AutoCAD writes handles that high): +/// the reference (40) lands on 2^48 + 1. +fn far_handles(src: &str) -> String { + const SHIFT: u64 = (1 << 48) - 0x3F; + let is_handle = |code: i32| matches!(code, 5 | 105 | 320..=369 | 390..=399 | 480 | 481 | 1005); + let mut out = String::new(); + for line in src.lines() { + let (code, value) = line.trim().split_once(' ').unwrap_or((line.trim(), "")); + let moved = match (code.parse::(), u64::from_str_radix(value, 16)) { + (Ok(c), Ok(h)) if is_handle(c) && h != 0 => format!("{:X}", h + SHIFT), + _ => value.to_string(), + }; + out.push_str(&format!("{code} {moved}\n")); + } + out +} + +#[test] +fn new_contexts_get_their_own_handles_when_the_file_s_are_above_2_pow_48() { + // As in the test above, but every file handle is above 2^48: the new 1:2 contexts and their + // scale take handles no other object has. + let mut d = read_dxf(dxf(&far_handles(FIXTURE)).as_bytes()).unwrap(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + let reference = Handle::parse_hex("1000000000001").unwrap(); + d.modify_entity(reference, |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut names: Vec = contexts(&text).into_iter().map(|c| c.0).collect(); + names.sort(); + assert_eq!(names, ["1:2", "1:5"]); + assert_eq!(attribute_contexts(&text).len(), 2); + let mut handles: Vec = records(&text).iter().filter_map(|(_, t)| get(t, 5).map(str::to_string)).collect(); + let n = handles.len(); + handles.sort(); + handles.dedup(); + assert_eq!(handles.len(), n, "every written handle is unique"); +} + #[test] fn two_attributes_with_one_tag_keep_their_own_contexts() { // A second attribute TAG on the reference, with its own extension dictionary (no contexts From 75d135c9e211157a6ad220bffbb59ca0f7561128 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:33:25 -0600 Subject: [PATCH 10/15] DXF: an attribute as read is found by its tag and place, and keeps its rotation A kept attribute placement was looked up by its index among the reference's attributes now, which differs once they are reordered or replaced (ATTSYNC). It is now found by tag and place among that tag, like the attribute's contexts. The rotation change is measured from the attribute as read too, not from its default context, so an unchanged save no longer turns every context when the ATTRIB (at the current scale) and the default context differ. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/foreign.rs | 17 +++++++-- crates/io/src/dxf_raw.rs | 29 +++++++++++----- crates/io/tests/annotative_block_contexts.rs | 36 ++++++++++++++++++++ 3 files changed, 70 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 84ca2031b..d5c836873 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -81,14 +81,25 @@ pub struct Foreign { } /// A block reference as read: its insertion point, rotation (radians) and scale, and each of its -/// attributes' insertion and alignment points, in order. Its kept contexts were written for it -/// then; what it did since moves them. +/// attributes as read, in order. Its kept contexts were written for it then; what it did since +/// moves them. #[derive(Clone, Debug, Default, PartialEq)] pub struct KeptPlacement { pub insert: crate::geom::Vec3, pub rotation: f64, pub scale: crate::geom::Vec3, - pub attribs: Vec<(crate::geom::Vec3, crate::geom::Vec3)>, + pub attribs: Vec, +} + +/// An attribute of a block reference as read: its tag, insertion and alignment points and +/// rotation (radians). Found again by tag and place among the reference's attributes with that +/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptAttrib { + pub tag: String, + pub insert: crate::geom::Vec3, + pub align: crate::geom::Vec3, + pub rotation: f64, } impl Foreign { diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 2aaed0276..fa6576cf0 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -436,7 +436,16 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { if let EntityKind::Insert(ins) = &e.kind && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) { - let attribs = ins.attribs.iter().map(|a| (a.text.insert, a.text.align_pt.unwrap_or(a.text.insert))).collect(); + let attribs = ins + .attribs + .iter() + .map(|a| cadcraft_doc::foreign::KeptAttrib { + tag: a.tag.clone(), + insert: a.text.insert, + align: a.text.align_pt.unwrap_or(a.text.insert), + rotation: a.text.rotation, + }) + .collect(); f.placements .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); } @@ -842,7 +851,7 @@ fn attribute_contexts( for (xd, list) in &by_attrib { let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some((index, a)) = ins.attribs.iter().enumerate().filter(|(_, a)| up(&a.tag) == *tag).nth(*nth) else { continue }; + let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; @@ -852,16 +861,18 @@ fn attribute_contexts( let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; let now_ins = to_block_now.apply(a.text.insert.xy()); let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); - // The attribute as read, in its reference as read, when that was kept; else its default - // context in the reference's. + // The attribute as read (the same tag and place among its tag), in its reference as read, + // when that was kept: its points in the block and its rotation from the reference's + // (degrees). Else its default context in the reference's. let kept = f.placements.get(r).and_then(|p| { - let (ins_then, align_then) = p.attribs.get(index)?; + let k = p.attribs.iter().filter(|k| up(&k.tag) == *tag).nth(*nth)?; let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; - Some((then.apply(ins_then.xy()), then.apply(align_then.xy()))) + Some((then.apply(k.insert.xy()), then.apply(k.align.xy()), k.rotation.to_degrees() - p.rotation.to_degrees())) }); - let then = kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?)))); - let Some((then_ins, then_align)) = then else { continue }; - let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); + let then = + kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?), num(def, 50).unwrap_or(0.0) - def_place.1))); + let Some((then_ins, then_align, then_turn)) = then else { continue }; + let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - then_turn; for c in list { let Some(s) = text(c, 340) else { continue }; let (Some(was), Some(is)) = (read.get(&(*r, s.clone())).copied(), now.get(&(*r, s)).copied()) else { continue }; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index fc5d944fe..cbe069eb0 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -707,3 +707,39 @@ fn the_default_context_is_the_one_whose_first_290_is_1() { .unwrap(); assert!((rot - 10.0).abs() < 1e-9, "{rot}"); } + +#[test] +fn an_unchanged_attribute_turned_at_the_current_scale_keeps_its_contexts_rotation() { + // The ATTRIB is turned 20° (it is the attribute at the file's current scale) while its default + // context says 0°: saved unchanged, no context turns (what turns them is what the attribute + // did since it was read). + let d = read_dxf(dxf(&FIXTURE.replace("1 X\n", "1 X\n50 20\n")).as_bytes()).unwrap(); + let text = write_dxf(&d); + let rots: Vec = records(&text) + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .filter_map(|(_, t)| get(t, 50).and_then(|v| v.parse::().ok())) + .collect(); + assert_eq!(rots.len(), 2, "{rots:?}"); + assert!(rots.iter().all(|r| r.abs() < 1e-9), "{rots:?}"); +} + +#[test] +fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() { + // A second attribute OTHER after TAG, then the reference's attributes reversed (as a block + // redefinition's attribute sync can): TAG is found as read by its tag, so saved otherwise + // unchanged its contexts don't move. + let other = "1 X\n100 AcDbAttribute\n2 TAG\n70 0\n0 ATTRIB\n5 80\n330 40\n100 AcDbEntity\n8 0\n100 AcDbText\n10 1\n20 2\n30 0\n40 1\n1 Y\n100 AcDbAttribute\n2 OTHER\n70 0\n"; + let src = FIXTURE.replacen("1 X\n100 AcDbAttribute\n2 TAG\n70 0\n", other, 1); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + assert_eq!(i.attribs.len(), 2); + i.attribs.reverse(); + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} From 0a6d97969b21ba1a825a59b2e7697da6eeeb54ca Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:21:44 -0600 Subject: [PATCH 11/15] DXF: the kept-context code in read and finish moves into helpers main now denies cognitive_complexity over 30 and too_many_arguments over 7. This PR's additions took read to 32 and finish to 31, and retained_objects to 8 arguments: the block-reference and attribute bookkeeping now lives in insert_handles, of_insert, keep_attrib_dictionaries, keep_placements, written_attribs and refreshed_contexts, and retained_objects takes the root and its entries as one pair. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/dxf_raw.rs | 134 +++++++++++++++--------- crates/io/src/dxf_read/tables.rs | 4 +- crates/io/tests/it/roundtrip/compare.rs | 2 + 3 files changed, 86 insertions(+), 54 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index fa6576cf0..95d3ade50 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -47,6 +47,17 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCO /// when written ([`block_contexts`]). const CONTEXTS_KEY: &str = "ACDBCONTEXTDATAMANAGER"; +/// The handles of the drawing's block references. +fn insert_handles(d: &Drawing) -> HashSet { + all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect() +} + +/// Whether the object `tags` belongs to a block reference (`inserts`) or one of its attributes +/// (an ATTRIB in `ids`): their extension dictionaries keep annotation scale contexts. +fn of_insert(tags: &[Tag], inserts: &HashSet, ids: &HashMap) -> bool { + head(tags).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")) +} + /// Whether extension dictionary entry `key` is left to CADCraft's model, in the extension /// dictionary of a block reference (`of_insert`) or of something else. fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { @@ -374,8 +385,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { }; // Block references and their attributes (their extension dictionaries keep annotation scale // contexts). - let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); - let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")); + let inserts = insert_handles(d); let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); @@ -386,7 +396,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue }; let mut tags: Vec = t.iter().map(raw).collect(); if is_xdict(i) { - strip_entries(&mut tags, of_insert(t)); + strip_entries(&mut tags, of_insert(t, &inserts, &ids)); } if head(t).owner == root && let Some(key) = root_key(&h.hex()) @@ -416,13 +426,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } put_xdata(d, xdata_of); - // Attributes' extension dictionaries (their annotation scale contexts), by attribute. - let attribs: Vec<&[Tag]> = blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); - for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { - if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { - f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); - } - } + keep_attrib_dictionaries(&mut f, (&blocks, &entities), &kept); for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; let x = extra(kind, t, kind == "BLOCK", false, &kept); @@ -430,26 +434,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.records.entry(key).or_insert(x); } } - // Block references whose extension dictionaries are kept (their annotation scale contexts), - // as read. - for e in all_entities(d) { - if let EntityKind::Insert(ins) = &e.kind - && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) - { - let attribs = ins - .attribs - .iter() - .map(|a| cadcraft_doc::foreign::KeptAttrib { - tag: a.tag.clone(), - insert: a.text.insert, - align: a.text.align_pt.unwrap_or(a.text.insert), - rotation: a.text.rotation, - }) - .collect(); - f.placements - .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); - } - } + keep_placements(&mut f, d); // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -538,6 +523,39 @@ fn extension_dictionaries( dictionaries } +/// Attributes' extension dictionaries (their annotation scale contexts), by attribute. +fn keep_attrib_dictionaries(f: &mut Foreign, (blocks, entities): (&Recs, &Recs), kept: &HashSet) { + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { + f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + } + } +} + +/// Block references whose extension dictionaries are kept (their annotation scale contexts), as +/// read: where the reference and its attributes were. +fn keep_placements(f: &mut Foreign, d: &Drawing) { + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins + .attribs + .iter() + .map(|a| cadcraft_doc::foreign::KeptAttrib { + tag: a.tag.clone(), + insert: a.text.insert, + align: a.text.align_pt.unwrap_or(a.text.insert), + rotation: a.text.rotation, + }) + .collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } +} + /// Determine which objects belong to unmodelled dictionary entries or owners. fn retained_objects( objects: &[(String, usize, &[Tag])], @@ -548,9 +566,6 @@ fn retained_objects( xdict_of: &HashMap, inserts: &HashSet, ) -> HashMap { - let of_insert = |tags: &[Tag]| { - head(tags).owner.is_some_and(|owner| inserts.contains(&owner) || records.get(&owner).is_some_and(|key| key.0 == "ATTRIB")) - }; let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -559,7 +574,7 @@ fn retained_objects( !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { - entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags))) + entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags, inserts, records))) }; let mut retained = HashMap::new(); for index in 0..objects.len() { @@ -590,7 +605,7 @@ fn retained_objects( continue; } if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags))); + break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags, inserts, records))); } break entities.get(&owner) == Some(&true); }; @@ -1190,6 +1205,35 @@ struct Rec { end: usize, } +/// The written attributes' identities ([`attrib_keys`]), by record start. +fn written_attribs(recs: &[Rec], tags: &[Tag]) -> HashMap { + let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); + let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); + attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect() +} + +/// The kept annotation scale contexts of block references and their attributes, up to date with +/// the references and in line with the drawing's scales ([`reconcile`]); the new objects' owners +/// join `owners`. +fn refreshed_contexts( + f: &Foreign, + d: &Drawing, + owners: &mut HashMap, + roles: &HashMap, + tags: &[Tag], +) -> (HashMap, Reconciled) { + let mut contexts = block_contexts(f, d, owners); + let attribute = attribute_contexts(f, d, owners, &contexts); + contexts.extend(attribute); + let rec = reconcile(f, d, owners, roles, &mut contexts, seed(tags).max(max_handle(tags))); + for o in &rec.added { + if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { + owners.insert(o.handle.hex(), norm(&parent.value)); + } + } + (contexts, rec) +} + fn written_records(tags: &[Tag]) -> Vec { let mut out: Vec = Vec::new(); let mut sec = String::new(); @@ -1406,9 +1450,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s); let root_keys: HashSet = objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default(); - // The written attributes' identities, by record. - let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); - let attribs: HashMap = attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect(); + let attribs = written_attribs(&recs, tags); // Extension dictionaries that go on a written record (one without its own). let mut block = String::new(); let mut attached: HashSet = HashSet::new(); @@ -1434,18 +1476,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); - // Block references' annotation scale contexts, up to date with the references. - let mut contexts = block_contexts(f, d, &owners); - let attribute = attribute_contexts(f, d, &owners, &contexts); - contexts.extend(attribute); - // In line with the drawing's scales and each reference's. - let rec = reconcile(f, d, &owners, &roles, &mut contexts, seed(tags).max(max_handle(tags))); + let (contexts, rec) = refreshed_contexts(f, d, &mut owners, &roles, tags); let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); - for o in &rec.added { - if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { - owners.insert(o.handle.hex(), norm(&parent.value)); - } - } // Which kept objects are written: those whose owner chain ends at a written owner. let objs: HashMap = all.iter().map(|o| (o.handle.hex(), *o)).collect(); let mut alive_memo: HashMap = HashMap::new(); @@ -1480,9 +1512,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { alive_memo.insert(p, verdict); } } - for h in &rec.dropped { - alive_memo.insert(h.clone(), false); - } + alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index c750ee3ff..3ecb51fcc 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -1,8 +1,8 @@ use super::common::T; use super::objects::MAX_OBJECTS; use super::{ - BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, - VportConfig, VportTile, records, + BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, + Vec3, VportConfig, VportTile, records, }; pub(super) fn header(tags: &[Tag], d: &mut Drawing) { diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index d4bd1541a..d6fe2faa0 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -29,6 +29,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { let Block { name, annotative, + scale_uniformly, base, entities: contents, description, @@ -42,6 +43,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { } = block.as_ref(); equal(name, &back.name, &path, "name"); equal(annotative, &back.annotative, &path, "annotative"); + equal(scale_uniformly, &back.scale_uniformly, &path, "scale_uniformly"); equal(base, &back.base, &path, "base"); equal(description, &back.description, &path, "description"); equal(xref_overlay, &back.xref_overlay, &path, "xref_overlay"); From 896fe05886d052428c9f165631b8fccc10fd0759 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:00:43 -0600 Subject: [PATCH 12/15] DXF: a block reference moved in elevation takes its contexts along, at their own heights block_contexts compared the reference with the one read in X and Y only, so a reference moved only in Z kept its contexts at their old heights; and any other change set every context's group 30 to the reference's Z, losing a context's own height. Z is part of the change check now, and each context keeps its offset from the reference as read, scaled with the reference's Z scale as X and Y follow theirs. FredApps on #1244. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 21 +++++++--- crates/io/tests/annotative_block_contexts.rs | 40 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9fe1430fa..d4ef99153 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -933,20 +933,29 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { continue }; // The reference as read: kept when it was read, else (data made before that was kept) // its default context. - let (at0, rot0, scale0) = match f.placements.get(&h) { - Some(p) => (p.insert.xy(), p.rotation, [p.scale.x, p.scale.y, p.scale.z]), + let (at0, z0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.insert.z, p.rotation, [p.scale.x, p.scale.y, p.scale.z]), None => { let def = list.iter().find(|o| is_default(o)).unwrap_or(first); let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; let s = |code: i32, now: f64| num(def, code).unwrap_or(now); let rot = num(def, 50).unwrap_or(0.0).to_radians(); - (cadcraft_doc::geom::Vec2::new(x0, y0), rot, [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)]) + ( + cadcraft_doc::geom::Vec2::new(x0, y0), + num(def, 30).unwrap_or(0.0), + rot, + [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)], + ) } }; let turn = ins.rotation - rot0; let ratio = |then: f64, now: f64| if then.abs() > 1e-12 { now / then } else { 1.0 }; let ratios = [(41, ratio(scale0[0], ins.scale.x)), (42, ratio(scale0[1], ins.scale.y)), (43, ratio(scale0[2], ins.scale.z))]; - let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); + // A move in elevation alone is a change too. + let unchanged = (ins.insert.xy() - at0).len() < 1e-9 + && (ins.insert.z - z0).abs() < 1e-9 + && turn.abs() < 1e-12 + && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { continue; } @@ -961,11 +970,13 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> } _ => ins.insert.xy(), }; + // Its height above or below the reference as read is kept, scaled with it. + let z = num(c, 30).map_or(ins.insert.z, |cz| ins.insert.z + (cz - z0) * ratios[2].1); for t in &mut o.tags { let v = match t.code { 10 => Some(at.x), 20 => Some(at.y), - 30 => Some(ins.insert.z), + 30 => Some(z), 50 => num(c, 50).map(|r| r + turn.to_degrees()), 41..=43 => ratios.iter().find(|(k, _)| *k == t.code).and_then(|(k, r)| num(c, *k).map(|s| s * r)), _ => None, diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 80eb8ad6b..ec96e7ebe 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -744,3 +744,43 @@ fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() actx.sort_by(|a, b| a.0.cmp(&b.0)); assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); } + +/// Each written block reference context's elevation (group 30), by scale name. +fn context_heights(text: &str) -> Vec<(String, f64)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let mut out: Vec<(String, f64)> = recs + .iter() + .filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| { + let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(); + (scale, get(t, 30).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN)) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +#[test] +fn a_reference_moved_only_in_elevation_takes_its_contexts_along_at_their_own_heights() { + // The 1:1 context 2 units above the reference, as read. + let src = FIXTURE.replace("10 10\n20 20\n30 0\n41 1\n", "10 10\n20 20\n30 2\n41 1\n"); + assert_ne!(src, FIXTURE); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert.z += 3.0; + } + }) + .unwrap(); + let written = write_dxf(&d); + let near = |h: &[(String, f64)], scale: &str, z: f64| h.iter().any(|(s, v)| s == scale && (v - z).abs() < 1e-9); + let h = context_heights(&written); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "both rise by 3, the 1:1 one staying 2 above: {h:?}"); + // Saved and opened again, then saved unchanged: the heights stay. + let again = write_dxf(&read_dxf(written.as_bytes()).unwrap()); + let h = context_heights(&again); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "{h:?}"); +} From f718f0f7f9b277b50a7bc1c02524bc6ecc98ca3c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:58:58 -0600 Subject: [PATCH 13/15] Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30) Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/{ => it}/annotative_block_contexts.rs | 0 crates/io/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/io/tests/{ => it}/annotative_block_contexts.rs (100%) diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/it/annotative_block_contexts.rs similarity index 100% rename from crates/io/tests/annotative_block_contexts.rs rename to crates/io/tests/it/annotative_block_contexts.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index c45a57658..c45dfed62 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -2,6 +2,7 @@ mod acad_interop; #[cfg(not(target_arch = "wasm32"))] mod acis_data_store; mod angle_header; +mod annotative_block_contexts; mod annotative_orientation; mod annotative_roundtrip; mod assoc_array_roundtrip; From b076ec4c9fd1ce6f8e7e9a8f4ae5188a5e0e6fe5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:43:44 -0600 Subject: [PATCH 14/15] DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them The DWG bridge doesn't carry annotation scale contexts into a DWG yet (storytold/craft-libs#2005): the DWG reader read them back as zeros, a reference at scale 0 at its other scales. A save through the bridge now leaves the kept block reference and attribute contexts out, as before they were kept, and the block's AcadAnnotative flag too (without its references' contexts AutoCAD would scale them by the annotation scale once more). DXF keeps both. The DWG round-trip test that waited for craft-libs#2005 (ignored, a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save leaves the contexts out and the reference reads back at its own scale. The round trip of the contexts through DWG follows once the bridge converts them. FredApps on #1362 (rule 31). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 41 ++++++++++++++++++- crates/io/src/dxf_write/sections.rs | 8 ++-- .../io/tests/it/annotative_block_contexts.rs | 34 +++++++-------- 3 files changed, 60 insertions(+), 23 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d4ef99153..e0a82a4b8 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1322,6 +1322,38 @@ fn reconcile( out } +/// The kept annotation scale context objects (each `AcDbContextDataManager` an extension +/// dictionary lists, and everything owned below it), by handle: what a DWG save leaves out. The +/// dictionaries that list them drop the entry when the manager isn't written. +fn kept_context_objects(f: &Foreign, own: &HashMap>) -> HashSet { + let mut managers: HashSet = HashSet::new(); + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind)) { + for w in o.tags.windows(2) { + if let [k, v] = w + && k.code == 3 + && up(&k.value) == CONTEXTS_KEY + && matches!(v.code, 350 | 360) + { + managers.insert(norm(&v.value)); + } + } + } + let under = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + if managers.contains(&cur) { + return true; + } + match own.get(&cur).cloned().flatten() { + Some(o) => cur = o, + None => return false, + } + } + false + }; + f.objects.iter().map(|o| o.handle.hex()).filter(|h| under(h)).collect() +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -1749,6 +1781,7 @@ pub(crate) fn finish( modern: bool, target_modern: bool, strings: bool, + bridge: bool, ) -> HashSet { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); @@ -1827,7 +1860,10 @@ pub(crate) fn finish( // Annotation scale contexts brought up to date follow owner chains by group 330, and give the // records they add an owner. let mut owners: HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); - let (contexts, rec) = refreshed_contexts(f, d, &mut owners, &roles, tags); + // The DWG bridge doesn't carry annotation scale contexts through to a DWG yet + // (storytold/craft-libs#2005): a DWG save leaves the kept block reference and attribute + // contexts out, as before they were kept. + let (contexts, rec) = if bridge { (HashMap::new(), Reconciled::default()) } else { refreshed_contexts(f, d, &mut owners, &roles, tags) }; for o in &rec.added { own.insert(o.handle.hex(), owners.get(&o.handle.hex()).cloned()); } @@ -1876,6 +1912,9 @@ pub(crate) fn finish( alive_memo }); alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); + if bridge { + alive_memo.extend(kept_context_objects(f, &own).into_iter().map(|h| (h, false))); + } // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 19f00b1c8..993db299d 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1213,12 +1213,14 @@ pub(super) fn tags_kept_for( w.s(340, layout.unwrap_or("0")); // User blocks: insertion units (70), explodability (280), uniform scaling (281) and // whether references are annotative (`AcadAnnotative` xdata: without it AutoCAD scales - // the references by their units instead of the annotation scale). + // the references by their units instead of the annotation scale). Not in a DWG yet: the + // bridge drops the references' contexts, and the flag alone would have AutoCAD scale them + // by the annotation scale once more (storytold/craft-libs#2005). if let Some(b) = blk { w.i(70, i64::from(b.units)); w.i(280, i64::from(b.explodable)); w.i(281, i64::from(b.scale_uniformly)); - if b.annotative { + if b.annotative && !bridge { annotative_xdata(w); } if let Some(a) = &b.array { @@ -1354,7 +1356,7 @@ pub(super) fn tags_kept_for( // no data store, so a solid whose geometry is only there is left out of it. // The DWG bridge keeps proxies in the DWG's own layout. let strings = bridge || version >= Version::R2007; - let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings); + let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings, bridge); // Kept constraint groups go in the order their reader expects: a DXF's own version. The // bridge's R2000 text is read as the version its kept groups came from when that is newer // (craft-dwg's `encode_kept_noted` declares it), so there they stay as read. diff --git a/crates/io/tests/it/annotative_block_contexts.rs b/crates/io/tests/it/annotative_block_contexts.rs index ec96e7ebe..545d8b7ba 100644 --- a/crates/io/tests/it/annotative_block_contexts.rs +++ b/crates/io/tests/it/annotative_block_contexts.rs @@ -418,28 +418,24 @@ fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> { d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect() } +/// A DWG save leaves the reference's contexts out, and the block's annotative flag with them: +/// the DWG bridge doesn't convert block reference contexts yet (storytold/craft-libs#2005), and +/// the flag without them would have AutoCAD scale the reference by the annotation scale once +/// more. The reference comes back at its own scale; DXF keeps both. #[cfg(not(target_arch = "wasm32"))] #[test] -#[ignore = "needs the DWG bridge's annotation context conversion (storytold/craft-libs#2005) in the pinned craft-dwg"] -fn a_reference_s_contexts_survive_dwg() { - // Turned 30° first, so the rotation's unit shows (DXF degrees, DWG radians). - let mut d = read(); +fn a_dwg_save_leaves_the_reference_s_contexts_out() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = read(); let r = Handle::parse_hex("40").unwrap(); - d.modify_entity(r, |e| { - if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { - i.rotation = 30f64.to_radians(); - } - }) - .unwrap(); - let back = - cadcraft_io::read(&cadcraft_io::read_dxf(write_dxf(&d).as_bytes()).map(|d| cadcraft_io::write(&d, "x.dwg").unwrap()).unwrap(), "x.dwg") - .unwrap(); - let mut ctx = kept_contexts(&back); - ctx.sort_by(|a, b| a.1.total_cmp(&b.1)); - assert_eq!(ctx.len(), 2, "{ctx:?}"); - for ((rot, sx), want) in ctx.iter().zip([1.0, 5.0]) { - assert!((rot - 30.0).abs() < 1e-9 && (sx - want).abs() < 1e-9, "{ctx:?}"); - } + let scale = |d: &Drawing| match d.entity(r).map(|e| &e.kind) { + Some(cadcraft_doc::EntityKind::Insert(i)) => i.scale.x, + _ => f64::NAN, + }; + let back = cadcraft_io::read(&cadcraft_io::write(&d, "x.dwg").unwrap(), "x.dwg").unwrap(); + assert!(kept_contexts(&back).is_empty(), "{:?}", kept_contexts(&back)); + assert!((scale(&back) - scale(&d)).abs() < 1e-9, "{} vs {}", scale(&back), scale(&d)); + assert!(!kept_contexts(&read_dxf(write_dxf(&d).as_bytes()).unwrap()).is_empty(), "DXF keeps them"); } /// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every From c12a1c12cad6d6a23309df2b619d7fac162c8283 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:05:25 -0600 Subject: [PATCH 15/15] DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit) Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index e0a82a4b8..2bbb2ff72 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1459,6 +1459,23 @@ fn refreshed_contexts( (contexts, rec) } +/// The kept annotation scale contexts as [`finish`] writes them: brought up to date +/// ([`refreshed_contexts`]), or for the DWG bridge, which doesn't carry them into a DWG yet +/// (storytold/craft-libs#2005), all of them dropped, as before they were kept. +fn contexts_for( + f: &Foreign, + d: &Drawing, + (owners, own): (&mut HashMap, &HashMap>), + roles: &HashMap, + tags: &[Tag], + bridge: bool, +) -> (HashMap, Reconciled) { + if bridge { + return (HashMap::new(), Reconciled { dropped: kept_context_objects(f, own), ..Reconciled::default() }); + } + refreshed_contexts(f, d, owners, roles, tags) +} + fn written_records(tags: &[Tag]) -> Vec { let mut out: Vec = Vec::new(); let mut sec = String::new(); @@ -1860,10 +1877,7 @@ pub(crate) fn finish( // Annotation scale contexts brought up to date follow owner chains by group 330, and give the // records they add an owner. let mut owners: HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); - // The DWG bridge doesn't carry annotation scale contexts through to a DWG yet - // (storytold/craft-libs#2005): a DWG save leaves the kept block reference and attribute - // contexts out, as before they were kept. - let (contexts, rec) = if bridge { (HashMap::new(), Reconciled::default()) } else { refreshed_contexts(f, d, &mut owners, &roles, tags) }; + let (contexts, rec) = contexts_for(f, d, (&mut owners, &own), &roles, tags, bridge); for o in &rec.added { own.insert(o.handle.hex(), owners.get(&o.handle.hex()).cloned()); } @@ -1912,9 +1926,6 @@ pub(crate) fn finish( alive_memo }); alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); - if bridge { - alive_memo.extend(kept_context_objects(f, &own).into_iter().map(|h| (h, false))); - } // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant.