mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 20:22:15 -05:00
Merge pull request #1244 from codyvogt/fix/block-record-annotative
DXF: annotative blocks keep their flag, uniform scaling, and their references' and attributes' annotation scale contexts on save
This commit is contained in:
13 files changed
+1512
-36
No files matched your search
@@ -89,11 +89,36 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// 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<Handle, KeptPlacement>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its
|
||||
/// 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<KeptAttrib>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any.
|
||||
/// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name.
|
||||
@@ -110,6 +135,7 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.placements.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
|
||||
@@ -725,6 +725,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<crate::ArrayParams>,
|
||||
@@ -778,6 +781,7 @@ impl Block {
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
scale_uniformly: false,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
}
|
||||
|
||||
@@ -428,6 +428,7 @@ mod tests {
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
scale_uniformly: false,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
xref_stamp: None,
|
||||
};
|
||||
|
||||
+661
-26
@@ -42,6 +42,30 @@ const MODELLED_KEYS: &[&str] = &[
|
||||
/// drawing).
|
||||
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "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";
|
||||
|
||||
/// The handles of the drawing's block references.
|
||||
fn insert_handles(d: &Drawing) -> HashSet<String> {
|
||||
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<String>, ids: &HashMap<String, ForeignKey>) -> 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 {
|
||||
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"];
|
||||
@@ -187,13 +211,18 @@ 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<String, ForeignKey> {
|
||||
fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> HashMap<String, ForeignKey> {
|
||||
let mut out: HashMap<String, ForeignKey> = HashMap::new();
|
||||
let mut put = |h: Option<String>, 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.
|
||||
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());
|
||||
if *kind == "TABLE" || !name.is_empty() {
|
||||
@@ -211,6 +240,13 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap<String, F
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// 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<String, (&str, &[Tag])> = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (*k, *t)))).rev().collect();
|
||||
@@ -334,7 +370,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], 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.
|
||||
@@ -355,7 +391,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], 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) && (handle(&o).is_some_and(|oh| ents.contains_key(&oh)) || ids.contains_key(&o))
|
||||
};
|
||||
let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of);
|
||||
// Block references and their attributes (their extension dictionaries keep annotation scale
|
||||
// contexts).
|
||||
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<String> = HashSet::new();
|
||||
for (i, (kind, _, t)) in objects.iter().enumerate() {
|
||||
@@ -365,7 +404,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue };
|
||||
let mut tags: Vec<RawTag> = t.iter().map(raw).collect();
|
||||
if is_xdict(i) {
|
||||
strip_entries(&mut tags);
|
||||
strip_entries(&mut tags, of_insert(t, &inserts, &ids));
|
||||
}
|
||||
if head(t).owner == root
|
||||
&& let Some(key) = root_key(&h.hex())
|
||||
@@ -394,6 +433,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
}
|
||||
}
|
||||
put_xdata(d, xdata_of);
|
||||
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);
|
||||
@@ -401,6 +441,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
f.records.entry(key).or_insert(x);
|
||||
}
|
||||
}
|
||||
keep_placements(&mut f, d);
|
||||
// The classes of kept objects and of entities of types CADCraft doesn't model.
|
||||
let mut types: HashSet<String> = f.objects.iter().map(|o| up(&o.kind)).collect();
|
||||
types.extend(all_entities(d).filter_map(|e| match &e.kind {
|
||||
@@ -515,6 +556,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<String>) {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The root dictionary's key for each entry handle (the first key when several name one handle),
|
||||
/// built once: a lookup per object scanning the entries made a large dictionary quadratic.
|
||||
fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> {
|
||||
@@ -531,9 +605,9 @@ fn retained_objects(
|
||||
entities: &HashMap<Handle, bool>,
|
||||
records: &HashMap<String, ForeignKey>,
|
||||
by_handle: &HashMap<String, usize>,
|
||||
root: Option<&str>,
|
||||
root_entries: &[(String, String)],
|
||||
(root, root_entries): (Option<&str>, &[(String, String)]),
|
||||
xdict_of: &HashMap<String, String>,
|
||||
inserts: &HashSet<String>,
|
||||
) -> HashMap<usize, bool> {
|
||||
let root_keys = root_key_index(root_entries);
|
||||
let root_key = |handle: &str| root_keys.get(handle).copied();
|
||||
@@ -546,7 +620,7 @@ fn retained_objects(
|
||||
&& (self::handle(&owner).is_some_and(|owner| 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, inserts, records)))
|
||||
};
|
||||
// is_xdict reads the whole record; a dictionary that owns many objects (ACAD_GROUP with
|
||||
// hundreds of thousands of groups) would be read once per child (#862).
|
||||
@@ -589,7 +663,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, inserts, records)));
|
||||
}
|
||||
break self::handle(&owner).and_then(|owner| entities.get(&owner)) == Some(&true);
|
||||
};
|
||||
@@ -799,12 +873,494 @@ fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drop a dictionary's modelled entries (key and handle) from its groups.
|
||||
fn strip_entries(tags: &mut Vec<RawTag>) {
|
||||
/// 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<Item = &'a [Tag]>) -> Vec<String> {
|
||||
let mut seen: HashMap<String, usize> = 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
|
||||
/// 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<String, String>) -> HashMap<String, ForeignObject> {
|
||||
let num = |o: &ForeignObject, code: i32| {
|
||||
o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::<f64>().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<String, Vec<&ForeignObject>> = 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(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, 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),
|
||||
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))];
|
||||
// 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;
|
||||
}
|
||||
for c in list {
|
||||
let mut o = (*c).clone();
|
||||
// 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)) => {
|
||||
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(),
|
||||
};
|
||||
// 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(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
|
||||
}
|
||||
|
||||
/// 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<String, String>,
|
||||
block: &HashMap<String, ForeignObject>,
|
||||
) -> HashMap<String, ForeignObject> {
|
||||
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::<f64>().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
|
||||
};
|
||||
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 =
|
||||
|o: &ForeignObject| -> Option<Place> { 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<String, Vec<&ForeignObject>> = 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, 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 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 };
|
||||
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());
|
||||
// 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 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(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)?), 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 };
|
||||
let (Some(from), to): (Option<Mat3>, 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::<f64>().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
|
||||
}
|
||||
|
||||
/// 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")
|
||||
}
|
||||
|
||||
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<String, (Handle, String, usize)> {
|
||||
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<String>,
|
||||
/// 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<ForeignObject>,
|
||||
/// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role.
|
||||
scales: HashMap<String, ForeignKey>,
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
/// 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<String, String>,
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
contexts: &mut HashMap<String, ForeignObject>,
|
||||
above: u64,
|
||||
) -> 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::<f64>().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<String> {
|
||||
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 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<String, (Handle, bool, Vec<ForeignObject>)> = 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 = 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}")
|
||||
};
|
||||
// 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<Handle, (String, Vec2)> = HashMap::new();
|
||||
for (r, attribute, list) in groups.values() {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
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<String> = 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::<f64>().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<n>`, 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::<u64>().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
|
||||
}
|
||||
|
||||
/// 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<String, Option<String>>) -> HashSet<String> {
|
||||
let mut managers: HashSet<String> = 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<RawTag>, 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;
|
||||
}
|
||||
@@ -874,6 +1430,52 @@ struct Rec {
|
||||
end: usize,
|
||||
}
|
||||
|
||||
/// The written attributes' identities ([`attrib_keys`]), by record start.
|
||||
fn written_attribs(recs: &[Rec], tags: &[Tag]) -> HashMap<usize, String> {
|
||||
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<String, String>,
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
tags: &[Tag],
|
||||
) -> (HashMap<String, ForeignObject>, 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)
|
||||
}
|
||||
|
||||
/// 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<String, String>, &HashMap<String, Option<String>>),
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
tags: &[Tag],
|
||||
bridge: bool,
|
||||
) -> (HashMap<String, ForeignObject>, 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<Rec> {
|
||||
let mut out: Vec<Rec> = Vec::new();
|
||||
let mut sec = String::new();
|
||||
@@ -906,7 +1508,8 @@ pub fn object_records(d: &Drawing) -> Vec<ObjectRecord> {
|
||||
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect()
|
||||
};
|
||||
let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS"));
|
||||
let ids = identities(&tables, &blocks, &objects);
|
||||
// Only non-graphic records are listed: no attribute identities are needed.
|
||||
let ids = identities(&tables, &blocks, &Vec::new(), &objects);
|
||||
let tables = tables.iter().filter(|(k, _, _)| *k != "ENDTAB");
|
||||
let blocks = blocks.iter().filter(|(k, _, _)| *k == "BLOCK");
|
||||
tables
|
||||
@@ -994,6 +1597,8 @@ struct Map<'a> {
|
||||
roles: HashMap<ForeignKey, String>,
|
||||
/// Entities in the written file.
|
||||
entities: HashSet<String>,
|
||||
/// Stand-in handles of the scales new contexts name ([`Reconciled::scales`]).
|
||||
scales: &'a HashMap<String, ForeignKey>,
|
||||
}
|
||||
|
||||
impl Map<'_> {
|
||||
@@ -1007,6 +1612,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();
|
||||
@@ -1098,10 +1706,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<Cow<'a, ForeignExtra>> {
|
||||
fn extra_for<'a>(
|
||||
f: &'a Foreign,
|
||||
xd: &XdataOf,
|
||||
attribs: &HashMap<usize, String>,
|
||||
rec: &Rec,
|
||||
body: &[Tag],
|
||||
block: &str,
|
||||
) -> Option<Cow<'a, ForeignExtra>> {
|
||||
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(), 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());
|
||||
@@ -1181,6 +1798,7 @@ pub(crate) fn finish(
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
strings: bool,
|
||||
bridge: bool,
|
||||
) -> HashSet<Handle> {
|
||||
let f = d.foreign.as_ref();
|
||||
let unknown = unknown_handles(d);
|
||||
@@ -1193,9 +1811,9 @@ pub(crate) fn finish(
|
||||
let by_sec = |name: &str| -> Recs {
|
||||
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), 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<ForeignKey, String> = 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<String> = recs.iter().filter_map(|r| head(body(r)).handle).collect();
|
||||
@@ -1236,20 +1854,19 @@ pub(crate) fn finish(
|
||||
let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s);
|
||||
let root_keys: HashSet<String> =
|
||||
objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default();
|
||||
let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags);
|
||||
let attribs = written_attribs(&recs, tags);
|
||||
let (mut attached, merged) = kept_dictionaries(f, &xd, &attribs, &recs, tags);
|
||||
for (_, t) in planned.values().flatten() {
|
||||
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<String, &ForeignObject> = f.objects.iter().map(|o| (o.handle.hex(), o)).collect();
|
||||
let dict_entries: HashMap<String, &str> = 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::<HashSet<_>>();
|
||||
let hard = hard_owners(
|
||||
f.objects.iter().map(|o| (o.handle.hex(), o.tags.iter().take_while(|t| t.code < 1000).filter(|t| t.code == 360).map(|t| t.value.trim()))),
|
||||
);
|
||||
// Each kept object's own owner (group 330), read one record at a time.
|
||||
let own: HashMap<String, Option<String>> = f
|
||||
let mut own: HashMap<String, Option<String>> = f
|
||||
.objects
|
||||
.iter()
|
||||
.map(|o| {
|
||||
@@ -1257,6 +1874,16 @@ pub(crate) fn finish(
|
||||
(o.handle.hex(), head(&t).owner)
|
||||
})
|
||||
.collect();
|
||||
// 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<String, String> = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect();
|
||||
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());
|
||||
}
|
||||
let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect();
|
||||
// Which kept objects are written: those whose owner chain ends at a written owner.
|
||||
let objs: HashMap<String, &ForeignObject> = all.iter().map(|o| (o.handle.hex(), *o)).collect();
|
||||
let mut alive_memo = settle(&hard, |kept: &HashMap<String, bool>| {
|
||||
// Keep established live paths available to descendants during this pass as well.
|
||||
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
|
||||
@@ -1268,7 +1895,7 @@ pub(crate) fn finish(
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
|
||||
alive_memo.insert(o.handle.hex(), false);
|
||||
}
|
||||
for o in &f.objects {
|
||||
for o in &all {
|
||||
let mut path: Vec<String> = Vec::new();
|
||||
let mut cur = o.handle.hex();
|
||||
let verdict = loop {
|
||||
@@ -1298,6 +1925,7 @@ pub(crate) fn finish(
|
||||
}
|
||||
alive_memo
|
||||
});
|
||||
alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), 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.
|
||||
@@ -1363,7 +1991,7 @@ pub(crate) fn finish(
|
||||
let placed = planned.values().flatten().filter_map(|(_, t)| head(t.get(1..).unwrap_or(&[])).handle);
|
||||
fresh.used.extend(placed.filter_map(|h| Handle::parse_hex(&h)).map(|h| h.0));
|
||||
let mut alive: HashMap<String, String> = 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!("{:X}", fresh.take()));
|
||||
}
|
||||
// A merged dictionary is not written: what pointed at it points at the written one.
|
||||
@@ -1373,7 +2001,7 @@ pub(crate) fn finish(
|
||||
}
|
||||
}
|
||||
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).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<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
|
||||
let mut block = String::new();
|
||||
for r in &recs {
|
||||
@@ -1385,7 +2013,8 @@ pub(crate) fn finish(
|
||||
continue;
|
||||
}
|
||||
if r.kind == "ENDSEC" && r.sec == "OBJECTS" {
|
||||
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) {
|
||||
for o in all.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.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) => {
|
||||
@@ -1408,7 +2037,7 @@ pub(crate) fn finish(
|
||||
record(&map, &ur, ub, x.as_deref(), Some(extra), 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);
|
||||
let joined = joined_into(&merged_into, b);
|
||||
if x.is_none() && Some(r.start) != root && joined.is_none() {
|
||||
out.extend(b.iter().map(|tag| {
|
||||
@@ -1435,7 +2064,13 @@ pub(crate) fn finish(
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
/// and those whose entries join the one the writer gave a table (the LAYER table's, holding the
|
||||
/// layer states) as kept dictionary → the written one.
|
||||
fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet<String>, HashMap<String, String>) {
|
||||
fn kept_dictionaries(
|
||||
f: &Foreign,
|
||||
xd: &XdataOf,
|
||||
attribs: &HashMap<usize, String>,
|
||||
recs: &[Rec],
|
||||
tags: &[Tag],
|
||||
) -> (HashSet<String>, HashMap<String, String>) {
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
let mut block = String::new();
|
||||
let mut attached: HashSet<String> = HashSet::new();
|
||||
@@ -1444,7 +2079,7 @@ fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (
|
||||
if r.kind == "BLOCK" {
|
||||
block = up(&val(body(r), 2).unwrap_or_default());
|
||||
}
|
||||
let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue };
|
||||
let Some(kept) = extra_for(f, xd, attribs, r, body(r), &block).and_then(|x| x.xdict) else { continue };
|
||||
match head(body(r)).xdict {
|
||||
None => {
|
||||
attached.insert(kept.hex());
|
||||
|
||||
@@ -35,6 +35,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 {
|
||||
@@ -44,8 +53,9 @@ struct Rx {
|
||||
brs: HashMap<String, String>,
|
||||
/// LTYPE record handle (upper case) → linetype name (DIMLTYPE, DIMLTEX1, DIMLTEX2).
|
||||
ltypes: HashMap<String, String>,
|
||||
/// Upper-case block name → (insertion units, explodable) from its BLOCK_RECORD.
|
||||
block_props: HashMap<String, (u8, bool)>,
|
||||
/// Upper-case block name → its BLOCK_RECORD's properties: units (70), explodable (280),
|
||||
/// scale uniformly (281) and annotative (`AcadAnnotative` xdata).
|
||||
block_props: HashMap<String, BlockProps>,
|
||||
/// Upper-case names of anonymous `*T` blocks drawn by ACAD_TABLE entities.
|
||||
table_blocks: std::collections::HashSet<String>,
|
||||
/// Upper-case block names used by INSERTs.
|
||||
|
||||
@@ -408,8 +408,8 @@ pub(super) fn place_blocks(
|
||||
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());
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
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,
|
||||
VportConfig, VportTile, record_slices,
|
||||
BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2,
|
||||
Vec3, VportConfig, VportTile, record_slices,
|
||||
};
|
||||
use crate::dxf_ext::ByName;
|
||||
use cadcraft_fonts::windows::windows_font;
|
||||
@@ -317,7 +317,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], 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);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{
|
||||
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");
|
||||
|
||||
@@ -1262,10 +1262,18 @@ pub(super) fn tags_kept_for(
|
||||
w.s(100, "AcDbBlockTableRecord");
|
||||
w.s(2, name);
|
||||
w.s(340, layout.unwrap_or("0"));
|
||||
// User blocks: insertion units (70) and explodability (280).
|
||||
// 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). 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 && !bridge {
|
||||
annotative_xdata(w);
|
||||
}
|
||||
if let Some(a) = &b.array {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
w.xdata(dxf_ext::array_xdata(a));
|
||||
@@ -1400,7 +1408,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.
|
||||
|
||||
@@ -0,0 +1,782 @@
|
||||
//! 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
|
||||
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
|
||||
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 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
|
||||
";
|
||||
|
||||
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::<i32>().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(tags: &[(i32, String)], code: i32) -> Option<&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::<f64>().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()
|
||||
}
|
||||
|
||||
/// 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::<f64>().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()
|
||||
}
|
||||
|
||||
#[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);
|
||||
// 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]
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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::<f64>().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()
|
||||
}
|
||||
|
||||
/// 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]
|
||||
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();
|
||||
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
|
||||
/// 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::<Vec<_>>(), [("1:5", true)]);
|
||||
let actx = attribute_contexts(&text);
|
||||
assert_eq!(actx.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["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 != "?"));
|
||||
}
|
||||
|
||||
/// 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::<i32>(), 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<String> = 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<String> = 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
|
||||
// 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<String>)> =
|
||||
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);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
/// 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::<f64>().ok())
|
||||
.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<f64> = records(&text)
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS")
|
||||
.filter_map(|(_, t)| get(t, 50).and_then(|v| v.parse::<f64>().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))]);
|
||||
}
|
||||
|
||||
/// 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::<f64>().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:?}");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -29,6 +29,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
|
||||
let Block {
|
||||
name,
|
||||
annotative,
|
||||
scale_uniformly,
|
||||
base,
|
||||
entities: contents,
|
||||
description,
|
||||
@@ -44,6 +45,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");
|
||||
|
||||
Reference in new issue
Block a user