From d9d4fb5197fed97c1297cd794e52c73775443666 Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Sat, 14 Nov 2026 14:15:08 +0100 Subject: [PATCH 1/4] Save: a DWG save reports the texts longer than a DWG text field holds A text over 65,535 characters (UTF-16 units from 2007, bytes before) keeps only its start in a DWG file. SAVE, SAVEAS, QSAVE and EXPORT now say how many entities that happens to, at the command line and as textsShortened, instead of cutting them silently. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file.rs | 55 +++++++++++++++++++ crates/engine/tests/save_reports_not_saved.rs | 51 +++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 69dc6918..9d6e814d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -826,6 +826,56 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap out } +/// The most a DWG text field holds: 65,535 UTF-16 units from 2007, before that 65,534 bytes in +/// the drawing's code page and the 0 that ends them. The writer keeps the start of a longer text. +fn dwg_text_fits(text: &str, version: Version) -> bool { + if version >= Version::R2007 { + text.encode_utf16().count() <= usize::from(u16::MAX) + } else { + // A character is at least one byte in any code page. + text.chars().count() < usize::from(u16::MAX) + } +} + +/// How many entities of `d` have a text longer than a DWG file of `version` holds in one field +/// ([`dwg_text_fits`]): text and multiline text, attributes and their definitions, a dimension's +/// text, a multileader's text and table cells. The file keeps the start of each. +pub fn texts_shortened_as(d: &Drawing, version: Version) -> usize { + use draftcraft_doc::EntityKind; + let long = |t: &str| !dwg_text_fits(t, version); + let attrib = |a: &draftcraft_doc::Attrib| long(&a.text.value) || a.multiline.as_ref().is_some_and(|m| long(&m.mtext.contents)); + let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); + stores + .flat_map(|s| s.iter()) + .filter(|e| match &e.kind { + EntityKind::Text(t) => long(&t.value), + EntityKind::MText(t) => long(&t.contents), + EntityKind::Insert(i) => i.attribs.iter().any(attrib), + EntityKind::AttDef(a) => attrib(a), + EntityKind::Dimension(dm) => long(&dm.text), + EntityKind::MLeader(m) => m.text.as_ref().is_some_and(|t| long(&t.contents)), + EntityKind::Table(t) => t.cells.iter().flatten().any(|c| long(&c.text)), + _ => false, + }) + .count() +} + +/// Report the texts a DWG file just written as `version` keeps only the start of +/// ([`texts_shortened_as`]): at the command line, and as `textsShortened` in the result. +pub(super) fn report_shortened(s: &mut Session, r: &mut Value, version: Version) { + let n = s.state().map(|st| texts_shortened_as(st.drawing(), version)).unwrap_or(0); + if n == 0 { + return; + } + let (count, them) = if n == 1 { ("1 entity has".to_string(), "its") } else { (format!("{n} entities have"), "their") }; + s.echo(format!( + "{count} a text longer than a DWG text field holds (65,535 characters): the DWG file keeps the start of {them} text; DXF keeps it whole" + )); + if let Some(o) = r.as_object_mut() { + o.insert("textsShortened".into(), json!(n)); + } +} + /// The command-line warning for [`not_saved`] entities, or `None` when the file keeps everything. pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Option { if lost.is_empty() { @@ -862,6 +912,10 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { } else { let lost = loss_on_save(s, path); report_not_saved(s, r, &lost); + if drops_unknown(path) { + let version = drawing_version(s, path); + report_shortened(s, r, version); + } } } @@ -942,6 +996,7 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R report_new_folder(s, &mut r, folder); if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { report_not_saved(s, &mut r, &lost); + report_shortened(s, &mut r, version); } else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) { report_sat_text_dropped(s, &mut r); } diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index ebea47f7..eb1fd890 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -241,3 +241,54 @@ fn ole_objects_are_not_reported() { assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}"); } } + +/// A text longer than a DWG text field holds (65,535 characters) keeps only its start in a DWG +/// file. Saving says so, instead of cutting it silently; DXF keeps it whole. +#[test] +fn a_dwg_save_reports_the_texts_it_shortens() { + use draftcraft_engine::cmd::file::texts_shortened_as; + use draftcraft_engine::doc::Text; + use draftcraft_engine::geom::Vec3; + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec())); + let text = |value: String| { + EntityKind::Text(Text { + insert: Vec3::ZERO, + align_pt: None, + height: 1.0, + value, + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }) + }; + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), text("x".repeat(70_000))).unwrap(); + d.add(&Space::Model, Common::default(), text("short".into())).unwrap(); + // 65,535 characters fit from 2007 (UTF-16 units), not before (bytes and the ending 0). + d.add(&Space::Model, Common::default(), text("y".repeat(65_535))).unwrap(); + assert_eq!(texts_shortened_as(&d, draftcraft_engine::cmd::file::Version::R2007), 1); + assert_eq!(texts_shortened_as(&d, draftcraft_engine::cmd::file::Version::R2004), 2); + // Characters outside the basic plane take two UTF-16 units. + let mut wide = Drawing::new_imperial(); + wide.add(&Space::Model, Common::default(), text("😀".repeat(40_000))).unwrap(); + assert_eq!(texts_shortened_as(&wide, draftcraft_engine::cmd::file::Version::R2018), 1); + + let mut s = Session::empty(); + s.open_drawing(d, "long.dxf", None); + let path = std::env::temp_dir().join(format!("draftcraft-long-text-{}.dwg", std::process::id())); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": "2018" })).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(r["textsShortened"], json!(1), "{r}"); + let msg = + "1 entity has a text longer than a DWG text field holds (65,535 characters): the DWG file keeps the start of its text; DXF keeps it whole"; + assert!(s.log.iter().any(|l| l == msg), "{:?}", s.log); + + let dxf = std::env::temp_dir().join(format!("draftcraft-long-text-{}.dxf", std::process::id())); + let r = s.execute("saveas", &json!({ "path": dxf.to_string_lossy() })).unwrap(); + let _ = std::fs::remove_file(&dxf); + assert!(r.get("textsShortened").is_none(), "DXF keeps it whole"); +} From 272e11821d5bb21536241fcc3f402d8a8963b7a2 Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Sat, 14 Nov 2026 14:29:47 +0100 Subject: [PATCH 2/4] Block Editor dynamic blocks keep their parameters and actions through a DWG save The Block Editor now rebuilds the evaluation graph's node list (id, flags, next id, member, links) whenever a parameter or action is added or removed, which is what the DWG encoder writes from. The authoring test saves both DXF and DWG. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/author.rs | 71 +++++++++++++++++++++++ crates/engine/tests/dynblock_authoring.rs | 8 +-- docs/dwg-writer-handoff.md | 9 ++- docs/dwg.md | 2 +- 4 files changed, 81 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/dynblock/author.rs b/crates/doc/src/dynblock/author.rs index 69321258..8cec8690 100644 --- a/crates/doc/src/dynblock/author.rs +++ b/crates/doc/src/dynblock/author.rs @@ -168,9 +168,36 @@ fn add_member(d: &mut Drawing, g: Handle, kind: &str, mut tags: Vec) -> if let Some(o) = find_mut(d, g) { o.tags.push(tag(360, h.hex())); } + rebuild_graph(d, g); h } +/// Write graph `g`'s node list as AutoCAD's files hold it, from the members it lists: the next +/// free id twice (96, 97), then each member as a node, its id (91, its expression's 90), flags +/// 32 (93), the id after it (95), the member (360) and four unused links (92 -1). The DWG writer +/// encodes the nodes from these groups; a bare list of members would be written as an empty +/// graph, and the block would open as a plain block. +fn rebuild_graph(d: &mut Drawing, g: Handle) { + let Some(graph) = find(d, g) else { return }; + let members: Vec = graph.tags.iter().filter(|t| t.code == 360).filter_map(|t| Handle::parse_hex(&t.value)).collect(); + let node_of = |h: Handle| -> Option { + let o = find(d, h)?; + let mut tags = o.tags.iter().skip_while(|t| !(t.code == 100 && t.value == "AcDbEvalExpr")); + tags.find(|t| t.code == 90).and_then(|t| t.value.trim().parse().ok()) + }; + let nodes: Vec<(i64, Handle)> = members.into_iter().filter_map(|h| Some((node_of(h)?, h))).collect(); + let free = nodes.iter().map(|n| n.0).max().map_or(0, |n| n.saturating_add(1)); + let Some(graph) = find_mut(d, g) else { return }; + let head = graph.tags.iter().position(|t| t.code == 100 && t.value == "AcDbEvalGraph").map_or(graph.tags.len(), |i| i + 1); + graph.tags.truncate(head); + graph.tags.extend([tag(96, free.to_string()), tag(97, free.to_string())]); + for (i, (id, h)) in nodes.iter().enumerate() { + let after = nodes.get(i + 1).map_or(free, |n| n.0); + graph.tags.extend([tag(91, id.to_string()), tag(93, "32"), tag(95, after.to_string()), tag(360, h.hex())]); + graph.tags.extend(std::iter::repeat_with(|| tag(92, "-1")).take(4)); + } +} + fn head(node: i32, element: &str) -> Vec { vec![tag(100, "AcDbEvalExpr"), tag(90, node.to_string()), tag(100, "AcDbBlockElement"), tag(300, element)] } @@ -319,8 +346,16 @@ pub fn remove(d: &mut Drawing, name: &str, node: i32) -> Result, Str let hs: std::collections::HashSet = gone.iter().map(|g| g.0).collect(); Arc::make_mut(&mut d.foreign).objects.retain(|o| !hs.contains(&o.handle)); let hexes: std::collections::HashSet = hs.iter().map(|h| h.hex()).collect(); + let mut graphs = Vec::new(); for o in Arc::make_mut(&mut d.foreign).objects.iter_mut().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH")) { + let before = o.tags.len(); o.tags.retain(|t| !(t.code == 360 && Handle::parse_hex(&t.value).is_some_and(|h| hexes.contains(&h.hex())))); + if o.tags.len() != before { + graphs.push(o.handle); + } + } + for g in graphs { + rebuild_graph(d, g); } Ok(gone.into_iter().map(|g| g.1).filter(|n| !n.is_empty()).collect()) } @@ -398,4 +433,40 @@ mod tests { assert!(m.parameters.is_empty() && m.actions.is_empty() && m.grip_objects.is_empty()); assert!(add_parameter(&mut d, "NOPE", &NewParameter::Point { at: Vec2::ZERO, label: String::new(), description: String::new() }).is_err()); } + + /// The graph lists its members as AutoCAD's files do, one node each (id, flags, the next id, + /// the member, four links), and keeps the list right when a member goes. + #[test] + fn the_graph_lists_each_member_as_a_node() { + let (mut d, hs, _) = drawing(); + let p = + add_parameter(&mut d, "B", &NewParameter::Point { at: Vec2::new(5.0, 5.0), label: "Top".into(), description: String::new() }).unwrap(); + let mv = add_action(&mut d, "B", &NewAction::Move { parameter: p.node, objects: vec![hs[2]] }).unwrap(); + let graph = |d: &Drawing| d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap().tags.clone(); + let nodes = |tags: &[RawTag]| -> Vec<(String, String, String)> { + let mut out = Vec::new(); + for (i, t) in tags.iter().enumerate().filter(|(_, t)| t.code == 91) { + let at = |k: usize| tags.get(i + k).map(|t| (t.code, t.value.clone())); + assert_eq!(at(1), Some((93, "32".into()))); + let Some((95, next)) = at(2) else { panic!("95 after 91") }; + let Some((360, member)) = at(3) else { panic!("360 after 95") }; + assert!((4..8).all(|k| at(k) == Some((92, "-1".into())))); + out.push((t.value.clone(), next, member)); + } + out + }; + let tags = graph(&d); + let listed = nodes(&tags); + // The point parameter, its grip and the move. + assert_eq!(listed.len(), 3, "{tags:?}"); + assert_eq!(listed.last().map(|n| n.2.clone()), Some(mv.handle.hex())); + let free = tags.iter().find(|t| t.code == 96).map(|t| t.value.clone()).unwrap(); + assert_eq!(listed.last().map(|n| n.1.clone()), Some(free.clone()), "the last node's next is the next free id"); + assert_eq!(tags.iter().filter(|t| t.code == 360).count(), 3); + remove(&mut d, "B", mv.node).unwrap(); + let tags = graph(&d); + assert_eq!(nodes(&tags).len(), 2, "{tags:?}"); + assert_eq!(tags.iter().filter(|t| t.code == 360).count(), 2); + assert!(dynamic_block(&d, "B").is_some_and(|m| m.actions.is_empty() && m.parameters.len() == 1)); + } } diff --git a/crates/engine/tests/dynblock_authoring.rs b/crates/engine/tests/dynblock_authoring.rs index fbd997f2..5c2d193c 100644 --- a/crates/engine/tests/dynblock_authoring.rs +++ b/crates/engine/tests/dynblock_authoring.rs @@ -1,8 +1,6 @@ //! A block made dynamic in the Block Editor (BPARAMETER, BACTION) keeps its parameters and -//! actions through a DXF save, and its references stretch after reopening. -//! -//! A DWG save doesn't keep them yet: the DWG writer encodes the dynamic block objects a file -//! brought, not yet the ones made here. +//! actions through a DXF and a DWG save, and its references stretch after reopening. The DWG +//! writer encodes the evaluation graph's nodes from the node list the Block Editor writes. use draftcraft_engine::Session; use draftcraft_engine::cmd::file::{IoHooks, set_io}; @@ -23,7 +21,7 @@ fn an_authored_dynamic_block_survives_save_and_reopen() { let dir = std::env::temp_dir().join(format!("draftcraft-dynauthor-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - for ext in ["dxf"] { + for ext in ["dxf", "dwg"] { let mut s = Session::new(); let mut hs = Vec::new(); for (a, b) in [([0, 0], [10, 0]), ([10, 0], [10, 5]), ([10, 5], [0, 5]), ([0, 5], [0, 0])] { diff --git a/docs/dwg-writer-handoff.md b/docs/dwg-writer-handoff.md index 0392e5f9..9cc00891 100644 --- a/docs/dwg-writer-handoff.md +++ b/docs/dwg-writer-handoff.md @@ -95,10 +95,13 @@ set; an AutoCAD 2018 MTEXT ends with a null reference. blocks stored unnumbered (`*D`, `*T`), the `AcDbSavedByObjectVersion` extended data on visual styles up to 2013, an empty VX table in 2000 files, and SEQENDs left out of the 2000 entity chain. The image files were not checked. -2. **Dynamic-block parameters and actions made in the Block Editor** are lost on a DWG save (those - a file brought are written; `crates/engine/tests/dynblock_authoring.rs` saves only DXF). +2. Dynamic-block parameters and actions made in the Block Editor are written to DWG: the Block + Editor keeps the evaluation graph's node list (`rebuild_graph` in + `crates/doc/src/dynblock/author.rs`), and `crates/engine/tests/dynblock_authoring.rs` saves + both DXF and DWG. 3. Text longer than 65,535 characters (UTF-16 units from 2007, bytes before) is cut to that - length, the most a DWG text field holds; it is not reported. + length, the most a DWG text field holds; the save reports how many entities were cut + (`textsShortened`). 4. Reader coverage that came from files acadrust wrote (edge hatch loops, curves, mirrored text, table cell styles) is now covered only by DraftCraft's own files; AutoCAD's files with them would make it independent again. diff --git a/docs/dwg.md b/docs/dwg.md index 93873588..a6b4be84 100644 --- a/docs/dwg.md +++ b/docs/dwg.md @@ -104,7 +104,7 @@ DraftCraft writes every version itself, and acadrust is gone. What remains: | 15–16 | DraftCraft's own DWG writer (objects, sections and container, a read-back check on every save) | done | | 17 | The other save versions: 2000, 2004, 2007, 2010, 2013 | done | | 18 | acadrust removed | done | -| 19 | Dynamic-block parameters and actions made in the Block Editor written to DWG (those a file brought are) | Lost on a DWG save; kept in DXF | +| 19 | Dynamic-block parameters and actions made in the Block Editor written to DWG | done | Decisions open: From 4808a421b196e4e04878d80a174adcba4f9cde69 Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Sat, 14 Nov 2026 14:33:18 +0100 Subject: [PATCH 3/4] DWG: remove the first writer; compose keeps the container and small sections it used crates/dwg/src/write (the writer over BlackCAD's records) had no caller left but compose and the style encoders. The paged container moves to compose/container.rs, the application information, revision history and header defaults to compose/small.rs, and the three-stream field writer the style encoders use to compose/fields.rs. The rest (object encoders, check, the AC1032 file builder) goes, with what only it used. Co-Authored-By: Claude Opus 5.5 --- .../dwg/src/{write => compose}/container.rs | 0 crates/dwg/src/compose/fields.rs | 53 + crates/dwg/src/compose/file.rs | 4 +- crates/dwg/src/compose/mod.rs | 4 + crates/dwg/src/compose/object.rs | 2 +- crates/dwg/src/compose/sections.rs | 2 +- crates/dwg/src/compose/small.rs | 152 ++ crates/dwg/src/lib.rs | 3 +- crates/dwg/src/read/mod.rs | 3 +- crates/dwg/src/read/nongraphic.rs | 4 - crates/dwg/src/read/styles.rs | 13 +- crates/dwg/src/records/model/objects.rs | 2 +- crates/dwg/src/write/check.rs | 125 -- crates/dwg/src/write/mod.rs | 385 ---- crates/dwg/src/write/objects.rs | 1846 ----------------- crates/dwg/src/write/sections.rs | 618 ------ docs/dwg-writer-handoff.md | 6 +- docs/dwg.md | 1 - 18 files changed, 222 insertions(+), 3001 deletions(-) rename crates/dwg/src/{write => compose}/container.rs (100%) create mode 100644 crates/dwg/src/compose/fields.rs create mode 100644 crates/dwg/src/compose/small.rs delete mode 100644 crates/dwg/src/write/check.rs delete mode 100644 crates/dwg/src/write/mod.rs delete mode 100644 crates/dwg/src/write/objects.rs delete mode 100644 crates/dwg/src/write/sections.rs diff --git a/crates/dwg/src/write/container.rs b/crates/dwg/src/compose/container.rs similarity index 100% rename from crates/dwg/src/write/container.rs rename to crates/dwg/src/compose/container.rs diff --git a/crates/dwg/src/compose/fields.rs b/crates/dwg/src/compose/fields.rs new file mode 100644 index 00000000..051dc7a6 --- /dev/null +++ b/crates/dwg/src/compose/fields.rs @@ -0,0 +1,53 @@ +//! The fields of one object as three bit streams (data, text, references), for the encoders that +//! write an object field by field from a layout ([`crate::read::styles`]); [`super::ObjectWriter`] +//! takes the streams over. + +use crate::bits::BitWriter; +use crate::read::model::Handle; +use crate::read::version::DwgVersion; + +/// The three streams an R2007+ object is written as. +pub(crate) struct ObjW { + pub ver: DwgVersion, + pub dat: BitWriter, + strs: BitWriter, + has_strings: bool, + pub hdl: BitWriter, +} + +/// Which handle-reference codes a field takes (spec §2.13): soft +/// hard ownership 3, soft pointer 4, hard pointer 5. +#[derive(Clone, Copy)] +pub(crate) enum FieldRef { + HardOwner = 3, + SoftPtr = 4, + HardPtr = 5, +} + +impl ObjW { + pub fn new(ver: DwgVersion) -> Self { + ObjW { ver, dat: BitWriter::new(), strs: BitWriter::new(), has_strings: false, hdl: BitWriter::new() } + } + + /// The object's three streams as written so far: fields, text (and whether it has any), + /// references. + pub(crate) fn into_streams(self) -> (BitWriter, BitWriter, bool, BitWriter) { + (self.dat, self.strs, self.has_strings, self.hdl) + } + + /// TV: from R2007 in the string stream, as UTF-16. + pub fn tv(&mut self, s: &str) { + if self.ver.has_string_stream() { + self.strs.text16(s); + self.has_strings = true; + } else { + let bytes: Vec = s.chars().map(|c| if (c as u32) < 0x100 { c as u8 } else { b'?' }).collect(); + self.dat.text8(&bytes); + } + } + + /// An absolute reference. + pub fn h(&mut self, kind: FieldRef, target: Handle) { + self.hdl.handle(kind as u8, target.0); + } +} diff --git a/crates/dwg/src/compose/file.rs b/crates/dwg/src/compose/file.rs index 345ff37a..2a93a8f0 100644 --- a/crates/dwg/src/compose/file.rs +++ b/crates/dwg/src/compose/file.rs @@ -1,13 +1,13 @@ //! The whole file from its parts, laid out as its version stores it. +use super::container::{self, FileInfo, MAX_PAGE, Section}; +use super::small as shared; use crate::bits::BitWriter; use crate::crc::{crc16, file_header_crc_xor}; use crate::file::HeaderValue; use crate::read::section::FILE_HEADER_END; use crate::read::version::DwgVersion as V; use crate::records::{Error, Result}; -use crate::write::container::{self, FileInfo, MAX_PAGE, Section}; -use crate::write::sections as shared; use super::object::TextEncoding; use super::sections::{Class, classes_section, header_section, object_map}; diff --git a/crates/dwg/src/compose/mod.rs b/crates/dwg/src/compose/mod.rs index 78b6a2fd..c348f2c4 100644 --- a/crates/dwg/src/compose/mod.rs +++ b/crates/dwg/src/compose/mod.rs @@ -3,11 +3,15 @@ //! the objects, the header variables and the classes over; this module lays the file out as the //! version asked for stores it. +mod container; +mod fields; mod file; mod object; mod r2007; mod sections; +mod small; +pub(crate) use fields::{FieldRef, ObjW}; pub use file::{Parts, Properties, compose}; pub use object::{EntityStart, ObjectWriter, Ref, TextEncoding, color_of_word, frame, method_word}; pub use sections::{Class, HeaderKind, class_versions, classes_section, header_section, header_variables, object_map}; diff --git a/crates/dwg/src/compose/object.rs b/crates/dwg/src/compose/object.rs index 9d1a42fc..2812e30e 100644 --- a/crates/dwg/src/compose/object.rs +++ b/crates/dwg/src/compose/object.rs @@ -576,7 +576,7 @@ impl ObjectWriter { pub fn grouped(&mut self, kind: &str, items: Vec<(u16, crate::file::XrValue)>, text_styles: &[(String, u64)]) -> crate::records::Result<()> { use crate::read::model::{Groups, Handle}; let lookup = crate::read::styles::Lookup::from_text_styles(text_styles.iter().map(|(n, h)| (n.clone(), Handle(*h))).collect()); - let mut w = crate::write::objects::ObjW::new(self.ver, Handle(self.handle)); + let mut w = super::ObjW::new(self.ver); crate::read::styles::encode_with(&mut w, &Groups { kind: kind.to_string(), items }, &lookup)?; let (dat, strs, has_strings, hdl) = w.into_streams(); self.dat.append(&dat); diff --git a/crates/dwg/src/compose/sections.rs b/crates/dwg/src/compose/sections.rs index d372bc04..c0cc763f 100644 --- a/crates/dwg/src/compose/sections.rs +++ b/crates/dwg/src/compose/sections.rs @@ -120,7 +120,7 @@ fn parse_floats(t: &str) -> Vec { /// A variable's value when the drawing has none: AutoCAD's own default. fn default_value(name: &str, kind: VarKind) -> HeaderValue { - let dt = crate::write::sections::default_text(name); + let dt = super::small::default_text(name); match kind { VarKind::B => HeaderValue::Bool(match dt { "" => matches!( diff --git a/crates/dwg/src/compose/small.rs b/crates/dwg/src/compose/small.rs new file mode 100644 index 00000000..f6b17e5f --- /dev/null +++ b/crates/dwg/src/compose/small.rs @@ -0,0 +1,152 @@ +//! The small sections every DWG file carries whatever the drawing: the application information +//! (AcDb:AppInfo and AcDb:AppInfoHistory), the revision history, and the header variables' default +//! values, in the forms AutoCAD 2027 writes them. + +/// Default values of the header variables for a drawing that has none +/// (AutoCAD's own defaults, as an imperial drawing carries them). +pub(crate) fn default_text(name: &str) -> &'static str { + match name { + "UNKNOWN_BD_412148564080" => "412148564080", + "UNKNOWN_BD_1A" | "UNKNOWN_BD_1B" | "UNKNOWN_BD_1C" => "1", + "UNKNOWN_TV_1" => "\"m\"", + // The spec gives 24; AutoCAD writes 0 in every file of the corpus. + "UNKNOWN_BL_24" => "0", + // Undocumented longs AutoCAD writes with the same values in every + // file of the corpus, 2004 to 2018, whatever the drawing. + "UNKNOWN_BL_R2004_1" | "UNKNOWN_BL_R2004_6" => "808464432", + "UNKNOWN_BL_R2004_2" | "UNKNOWN_BL_R2004_5" => "486539264", + "UNKNOWN_BL_R2004_3" | "UNKNOWN_BL_R2004_4" => "1295003696", + "MENUNAME" => "\".\"", + "DIMASO" | "DIMSHO" | "REGENMODE" | "FILLMODE" | "PSLTSCALE" | "USRTIMER" | "WORLDVIEW" | "TILEMODE" | "VISRETAIN" | "DIMTIH" | "DIMTOH" + | "CAMERADISPLAY" => "", + "PROXYGRAPHICS" | "ATTMODE" | "SHOWHIST" | "LOFTNORMALS" | "LIGHTGLYPHDISPLAY" | "TILEMODELIGHTSYNCH" | "HIDETEXT" | "DIMTOLJ" => "1", + "TREEDEPTH" => "3020", + "LUNITS" | "DIMALTD" | "DIMALTU" | "DIMALTTD" | "DIMLUNIT" | "XCLIPFRAME" | "DIMASSOC" | "DWFFRAME" => "2", + "LUPREC" | "DIMDEC" | "DIMTDEC" => "4", + "SPLINESEGS" | "ISOLINES" => "8", + "SURFU" | "SURFV" | "SURFTYPE" | "SURFTAB1" | "SURFTAB2" | "SPLINETYPE" => "6", + "SHADEDGE" | "DIMATFIT" => "3", + "SHADEDIF" | "TSTACKSIZE" => "70", + "MAXACTVP" => "64", + "TEXTQLTY" => "50", + "LTSCALE" | "CMLSCALE" | "CELTSCALE" | "DIMSCALE" | "DIMLFAC" | "DIMTFAC" | "DIMFXL" | "UNKNOWN_BD_R2007_1" => "1", + "TEXTSIZE" => "0.2", + "TRACEWID" => "0.05", + "SKETCHINC" => "0.1", + "FACETRES" => "0.5", + "PEXTMIN" | "EXTMIN" => "(100000000000000000000, 100000000000000000000, 100000000000000000000)", + "PEXTMAX" | "EXTMAX" => "(-100000000000000000000, -100000000000000000000, -100000000000000000000)", + "PLIMMAX" | "LIMMAX" => "(12, 9)", + "PUCSXDIR" | "UCSXDIR" => "(1, 0, 0)", + "PUCSYDIR" | "UCSYDIR" => "(0, 1, 0)", + "DIMASZ" | "DIMEXE" | "DIMTXT" => "0.18", + "DIMEXO" => "0.0625", + "DIMDLI" => "0.38", + "DIMCEN" | "DIMGAP" => "0.09", + "DIMALTF" => "25.4", + "DIMJOGANG" => "0.7853981633974483", + "DIMDSEP" => "46", + "DIMLWD" | "DIMLWE" => "-2", + "DIMALTMZF" | "DIMMZF" => "100", + "FLAGS" => "10781", + "SORTENTS" => "127", + "OBSCUREDCOLOR" | "INTERSECTIONCOLOR" => "257", + "TSTACKALIGN" => "1", + "UNKNOWN_BL_R2007_2" => "10", + "STEPSPERSEC" | "3DDWFPREC" => "2", + "STEPSIZE" => "6", + "LENSLENGTH" => "50", + "PSOLWIDTH" => "0.25", + "PSOLHEIGHT" => "4", + "LOFTANG1" | "LOFTANG2" => "1.5707963267948966", + "LOFTPARAM" => "7", + "LATITUDE" => "37.795", + "LONGITUDE" => "-122.394", + "TIMEZONE" => "-8000", + "UNKNOWN_B_R2007" => "true", + _ => "", + } +} + +/// The maintenance release AutoCAD 2027 writes for AC1032 (file header, +/// auxiliary header, class records), whose object layout the writer +/// follows bit for bit. +pub(crate) const ACAD_MAINTENANCE: u32 = 427; + +/// AcDb:RevHistory (chapter 18), as AutoCAD 2027 writes it for a drawing +/// with no revision records. +pub(crate) fn rev_history() -> Vec { + [0u32, 0, 1, 0].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// The kinds of entry in an application information list, each written +/// before its text. The spec calls these 16 bytes a checksum that may be +/// zero; in AutoCAD's files they are fixed identifiers, the same in every +/// file of the corpus whatever the text (the property set's is the format +/// id its XML names). +const APPINFO_COMMENT: [u8; 16] = [0xB8, 0xD0, 0xF0, 0x25, 0xA1, 0xD7, 0x93, 0x49, 0xB2, 0xFA, 0x9B, 0xF9, 0x28, 0x6F, 0xA1, 0xFD]; + +const APPINFO_PROPERTIES: [u8; 16] = [0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F, 0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9]; + +const APPINFO_PRODUCT: [u8; 16] = [0xE8, 0xE0, 0x96, 0x51, 0xC5, 0xCE, 0xB2, 0x44, 0xA8, 0xBF, 0xF6, 0xE8, 0x3B, 0x85, 0x9D, 0x44]; + +/// The 32 bytes AcDb:AppInfoHistory starts with, the same in every file of +/// the corpus (2004 to 2018, every save). +const APPINFO_HISTORY_START: [u8; 32] = [ + 0x53, 0xDE, 0x38, 0x1D, 0xEC, 0x43, 0x21, 0xCA, 0x96, 0x19, 0xE1, 0xE2, 0x17, 0x1A, 0x2A, 0x67, 0x3B, 0xD9, 0x7F, 0xF7, 0x3C, 0xBB, 0xCE, 0x08, + 0xA0, 0x53, 0xD8, 0xED, 0xD2, 0x8D, 0xC5, 0xC7, +]; + +/// TU as the R2007+ small sections store it: RS length counting the +/// terminating 0, then UTF-16 units with that 0. +fn tu(out: &mut Vec, s: &str) { + let units: Vec = s.encode_utf16().filter(|&u| u != 0).chain([0]).collect(); + out.extend_from_slice(&(units.len() as u16).to_le_bytes()); + for u in units { + out.extend_from_slice(&u.to_le_bytes()); + } +} + +fn appinfo_comment(name: &str, version: &str) -> String { + format!("Saved by {name} {version}.") +} + +fn appinfo_product(name: &str, version: &str) -> String { + let registry: String = version.split('.').take(2).collect::>().join("."); + format!( + "" + ) +} + +/// AcDb:AppInfo (chapter 16) in the layout AutoCAD 2027 writes: format 3, +/// "AppInfoDataList", two entries (a comment and the product +/// information), each after the identifier of its kind. It names the +/// program writing the file, never claims to be an Autodesk application. +pub(crate) fn app_info(name: &str, version: &str) -> Vec { + let mut o = Vec::new(); + o.extend_from_slice(&3u32.to_le_bytes()); + tu(&mut o, "AppInfoDataList"); + o.extend_from_slice(&2u32.to_le_bytes()); + o.extend_from_slice(&APPINFO_COMMENT); + tu(&mut o, &appinfo_comment(name, version)); + o.extend_from_slice(&APPINFO_PRODUCT); + tu(&mut o, &appinfo_product(name, version)); + o +} + +/// AcDb:AppInfoHistory (not in the spec) from a ready property set: the fixed 32 bytes, a +/// zero long, then an application information list of three entries (the comment, the property +/// set and the product information). +pub(crate) fn app_info_history_with(props: &str, name: &str, version: &str) -> Vec { + let mut o = APPINFO_HISTORY_START.to_vec(); + o.extend_from_slice(&0u32.to_le_bytes()); + tu(&mut o, "AppInfoDataList"); + o.extend_from_slice(&3u32.to_le_bytes()); + o.extend_from_slice(&APPINFO_COMMENT); + tu(&mut o, &appinfo_comment(name, version)); + o.extend_from_slice(&APPINFO_PROPERTIES); + tu(&mut o, props); + o.extend_from_slice(&APPINFO_PRODUCT); + tu(&mut o, &appinfo_product(name, version)); + o +} diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 21d5b066..d572ab33 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -2,7 +2,7 @@ //! //! - [`read`]: DWG files from R13 to AutoCAD 2018 and later into the [`records`] of //! their objects, which `draftcraft-io` maps straight into the drawing. -//! - [`write`] and [`compose`]: DWG files of every version AutoCAD saves (2000 to 2018) from the +//! - [`compose`]: DWG files of every version AutoCAD saves (2000 to 2018) from the //! drawing's objects. //! - [`file`]: a DWG file opened to its parts (version, sections, the object list), for a reader //! that builds the drawing itself. @@ -22,7 +22,6 @@ pub mod file; pub mod lz77; pub mod read; pub mod records; -pub mod write; pub use read::{DwgVersion, read_bytes}; diff --git a/crates/dwg/src/read/mod.rs b/crates/dwg/src/read/mod.rs index 6c17f502..5bed05a2 100644 --- a/crates/dwg/src/read/mod.rs +++ b/crates/dwg/src/read/mod.rs @@ -2,8 +2,7 @@ //! //! Reading: [`read_bytes`] turns a DWG file of any version from R13 to //! AutoCAD 2018 and later (AC1012–AC1032) into a [`Drawing`]. -//! Writing: [`write::to_bytes`] writes a drawing as an AutoCAD 2018 -//! (AC1032) file. +//! Writing is [`crate::compose`]'s. //! //! The drawing is `cad-model`'s database, re-exported here as //! [`cad_model`]. diff --git a/crates/dwg/src/read/nongraphic.rs b/crates/dwg/src/read/nongraphic.rs index a49ec940..9d6841cc 100644 --- a/crates/dwg/src/read/nongraphic.rs +++ b/crates/dwg/src/read/nongraphic.rs @@ -339,10 +339,6 @@ pub(crate) fn mline_flags_to_dxf(dwg: u16) -> u16 { MLINE_FLAG_BITS.iter().filter(|(d, _)| dwg & d != 0).fold(0, |acc, (_, x)| acc | x) } -pub(crate) fn mline_flags_to_dwg(dxf: u16) -> u16 { - MLINE_FLAG_BITS.iter().filter(|(_, x)| dxf & x != 0).fold(0, |acc, (d, _)| acc | d) -} - fn mlinestyle_data(s: &mut Streams) -> Result { let name = s.tv()?; let description = s.tv()?; diff --git a/crates/dwg/src/read/styles.rs b/crates/dwg/src/read/styles.rs index e9d16b6e..946d92b1 100644 --- a/crates/dwg/src/read/styles.rs +++ b/crates/dwg/src/read/styles.rs @@ -15,10 +15,10 @@ use super::streams::Streams; use super::version::DwgVersion as V; use crate::bits::BitReader; +use crate::compose::{FieldRef as Ref, ObjW}; use crate::read::error::{Error, Result}; use crate::read::geom::Vec3; use crate::read::model::{Drawing, Groups, Handle, ObjectKind, XrValue}; -use crate::write::objects::{ObjW, Ref}; /// How a value is stored in the DWG record. #[derive(Clone, Copy, Debug, PartialEq)] @@ -1078,12 +1078,7 @@ fn encode_layout(w: &mut ObjW, g: &Groups, l: &Layout) -> Result<()> { } /// Write a style object's type data and handles (after the common part -/// and common handles). -pub(crate) fn encode(w: &mut ObjW, g: &Groups, d: &Drawing) -> Result<()> { - encode_with(w, g, &Lookup::new(d)) -} - -/// [`encode`] with the text styles given. +/// and common handles), with the text styles a table style refers to given. pub(crate) fn encode_with(w: &mut ObjW, g: &Groups, lookup: &Lookup) -> Result<()> { if w.ver < since(&g.kind) { return Err(Error::unsupported(format!("{} before {:?}", g.kind, since(&g.kind)))); @@ -1845,11 +1840,11 @@ mod tests { fn a_claimed_count_does_not_size_the_list() { let l = layout("ACDBSECTIONVIEWSTYLE", V::R2018).expect("laid out"); // Sound: two items, both written. - let mut w = ObjW::new(V::R2018, Handle(0x100)); + let mut w = ObjW::new(V::R2018); encode_layout(&mut w, &groups("ACDBSECTIONVIEWSTYLE", 2), &l).unwrap(); // Two billion claimed: the list holds what is there, and nothing // the size of the claim is allocated (that aborted the process). - let mut w = ObjW::new(V::R2018, Handle(0x100)); + let mut w = ObjW::new(V::R2018); encode_layout(&mut w, &groups("ACDBSECTIONVIEWSTYLE", i32::MAX), &l).unwrap(); } } diff --git a/crates/dwg/src/records/model/objects.rs b/crates/dwg/src/records/model/objects.rs index f4e6a5fb..708e8826 100644 --- a/crates/dwg/src/records/model/objects.rs +++ b/crates/dwg/src/records/model/objects.rs @@ -8,7 +8,7 @@ //! §20.4.45, MLINESTYLE §20.4.73, DICTIONARYVAR §20.4.74, LAYOUT §20.4.84, //! SCALE §20.4.92, XRECORD §20.4.104, VPORT §20.4.64, DIMSTYLE §20.4.68). //! `dwg::nongraphic` reads them from DWG records, `dxf` reads and writes -//! them as DXF, `dwg::write` encodes them, and `native` stores them. +//! them as DXF, and `native` stores them. use super::{Color, DimStyle, Handle, Lineweight}; use crate::records::geom::{Vec2, Vec3}; diff --git a/crates/dwg/src/write/check.rs b/crates/dwg/src/write/check.rs deleted file mode 100644 index 000e6f3d..00000000 --- a/crates/dwg/src/write/check.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Reading a written file back and comparing it with the drawing it was -//! written from, object by object. -//! -//! The writer reports what it could not encode (`DwgOutput::left_out`). A -//! file can still lose more than that without the writer knowing: a field -//! written in the wrong place, or one the model holds and the encoder never -//! writes, reads back as a different value. Counting objects does not see -//! that; comparing them does. - -use super::{DwgOutput, dxf_only_objects, without_dxf_only}; -use crate::read::model::{Drawing, NonGraphic, Object, ObjectKind, XrValue}; -use std::collections::BTreeMap; - -/// How a written file compares with the drawing it was written from. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct Check { - /// Objects that read back different from what was written, by type. - pub changed: BTreeMap, - /// Objects that did not read back at all, beyond those the writer - /// reported leaving out, by type. - pub vanished: BTreeMap, - /// What differed, for people to read: the first few objects, each with - /// the first field that differs. - pub notes: Vec, -} - -impl Check { - /// True when every object the writer kept reads back as it was. - pub fn is_whole(&self) -> bool { - self.changed.is_empty() && self.vanished.is_empty() - } -} - -/// Most objects described in [`Check::notes`]. -const NOTES: usize = 8; - -/// Read `out` back and compare it with `d`, the drawing it was written -/// from. -/// -/// Objects the writer reported leaving out, objects kept only as their -/// original file records, and the objects AutoCAD keeps in DXF but not in -/// DWG are not compared. For each other object the type, owner, extension -/// dictionary, reactors, entity properties, extended data and everything -/// the model decodes must come back equal. Header variables are not -/// compared. -/// -/// An error means the written file could not be read at all. -pub fn check(d: &Drawing, out: &DwgOutput) -> crate::read::error::Result { - let back = crate::read::read_bytes(&out.bytes)?; - let dxf_only = dxf_only_objects(d); - let mut c = Check::default(); - let mut missing: BTreeMap = BTreeMap::new(); - for o in d.objects.values() { - if dxf_only.contains(&o.handle) || o.raw.is_some() { - continue; - } - let written = without_dxf_only(o, &dxf_only); - let o = written.as_ref().unwrap_or(o); - let Some(b) = back.objects.get(&o.handle) else { - *missing.entry(o.type_name.clone()).or_default() += 1; - continue; - }; - if let Some(field) = first_difference(o, b) { - *c.changed.entry(o.type_name.clone()).or_default() += 1; - if c.notes.len() < NOTES { - c.notes.push(format!("{:X} {}: {field} reads back different", o.handle.0, o.type_name)); - } - } - } - for (t, n) in missing { - let reported = out.left_out.get(&t).copied().unwrap_or(0); - if n > reported { - c.vanished.insert(t.clone(), n - reported); - if c.notes.len() < NOTES { - c.notes.push(format!("{} {t} missing from the file", n - reported)); - } - } - } - Ok(c) -} - -/// The first part of `a` that `b` does not hold the same, or `None`. -fn first_difference(a: &Object, b: &Object) -> Option<&'static str> { - if a.type_name != b.type_name { - Some("its type") - } else if a.owner != b.owner { - Some("its owner") - } else if a.xdictionary != b.xdictionary { - Some("its extension dictionary") - } else if a.reactors != b.reactors { - Some("its reactors") - } else if a.entity != b.entity { - Some("its entity properties") - } else if a.xdata != b.xdata { - Some("its extended data") - } else if !same_data(&a.kind, &b.kind) { - Some("its data") - } else { - None - } -} - -/// Whether `b` holds everything `a` does. An object kept as its DXF -/// groups may come back with groups the file's version adds (a 2018 file -/// stores fields an older DXF had no place for), and in the order the -/// reader gives them, which is AutoCAD's: a table style's border groups, -/// for one, come back row by row rather than kind by kind. It holds the -/// same as long as every group written comes back, as often as it was -/// written. -fn same_data(a: &ObjectKind, b: &ObjectKind) -> bool { - match (a, b) { - (ObjectKind::NonGraphic(NonGraphic::Groups(ga)), ObjectKind::NonGraphic(NonGraphic::Groups(gb))) => { - let mut left: Vec<&(u16, XrValue)> = gb.items.iter().collect(); - ga.kind == gb.kind - && ga.items.iter().all(|item| match left.iter().position(|x| *x == item) { - Some(i) => { - left.swap_remove(i); - true - } - None => false, - }) - } - _ => a == b, - } -} diff --git a/crates/dwg/src/write/mod.rs b/crates/dwg/src/write/mod.rs deleted file mode 100644 index 9a15f5a2..00000000 --- a/crates/dwg/src/write/mod.rs +++ /dev/null @@ -1,385 +0,0 @@ -//! DWG writer: the drawing as an AC1032 (AutoCAD 2018) file. -//! -//! Objects the model holds whole are encoded from it (`objects`); objects -//! kept as their original DWG records of the same version are written as -//! they were. The header, classes, object map and the small sections are -//! built from the drawing (`sections`), and everything is packed into the -//! R2004-family paged container (`container`). -//! -//! Every layout choice follows what AutoCAD 2027 writes for AC1032, checked -//! against its MI-201 file byte for byte where the content is the same -//! (`tests`). - -mod check; -pub(crate) mod container; -pub(crate) mod objects; -pub(crate) mod sections; - -use crate::read::error::{Error, Result}; -use crate::read::model::{Drawing, Handle, HatchLibrary, Object, ObjectKind}; -use crate::read::nongraphic::{self, DimVars, NonGraphic, Vport}; -use crate::read::version::DwgVersion; -use container::{MAX_PAGE, Section}; -use objects::Ctx; -use std::collections::BTreeMap; - -pub use check::{Check, check}; - -/// A DWG file and what the writer had to leave out. -#[derive(Debug, Clone)] -pub struct DwgOutput { - pub bytes: Vec, - /// What was left out, for people to read. - pub notes: Vec, - /// The objects the file does not hold, by type name: those the model - /// cannot encode and keeps no record of in this version. Empty when the - /// file holds the whole drawing. - pub left_out: BTreeMap, -} - -/// What a DWG file records about the program that wrote it, and the parts -/// of the file the writer takes from that program when it has them. -/// -/// [`WriteOptions::default`] names this crate as the writer, stores a -/// one-pixel preview, estimates text widths, and writes a pattern hatch's -/// line families only when the drawing holds them. -#[derive(Clone, Copy)] -pub struct WriteOptions<'a> { - /// The program's name, recorded in the file's application information - /// ("Saved by {name} {version}.") and its save history. The file never - /// claims to come from another program. - pub app_name: &'a str, - /// The program's version, `major.minor.patch`. - pub app_version: &'a str, - /// The preview image (a PNG) that file browsers and AutoCAD's open - /// dialog show. `None` stores a one-pixel image. - pub preview_png: Option<&'a [u8]>, - /// The width of one line of text at height 1, in the program's own - /// font. A DWG's MTEXT records its extents, which AutoCAD measures - /// again when it regenerates the text. `None` estimates from the - /// number of characters ([`estimated_text_width`]). - pub text_width: Option<&'a dyn Fn(&str) -> f64>, - /// The line families of a pattern hatch that holds none, so that - /// other programs draw the pattern: given the drawing and the hatch, - /// the lines to store. `None` writes such hatches with no lines. - pub hatch_lines: Option<&'a HatchLibrary<'a>>, -} - -impl Default for WriteOptions<'_> { - fn default() -> Self { - WriteOptions { app_name: "cad-dwg", app_version: env!("CARGO_PKG_VERSION"), preview_png: None, text_width: None, hatch_lines: None } - } -} - -impl std::fmt::Debug for WriteOptions<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WriteOptions") - .field("app_name", &self.app_name) - .field("app_version", &self.app_version) - .field("preview_png", &self.preview_png.map(<[u8]>::len)) - .field("text_width", &self.text_width.is_some()) - .field("hatch_lines", &self.hatch_lines.is_some()) - .finish() - } -} - -/// A line of text's width at height 1 when the program gives no font: -/// 0.8 of the height per character, about the average advance of a -/// single-stroke drafting font. -pub fn estimated_text_width(line: &str) -> f64 { - line.chars().count() as f64 * 0.8 -} - -/// The preview stored when the program gives none: a one-pixel PNG in the -/// colour of AutoCAD's model-space background (a test checks its CRCs). -const BLANK_PREVIEW: &[u8] = &[ - // signature - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // IHDR: 1 × 1, 8-bit palette indices - 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x03, 0x00, 0x00, 0x00, 0x28, 0xCB, 0x34, - 0xBB, // PLTE: one colour, #212830 - 0x00, 0x00, 0x00, 0x03, 0x50, 0x4C, 0x54, 0x45, 0x21, 0x28, 0x30, 0xE5, 0x71, 0x8F, 0x0B, // IDAT: one row, no filter, index 0 - 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0xDA, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE5, 0x27, 0xDE, 0xFC, - // IEND - 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, -]; - -/// The objects the writer would encode and the ones it leaves out, by -/// handle, for a drawing. -struct Encoded { - /// (handle, framed object bytes), in handle order. - objects: Vec<(u64, Vec)>, - notes: Vec, - /// Objects left out, by type name. - left_out: BTreeMap, -} - -fn named_entry(d: &Drawing, dict: Handle, name: &str) -> Option { - let o = d.objects.get(&dict)?; - match nongraphic::decode(o, &d.classes, d.codepage)? { - Ok(NonGraphic::Dictionary(dc)) => dc.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, h)| *h).or(dc.default), - _ => None, - } -} - -fn default_entry(d: &Drawing, dict: Handle, name: &str) -> Option { - let o = d.objects.get(&dict)?; - match nongraphic::decode(o, &d.classes, d.codepage)? { - Ok(NonGraphic::Dictionary(dc)) => dc.default.or_else(|| dc.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, h)| *h)), - _ => None, - } -} - -fn encode_objects(d: &Drawing, ver: DwgVersion, opts: &WriteOptions<'_>) -> Encoded { - let hv = crate::read::hvars::Hv::new(d); - let appids: BTreeMap = d - .objects - .values() - .filter_map(|o| match &o.kind { - ObjectKind::NamedRecord(r) if o.type_code == 0x43 => Some((r.name.to_ascii_uppercase(), o.handle)), - _ => None, - }) - .collect(); - let header_dims = nongraphic::dim_vars_from_header(&hv); - let dv = |o: &Object| -> DimVars { - match nongraphic::dimstyle(o, &d.classes, d.codepage) { - Some(Ok((_, v))) => v, - _ => { - let mut v = header_dims.clone(); - if let ObjectKind::DimStyle(s) = &o.kind { - v.apply_model(s); - } - v - } - } - }; - let extents = (hv.p3("EXTMIN", Default::default()), hv.p3("EXTMAX", Default::default())); - let vp = |o: &Object| -> Vport { - match nongraphic::vport(o, &d.classes, d.codepage) { - Some(Ok(v)) => v, - _ => Vport::looking_at(crate::read::geom::Vec2::new(extents.0.x, extents.0.y), crate::read::geom::Vec2::new(extents.1.x, extents.1.y)), - } - }; - let plot_style = default_entry(d, hv.handle("DICTIONARY_PLOTSTYLES"), "Normal").unwrap_or(Handle::NULL); - let material = named_entry(d, hv.handle("DICTIONARY_MATERIALS"), "Global").unwrap_or(Handle::NULL); - let ctx = Ctx { - d, - appids: &appids, - plot_style, - material, - dimstyle_vars: &dv, - vport: &vp, - text_width: opts.text_width.unwrap_or(&estimated_text_width), - hatch_lines: opts.hatch_lines, - }; - let mut objects = Vec::with_capacity(d.objects.len()); - let mut notes = Vec::new(); - let mut left_out: BTreeMap = BTreeMap::new(); - let dxf_only = dxf_only_objects(d); - let mut patched: Option = None; - for o in d.objects.values() { - if dxf_only.contains(&o.handle) { - continue; - } - let o = match without_dxf_only(o, &dxf_only) { - Some(p) => patched.insert(p), - None => o, - }; - let from_raw = || -> Option> { - let raw = o.raw.as_ref()?; - (raw.version == ver).then(|| objects::frame(ver, &raw.data, raw.handle_stream_bits)) - }; - let bytes = match objects::encode(o, &ctx, ver) { - Ok(Some(b)) => Some(b), - Ok(None) => from_raw(), - Err(e) => { - let b = from_raw(); - if b.is_none() { - notes.push(format!("{:X} {}: {}", o.handle.0, o.type_name, e.message)); - } - b - } - }; - match bytes { - Some(b) => objects.push((o.handle.0, b)), - None => { - *left_out.entry(o.type_name.clone()).or_default() += 1; - if !notes.iter().any(|n| n.starts_with(&format!("{:X} ", o.handle.0))) { - let why = match &o.raw { - Some(r) => format!("kept only as a {} record", r.version.magic()), - None => "not decoded".into(), - }; - notes.push(format!("{:X} {}: left out, {why}", o.handle.0, o.type_name)); - } - } - } - } - Encoded { objects, notes, left_out } -} - -/// Objects a DXF holds that the DWG of the same drawing does not: the -/// cell style maps AutoCAD adds to each table style in DXF (and the -/// dictionaries that hold them), and the recomposition record it adds to -/// the named object dictionary. AutoCAD writes them when it saves a DXF -/// and folds them back in when it reads one. -fn dxf_only_objects(d: &Drawing) -> std::collections::HashSet { - let mut out = std::collections::HashSet::new(); - for o in d.objects.values() { - match &o.kind { - ObjectKind::NonGraphic(NonGraphic::Groups(g)) if g.kind == "CELLSTYLEMAP" => { - out.insert(o.handle); - } - ObjectKind::NonGraphic(NonGraphic::Dictionary(dc)) - if !dc.entries.is_empty() && dc.entries.iter().all(|(k, _)| k == "ACAD_ROUNDTRIP_2008_TABLESTYLE_CELLSTYLEMAP") => - { - out.insert(o.handle); - } - _ => {} - } - } - if let Some(root) = d.objects.get(&d.header.named_objects_dict) - && let ObjectKind::NonGraphic(NonGraphic::Dictionary(dc)) = &root.kind - { - for (k, h) in &dc.entries { - if k == "ACDB_RECOMPOSE_DATA" { - out.insert(*h); - } - } - } - out -} - -/// The object without references to DXF-only objects (an extension -/// dictionary, dictionary entries), or `None` when it has none. -fn without_dxf_only(o: &Object, dxf_only: &std::collections::HashSet) -> Option { - let xdic = dxf_only.contains(&o.xdictionary); - let entries = match &o.kind { - ObjectKind::NonGraphic(NonGraphic::Dictionary(dc)) => dc.entries.iter().any(|(_, h)| dxf_only.contains(h)), - _ => false, - }; - if !xdic && !entries { - return None; - } - let mut p = o.clone(); - if xdic { - p.xdictionary = Handle::NULL; - } - if let ObjectKind::NonGraphic(NonGraphic::Dictionary(dc)) = &mut p.kind { - dc.entries.retain(|(_, h)| !dxf_only.contains(h)); - } - Some(p) -} - -/// The section map order AutoCAD 2027 uses (ids descending from the first). -const MAP_ORDER: [&str; 13] = [ - "AcDb:XrefManifest", - "AcDb:AppInfoHistory", - "AcDb:AppInfo", - "AcDb:Preview", - "AcDb:SummaryInfo", - "AcDb:RevHistory", - "AcDb:AcDbObjects", - "AcDb:ObjFreeSpace", - "AcDb:Template", - "AcDb:Handles", - "AcDb:Classes", - "AcDb:AuxHeader", - "AcDb:Header", -]; - -fn round_up(n: usize, to: usize) -> usize { - n.max(1).div_ceil(to) * to -} - -/// The drawing as an AutoCAD 2018 (AC1032) DWG file, with -/// [`WriteOptions::default`]. -pub fn to_bytes(d: &Drawing) -> Result { - to_bytes_with(d, &WriteOptions::default()) -} - -/// The drawing as an AutoCAD 2018 (AC1032) DWG file. -/// -/// Objects are written as the drawing holds them. A dimension whose -/// graphics block is missing is written without one; a program that draws -/// dimensions adds the blocks first, so that other programs show them. -pub fn to_bytes_with(d: &Drawing, opts: &WriteOptions<'_>) -> Result { - let (stream, mut notes, left_out) = stream_sections(d, opts)?; - let bytes = container::pack(&file_info(d), &stream, &MAP_ORDER)?; - if !notes.is_empty() { - notes.insert(0, format!("{} objects could not be written to AC1032", notes.len())); - } - Ok(DwgOutput { bytes, notes, left_out }) -} - -fn file_info(d: &Drawing) -> container::FileInfo { - container::FileInfo { - version: *b"AC1032", - maintenance: 0, - app_version: 33, - app_maintenance: 0, - codepage: d.codepage, - acad_maintenance: sections::ACAD_MAINTENANCE, - } -} - -/// Every section of the file in stream order, the notes on what was left -/// out, and what was left out by type. -type Sections = (Vec
, Vec, BTreeMap); - -/// Every section of the file, in stream order, and notes on what was left -/// out. -fn stream_sections(d: &Drawing, opts: &WriteOptions<'_>) -> Result { - let ver = DwgVersion::R2018; - let Encoded { objects, notes, left_out } = encode_objects(d, ver, opts); - if objects.is_empty() { - return Err(Error::format("the drawing has no objects to write")); - } - - // AcDb:AcDbObjects: RL 0x0DCA, then the objects; the object map - // records where each starts. - let mut obj_section = 0x0DCAu32.to_le_bytes().to_vec(); - let mut map = Vec::with_capacity(objects.len()); - for (h, b) in &objects { - map.push((*h, obj_section.len() as u64)); - obj_section.extend_from_slice(b); - } - // The map is in handle order. Objects are encoded in key order, and an - // object read from a damaged file can carry a handle other than its - // key; two with the same handle keep the first. - map.sort_by_key(|e| e.0); - map.dedup_by_key(|e| e.0); - let max_handle = objects.iter().map(|(h, _)| *h).max().unwrap_or(0); - let handseed = d.header.handseed.unwrap_or(0).max(max_handle.saturating_add(1)); - - let summary = sections::summary_info(d); - let summary_page = round_up(summary.len(), 0x80); - let png = opts.preview_png.unwrap_or(BLANK_PREVIEW); - let preview_len = sections::preview(png, 0).len(); - let preview_page = round_up(preview_len, 0x400); - let preview_address = 0x100 + container::uncompressed_page_extent(summary_page) + 0x20; - let preview = sections::preview(png, preview_address as u64); - let app_info = sections::app_info(opts.app_name, opts.app_version); - let app_info_page = round_up(app_info.len(), 0x80); - // Every write is the drawing's first save as far as the file records: - // the model keeps no count of earlier saves. - let saves = 1; - let history = sections::app_info_history(d, saves == 1, opts.app_name, opts.app_version); - let history_page = round_up(history.len(), 0x80); - - let compressed = |name, data| Section { name, data, compressed: true, page_size: MAX_PAGE }; - let stream = vec![ - Section { name: "AcDb:SummaryInfo", data: summary, compressed: false, page_size: summary_page }, - Section { name: "AcDb:Preview", data: preview, compressed: false, page_size: preview_page }, - Section { name: "AcDb:AppInfo", data: app_info, compressed: false, page_size: app_info_page }, - Section { name: "AcDb:AppInfoHistory", data: history, compressed: false, page_size: history_page }, - compressed("AcDb:XrefManifest", sections::xref_manifest(d)), - compressed("AcDb:RevHistory", sections::rev_history()), - compressed("AcDb:AcDbObjects", obj_section), - compressed("AcDb:ObjFreeSpace", sections::obj_free_space(d, map.len())), - compressed("AcDb:Template", sections::template(d)), - compressed("AcDb:Handles", sections::handles_section(&map)), - compressed("AcDb:Classes", sections::classes_section(d, ver)), - compressed("AcDb:AuxHeader", sections::aux_header(d, handseed, saves)), - compressed("AcDb:Header", sections::header_section(d, ver, handseed)), - ]; - Ok((stream, notes, left_out)) -} diff --git a/crates/dwg/src/write/objects.rs b/crates/dwg/src/write/objects.rs deleted file mode 100644 index 4bad7a2d..00000000 --- a/crates/dwg/src/write/objects.rs +++ /dev/null @@ -1,1846 +0,0 @@ -//! Encoding single objects in the R2010+ object format (spec §20.1, -//! §20.2 and the per-type prescriptions of §20.4), the mirror of -//! `dwg::object` and the per-type readers. -//! -//! Field order and every choice the format leaves open (which compressed -//! form a value takes, how a handle reference is coded, where padding -//! goes) follow what AutoCAD 2027 writes: the tests encode every object of -//! the AutoCAD-saved MI-201 corpus file that the drawing model holds whole -//! and compare the bytes. - -use crate::bits::BitWriter; -use crate::crc::crc16; -use crate::read::error::{Error, Result}; -use crate::read::geom::{Vec2, Vec3}; -use crate::read::model::{ - BlockHeader, Color, Dimension, DimensionKind, Drawing, Handle, Hatch, HatchEdge, HatchLibrary, HatchPath, Leader, Linetype, LinetypeRef, MText, - NonGraphic, Object, ObjectKind, PaperViewport, PolylineKind, Space, Spline, Text, TextStyle, VertexKind, XDataApp, XValue, XrValue, -}; -use crate::read::nongraphic::{DimVars, Vport}; -use crate::read::version::DwgVersion as V; -use crate::read::version::DwgVersion; - -/// The three streams an R2007+ object is written as. -pub(crate) struct ObjW { - pub ver: DwgVersion, - /// The object's own handle, for relative references. - pub own: u64, - pub dat: BitWriter, - strs: BitWriter, - has_strings: bool, - pub hdl: BitWriter, -} - -/// Which handle-reference codes a field takes (spec §2.13): soft -/// ownership 2, hard ownership 3, soft pointer 4, hard pointer 5. -#[derive(Clone, Copy)] -pub(crate) enum Ref { - SoftOwner = 2, - HardOwner = 3, - SoftPtr = 4, - HardPtr = 5, -} - -impl ObjW { - pub fn new(ver: DwgVersion, own: Handle) -> Self { - ObjW { ver, own: own.0, dat: BitWriter::new(), strs: BitWriter::new(), has_strings: false, hdl: BitWriter::new() } - } - - /// The object's three streams as written so far: fields, text (and whether it has any), - /// references. - pub(crate) fn into_streams(self) -> (BitWriter, BitWriter, bool, BitWriter) { - (self.dat, self.strs, self.has_strings, self.hdl) - } - - /// TV: from R2007 in the string stream, as UTF-16. - pub fn tv(&mut self, s: &str) { - if self.ver.has_string_stream() { - self.strs.text16(s); - self.has_strings = true; - } else { - let bytes: Vec = s.chars().map(|c| if (c as u32) < 0x100 { c as u8 } else { b'?' }).collect(); - self.dat.text8(&bytes); - } - } - - /// An absolute reference. - pub fn h(&mut self, kind: Ref, target: Handle) { - self.hdl.handle(kind as u8, target.0); - } - - /// A soft pointer in its shortest form: absolute (code 4), the next - /// or previous handle (6, 8: no bytes) or an offset from this object - /// (0xA, 0xC) when the offset is smaller than the handle, as AutoCAD - /// writes owners. - pub fn h_rel(&mut self, target: Handle) { - let t = target.0; - let own = self.own; - if t == 0 { - self.hdl.handle(4, 0); - } else if t == own.wrapping_add(1) { - self.hdl.handle(6, 0); - } else if t.wrapping_add(1) == own { - self.hdl.handle(8, 0); - } else if t > own && t - own < t { - self.hdl.handle(0xA, t - own); - } else if t < own && own - t < t { - // AutoCAD codes an owner relative to the object only when the - // offset is the smaller number (LAYER A owned by 8: C.2; APPID - // 13 owned by 9: 4.9, not C.A). - self.hdl.handle(0xC, own - t); - } else { - self.hdl.handle(4, t); - } - } - - /// CMC (R2004+): BS index, BL method word, RC name flags. - pub fn cmc(&mut self, c: Color) { - if self.ver < V::R2004 { - self.dat.bs(c.to_aci() as u16); - return; - } - // The index field stays 0: the colour is in the method word, as - // AutoCAD writes every CmColor from R2004 on. - self.dat.bs(0); - self.dat.bl(c.to_method_word()); - self.dat.rc(0); - } - - /// The finished object as it sits in the objects section: MS size, MC - /// handle-stream size in bits, the data, the CRC. - pub fn finish(mut self) -> Vec { - if self.ver.has_string_stream() { - if self.has_strings { - let n = self.strs.position(); - self.dat.append(&self.strs); - if n >= 0x8000 { - self.dat.rs((n >> 15) as u16); - self.dat.rs((n & 0x7FFF) as u16 | 0x8000); - } else { - self.dat.rs(n as u16); - } - self.dat.b(true); - } else { - self.dat.b(false); - } - } - let endbit = self.dat.position(); - self.dat.append(&self.hdl); - // AutoCAD fills the last byte with 1 bits. - while !self.dat.position().is_multiple_of(8) { - self.dat.b(true); - } - let total_bits = self.dat.position(); - let data = self.dat.into_bytes(); - frame(self.ver, &data, (total_bits - endbit) as u64) - } -} - -/// Wrap object data in its size fields and CRC. -pub(crate) fn frame(ver: DwgVersion, data: &[u8], handle_bits: u64) -> Vec { - let mut w = BitWriter::new(); - w.ms(data.len() as u32); - if ver >= V::R2010 { - w.mc_unsigned(handle_bits); - } - let mut out = w.into_bytes(); - out.extend_from_slice(data); - let crc = crc16(0xC0C1, &out); - out.extend_from_slice(&crc.to_le_bytes()); - out -} - -/// What the encoder needs to know about the drawing beyond the object. -pub(crate) struct Ctx<'a> { - pub d: &'a Drawing, - /// The handle of the APPID record of each application name. - pub appids: &'a std::collections::BTreeMap, - /// The "Normal" plot style and "Global" material, for layers. - pub plot_style: Handle, - pub material: Handle, - /// Text style and linetype handles the ByLayer/ByBlock entries need. - pub dimstyle_vars: &'a dyn Fn(&Object) -> DimVars, - pub vport: &'a dyn Fn(&Object) -> Vport, - /// A line of text's width at height 1 (`WriteOptions::text_width`). - pub text_width: &'a dyn Fn(&str) -> f64, - /// Line families for a pattern hatch without them - /// (`WriteOptions::hatch_lines`). - pub hatch_lines: Option<&'a HatchLibrary<'a>>, -} - -fn v3(p: Vec3) -> [f64; 3] { - p.to_array() -} -fn v2(p: Vec2) -> [f64; 2] { - [p.x, p.y] -} - -/// Extended data (chapter 28), the mirror of `eed::read`. -fn eed(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - for x in &o.xdata { - let app = match &x.app { - XDataApp::Handle(h) => *h, - XDataApp::Name(n) => match ctx.appids.get(&n.to_ascii_uppercase()) { - Some(h) => *h, - None => continue, - }, - }; - let mut b: Vec = Vec::new(); - for it in &x.items { - match it { - XValue::Str(s) => { - b.push(0); - if w.ver.has_string_stream() { - let units: Vec = s.encode_utf16().collect(); - b.extend_from_slice(&(units.len() as u16).to_le_bytes()); - for u in units { - b.extend_from_slice(&u.to_le_bytes()); - } - } else { - let bytes: Vec = s.chars().map(|c| c as u32 as u8).collect(); - b.push(bytes.len() as u8); - b.extend_from_slice(&[0, 30]); - b.extend_from_slice(&bytes); - } - } - XValue::Open => b.extend_from_slice(&[2, 0]), - XValue::Close => b.extend_from_slice(&[2, 1]), - XValue::Layer(h) => { - b.push(3); - b.extend_from_slice(&h.0.to_be_bytes()); - } - XValue::Bytes(bytes) => { - b.push(4); - b.push(bytes.len().min(255) as u8); - b.extend_from_slice(&bytes[..bytes.len().min(255)]); - } - XValue::Handle(h) => { - b.push(5); - b.extend_from_slice(&h.0.to_be_bytes()); - } - XValue::Point(p) | XValue::Position(p) | XValue::Displacement(p) | XValue::Direction(p) => { - b.push(match it { - XValue::Point(_) => 10, - XValue::Position(_) => 11, - XValue::Displacement(_) => 12, - _ => 13, - }); - for c in p.to_array() { - b.extend_from_slice(&c.to_le_bytes()); - } - } - XValue::Real(v) | XValue::Distance(v) | XValue::ScaleFactor(v) => { - b.push(match it { - XValue::Real(_) => 40, - XValue::Distance(_) => 41, - _ => 42, - }); - b.extend_from_slice(&v.to_le_bytes()); - } - XValue::Int16(v) => { - b.push(70); - b.extend_from_slice(&v.to_le_bytes()); - } - XValue::Int32(v) => { - b.push(71); - b.extend_from_slice(&v.to_le_bytes()); - } - XValue::Undecoded { version, data } => { - if *version != w.ver && version.has_string_stream() != w.ver.has_string_stream() { - return Err(Error::unsupported("extended data from another DWG version could not be decoded")); - } - b.extend_from_slice(data); - } - } - } - if b.is_empty() || b.len() > 0x7FFF { - continue; - } - w.dat.bs(b.len() as u16); - w.dat.handle(5, app.0); - w.dat.raw_bytes(&b); - } - w.dat.bs(0); - Ok(()) -} - -/// The type code an object is written with: its own, or for a class -/// object the class number. -fn type_code(o: &Object) -> u16 { - o.type_code -} - -/// The common start of every object: type, handle, extended data, and -/// for an entity its graphics flag and common entity data. -fn common(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - if w.ver >= V::R2010 { - w.dat.ot(type_code(o)); - } else { - w.dat.bs(type_code(o)); - } - if (V::R2000..=V::R2007).contains(&w.ver) { - // R2000–R2007 store the data size in bits here; not supported. - return Err(Error::unsupported("writing R2000–R2007 objects")); - } - w.dat.handle(0, o.handle.0); - eed(w, o, ctx)?; - let xdic_missing = o.xdictionary.is_null(); - match &o.entity { - Some(e) => { - w.dat.b(false); // no proxy graphics - w.dat.bb(match e.space { - Space::Owned => 0, - Space::Paper => 1, - Space::Model => 2, - }); - w.dat.bl(o.reactors.len() as u32); - w.dat.b(xdic_missing); - if w.ver >= V::R2013 { - w.dat.b(false); - } - enc(w, e.color, e.transparency); - w.dat.bd(e.linetype_scale); - w.dat.bb(match e.linetype { - LinetypeRef::ByLayer => 0, - LinetypeRef::ByBlock => 1, - LinetypeRef::Continuous => 2, - LinetypeRef::Handle(_) => 3, - }); - w.dat.bb(if e.plotstyle.is_null() { 0 } else { 3 }); - w.dat.bb(if e.material.is_null() { 0 } else { 3 }); - w.dat.rc(0); // shadow flags - if w.ver >= V::R2010 { - w.dat.b(false); - w.dat.b(false); - w.dat.b(false); - } - w.dat.bs(e.invisible as u16); - w.dat.rc(e.lineweight); - } - None => { - w.dat.bl(o.reactors.len() as u32); - w.dat.b(xdic_missing); - if w.ver >= V::R2013 { - w.dat.b(false); - } - } - } - Ok(()) -} - -/// ENC (§2.11, R2004+): BS index with flag bits, then the method word -/// (true colour) and the transparency when present. -fn enc(w: &mut ObjW, c: Color, transparency: Option) { - let mut flags: u16 = match c { - Color::ByLayer => 256, - Color::ByBlock => 0, - Color::Index(i) => i as u16, - Color::Rgb(..) => 0x8000, - Color::None => 257, - }; - if transparency.is_some() { - flags |= 0x2000; - } - w.dat.bs(flags); - if let Color::Rgb(..) = c { - w.dat.bl(c.to_method_word()); - } - if let Some(t) = transparency { - w.dat.bl(t); - } -} - -/// The common handles: owner, reactors, extension dictionary, and for an -/// entity its layer, linetype, material and plot style. -fn common_handles(w: &mut ObjW, o: &Object) { - let owned = o.entity.as_ref().map(|e| e.space == Space::Owned).unwrap_or(true); - if owned { - w.h_rel(o.owner); - } - for r in &o.reactors { - w.h(Ref::SoftPtr, *r); - } - if !o.xdictionary.is_null() { - w.h(Ref::HardOwner, o.xdictionary); - } - if let Some(e) = &o.entity { - w.h(Ref::HardPtr, e.layer); - if let LinetypeRef::Handle(h) = e.linetype { - w.h(Ref::HardPtr, h); - } - if !e.material.is_null() { - w.h(Ref::HardPtr, e.material); - } - if !e.plotstyle.is_null() { - w.h(Ref::HardPtr, e.plotstyle); - } - } -} - -/// A table record's name and xref index (R2007+: no 64-flag or -/// xref-dependent bit; see `tables::record_common_flags`). -fn record_name(w: &mut ObjW, name: &str) { - w.tv(name); - if !w.ver.has_string_stream() { - w.dat.b(false); - } - w.dat.bs(0); - if !w.ver.has_string_stream() { - w.dat.b(false); - } -} - -/// Encode one object the drawing model holds whole. `Ok(None)` for kinds -/// it does not hold whole (those are written from their DWG record). -pub(crate) fn encode(o: &Object, ctx: &Ctx, ver: DwgVersion) -> Result>> { - let mut w = ObjW::new(ver, o.handle); - match &o.kind { - ObjectKind::Unsupported | ObjectKind::Failed(_) | ObjectKind::NewerKind(_) | ObjectKind::Damaged(_) => return Ok(None), - ObjectKind::NamedRecord(_) if !matches!(o.type_code, 0x41 | 0x43 | 0x45 | 0x39 | 0x35) => return Ok(None), - _ => {} - } - common(&mut w, o, ctx)?; - specific(&mut w, o, ctx)?; - Ok(Some(w.finish())) -} - -/// Type data, then the handles (common, then the type's own): one function per group of types. -fn specific(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - match &o.kind { - ObjectKind::Arc(..) - | ObjectKind::Attribute(..) - | ObjectKind::BlockBegin { .. } - | ObjectKind::BlockEnd - | ObjectKind::SeqEnd - | ObjectKind::Circle(..) - | ObjectKind::Ellipse(..) - | ObjectKind::Face3d(..) - | ObjectKind::Insert(..) - | ObjectKind::Line(..) - | ObjectKind::Point(..) - | ObjectKind::Solid(..) - | ObjectKind::Text(..) => specific_curves(w, o, ctx), - ObjectKind::LwPolyline(..) | ObjectKind::Polyline(..) | ObjectKind::Vertex(..) => specific_polylines(w, o, ctx), - ObjectKind::Dimension(..) - | ObjectKind::Hatch(..) - | ObjectKind::MText(..) - | ObjectKind::Spline(..) - | ObjectKind::Image(..) - | ObjectKind::Leader(..) - | ObjectKind::MLine(..) - | ObjectKind::PaperViewport(..) - | ObjectKind::Tolerance(..) - | ObjectKind::Xline(..) - | ObjectKind::Ray(..) - | ObjectKind::Wipeout(..) => specific_annotation(w, o, ctx), - _ => specific_records(w, o, ctx), - } -} - -fn specific_curves(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - let ver = w.ver; - let d = ctx.d; - match &o.kind { - ObjectKind::Line(l) => { - let z_zero = l.start.z == 0.0 && l.end.z == 0.0; - w.dat.b(z_zero); - w.dat.rd(l.start.x); - w.dat.dd(l.end.x, l.start.x); - w.dat.rd(l.start.y); - w.dat.dd(l.end.y, l.start.y); - if !z_zero { - w.dat.rd(l.start.z); - w.dat.dd(l.end.z, l.start.z); - } - w.dat.bt(l.thickness, ver); - w.dat.be(v3(l.extrusion), ver); - common_handles(w, o); - } - ObjectKind::Circle(c) => { - w.dat.bd3(v3(c.center)); - w.dat.bd(c.radius); - w.dat.bt(c.thickness, ver); - w.dat.be(v3(c.extrusion), ver); - common_handles(w, o); - } - ObjectKind::Arc(a) => { - w.dat.bd3(v3(a.center)); - w.dat.bd(a.radius); - w.dat.bt(a.thickness, ver); - w.dat.be(v3(a.extrusion), ver); - w.dat.bd(a.start_angle); - w.dat.bd(a.end_angle); - common_handles(w, o); - } - ObjectKind::Point(p) => { - w.dat.bd3(v3(p.position)); - w.dat.bt(p.thickness, ver); - w.dat.be(v3(p.extrusion), ver); - w.dat.bd(p.x_axis_angle); - common_handles(w, o); - } - ObjectKind::Ellipse(e) => { - w.dat.bd3(v3(e.center)); - w.dat.bd3(v3(e.major_axis)); - w.dat.bd3(v3(e.extrusion)); - w.dat.bd(e.axis_ratio); - w.dat.bd(e.start_param); - w.dat.bd(e.end_param); - common_handles(w, o); - } - ObjectKind::Solid(s) => { - w.dat.bt(s.thickness, ver); - w.dat.bd(s.elevation); - for c in s.corners { - w.dat.rd2(v2(c)); - } - w.dat.be(v3(s.extrusion), ver); - common_handles(w, o); - } - ObjectKind::Face3d(f) => { - let no_flags = f.invisible_edges == 0; - let z_zero = f.corners[0].z == 0.0; - w.dat.b(no_flags); - w.dat.b(z_zero); - w.dat.rd(f.corners[0].x); - w.dat.rd(f.corners[0].y); - if !z_zero { - w.dat.rd(f.corners[0].z); - } - for i in 1..4 { - let (p, c) = (f.corners[i - 1], f.corners[i]); - w.dat.dd(c.x, p.x); - w.dat.dd(c.y, p.y); - w.dat.dd(c.z, p.z); - } - if !no_flags { - w.dat.bs(f.invisible_edges); - } - common_handles(w, o); - } - ObjectKind::Text(t) => { - text_data(w, t); - common_handles(w, o); - w.h(Ref::HardPtr, t.style); - } - ObjectKind::Attribute(a) => { - text_data(w, &a.text); - if ver >= V::R2010 { - w.dat.rc(0); - } - if ver >= V::R2018 { - w.dat.rc(1); // single-line - } - w.tv(&a.tag); - w.dat.bs(a.field_length); - w.dat.rc(a.flags); - if ver >= V::R2007 { - w.dat.b(a.lock_position); - } - if a.is_definition { - if ver >= V::R2010 { - w.dat.rc(0); - } - w.tv(&a.prompt); - } - common_handles(w, o); - w.h(Ref::HardPtr, a.text.style); - } - ObjectKind::BlockBegin { name } => { - w.tv(name); - common_handles(w, o); - } - ObjectKind::BlockEnd | ObjectKind::SeqEnd => common_handles(w, o), - ObjectKind::Insert(ins) => { - w.dat.bd3(v3(ins.insertion)); - let s = ins.scale; - if s == Vec3::new(1.0, 1.0, 1.0) { - w.dat.bb(3); - } else if s.x == 1.0 { - w.dat.bb(1); - w.dat.dd(s.y, 1.0); - w.dat.dd(s.z, 1.0); - } else if s.y == s.x && s.z == s.x { - w.dat.bb(2); - w.dat.rd(s.x); - } else { - w.dat.bb(0); - w.dat.rd(s.x); - w.dat.dd(s.y, s.x); - w.dat.dd(s.z, s.x); - } - w.dat.bd(ins.rotation); - w.dat.bd3(v3(ins.extrusion)); - w.dat.b(ins.has_attribs); - let attribs: Vec = - if ins.attribs.is_empty() { d.insert_attributes(o).iter().map(|a| a.handle).collect() } else { ins.attribs.clone() }; - if ins.has_attribs { - w.dat.bl(attribs.len() as u32); - } - if let Some((cols, rows, cs, rs)) = ins.array { - w.dat.bs(cols); - w.dat.bs(rows); - w.dat.bd(cs); - w.dat.bd(rs); - } - common_handles(w, o); - w.h(Ref::HardPtr, ins.block_header); - if ins.has_attribs { - for a in attribs { - w.h(Ref::HardOwner, a); - } - w.h(Ref::HardOwner, ins.seqend); - } - } - other => { - return Err(Error::unsupported(format!("{} {}: writing {:?} is not supported", o.type_name, o.handle, std::mem::discriminant(other)))); - } - } - Ok(()) -} - -fn specific_polylines(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - let ver = w.ver; - let d = ctx.d; - match &o.kind { - ObjectKind::Vertex(v) => { - match v.kind { - VertexKind::Vertex2d => { - w.dat.rc(v.flags); - w.dat.bd3(v3(v.point)); - if v.start_width == v.end_width && v.start_width != 0.0 { - w.dat.bd(-v.start_width); - } else { - w.dat.bd(v.start_width); - w.dat.bd(v.end_width); - } - w.dat.bd(v.bulge); - if ver >= V::R2010 { - w.dat.bl(v.id); - } - w.dat.bd(v.tangent_dir); - } - VertexKind::PfaceFace => { - for f in v.face { - w.dat.bs(f as u16); - } - } - _ => { - w.dat.rc(v.flags); - w.dat.bd3(v3(v.point)); - } - } - common_handles(w, o); - } - ObjectKind::Polyline(p) => { - let verts: Vec = if p.vertices.is_empty() { - d.owned_by(o.handle).filter(|c| matches!(c.kind, ObjectKind::Vertex(_))).map(|c| c.handle).collect() - } else { - p.vertices.clone() - }; - match p.kind { - PolylineKind::Polyline2d => { - w.dat.bs(p.flags); - w.dat.bs(p.curve_type); - w.dat.bd(p.start_width); - w.dat.bd(p.end_width); - w.dat.bt(p.thickness, ver); - w.dat.bd(p.elevation); - w.dat.be(v3(p.extrusion), ver); - } - PolylineKind::Polyline3d => { - w.dat.rc(p.curve_type as u8); - w.dat.rc((p.flags & 1) as u8); - } - PolylineKind::PolyfaceMesh => { - let all = d.polyline_vertices(o); - let nv = all.iter().filter(|v| v.kind == VertexKind::PfaceVertex).count(); - w.dat.bs(nv as u16); - w.dat.bs((all.len() - nv) as u16); - } - PolylineKind::PolygonMesh => { - w.dat.bs(p.flags & !16); - w.dat.bs(p.curve_type); - for _ in 0..4 { - w.dat.bs(0); - } - } - } - w.dat.bl(verts.len() as u32); - common_handles(w, o); - for v in verts { - w.h(Ref::HardOwner, v); - } - w.h(Ref::HardOwner, p.seqend); - } - ObjectKind::LwPolyline(p) => { - let mut flags = p.flags & !(1 | 2 | 4 | 8 | 16 | 32 | 1024); - if p.extrusion != Vec3::Z { - flags |= 1; - } - if p.thickness != 0.0 { - flags |= 2; - } - if p.const_width != 0.0 { - flags |= 4; - } - if p.elevation != 0.0 { - flags |= 8; - } - let bulges = p.bulges.iter().any(|b| *b != 0.0); - if bulges { - flags |= 16; - } - if !p.widths.is_empty() { - flags |= 32; - } - if !p.vertex_ids.is_empty() { - flags |= 1024; - } - w.dat.bs(flags); - if flags & 4 != 0 { - w.dat.bd(p.const_width); - } - if flags & 8 != 0 { - w.dat.bd(p.elevation); - } - if flags & 2 != 0 { - w.dat.bd(p.thickness); - } - if flags & 1 != 0 { - w.dat.bd3(v3(p.extrusion)); - } - w.dat.bl(p.points.len() as u32); - if bulges { - w.dat.bl(p.points.len() as u32); - } - if flags & 1024 != 0 { - w.dat.bl(p.vertex_ids.len() as u32); - } - if flags & 32 != 0 { - w.dat.bl(p.widths.len() as u32); - } - let mut prev: Option = None; - for pt in &p.points { - match prev { - None => w.dat.rd2(v2(*pt)), - Some(q) => { - w.dat.dd(pt.x, q.x); - w.dat.dd(pt.y, q.y); - } - } - prev = Some(*pt); - } - if bulges { - for i in 0..p.points.len() { - w.dat.bd(p.bulge(i)); - } - } - for id in &p.vertex_ids { - w.dat.bl(*id); - } - for (a, b) in &p.widths { - w.dat.bd(*a); - w.dat.bd(*b); - } - common_handles(w, o); - } - other => { - return Err(Error::unsupported(format!("{} {}: writing {:?} is not supported", o.type_name, o.handle, std::mem::discriminant(other)))); - } - } - Ok(()) -} - -fn specific_annotation(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - let d = ctx.d; - let ver = w.ver; - match &o.kind { - ObjectKind::Spline(sp) => { - spline_data(w, sp); - common_handles(w, o); - } - ObjectKind::MText(m) => { - mtext_data(w, m, ctx.text_width); - common_handles(w, o); - w.h(Ref::HardPtr, m.style); - if ver >= V::R2018 { - w.h(Ref::HardPtr, Handle::NULL); // registered application - } - } - ObjectKind::Dimension(m) => { - dimension_data(w, o, m)?; - common_handles(w, o); - w.h(Ref::HardPtr, m.dimstyle); - w.h(Ref::HardPtr, m.block); - } - ObjectKind::Hatch(h) => { - hatch_data(w, h, d, ctx.hatch_lines); - common_handles(w, o); - for i in 0..h.paths.len() { - for s in h.sources.get(i).map(Vec::as_slice).unwrap_or_default() { - w.h(Ref::SoftPtr, *s); - } - } - } - ObjectKind::Xline(x) | ObjectKind::Ray(x) => { - w.dat.bd3(v3(x.base)); - w.dat.bd3(v3(x.direction)); - common_handles(w, o); - } - ObjectKind::Leader(l) => { - leader_data(w, l); - common_handles(w, o); - w.h(Ref::HardPtr, l.annotation); - w.h(Ref::HardPtr, l.dimstyle); - } - ObjectKind::MLine(m) => { - // §20.4.50, the mirror of `entities::mline`. - w.dat.bd(m.scale); - w.dat.rc(m.justification); - w.dat.bd3(v3(m.base)); - w.dat.bd3(v3(if m.extrusion == Vec3::ZERO { Vec3::Z } else { m.extrusion })); - w.dat.bs(m.flags); - w.dat.rc(m.lines_in_style); - w.dat.bs(m.vertices.len().min(usize::from(u16::MAX)) as u16); - for v in m.vertices.iter().take(usize::from(u16::MAX)) { - w.dat.bd3(v3(v.point)); - w.dat.bd3(v3(v.direction)); - w.dat.bd3(v3(v.miter)); - // Exactly one parameter list per element of the style. - for i in 0..usize::from(m.lines_in_style) { - let (seg, fill) = v.params.get(i).map(|(a, b)| (a.as_slice(), b.as_slice())).unwrap_or((&[], &[])); - w.dat.bs(seg.len().min(usize::from(u16::MAX)) as u16); - for x in seg.iter().take(usize::from(u16::MAX)) { - w.dat.bd(*x); - } - w.dat.bs(fill.len().min(usize::from(u16::MAX)) as u16); - for x in fill.iter().take(usize::from(u16::MAX)) { - w.dat.bd(*x); - } - } - } - common_handles(w, o); - w.h(Ref::HardPtr, m.style); - } - ObjectKind::Image(r) | ObjectKind::Wipeout(r) => { - // §20.4.80, the mirror of `entities::raster_image`. - w.dat.bl(r.class_version); - w.dat.bd3(v3(r.insertion)); - w.dat.bd3(v3(r.u)); - w.dat.bd3(v3(r.v)); - w.dat.rd2(v2(r.size)); - w.dat.bs(r.display); - w.dat.b(r.clipping); - w.dat.rc(r.brightness); - w.dat.rc(r.contrast); - w.dat.rc(r.fade); - if ver >= V::R2010 { - w.dat.b(r.clip_inside); - } - // A rectangle is two corners; anything else is a polygon. No - // boundary at all is the whole image, pixel centres at whole - // numbers (DXF reference, IMAGE group 14). - let whole = [Vec2::new(-0.5, -0.5), Vec2::new(r.size.x - 0.5, r.size.y - 0.5)]; - let clip: &[Vec2] = if r.clip.is_empty() { &whole } else { &r.clip }; - let rect = clip.len() == 2 && (r.clip_type == 1 || r.clip.is_empty()); - w.dat.bs(if rect { 1 } else { 2 }); - if !rect { - w.dat.bl(clip.len() as u32); - } - for p in clip { - w.dat.rd2(v2(*p)); - } - common_handles(w, o); - w.h(Ref::HardPtr, r.definition); - w.h(Ref::HardOwner, r.reactor); - } - ObjectKind::Tolerance(t) => { - // §20.4.49, the mirror of `entities::tolerance`. - if ver <= V::R14 { - let (short, height, gap) = t.r14.unwrap_or((0, 0.0, 0.0)); - w.dat.bs(short); - w.dat.bd(height); - w.dat.bd(gap); - } - w.dat.bd3(v3(t.insertion)); - w.dat.bd3(v3(t.x_direction)); - w.dat.bd3(v3(if t.extrusion == Vec3::ZERO { Vec3::Z } else { t.extrusion })); - w.tv(&t.text); - common_handles(w, o); - w.h(Ref::HardPtr, t.dimstyle); - } - ObjectKind::PaperViewport(v) => { - viewport_data(w, v); - common_handles(w, o); - if ver <= V::R14 { - w.h(Ref::HardPtr, Handle::NULL); - } else { - for h in &v.frozen_layers { - w.h(if ver >= V::R2004 { Ref::SoftPtr } else { Ref::HardPtr }, *h); - } - w.h(Ref::SoftPtr, v.clip_boundary); - if ver == V::R2000 { - w.h(Ref::HardPtr, Handle::NULL); - } - w.h(Ref::HardPtr, v.named_ucs); - w.h(Ref::HardPtr, v.base_ucs); - if ver >= V::R2007 { - w.h(Ref::SoftPtr, v.background); - w.h(Ref::HardPtr, v.visual_style); - w.h(Ref::SoftPtr, v.shade_plot); - w.h(Ref::HardOwner, v.sun); - } - } - } - other => { - return Err(Error::unsupported(format!("{} {}: writing {:?} is not supported", o.type_name, o.handle, std::mem::discriminant(other)))); - } - } - Ok(()) -} - -fn specific_records(w: &mut ObjW, o: &Object, ctx: &Ctx) -> Result<()> { - let ver = w.ver; - let d = ctx.d; - match &o.kind { - ObjectKind::Control(c) => { - w.dat.bl(c.entries.len() as u32); - // DIMSTYLE_CONTROL (R2000+) adds a count and as many hard - // pointers; AutoCAD 2027 points them at the styles again. - if o.type_code == 0x44 && ver >= V::R2000 { - w.dat.rc(c.entries.len().min(255) as u8); - } - common_handles(w, o); - for e in &c.entries { - w.h(Ref::SoftOwner, *e); - } - if o.type_code == 0x44 && ver >= V::R2000 { - for e in c.entries.iter().take(255) { - w.h(Ref::HardPtr, *e); - } - } - match o.type_code { - 0x30 => { - w.h(Ref::HardOwner, c.model_space); - w.h(Ref::HardOwner, c.paper_space); - } - 0x38 => { - let hv = crate::read::hvars::Hv::new(d); - w.h(Ref::HardOwner, hv.handle("LTYPE_BYBLOCK")); - w.h(Ref::HardOwner, hv.handle("LTYPE_BYLAYER")); - } - _ => {} - } - } - ObjectKind::BlockHeader(b) => { - block_header(w, o, b, d); - } - ObjectKind::Layer(l) => { - record_name(w, &l.name); - // Off is the flag word's 0x02 bit (clear): from R2004 the - // colour's index field, whose sign once marked it, is 0. - w.dat.bs(l.dwg_flags()); - w.cmc(l.color); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); // xref block - w.h(Ref::HardPtr, ctx.plot_style); - w.h(Ref::HardPtr, ctx.material); - w.h(Ref::HardPtr, l.linetype); - if ver >= V::R2013 { - w.h(Ref::HardPtr, Handle::NULL); - } - } - ObjectKind::Linetype(l) => { - record_name(w, &l.name); - linetype_body(w, l); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - for e in &l.elements { - w.h(Ref::HardPtr, e.style); - } - } - ObjectKind::NamedRecord(r) if o.type_code == 0x39 => { - record_name(w, &r.name); - linetype_body(w, &Linetype::default()); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - } - ObjectKind::TextStyle(t) => { - record_name(w, &t.name); - text_style_body(w, t); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - } - ObjectKind::NamedRecord(r) if o.type_code == 0x35 => { - record_name(w, &r.name); - text_style_body(w, &TextStyle { name: r.name.clone(), last_height: 0.2, font_file: "txt".into(), ..Default::default() }); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - } - ObjectKind::NamedRecord(r) if o.type_code == 0x43 => { - record_name(w, &r.name); - w.dat.rc(0); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - } - ObjectKind::NamedRecord(_) | ObjectKind::DimStyle(_) | ObjectKind::DimStyleRecord(_) if o.type_code == 0x45 => { - let name = d.record_name(o.handle).unwrap_or("").to_string(); - let v = (ctx.dimstyle_vars)(o); - record_name(w, &name); - dimstyle_body(w, &v); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - for h in [v.txsty, v.ldrblk, v.blk, v.blk1, v.blk2] { - w.h(Ref::HardPtr, h); - } - if ver >= V::R2007 { - for h in [v.ltype, v.ltex1, v.ltex2] { - w.h(Ref::HardPtr, h); - } - } - } - ObjectKind::NamedRecord(_) | ObjectKind::Viewport(_) if o.type_code == 0x41 => { - let v = (ctx.vport)(o); - record_name(w, &v.name); - vport_body(w, &v); - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - if ver >= V::R2007 { - w.h(Ref::SoftPtr, v.background); - w.h(Ref::HardPtr, v.visual_style); - w.h(Ref::HardOwner, v.sun); - } - w.h(Ref::HardPtr, v.named_ucs); - w.h(Ref::HardPtr, v.base_ucs); - } - ObjectKind::NonGraphic(NonGraphic::Groups(g)) => { - common_handles(w, o); - crate::read::styles::encode(w, g, d)?; - } - ObjectKind::NonGraphic(n) => nongraphic(w, o, n)?, - other => { - return Err(Error::unsupported(format!("{} {}: writing {:?} is not supported", o.type_name, o.handle, std::mem::discriminant(other)))); - } - } - Ok(()) -} - -fn text_data(w: &mut ObjW, t: &Text) { - let ver = w.ver; - let mut flags = 0u8; - if t.elevation == 0.0 { - flags |= 0x01; - } - if t.alignment == t.insertion { - flags |= 0x02; - } - if t.oblique == 0.0 { - flags |= 0x04; - } - if t.rotation == 0.0 { - flags |= 0x08; - } - if t.width_factor == 1.0 { - flags |= 0x10; - } - if t.generation == 0 { - flags |= 0x20; - } - if t.h_align == 0 { - flags |= 0x40; - } - if t.v_align == 0 { - flags |= 0x80; - } - w.dat.rc(flags); - if flags & 0x01 == 0 { - w.dat.rd(t.elevation); - } - w.dat.rd2(v2(t.insertion)); - if flags & 0x02 == 0 { - w.dat.dd(t.alignment.x, t.insertion.x); - w.dat.dd(t.alignment.y, t.insertion.y); - } - // AutoCAD writes a text's extrusion in full, even (0, 0, 1). - w.dat.b(false); - w.dat.bd3(v3(t.extrusion)); - w.dat.bt(t.thickness, ver); - if flags & 0x04 == 0 { - w.dat.rd(t.oblique); - } - if flags & 0x08 == 0 { - w.dat.rd(t.rotation); - } - w.dat.rd(t.height); - if flags & 0x10 == 0 { - w.dat.rd(t.width_factor); - } - w.tv(&t.value); - if flags & 0x20 == 0 { - w.dat.bs(t.generation); - } - if flags & 0x40 == 0 { - w.dat.bs(t.h_align); - } - if flags & 0x80 == 0 { - w.dat.bs(t.v_align); - } -} - -fn mtext_data(w: &mut ObjW, m: &MText, text_width: &dyn Fn(&str) -> f64) { - let ver = w.ver; - w.dat.bd3(v3(m.insertion)); - w.dat.bd3(v3(m.extrusion)); - w.dat.bd3(v3(m.x_axis)); - w.dat.bd(m.rect_width); - if ver >= V::R2007 { - w.dat.bd(m.rect_height); - } - w.dat.bd(m.text_height); - w.dat.bs(m.attachment); - w.dat.bs(m.drawing_dir); - let (ext_h, ext_w) = mtext_extents(m, text_width); - w.dat.bd(ext_h); - w.dat.bd(ext_w); - w.tv(&m.contents); - w.dat.bs(if m.linespacing_exact { 2 } else { 1 }); // 1 at least, 2 exactly - w.dat.bd(m.linespacing_factor); - w.dat.b(false); - if ver >= V::R2004 { - w.dat.bl(0); // no background - } - if ver >= V::R2018 { - w.dat.b(true); // not annotative - w.dat.bs(4); - w.dat.b(true); - w.dat.bl(m.attachment as u32); - w.dat.bd3(v3(m.x_axis)); - w.dat.bd3(v3(m.insertion)); - w.dat.bd(m.rect_width); - w.dat.bd(m.rect_height); - w.dat.bd(ext_w); - w.dat.bd(ext_h); - w.dat.bs(0); // no columns - } -} - -/// The text's extents (height, width) as the writing program's font sets -/// it: one line per paragraph. AutoCAD stores its own font's extents here -/// and measures again when it regenerates the text. -fn mtext_extents(m: &MText, text_width: &dyn Fn(&str) -> f64) -> (f64, f64) { - let plain = crate::read::text::strip_mtext(&m.contents); - let lines: Vec<&str> = plain.split('\n').collect(); - let n = lines.len().max(1) as f64; - let widest = lines.iter().map(|l| text_width(l)).fold(0.0, f64::max); - let h = m.text_height * (1.0 + (n - 1.0) * 1.6667 * m.linespacing_factor); - (h, widest * m.text_height) -} - -fn dimension_data(w: &mut ObjW, o: &Object, m: &Dimension) -> Result<()> { - let ver = w.ver; - if ver >= V::R2010 { - w.dat.rc(0); - } - w.dat.bd3(v3(m.extrusion)); - w.dat.rd2(v2(m.text_midpoint)); - w.dat.bd(m.elevation); - w.dat.rc(m.flags); - w.tv(&m.user_text); - w.dat.bd(m.text_rotation); - w.dat.bd(m.horizontal_direction); - w.dat.bd3(v3(m.insert_scale)); - w.dat.bd(m.insert_rotation); - w.dat.bs(m.attachment); - w.dat.bs(1); - w.dat.bd(1.0); - w.dat.bd(m.measurement); - if ver >= V::R2007 { - w.dat.b(false); - w.dat.b(false); - w.dat.b(false); - } - w.dat.rd2(v2(m.clone_insertion)); - let code = o.type_code; - match m.kind { - DimensionKind::Ordinate => { - w.dat.bd3(v3(m.pt10)); - w.dat.bd3(v3(m.pt13)); - w.dat.bd3(v3(m.pt14)); - w.dat.rc(0); - } - DimensionKind::Linear => { - w.dat.bd3(v3(m.pt13)); - w.dat.bd3(v3(m.pt14)); - w.dat.bd3(v3(m.pt10)); - w.dat.bd(m.ext_line_rotation); - w.dat.bd(m.dim_rotation); - } - DimensionKind::Aligned => { - w.dat.bd3(v3(m.pt13)); - w.dat.bd3(v3(m.pt14)); - w.dat.bd3(v3(m.pt10)); - w.dat.bd(m.ext_line_rotation); - } - DimensionKind::Angular3Pt => { - w.dat.bd3(v3(m.pt10)); - w.dat.bd3(v3(m.pt13)); - w.dat.bd3(v3(m.pt14)); - w.dat.bd3(v3(m.pt15)); - } - DimensionKind::Angular2Line => { - w.dat.rd2(v2(m.pt16)); - w.dat.bd3(v3(m.pt13)); - w.dat.bd3(v3(m.pt14)); - w.dat.bd3(v3(m.pt15)); - w.dat.bd3(v3(m.pt10)); - } - DimensionKind::Radius | DimensionKind::Diameter => { - w.dat.bd3(v3(m.pt10)); - w.dat.bd3(v3(m.pt15)); - w.dat.bd(m.leader_length); - } - } - let _ = code; - Ok(()) -} - -fn spline_data(w: &mut ObjW, sp: &Spline) { - let ver = w.ver; - let fit = !sp.fit_points.is_empty() && sp.control_points.is_empty(); - let scenario = if fit { 2 } else { 1 }; - w.dat.bl(scenario); - if ver >= V::R2013 { - let mut flags1 = 0u32; - if sp.closed { - flags1 |= 4; - } - if fit { - flags1 |= 1; - } - w.dat.bl(flags1); - w.dat.bl(0); - } - w.dat.bl(sp.degree); - if fit { - w.dat.bd(sp.fit_tolerance); - w.dat.bd3(v3(sp.start_tangent)); - w.dat.bd3(v3(sp.end_tangent)); - w.dat.bl(sp.fit_points.len() as u32); - } else { - w.dat.b(sp.rational); - w.dat.b(sp.closed); - w.dat.b(sp.periodic); - w.dat.bd(1e-10); - w.dat.bd(1e-10); - w.dat.bl(sp.knots.len() as u32); - w.dat.bl(sp.control_points.len() as u32); - w.dat.b(!sp.weights.is_empty()); - } - if !fit { - for k in &sp.knots { - w.dat.bd(*k); - } - for (i, p) in sp.control_points.iter().enumerate() { - w.dat.bd3(v3(*p)); - if !sp.weights.is_empty() { - w.dat.bd(sp.weights.get(i).copied().unwrap_or(1.0)); - } - } - } else { - for p in &sp.fit_points { - w.dat.bd3(v3(*p)); - } - } -} - -fn hatch_data(w: &mut ObjW, h: &Hatch, d: &Drawing, library: Option<&HatchLibrary<'_>>) { - let ver = w.ver; - if ver >= V::R2004 { - w.dat.bl(h.is_gradient as u32); - w.dat.bl(0); - w.dat.bd(0.0); - w.dat.bd(0.0); - w.dat.bl(0); - w.dat.bd(0.0); - w.dat.bl(0); - w.tv(""); - } - w.dat.bd(h.elevation); - w.dat.bd3(v3(h.extrusion)); - w.tv(&h.pattern_name); - w.dat.b(h.solid_fill); - w.dat.b(h.associative); - w.dat.bl(h.paths.len() as u32); - for (i, p) in h.paths.iter().enumerate() { - match p { - HatchPath::Edges { flags, edges } => { - // Bit 4 (made by picking) would call for a pixel size, - // which the model does not keep. - w.dat.bl(*flags & !(2 | 4)); - w.dat.bl(edges.len() as u32); - for e in edges { - match e { - HatchEdge::Line { a, b } => { - w.dat.rc(1); - w.dat.rd2(v2(*a)); - w.dat.rd2(v2(*b)); - } - HatchEdge::Arc { center, radius, start, end, ccw } => { - w.dat.rc(2); - w.dat.rd2(v2(*center)); - w.dat.bd(*radius); - w.dat.bd(*start); - w.dat.bd(*end); - w.dat.b(*ccw); - } - HatchEdge::Ellipse { center, major, ratio, start, end, ccw } => { - w.dat.rc(3); - w.dat.rd2(v2(*center)); - w.dat.rd2(v2(*major)); - w.dat.bd(*ratio); - w.dat.bd(*start); - w.dat.bd(*end); - w.dat.b(*ccw); - } - HatchEdge::Spline { degree, knots, control_points, weights } => { - w.dat.rc(4); - w.dat.bl(*degree); - w.dat.b(!weights.is_empty()); - w.dat.b(false); - w.dat.bl(knots.len() as u32); - w.dat.bl(control_points.len() as u32); - for k in knots { - w.dat.bd(*k); - } - for (i, c) in control_points.iter().enumerate() { - w.dat.rd2(v2(*c)); - if !weights.is_empty() { - w.dat.bd(weights.get(i).copied().unwrap_or(1.0)); - } - } - if ver >= V::R2010 { - w.dat.bl(0); - } - } - } - } - } - HatchPath::Polyline { flags, closed, vertices } => { - w.dat.bl((*flags | 2) & !4); - let bulges = vertices.iter().any(|(_, b)| *b != 0.0); - w.dat.b(bulges); - w.dat.b(*closed); - w.dat.bl(vertices.len() as u32); - for (p, b) in vertices { - w.dat.rd2(v2(*p)); - if bulges { - w.dat.bd(*b); - } - } - } - } - // Boundary objects; their handles follow the common handles. - w.dat.bl(h.sources.get(i).map_or(0, Vec::len) as u32); - } - w.dat.bs(h.style); - w.dat.bs(h.pattern_type); - if !h.solid_fill { - w.dat.bd(h.pattern_angle); - w.dat.bd(h.pattern_scale); - w.dat.b(h.pattern_double); - // The line families: as stored, or from the program's library for - // a hatch that has none, so other programs draw the same pattern. - let lines = match library { - Some(library) if h.pattern_lines.is_empty() => library(d, h), - _ => h.pattern_lines.clone(), - }; - w.dat.bs(lines.len().min(u16::MAX as usize) as u16); - for l in lines.iter().take(u16::MAX as usize) { - w.dat.bd(l.angle); - w.dat.bd2(v2(l.base)); - w.dat.bd2(v2(l.offset)); - w.dat.bs(l.dashes.len().min(u16::MAX as usize) as u16); - for d in l.dashes.iter().take(u16::MAX as usize) { - w.dat.bd(*d); - } - } - } - w.dat.bl(h.seed_points.len() as u32); - for p in &h.seed_points { - w.dat.rd2(v2(*p)); - } -} - -/// LEADER (§20.4.47), the mirror of `entities::leader`. -fn leader_data(w: &mut ObjW, l: &Leader) { - let ver = w.ver; - w.dat.b(l.unknown.0); - w.dat.bs(l.annotation_type); - w.dat.bs(l.spline as u16); - w.dat.bl(l.vertices.len() as u32); - for p in &l.vertices { - w.dat.bd3(v3(*p)); - } - w.dat.bd3(v3(l.origin)); - w.dat.bd3(v3(if l.extrusion == Vec3::ZERO { Vec3::Z } else { l.extrusion })); - w.dat.bd3(v3(l.x_direction)); - w.dat.bd3(v3(l.block_offset)); - if ver >= V::R14 { - w.dat.bd3(v3(l.annotation_offset)); - } - if ver <= V::R14 { - w.dat.bd(0.0); - } - w.dat.bd(l.text_height); - w.dat.bd(l.text_width); - w.dat.b(l.hookline_on_x); - w.dat.b(l.arrowhead); - if ver <= V::R14 { - w.dat.bs(0); - w.dat.bd(0.0); - w.dat.b(false); - w.dat.b(false); - w.dat.bs(0); - w.dat.bs(0); - w.dat.b(false); - w.dat.b(false); - } else { - w.dat.bs(l.unknown.1); - w.dat.b(l.unknown.2); - w.dat.b(l.unknown.3); - } -} - -/// VIEWPORT (§20.4.38), the mirror of `entities::viewport`. -fn viewport_data(w: &mut ObjW, v: &PaperViewport) { - let ver = w.ver; - w.dat.bd3(v3(v.center)); - w.dat.bd(v.width); - w.dat.bd(v.height); - if ver >= V::R2000 { - w.dat.bd3(v3(v.view_target)); - w.dat.bd3(v3(v.view_direction)); - w.dat.bd(v.twist); - w.dat.bd(v.view_height); - w.dat.bd(v.lens); - w.dat.bd(v.front_clip); - w.dat.bd(v.back_clip); - w.dat.bd(v.snap_angle); - w.dat.rd2(v2(v.view_center)); - w.dat.rd2(v2(v.snap_base)); - w.dat.rd2(v2(v.snap_spacing)); - w.dat.rd2(v2(v.grid_spacing)); - w.dat.bs(v.circle_zoom); - if ver >= V::R2007 { - w.dat.bs(v.grid_major); - } - w.dat.bl(v.frozen_layers.len() as u32); - w.dat.bl(v.status); - w.tv(&v.style_sheet); - w.dat.rc(v.render_mode); - w.dat.b(v.ucs_at_origin); - w.dat.b(v.ucs_per_viewport); - w.dat.bd3(v3(v.ucs_origin)); - w.dat.bd3(v3(v.ucs_x)); - w.dat.bd3(v3(v.ucs_y)); - w.dat.bd(v.ucs_elevation); - w.dat.bs(v.ucs_ortho_type); - if ver >= V::R2004 { - w.dat.bs(v.shade_plot_mode); - } - if ver >= V::R2007 { - w.dat.b(v.default_lights); - w.dat.rc(v.lighting_type); - w.dat.bd(v.brightness); - w.dat.bd(v.contrast); - w.cmc(v.ambient); - } - } -} - -fn block_header(w: &mut ObjW, o: &Object, b: &BlockHeader, d: &Drawing) { - let ver = w.ver; - record_name(w, &b.name); - w.dat.b(b.anonymous); - w.dat.b(b.has_attribs); - w.dat.b(b.is_xref); - w.dat.b(b.is_overlaid); - w.dat.b(false); // loaded - let lists = !b.is_xref && !b.is_overlaid; - let entities: Vec = - if !b.entities.is_empty() { b.entities.clone() } else { d.block_entities(o.handle).iter().map(|e| e.handle).collect() }; - if ver >= V::R2004 && lists { - w.dat.bl(entities.len() as u32); - } - w.dat.bd3(v3(b.base_point)); - w.tv(&b.xref_path); - let inserts: Vec = - d.objects.values().filter(|i| matches!(&i.kind, ObjectKind::Insert(ins) if ins.block_header == o.handle)).map(|i| i.handle).collect(); - for _ in &inserts { - w.dat.rc(1); - } - w.dat.rc(0); - w.tv(&b.description); - w.dat.bl(0); // no preview - if ver >= V::R2007 { - w.dat.bs(b.insert_units); - w.dat.b(!b.not_explodable); - w.dat.rc(0); // scaling: any - } - common_handles(w, o); - w.h(Ref::HardPtr, Handle::NULL); - w.h(Ref::HardOwner, b.block_entity); - if lists { - for e in &entities { - w.h(Ref::HardOwner, *e); - } - } - w.h(Ref::HardOwner, b.endblk); - for i in inserts { - w.h(Ref::SoftPtr, i); - } - w.h(Ref::HardPtr, b.layout); -} - -fn linetype_body(w: &mut ObjW, l: &Linetype) { - w.tv(&l.description); - w.dat.bd(l.pattern_length); - w.dat.rc(b'A'); - w.dat.rc(l.elements.len() as u8); - let has_text = l.elements.iter().any(|e| e.complex & 2 != 0); - let mut area = vec![0u8; 512]; - let mut at = 0usize; - for e in &l.elements { - w.dat.bd(e.length); - let shape = if e.complex & 2 != 0 { - let pos = at; - for u in e.text.encode_utf16() { - if at + 2 < area.len() { - area[at..at + 2].copy_from_slice(&u.to_le_bytes()); - at += 2; - } - } - at += 2; - pos as u16 - } else { - e.shape - }; - w.dat.bs(shape); - w.dat.rd(e.offset.x); - w.dat.rd(e.offset.y); - w.dat.bd(e.scale); - w.dat.bd(e.rotation); - w.dat.bs(e.complex); - } - if has_text { - w.dat.raw_bytes(&area); - } -} - -fn text_style_body(w: &mut ObjW, t: &TextStyle) { - w.dat.b(t.flags & 4 != 0); - w.dat.b(t.flags & 1 != 0); - w.dat.bd(t.height); - w.dat.bd(t.width_factor); - w.dat.bd(t.oblique); - w.dat.rc(t.generation as u8); - w.dat.bd(t.last_height); - w.tv(&t.font_file); - w.tv(&t.bigfont_file); -} - -fn dimstyle_body(w: &mut ObjW, v: &DimVars) { - let ver = w.ver; - w.tv(&v.post); - w.tv(&v.apost); - for x in [v.scale, v.asz, v.exo, v.dli, v.exe, v.rnd, v.dle, v.tp, v.tm] { - w.dat.bd(x); - } - if ver >= V::R2007 { - w.dat.bd(v.fxl); - w.dat.bd(v.jogang); - w.dat.bs(v.tfill); - w.cmc(v.tfillclr); - } - for b in [v.tol, v.lim, v.tih, v.toh, v.se1, v.se2] { - w.dat.b(b); - } - w.dat.bs(v.tad); - w.dat.bs(v.zin); - w.dat.bs(v.azin); - if ver >= V::R2007 { - w.dat.bs(v.arcsym); - } - for x in [v.txt, v.cen, v.tsz, v.altf, v.lfac, v.tvp, v.tfac, v.gap, v.altrnd] { - w.dat.bd(x); - } - w.dat.b(v.alt); - w.dat.bs(v.altd); - for b in [v.tofl, v.sah, v.tix, v.soxd] { - w.dat.b(b); - } - w.cmc(v.clrd); - w.cmc(v.clre); - w.cmc(v.clrt); - for x in [v.adec, v.dec, v.tdec, v.altu, v.alttd, v.aunit, v.frac, v.lunit, v.dsep, v.tmove, v.just] { - w.dat.bs(x); - } - w.dat.b(v.sd1); - w.dat.b(v.sd2); - for x in [v.tolj, v.tzin, v.altz, v.alttz] { - w.dat.bs(x); - } - w.dat.b(v.upt); - w.dat.bs(v.fit); - if ver >= V::R2007 { - w.dat.b(v.fxlon); - } - if ver >= V::R2010 { - w.dat.b(v.txtdirection); - w.dat.bd(v.altmzf); - w.tv(&v.altmzs); - w.dat.bd(v.mzf); - w.tv(&v.mzs); - } - w.dat.bs(v.lwd as u16); - w.dat.bs(v.lwe as u16); - w.dat.b(v.flag_bit); -} - -fn vport_body(w: &mut ObjW, v: &Vport) { - let ver = w.ver; - w.dat.bd(v.view_height); - w.dat.bd(v.aspect * v.view_height); - w.dat.rd2(v2(v.center)); - w.dat.bd3(v3(v.target)); - w.dat.bd3(v3(v.direction)); - w.dat.bd(v.twist); - w.dat.bd(v.lens); - w.dat.bd(v.front_clip); - w.dat.bd(v.back_clip); - let m = v.view_mode; - w.dat.b(m & 1 != 0); - w.dat.b(m & 2 != 0); - w.dat.b(m & 4 != 0); - w.dat.b(m & 16 == 0); - w.dat.rc(v.render_mode); - if ver >= V::R2007 { - w.dat.b(v.default_lights); - w.dat.rc(v.lighting_type); - w.dat.bd(v.brightness); - w.dat.bd(v.contrast); - w.cmc(v.ambient); - } - w.dat.rd2(v2(v.lower_left)); - w.dat.rd2(v2(v.upper_right)); - w.dat.b(m & 8 != 0); - w.dat.bs(v.circle_zoom); - w.dat.b(v.fast_zoom); - w.dat.bits(v.ucsicon as u64 & 3, 2); - w.dat.b(v.grid_on); - w.dat.rd2(v2(v.grid_spacing)); - w.dat.b(v.snap_on); - w.dat.b(v.snap_style); - w.dat.bs(v.snap_isopair); - w.dat.bd(v.snap_rotation); - w.dat.rd2(v2(v.snap_base)); - w.dat.rd2(v2(v.snap_spacing)); - w.dat.b(v.unknown_bit); - w.dat.b(v.ucs_per_viewport); - w.dat.bd3(v3(v.ucs_origin)); - w.dat.bd3(v3(v.ucs_x)); - w.dat.bd3(v3(v.ucs_y)); - w.dat.bd(v.ucs_elevation); - w.dat.bs(v.ucs_ortho_type); - if ver >= V::R2007 { - w.dat.bs(v.grid_flags); - w.dat.bs(v.grid_major); - } -} - -/// The XRECORD data bytes (spec §20.4.104): each item's group code, then -/// its value in the size its code takes, strings as UTF-16 from R2007. -fn xrecord_bytes(items: &[(u16, XrValue)], ver: DwgVersion) -> Vec { - let mut b = Vec::new(); - for (code, v) in items { - b.extend_from_slice(&code.to_le_bytes()); - match v { - XrValue::Str(s) => { - if ver.has_string_stream() { - let units: Vec = s.encode_utf16().collect(); - b.extend_from_slice(&(units.len() as u16).to_le_bytes()); - for u in units { - b.extend_from_slice(&u.to_le_bytes()); - } - } else { - // A 16-bit length, the code page, the bytes. - let bytes: Vec = s.chars().map(|c| c as u32 as u8).collect(); - let n = bytes.len().min(usize::from(u16::MAX)); - b.extend_from_slice(&(n as u16).to_le_bytes()); - b.push(30); - b.extend_from_slice(&bytes[..n]); - } - } - XrValue::Point(p) => { - for c in p.to_array() { - b.extend_from_slice(&c.to_le_bytes()); - } - } - XrValue::Real(r) => b.extend_from_slice(&r.to_le_bytes()), - XrValue::Int8(i) => b.push(*i as u8), - XrValue::Int16(i) => b.extend_from_slice(&i.to_le_bytes()), - XrValue::Int32(i) => b.extend_from_slice(&i.to_le_bytes()), - XrValue::Int64(i) => b.extend_from_slice(&i.to_le_bytes()), - XrValue::Bool(v) => b.push(*v as u8), - XrValue::Bytes(x) => { - b.push(x.len().min(255) as u8); - b.extend_from_slice(&x[..x.len().min(255)]); - } - XrValue::Handle(h) => b.extend_from_slice(&h.0.to_le_bytes()), - } - } - b -} - -/// DWG keeps the MLINESTYLE flag bits in a different order from DXF 70. -fn mline_flags_to_dwg(dxf: u16) -> u16 { - crate::read::nongraphic::mline_flags_to_dwg(dxf) -} - -/// The non-graphical objects (the mirror of `dwg::nongraphic::decode`): -/// type data, the common handles, then the type's own handles, coded as -/// AutoCAD 2027 codes them. -fn nongraphic(w: &mut ObjW, o: &Object, n: &NonGraphic) -> Result<()> { - let ver = w.ver; - match n { - // Written by styles::encode, which `specific` calls instead. - NonGraphic::Groups(_) => return Err(Error::format("style object reached the wrong encoder")), - NonGraphic::Dictionary(d) => { - w.dat.bl(d.entries.len() as u32); - w.dat.bs(d.cloning); - w.dat.rc(d.hard_owner); - for (k, _) in &d.entries { - w.tv(k); - } - common_handles(w, o); - // Entries are soft-owner references even in a dictionary that - // owns them hard (DXF 280 = 1, entries under 360): AutoCAD - // 2027 codes both kinds 2. - for (_, h) in &d.entries { - w.h(Ref::SoftOwner, *h); - } - if let Some(def) = d.default { - w.h(Ref::HardPtr, def); - } - } - NonGraphic::XRecord(x) => { - let bytes = xrecord_bytes(&x.items, ver); - w.dat.bl(bytes.len() as u32); - w.dat.raw_bytes(&bytes); - w.dat.bs(x.cloning); - common_handles(w, o); - } - NonGraphic::Placeholder => common_handles(w, o), - NonGraphic::DictionaryVar { schema, value } => { - w.dat.rc(*schema); - w.tv(value); - common_handles(w, o); - } - NonGraphic::Scale(s) => { - w.dat.bs(s.flag); - w.tv(&s.name); - w.dat.bd(s.paper_units); - w.dat.bd(s.drawing_units); - w.dat.b(s.unit_scale); - common_handles(w, o); - } - NonGraphic::Layout(l) => { - let p = &l.plot; - w.tv(&p.page_setup_name); - w.tv(&p.printer); - w.dat.bs(p.flags); - for m in p.margins { - w.dat.bd(m); - } - w.dat.bd(p.paper_width); - w.dat.bd(p.paper_height); - w.tv(&p.paper_size); - w.dat.bd2(v2(p.origin)); - w.dat.bs(p.paper_units); - w.dat.bs(p.rotation); - w.dat.bs(p.plot_type); - w.dat.bd2(v2(p.window_min)); - w.dat.bd2(v2(p.window_max)); - if ver <= V::R2000 { - w.tv(""); - } - w.dat.bd(p.real_world_units); - w.dat.bd(p.drawing_units); - w.tv(&p.style_sheet); - w.dat.bs(p.scale_type); - w.dat.bd(p.scale_factor); - w.dat.bd2(v2(p.image_origin)); - if ver >= V::R2004 { - w.dat.bs(p.shade_plot_mode); - w.dat.bs(p.shade_plot_res_level); - w.dat.bs(p.shade_plot_custom_dpi); - } - w.tv(&l.name); - w.dat.bl(l.tab_order); - w.dat.bs(l.flags); - w.dat.bd3(v3(l.ucs_origin)); - w.dat.rd2(v2(l.limmin)); - w.dat.rd2(v2(l.limmax)); - w.dat.bd3(v3(l.insbase)); - w.dat.bd3(v3(l.ucs_x)); - w.dat.bd3(v3(l.ucs_y)); - w.dat.bd(l.elevation); - w.dat.bs(l.ortho_type); - w.dat.bd3(v3(l.extmin)); - w.dat.bd3(v3(l.extmax)); - if ver >= V::R2004 { - w.dat.bl(l.viewports.len() as u32); - } - common_handles(w, o); - if ver >= V::R2004 { - w.h(Ref::HardPtr, p.plot_view); - } - if ver >= V::R2007 { - w.h(Ref::SoftPtr, p.visual_style); - } - w.h(Ref::SoftPtr, l.block); - w.h(Ref::SoftPtr, l.last_viewport); - w.h(Ref::HardPtr, l.base_ucs); - w.h(Ref::HardPtr, l.named_ucs); - if ver >= V::R2004 { - for h in &l.viewports { - w.h(Ref::SoftPtr, *h); - } - } - } - NonGraphic::MLineStyle(m) => { - w.tv(&m.name); - w.tv(&m.description); - w.dat.bs(mline_flags_to_dwg(m.flags)); - w.cmc(m.fill_color); - w.dat.bd(m.start_angle); - w.dat.bd(m.end_angle); - w.dat.rc(m.elements.len().min(255) as u8); - for e in m.elements.iter().take(255) { - w.dat.bd(e.offset); - w.cmc(e.color); - if ver < V::R2018 { - w.dat.bs(e.linetype_index as u16); - } - } - common_handles(w, o); - if ver >= V::R2018 { - for e in m.elements.iter().take(255) { - w.h(Ref::HardPtr, e.linetype); - } - } - } - } - Ok(()) -} diff --git a/crates/dwg/src/write/sections.rs b/crates/dwg/src/write/sections.rs deleted file mode 100644 index 25de79c3..00000000 --- a/crates/dwg/src/write/sections.rs +++ /dev/null @@ -1,618 +0,0 @@ -//! The sections around the objects: AcDb:Header (spec chapter 9), -//! AcDb:Classes (chapter 10), AcDb:Handles (chapter 23), AcDb:AuxHeader -//! (chapter 27), AcDb:Template (22), AcDb:ObjFreeSpace (21), -//! AcDb:RevHistory (18), AcDb:SummaryInfo (13), AcDb:Preview (14) and -//! AcDb:AppInfo (16), in the R2018 forms AutoCAD 2027 writes them. - -use crate::bits::BitWriter; -use crate::crc::crc16; -use crate::read::geom::{Vec2, Vec3}; -use crate::read::header::{self, VarKind}; -use crate::read::hvars::Hv; -use crate::read::model::{Color, Drawing, ObjectKind}; -use crate::read::section::{CLASSES_END, CLASSES_START, HEADER_END, HEADER_START}; -use crate::read::version::DwgVersion as V; -use crate::read::version::DwgVersion; - -/// A body of bit fields with an R2007+ string stream and handle stream, -/// laid out like an object: main data, strings, string-stream size and -/// flag, then the handles. -pub(crate) struct Streams3 { - pub dat: BitWriter, - pub strs: BitWriter, - pub hdl: BitWriter, -} - -impl Streams3 { - fn new() -> Self { - Streams3 { dat: BitWriter::new(), strs: BitWriter::new(), hdl: BitWriter::new() } - } - - /// The body: RL end-of-data bit (counted from the body's start), main - /// data, strings, their size and the presence bit, then the handles. - /// `pad` fills the last byte. - fn body(self, pad: bool) -> Vec { - let mut w = BitWriter::new(); - w.rl(0); // patched below - w.append(&self.dat); - let n = self.strs.position(); - w.append(&self.strs); - if n >= 0x8000 { - w.rs((n >> 15) as u16); - w.rs((n & 0x7FFF) as u16 | 0x8000); - } else { - w.rs(n as u16); - } - w.b(true); - let endbit = w.position(); - w.append(&self.hdl); - while !w.position().is_multiple_of(8) { - w.b(pad); - } - let mut out = w.into_bytes(); - out[..4].copy_from_slice(&(endbit as u32).to_le_bytes()); - out - } -} - -/// Wrap a body in sentinels: size, high size (R2010+), body, CRC. -fn wrap(start: &[u8; 16], end: &[u8; 16], body: &[u8], ver: DwgVersion) -> Vec { - let mut out = start.to_vec(); - let from = out.len(); - out.extend_from_slice(&(body.len() as u32).to_le_bytes()); - if ver >= V::R2010 { - out.extend_from_slice(&0u32.to_le_bytes()); - } - out.extend_from_slice(body); - let crc = crc16(0xC0C1, &out[from..]); - out.extend_from_slice(&crc.to_le_bytes()); - out.extend_from_slice(end); - out -} - -fn julian(v: f64) -> (u32, u32) { - let day = v.floor(); - let ms = ((v - day) * 86_400_000.0).round(); - (day as u32, ms as u32) -} - -/// Default values of the header variables for a drawing that has none -/// (AutoCAD's own defaults, as an imperial drawing carries them). -pub(crate) fn default_text(name: &str) -> &'static str { - match name { - "UNKNOWN_BD_412148564080" => "412148564080", - "UNKNOWN_BD_1A" | "UNKNOWN_BD_1B" | "UNKNOWN_BD_1C" => "1", - "UNKNOWN_TV_1" => "\"m\"", - // The spec gives 24; AutoCAD writes 0 in every file of the corpus. - "UNKNOWN_BL_24" => "0", - // Undocumented longs AutoCAD writes with the same values in every - // file of the corpus, 2004 to 2018, whatever the drawing. - "UNKNOWN_BL_R2004_1" | "UNKNOWN_BL_R2004_6" => "808464432", - "UNKNOWN_BL_R2004_2" | "UNKNOWN_BL_R2004_5" => "486539264", - "UNKNOWN_BL_R2004_3" | "UNKNOWN_BL_R2004_4" => "1295003696", - "MENUNAME" => "\".\"", - "DIMASO" | "DIMSHO" | "REGENMODE" | "FILLMODE" | "PSLTSCALE" | "USRTIMER" | "WORLDVIEW" | "TILEMODE" | "VISRETAIN" | "DIMTIH" | "DIMTOH" - | "CAMERADISPLAY" => "", - "PROXYGRAPHICS" | "ATTMODE" | "SHOWHIST" | "LOFTNORMALS" | "LIGHTGLYPHDISPLAY" | "TILEMODELIGHTSYNCH" | "HIDETEXT" | "DIMTOLJ" => "1", - "TREEDEPTH" => "3020", - "LUNITS" | "DIMALTD" | "DIMALTU" | "DIMALTTD" | "DIMLUNIT" | "XCLIPFRAME" | "DIMASSOC" | "DWFFRAME" => "2", - "LUPREC" | "DIMDEC" | "DIMTDEC" => "4", - "SPLINESEGS" | "ISOLINES" => "8", - "SURFU" | "SURFV" | "SURFTYPE" | "SURFTAB1" | "SURFTAB2" | "SPLINETYPE" => "6", - "SHADEDGE" | "DIMATFIT" => "3", - "SHADEDIF" | "TSTACKSIZE" => "70", - "MAXACTVP" => "64", - "TEXTQLTY" => "50", - "LTSCALE" | "CMLSCALE" | "CELTSCALE" | "DIMSCALE" | "DIMLFAC" | "DIMTFAC" | "DIMFXL" | "UNKNOWN_BD_R2007_1" => "1", - "TEXTSIZE" => "0.2", - "TRACEWID" => "0.05", - "SKETCHINC" => "0.1", - "FACETRES" => "0.5", - "PEXTMIN" | "EXTMIN" => "(100000000000000000000, 100000000000000000000, 100000000000000000000)", - "PEXTMAX" | "EXTMAX" => "(-100000000000000000000, -100000000000000000000, -100000000000000000000)", - "PLIMMAX" | "LIMMAX" => "(12, 9)", - "PUCSXDIR" | "UCSXDIR" => "(1, 0, 0)", - "PUCSYDIR" | "UCSYDIR" => "(0, 1, 0)", - "DIMASZ" | "DIMEXE" | "DIMTXT" => "0.18", - "DIMEXO" => "0.0625", - "DIMDLI" => "0.38", - "DIMCEN" | "DIMGAP" => "0.09", - "DIMALTF" => "25.4", - "DIMJOGANG" => "0.7853981633974483", - "DIMDSEP" => "46", - "DIMLWD" | "DIMLWE" => "-2", - "DIMALTMZF" | "DIMMZF" => "100", - "FLAGS" => "10781", - "SORTENTS" => "127", - "OBSCUREDCOLOR" | "INTERSECTIONCOLOR" => "257", - "TSTACKALIGN" => "1", - "UNKNOWN_BL_R2007_2" => "10", - "STEPSPERSEC" | "3DDWFPREC" => "2", - "STEPSIZE" => "6", - "LENSLENGTH" => "50", - "PSOLWIDTH" => "0.25", - "PSOLHEIGHT" => "4", - "LOFTANG1" | "LOFTANG2" => "1.5707963267948966", - "LOFTPARAM" => "7", - "LATITUDE" => "37.795", - "LONGITUDE" => "-122.394", - "TIMEZONE" => "-8000", - "UNKNOWN_B_R2007" => "true", - _ => "", - } -} - -/// AcDb:Header for R2018 (the variable list of `dwg::header`), from the -/// drawing's header variables. -pub(crate) fn header_section(d: &Drawing, ver: DwgVersion, handseed: u64) -> Vec { - let hv = Hv::new(d); - let mut s = Streams3::new(); - let mut cepsntype = 0i64; - for (name, kind, applies) in header::vars() { - if !applies(ver, cepsntype) { - continue; - } - let dt = default_text(name); - let truthy = |t: &str| t == "true" || t == "1"; - match kind { - VarKind::B => { - let default = match dt { - "" => matches!( - name, - "DIMASO" - | "DIMSHO" - | "REGENMODE" - | "FILLMODE" - | "PSLTSCALE" - | "USRTIMER" - | "WORLDVIEW" - | "TILEMODE" - | "VISRETAIN" - | "DIMTIH" - | "DIMTOH" - ), - t => truthy(t), - }; - s.dat.b(hv.bool(name, default)); - } - VarKind::Bs => { - let v = hv.int(name, dt.parse().unwrap_or(0)); - if name == "CEPSNTYPE" { - cepsntype = v; - } - s.dat.bs(v as i16 as u16); - } - VarKind::Bl => s.dat.bl(hv.int(name, dt.parse().unwrap_or(0)) as i32 as u32), - VarKind::Bll => s.dat.bll(hv.int(name, dt.parse().unwrap_or(0)) as u64), - VarKind::Rc => s.dat.rc(hv.int(name, dt.parse().unwrap_or(0)) as u8), - VarKind::Bd => s.dat.bd(hv.real(name, dt.parse().unwrap_or(0.0))), - VarKind::Rd2 => { - let p = hv.p2(name, parse_p2(dt)); - s.dat.rd2([p.x, p.y]); - } - VarKind::Bd3 => { - let p = hv.p3(name, parse_p3(dt)); - s.dat.bd3(p.to_array()); - } - VarKind::Tv => { - let default = dt.trim_matches('"'); - s.strs.text16(&hv.text(name, default)); - } - VarKind::Cmc => { - let fallback = match name { - "CECOLOR" => Color::ByLayer, - "INTERFERECOLOR" => Color::Index(1), - _ => Color::ByBlock, - }; - let c = hv.color(name, fallback); - s.dat.bs(0); - s.dat.bl(c.to_method_word()); - s.dat.rc(0); - } - VarKind::H => { - // The tables' control objects and the named-object - // dictionary are owned (code 3); the rest are pointers. - let code = if name.ends_with("_CONTROL") || name == "DICTIONARY_NAMED_OBJECTS" { 3 } else { 5 }; - s.hdl.handle(code, hv.handle(name).0); - } - VarKind::Seed => s.dat.handle(0, handseed), - VarKind::Time => { - let (day, ms) = julian(hv.time(name, 0.0)); - s.dat.bl(day); - s.dat.bl(ms); - } - } - } - // The spec's trailing "R14+" shorts (types 5 and 6 only) are not - // written by AutoCAD 2027. - let body = s.body(false); - wrap(&HEADER_START, &HEADER_END, &body, ver) -} - -fn parse_p2(t: &str) -> Vec2 { - let v: Vec = t.trim_matches(|c| c == '(' || c == ')').split(',').filter_map(|x| x.trim().parse().ok()).collect(); - Vec2::new(v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0)) -} - -fn parse_p3(t: &str) -> Vec3 { - let v: Vec = t.trim_matches(|c| c == '(' || c == ')').split(',').filter_map(|x| x.trim().parse().ok()).collect(); - Vec3::new(v.first().copied().unwrap_or(0.0), v.get(1).copied().unwrap_or(0.0), v.get(2).copied().unwrap_or(0.0)) -} - -/// AcDb:Classes for R2004+. -pub(crate) fn classes_section(d: &Drawing, ver: DwgVersion) -> Vec { - let mut s = Streams3::new(); - let max = d.classes.iter().map(|c| c.number).max().unwrap_or(499); - s.dat.bs(max); - s.dat.rc(0); - s.dat.rc(0); - s.dat.b(true); - for c in &d.classes { - s.dat.bs(c.number); - s.dat.bs(c.proxy_flags); - s.strs.text16(&c.app_name); - s.strs.text16(&c.cpp_name); - s.strs.text16(&c.dxf_name); - s.dat.b(c.was_zombie); - s.dat.bs(c.item_class_id); - let count = d.objects.values().filter(|o| o.type_code == c.number).count() as u32; - s.dat.bl(c.instance_count.max(count)); - let (dwg, maint) = if c.dwg_version != 0 { (c.dwg_version, c.maintenance_version) } else { class_versions(&c.dxf_name) }; - s.dat.bl(dwg); - s.dat.bl(maint); - s.dat.bl(0); - s.dat.bl(0); - } - let body = s.body(true); - let mut out = wrap(&CLASSES_START, &CLASSES_END, &body, ver); - out.extend_from_slice(&[0u8; 8]); - out -} - -/// The DWG and maintenance version a class says it came with, for -/// drawings saved before the native format kept them (2.0): the values -/// AutoCAD 2027 writes for the classes of its own drawings, 0 otherwise. -fn class_versions(dxf_name: &str) -> (u32, u32) { - match dxf_name { - "ACDBDICTIONARYWDFLT" => (22, 42), - "MATERIAL" => (23, 14), - "VISUALSTYLE" => (26, 0), - "TABLESTYLE" => (25, 20), - "SCALE" => (27, 1), - "MLEADERSTYLE" => (33, 427), - "ACDBSECTIONVIEWSTYLE" => (27, 50), - "ACDBDETAILVIEWSTYLE" => (33, 427), - "DIMASSOC" => (23, 12), - "DICTIONARYVAR" => (20, 0), - _ => (0, 0), - } -} - -/// AcDb:Handles: (handle, offset) pairs in handle order, as modular-char -/// deltas, in blocks of at most 2032 bytes, each with a big-endian size -/// and CRC, ended by an empty block. Deltas restart in every block. -pub(crate) fn handles_section(entries: &[(u64, u64)]) -> Vec { - let mut out = Vec::new(); - let mut i = 0; - while i < entries.len() { - let mut block: Vec = vec![0, 0]; - let (mut last_h, mut last_o) = (0u64, 0i64); - while i < entries.len() { - let (h, o) = entries[i]; - let mut w = BitWriter::new(); - w.mc_unsigned(h - last_h); - w.mc_signed(o as i64 - last_o); - let bytes = w.into_bytes(); - if block.len() + bytes.len() > 2032 { - break; - } - block.extend_from_slice(&bytes); - last_h = h; - last_o = o as i64; - i += 1; - } - let n = block.len() as u16; - block[..2].copy_from_slice(&n.to_be_bytes()); - let crc = crc16(0xC0C1, &block); - out.extend_from_slice(&block); - out.extend_from_slice(&crc.to_be_bytes()); - } - let end = [0u8, 2]; - let crc = crc16(0xC0C1, &end); - out.extend_from_slice(&end); - out.extend_from_slice(&crc.to_be_bytes()); - out -} - -/// TU as the R2007+ small sections store it: RS length counting the -/// terminating 0, then UTF-16 units with that 0. -fn tu(out: &mut Vec, s: &str) { - let units: Vec = s.encode_utf16().filter(|&u| u != 0).chain([0]).collect(); - out.extend_from_slice(&(units.len() as u16).to_le_bytes()); - for u in units { - out.extend_from_slice(&u.to_le_bytes()); - } -} - -fn td(out: &mut Vec, v: f64) { - let (day, ms) = julian(v); - out.extend_from_slice(&day.to_le_bytes()); - out.extend_from_slice(&ms.to_le_bytes()); -} - -/// The maintenance release AutoCAD 2027 writes for AC1032 (file header, -/// auxiliary header, class records), whose object layout the writer -/// follows bit for bit. -pub(crate) const ACAD_MAINTENANCE: u32 = 427; - -/// AcDb:AuxHeader (chapter 27) as AutoCAD 2027 writes it for AC1032: the -/// version and maintenance release three times, the save count, the -/// creation and update times, the handle seed. The spec's 5 and 0x893 -/// shorts are zero in AutoCAD's file, and bytes 0x3D–0x44 hold values the -/// spec lists as zero; both are written as AutoCAD writes them. -pub(crate) fn aux_header(d: &Drawing, handseed: u64, saves: u32) -> Vec { - let hv = Hv::new(d); - let ver: u16 = 33; - let maint = ACAD_MAINTENANCE; - // AutoCAD starts the section 0xFF on a drawing's first save, 0x00 on - // later ones. - let mut o = vec![if saves <= 1 { 0xFF } else { 0x00 }, 0x77, 0x01]; - o.extend_from_slice(&ver.to_le_bytes()); - o.extend_from_slice(&maint.to_le_bytes()); - o.extend_from_slice(&saves.to_le_bytes()); - o.extend_from_slice(&(-1i32).to_le_bytes()); - o.extend_from_slice(&1u16.to_le_bytes()); - o.extend_from_slice(&0u16.to_le_bytes()); - o.extend_from_slice(&0u32.to_le_bytes()); - for _ in 0..2 { - o.extend_from_slice(&ver.to_le_bytes()); - o.extend_from_slice(&maint.to_le_bytes()); - } - o.extend_from_slice(&[0; 8]); - o.extend_from_slice(&0u16.to_le_bytes()); - o.extend_from_slice(&1u16.to_le_bytes()); - o.extend_from_slice(&[0; 12]); - o.extend_from_slice(&[0x00, 0x01, 0x00, 0x00, 0x01, 0x00]); - o.extend_from_slice(&(saves as u16).to_le_bytes()); - td(&mut o, hv.time("TDCREATE", 0.0)); - td(&mut o, hv.time("TDUPDATE", 0.0)); - let seed = if handseed < 0x7FFF_FFFF { handseed as u32 } else { u32::MAX }; - o.extend_from_slice(&seed.to_le_bytes()); - o.extend_from_slice(&0u32.to_le_bytes()); // educational plot stamp - o.extend_from_slice(&0u16.to_le_bytes()); - o.extend_from_slice(&1u16.to_le_bytes()); - o.extend_from_slice(&[0; 12]); - o.extend_from_slice(&saves.to_le_bytes()); - o.extend_from_slice(&[0; 16]); - debug_assert_eq!(o.len(), 129); - o -} - -/// AcDb:Template (chapter 22): AutoCAD 2027 writes four bytes `01 00 00 -/// 00`, then MEASUREMENT as a short. -pub(crate) fn template(d: &Drawing) -> Vec { - let m = Hv::new(d).int("MEASUREMENT", 0) as u16; - let mut o = vec![1, 0, 0, 0]; - o.extend_from_slice(&m.to_le_bytes()); - o -} - -/// AcDb:ObjFreeSpace (chapter 21) in its R2004+ form as AutoCAD writes -/// it: 64-bit zero, the approximate object count, TDUPDATE, then the four -/// 64-bit value pairs the spec lists. -pub(crate) fn obj_free_space(d: &Drawing, objects: usize) -> Vec { - let mut o = Vec::with_capacity(89); - o.extend_from_slice(&0u64.to_le_bytes()); - o.extend_from_slice(&(objects as u64).to_le_bytes()); - td(&mut o, Hv::new(d).time("TDUPDATE", 0.0)); - o.push(4); - for v in [0x32u64, 0x64, 0x200, 0xFFFF_FFFF] { - o.extend_from_slice(&v.to_le_bytes()); - o.extend_from_slice(&0u64.to_le_bytes()); - } - o -} - -/// AcDb:RevHistory (chapter 18), as AutoCAD 2027 writes it for a drawing -/// with no revision records. -pub(crate) fn rev_history() -> Vec { - [0u32, 0, 1, 0].iter().flat_map(|v| v.to_le_bytes()).collect() -} - -/// AcDb:SummaryInfo (chapter 13), R2007+ strings: the drawing -/// properties, total editing time, creation and update times, custom -/// properties. -pub(crate) fn summary_info(d: &Drawing) -> Vec { - let hv = Hv::new(d); - let p = &d.header.properties; - let mut o = Vec::new(); - for s in [&p.title, &p.subject, &p.author, &p.keywords, &p.comments, &p.last_saved_by, &p.revision, &p.hyperlink_base] { - tu(&mut o, s); - } - td(&mut o, hv.time("TDINDWG", 0.0)); - td(&mut o, hv.time("TDCREATE", 0.0)); - td(&mut o, hv.time("TDUPDATE", 0.0)); - o.extend_from_slice(&(p.custom.len() as u16).to_le_bytes()); - for (k, v) in &p.custom { - tu(&mut o, k); - tu(&mut o, v); - } - o.extend_from_slice(&[0; 8]); - o -} - -/// The kinds of entry in an application information list, each written -/// before its text. The spec calls these 16 bytes a checksum that may be -/// zero; in AutoCAD's files they are fixed identifiers, the same in every -/// file of the corpus whatever the text (the property set's is the format -/// id its XML names). -const APPINFO_COMMENT: [u8; 16] = [0xB8, 0xD0, 0xF0, 0x25, 0xA1, 0xD7, 0x93, 0x49, 0xB2, 0xFA, 0x9B, 0xF9, 0x28, 0x6F, 0xA1, 0xFD]; -const APPINFO_PROPERTIES: [u8; 16] = [0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F, 0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9]; -const APPINFO_PRODUCT: [u8; 16] = [0xE8, 0xE0, 0x96, 0x51, 0xC5, 0xCE, 0xB2, 0x44, 0xA8, 0xBF, 0xF6, 0xE8, 0x3B, 0x85, 0x9D, 0x44]; -/// The 32 bytes AcDb:AppInfoHistory starts with, the same in every file of -/// the corpus (2004 to 2018, every save). -const APPINFO_HISTORY_START: [u8; 32] = [ - 0x53, 0xDE, 0x38, 0x1D, 0xEC, 0x43, 0x21, 0xCA, 0x96, 0x19, 0xE1, 0xE2, 0x17, 0x1A, 0x2A, 0x67, 0x3B, 0xD9, 0x7F, 0xF7, 0x3C, 0xBB, 0xCE, 0x08, - 0xA0, 0x53, 0xD8, 0xED, 0xD2, 0x8D, 0xC5, 0xC7, -]; - -fn appinfo_comment(name: &str, version: &str) -> String { - format!("Saved by {name} {version}.") -} - -fn appinfo_product(name: &str, version: &str) -> String { - let registry: String = version.split('.').take(2).collect::>().join("."); - format!( - "" - ) -} - -/// AcDb:AppInfo (chapter 16) in the layout AutoCAD 2027 writes: format 3, -/// "AppInfoDataList", two entries (a comment and the product -/// information), each after the identifier of its kind. It names the -/// program writing the file, never claims to be an Autodesk application. -pub(crate) fn app_info(name: &str, version: &str) -> Vec { - let mut o = Vec::new(); - o.extend_from_slice(&3u32.to_le_bytes()); - tu(&mut o, "AppInfoDataList"); - o.extend_from_slice(&2u32.to_le_bytes()); - o.extend_from_slice(&APPINFO_COMMENT); - tu(&mut o, &appinfo_comment(name, version)); - o.extend_from_slice(&APPINFO_PRODUCT); - tu(&mut o, &appinfo_product(name, version)); - o -} - -/// A Julian date and time as `YYYY-MM-DDTHH:MM:SS` (empty for a day chrono can't place). -fn iso_datetime(v: f64) -> String { - let (day, ms) = julian(v); - // Julian day 1721426 is 1 January of the year 1. - let date = i32::try_from(i64::from(day) - 1_721_425).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); - let time = chrono::NaiveTime::from_num_seconds_from_midnight_opt((ms / 1000).min(86_399), 0); - match (date, time) { - (Some(d), Some(t)) => d.and_time(t).format("%Y-%m-%dT%H:%M:%S").to_string(), - _ => String::new(), - } -} - -fn xml_text(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">") -} - -/// [`app_info_history`] from a ready property set. -pub(crate) fn app_info_history_with(props: &str, name: &str, version: &str) -> Vec { - let mut o = APPINFO_HISTORY_START.to_vec(); - o.extend_from_slice(&0u32.to_le_bytes()); - tu(&mut o, "AppInfoDataList"); - o.extend_from_slice(&3u32.to_le_bytes()); - o.extend_from_slice(&APPINFO_COMMENT); - tu(&mut o, &appinfo_comment(name, version)); - o.extend_from_slice(&APPINFO_PROPERTIES); - tu(&mut o, props); - o.extend_from_slice(&APPINFO_PRODUCT); - tu(&mut o, &appinfo_product(name, version)); - o -} - -/// AcDb:AppInfoHistory (not in the spec), as AutoCAD 2027 writes it: the -/// fixed 32 bytes, a zero long, then an application information list of -/// three entries: the comment, a property set (on a drawing's first save: -/// creation and save times, an empty string, who saved it, the program -/// and its version; later saves leave out the creation time and the empty -/// string) and the product information. -pub(crate) fn app_info_history(d: &Drawing, first_save: bool, name: &str, version: &str) -> Vec { - let hv = Hv::new(d); - let mut props = String::from(""); - let saved = iso_datetime(hv.time("TDUPDATE", 0.0)); - let by = xml_text(&d.header.properties.last_saved_by); - if first_save { - let created = iso_datetime(hv.time("TDCREATE", 0.0)); - props += &format!("{created}"); - props += &format!("{saved}"); - props += ""; - props += &format!("{by}"); - } else { - props += &format!("{by}"); - props += &format!("{saved}"); - } - props += &format!("{name}"); - props += &format!("{version}"); - props += ""; - let mut o = APPINFO_HISTORY_START.to_vec(); - o.extend_from_slice(&0u32.to_le_bytes()); - tu(&mut o, "AppInfoDataList"); - o.extend_from_slice(&3u32.to_le_bytes()); - o.extend_from_slice(&APPINFO_COMMENT); - tu(&mut o, &appinfo_comment(name, version)); - o.extend_from_slice(&APPINFO_PROPERTIES); - tu(&mut o, &props); - o.extend_from_slice(&APPINFO_PRODUCT); - tu(&mut o, &appinfo_product(name, version)); - o -} - -fn json_text(s: &str) -> String { - let mut o = String::new(); - for c in s.chars() { - match c { - '"' => o += "\\\"", - '\\' => o += "\\\\", - c if (c as u32) < 0x20 => o += &format!("\\u{:04x}", c as u32), - c => o.push(c), - } - } - o -} - -/// AcDb:XrefManifest (not in the spec), as AutoCAD 2027 writes it: a -/// 64-bit length, then JSON listing the files the drawing refers to (the -/// font of each text style, by the style's handle) with four-space -/// indents. -pub(crate) fn xref_manifest(d: &Drawing) -> Vec { - let mut entries = Vec::new(); - for o in d.objects.values() { - if let ObjectKind::TextStyle(t) = &o.kind - && !t.font_file.is_empty() - { - entries.push(format!( - " {{\n \"path\": \"{}\",\n \"handle\": \"{:x}\",\n \"class\": \"AcDbTextStyleTableRecord\"\n }}", - json_text(&t.font_file), - o.handle.0 - )); - } - } - let list = if entries.is_empty() { "[]".to_string() } else { format!("[\n{}\n ]", entries.join(",\n")) }; - let json = format!("{{\n \"xrefs\": {list},\n \"version\": \"1.0\",\n \"wasFullSave\": \"true\"\n}}\n"); - let mut o = (json.len() as u64).to_le_bytes().to_vec(); - o.extend_from_slice(json.as_bytes()); - o -} - -const PREVIEW_START: [u8; 16] = [0x1F, 0x25, 0x6D, 0x07, 0xD4, 0x36, 0x28, 0x28, 0x9D, 0x57, 0xCA, 0x3F, 0x9D, 0x44, 0x10, 0x2B]; -const PREVIEW_END: [u8; 16] = [0xE0, 0xDA, 0x92, 0xF8, 0x2B, 0xC9, 0xD7, 0xD7, 0x62, 0xA8, 0x35, 0xC0, 0x62, 0xBB, 0xEF, 0xD4]; - -/// AcDb:Preview (chapter 14.2) as AutoCAD 2027 writes it for R2013+: a -/// header entry (code 1, 80 zero bytes) and a PNG (code 6). The entries -/// give their data's position as an address in the file, so the caller -/// passes where the section's first byte will be. -pub(crate) fn preview(png: &[u8], section_address: u64) -> Vec { - let header = [0u8; 80]; - let entries = 2usize; - let head = 16 + 4 + 1 + entries * 9; - let header_at = section_address + head as u64; - let png_at = header_at + header.len() as u64; - let mut o = PREVIEW_START.to_vec(); - let size = 1 + entries * 9 + header.len() + png.len(); - o.extend_from_slice(&(size as u32).to_le_bytes()); - o.push(entries as u8); - o.push(1); - o.extend_from_slice(&(header_at as u32).to_le_bytes()); - o.extend_from_slice(&(header.len() as u32).to_le_bytes()); - o.push(6); - o.extend_from_slice(&(png_at as u32).to_le_bytes()); - o.extend_from_slice(&(png.len() as u32).to_le_bytes()); - o.extend_from_slice(&header); - o.extend_from_slice(png); - o.extend_from_slice(&PREVIEW_END); - o -} diff --git a/docs/dwg-writer-handoff.md b/docs/dwg-writer-handoff.md index 9cc00891..3df762bb 100644 --- a/docs/dwg-writer-handoff.md +++ b/docs/dwg-writer-handoff.md @@ -35,7 +35,8 @@ holds what the DXF of the same drawing holds, and what a command adds to one is |---|---| | `crates/dwg/src/compose/object.rs` | `ObjectWriter`: one object, field by field, in every version (the mirror of `file::ObjectReader`) | | `crates/dwg/src/compose/sections.rs` | header variables, classes, object map | -| `crates/dwg/src/compose/file.rs` | `compose(Parts)`: the file laid out for 2000 (flat) and 2004/2010/2013/2018 (paged, through `write::container::pack`) | +| `crates/dwg/src/compose/file.rs` | `compose(Parts)`: the file laid out for 2000 (flat) and 2004/2010/2013/2018 (paged, through `compose/container.rs`) | +| `crates/dwg/src/compose/small.rs`, `fields.rs` | the application information and revision history sections; the three bit streams the style encoders (`read/styles.rs`) write into | | `crates/dwg/src/compose/r2007/` | AutoCAD 2007 container: Reed-Solomon pages (`codes.rs`), its compression (`compress.rs`), CRC-64 checks, the page and section maps | | `crates/io/src/dwg/write/rec.rs` | the records: `Doc`, `Rec`, `Groups` | | `crates/io/src/dwg/write/mod.rs` | `Cx` (names to handles, classes, structure), `encode`, `write` | @@ -108,9 +109,6 @@ set; an AutoCAD 2018 MTEXT ends with a null reference. ## Known choices to revisit -- `crates/dwg/src/write` (withshalom's first writer, over BlackCAD's records) is still there: - `compose` uses its container, its small sections and its style codec. Once nothing else needs - it, what `compose` uses moves there and the rest goes. - A LEADER's first field after its vertices ("origin") is written as zero; a hatch gradient, a UCS and a named view are written from the specification and the reader, with no AutoCAD file of them to compare with. ACadSharp's samples (MIT, not in the repository) hold most entity diff --git a/docs/dwg.md b/docs/dwg.md index a6b4be84..2d7b7e12 100644 --- a/docs/dwg.md +++ b/docs/dwg.md @@ -16,7 +16,6 @@ crates/dwg (draftcraft-dwg: layer 0, depends on no other workspace crate) read/ DWG R13 to 2018 and later: container (r2000, r2004, r2007), sections, classes, objects compose/ a DWG file laid out from its objects, header and classes, as each version stores it (r2000 sections, the 2004 pages, the 2007 Reed-Solomon pages in r2007/) - write/ BlackCAD's writer from records (its object encoding and read-back check) records/ BlackCAD's records, for the first mapping (dwg_read) and as an independent reading of the files the writer makes, in tests bits.rs, crc.rs, lz77.rs the format's primitives, shared by reading and writing From 8318ca0ce2e94f9724d68bb59c3c249f365489cd Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Sat, 14 Nov 2026 15:07:15 +0100 Subject: [PATCH 4/4] Arc length and jogged radius dimensions are AutoCAD's own types in DXF and DWG An arc length dimension is written as ARC_DIMENSION (AcDbArcDimension: centre, arc ends, angles, partial and leader flags) and a jogged radius as LARGE_RADIAL_DIMENSION (AcDbRadialDimensionLarge: chord point, override centre, jog), in DXF and in every DWG version, laid out as AutoCAD 2027 writes them; both are read back from AutoCAD's files. DraftCraft's older ARCLEN extended data still reads. AutoCAD 2027 opens the dimensions fixture with AUDIT 0 and lists both as its own types; the handoff notes the fixtures checked in AutoCAD since PR #16. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/entity/dim.rs | 11 ++ crates/dwg/src/compose/sections.rs | 1 + crates/io/src/dwg/entities.rs | 55 +++++++++- crates/io/src/dwg/write/annotation.rs | 142 ++++++++++++++++---------- crates/io/src/dwg/write/mod.rs | 2 + crates/io/src/dxf_ext.rs | 22 ++-- crates/io/src/dxf_raw.rs | 3 +- crates/io/src/dxf_read/entities.rs | 68 ++++++++---- crates/io/src/dxf_read/mtext_dxf.rs | 2 +- crates/io/src/dxf_write/common.rs | 10 +- crates/io/src/dxf_write/entity.rs | 48 +++++++-- crates/io/src/dxf_write/sections.rs | 7 ++ crates/io/src/tests.rs | 107 +++++++++++++++++-- crates/io/tests/it/dwg_direct.rs | 113 +++++++++++++++++++- docs/dwg-handoff.md | 2 - docs/dwg-writer-handoff.md | 10 +- docs/dwg.md | 11 +- 17 files changed, 496 insertions(+), 118 deletions(-) diff --git a/crates/doc/src/entity/dim.rs b/crates/doc/src/entity/dim.rs index 5fbdcb1a..7073198f 100644 --- a/crates/doc/src/entity/dim.rs +++ b/crates/doc/src/entity/dim.rs @@ -90,6 +90,17 @@ pub struct DimMarks { /// Inspection frame, label and rate (DIMINSPECT). #[serde(skip_serializing_if = "Option::is_none")] pub inspect: Option, + /// An arc-length dimension of part of its arc (DIMARC Partial): `p13` and `p14` are the + /// picked points rather than the arc's ends. + #[serde(skip_serializing_if = "is_false")] + pub arc_partial: bool, + /// An arc-length dimension with a leader from its text to the arc (DIMARC Leader). + #[serde(skip_serializing_if = "is_false")] + pub arc_leader: bool, +} + +fn is_false(b: &bool) -> bool { + !*b } impl DimMarks { diff --git a/crates/dwg/src/compose/sections.rs b/crates/dwg/src/compose/sections.rs index c0cc763f..85aad455 100644 --- a/crates/dwg/src/compose/sections.rs +++ b/crates/dwg/src/compose/sections.rs @@ -289,6 +289,7 @@ pub fn class_versions(dxf_name: &str) -> (u32, u32) { "ACDBDETAILVIEWSTYLE" => (33, 427), "DIMASSOC" => (23, 12), "DICTIONARYVAR" => (20, 0), + "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" => (25, 20), _ => (0, 0), } } diff --git a/crates/io/src/dwg/entities.rs b/crates/io/src/dwg/entities.rs index a9333bb0..55f41c45 100644 --- a/crates/io/src/dwg/entities.rs +++ b/crates/io/src/dwg/entities.rs @@ -343,6 +343,8 @@ fn reads(type_name: &str) -> bool { | "DIMENSION_ANG_2LN" | "DIMENSION_RADIUS" | "DIMENSION_DIAMETER" + | "ARC_DIMENSION" + | "LARGE_RADIAL_DIMENSION" ) } @@ -1027,7 +1029,45 @@ fn dimension(r: &mut ObjectReader, type_name: &str) -> DwgResult { let defpt; let (mut p13, mut p14, mut p15, mut p16) = (Vec3::ZERO, Vec3::ZERO, Vec3::ZERO, Vec3::ZERO); let mut oblique = 0.0; + let mut marks = draftcraft_doc::DimMarks::default(); let kind = match type_name { + "ARC_DIMENSION" => { + // The point on the dimension arc, the arc's two points and centre, whether it + // measures part of the arc, its start and end angles, whether it has a leader, and + // the two points again (AutoCAD's files, 2000 to 2018). + defpt = p(r)?; + p13 = p(r)?; + p14 = p(r)?; + p15 = p(r)?; + marks.arc_partial = r.b()?; + let start = r.bd()?; + let _end = r.bd()?; + marks.arc_leader = r.b()?; + let _first = p(r)?; + let _second = p(r)?; + // DraftCraft draws the arc counter-clockwise from p13 to p14: p13 is the point at + // the start angle. + let c = p15.xy(); + let off = |q: Vec3| { + let a = c.angle_to(q.xy()); + draftcraft_geom::norm_angle(a - start).min(draftcraft_geom::norm_angle(start - a)) + }; + if start.is_finite() && off(p14) < off(p13) { + std::mem::swap(&mut p13, &mut p14); + } + DimKind::ArcLength + } + "LARGE_RADIAL_DIMENSION" => { + // The centre, the point on the arc, the leader length, then the centre the + // dimension line starts from instead and the jog. + defpt = p(r)?; + p15 = p(r)?; + let _leader_length = r.bd()?; + let center = p(r)?; + let jog = p(r)?; + marks.jogged = Some(draftcraft_doc::JoggedRadius { center, jog }); + DimKind::Radius + } "DIMENSION_ORDINATE" => { defpt = p(r)?; p13 = p(r)?; @@ -1091,7 +1131,7 @@ fn dimension(r: &mut ObjectReader, type_name: &str) -> DwgResult { insertion_point: Vec3::new(ix, iy, 0.0), overrides: Default::default(), assoc: Vec::new(), - marks: Default::default(), + marks, }; Ok(Shape { body: Body::Dimension(Box::new(dim), oblique), thickness: 0.0, normal }) } @@ -2026,8 +2066,15 @@ fn shape(r: &mut ObjectReader, type_name: &str, partial: &mut Vec<&'static str>) "MLINE" => mline(r)?, "WIPEOUT" => raster(r, true)?, "PDFUNDERLAY" => underlay(r)?, - "DIMENSION_ORDINATE" | "DIMENSION_LINEAR" | "DIMENSION_ALIGNED" | "DIMENSION_ANG_3PT" | "DIMENSION_ANG_2LN" | "DIMENSION_RADIUS" - | "DIMENSION_DIAMETER" => dimension(r, type_name)?, + "DIMENSION_ORDINATE" + | "DIMENSION_LINEAR" + | "DIMENSION_ALIGNED" + | "DIMENSION_ANG_3PT" + | "DIMENSION_ANG_2LN" + | "DIMENSION_RADIUS" + | "DIMENSION_DIAMETER" + | "ARC_DIMENSION" + | "LARGE_RADIAL_DIMENSION" => dimension(r, type_name)?, "ATTDEF" => attribute(r, true, partial)?, "MINSERT" => insert(r, true)?, "SOLID" => solid(r, false)?, @@ -2165,7 +2212,7 @@ fn entity(r: &mut ObjectReader, o: &ObjectRef, n: &Names) -> DwgResult<(Decoded, dm.kind = DimKind::ArcLength; dm.p15 = center; } - dm.marks = crate::dxf_ext::read_marks(&tags); + dm.marks = crate::dxf_ext::merge_marks(std::mem::take(&mut dm.marks), crate::dxf_ext::read_marks(&tags)); // The extension lines' angle relative to the dimension line (DIMEDIT Oblique), as // a DXF holds it in group 52, in degrees. let base = match dm.kind { diff --git a/crates/io/src/dwg/write/annotation.rs b/crates/io/src/dwg/write/annotation.rs index f6adb7f8..a9f9112f 100644 --- a/crates/io/src/dwg/write/annotation.rs +++ b/crates/io/src/dwg/write/annotation.rs @@ -23,7 +23,7 @@ pub(super) fn entity(cx: &Cx<'_>, r: &Rec<'_>) -> Option { } w } - "DIMENSION" => dimension(cx, r)?, + "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" => dimension(cx, r)?, "SPLINE" => { let mut w = begin(cx, 0x24, r); spline_fields(cx, &mut w, r.sub("AcDbSpline")); @@ -210,15 +210,19 @@ fn dimension(cx: &Cx<'_>, r: &Rec<'_>) -> Option { let ver = cx.ver; let g = r.sub("AcDbDimension"); let flags = g.i(70); - let code = match flags & 7 { - 0 => 0x15, - 1 => 0x16, - 2 => 0x18, - 3 => 0x1A, - 4 => 0x19, - 5 => 0x17, - 6 => 0x14, - _ => return None, + let code = match r.kind { + "ARC_DIMENSION" => cx.class("ARC_DIMENSION")?, + "LARGE_RADIAL_DIMENSION" => cx.class("LARGE_RADIAL_DIMENSION")?, + _ => match flags & 7 { + 0 => 0x15, + 1 => 0x16, + 2 => 0x18, + 3 => 0x1A, + 4 => 0x19, + 5 => 0x17, + 6 => 0x14, + _ => return None, + }, }; let mut w = begin(cx, code, r); if ver >= V::R2010 { @@ -248,53 +252,79 @@ fn dimension(cx: &Cx<'_>, r: &Rec<'_>) -> Option { w.rd2(g.p2(12)); let defpt = g.p3(10); let (aligned, rotated) = (r.sub("AcDbAlignedDimension"), r.sub("AcDbRotatedDimension")); - match code { - 0x14 => { - let o = r.sub("AcDbOrdinateDimension"); - w.bd3(defpt); - w.bd3(o.p3(13)); - w.bd3(o.p3(14)); - w.rc(u8::from(flags & 64 != 0)); - } - 0x15 | 0x16 => { - w.bd3(aligned.p3(13)); - w.bd3(aligned.p3(14)); - w.bd3(defpt); - // The oblique angle and the rotation are the aligned subclass's, or (AutoCAD's own - // DXF) the rotated one's. - let pick = |code: i32| aligned.get(code).or_else(|| rotated.get(code)).map_or(0.0, Tag::f64).to_radians(); - w.bd(pick(52)); - if code == 0x15 { - w.bd(pick(50)); + if r.kind == "ARC_DIMENSION" { + // The point on the dimension arc, the arc's two points and centre, whether it measures + // part of the arc, its start and end angles, whether it has a leader, the two points + // again (AutoCAD's files, 2000 to 2018). + let a = r.sub("AcDbArcDimension"); + w.bd3(defpt); + w.bd3(a.p3(13)); + w.bd3(a.p3(14)); + w.bd3(a.p3(15)); + w.b(a.i(70) != 0); + w.bd(a.f(40)); + w.bd(a.f(41)); + w.b(a.i(71) != 0); + w.bd3(a.p3(16)); + w.bd3(a.p3(17)); + } else if r.kind == "LARGE_RADIAL_DIMENSION" { + // The centre, the point on the arc, the leader length, the centre the dimension line + // starts from instead and the jog. + let a = r.sub("AcDbRadialDimensionLarge"); + w.bd3(defpt); + w.bd3(a.p3(15)); + w.bd(a.f(40)); + w.bd3(a.p3(13)); + w.bd3(a.p3(14)); + } else { + match code { + 0x14 => { + let o = r.sub("AcDbOrdinateDimension"); + w.bd3(defpt); + w.bd3(o.p3(13)); + w.bd3(o.p3(14)); + w.rc(u8::from(flags & 64 != 0)); + } + 0x15 | 0x16 => { + w.bd3(aligned.p3(13)); + w.bd3(aligned.p3(14)); + w.bd3(defpt); + // The oblique angle and the rotation are the aligned subclass's, or (AutoCAD's own + // DXF) the rotated one's. + let pick = |code: i32| aligned.get(code).or_else(|| rotated.get(code)).map_or(0.0, Tag::f64).to_radians(); + w.bd(pick(52)); + if code == 0x15 { + w.bd(pick(50)); + } + } + 0x17 => { + let a = r.sub("AcDb3PointAngularDimension"); + w.bd3(defpt); + w.bd3(a.p3(13)); + w.bd3(a.p3(14)); + w.bd3(a.p3(15)); + } + 0x18 => { + let a = r.sub("AcDb2LineAngularDimension"); + w.rd2(a.p2(16)); + w.bd3(a.p3(13)); + w.bd3(a.p3(14)); + w.bd3(a.p3(15)); + w.bd3(defpt); + } + 0x19 => { + let a = r.sub("AcDbRadialDimension"); + w.bd3(defpt); + w.bd3(a.p3(15)); + w.bd(a.f(40)); + } + _ => { + // The far end of the chord (15) first, then its near end (10). + let a = r.sub("AcDbDiametricDimension"); + w.bd3(a.p3(15)); + w.bd3(defpt); + w.bd(a.f(40)); } - } - 0x17 => { - let a = r.sub("AcDb3PointAngularDimension"); - w.bd3(defpt); - w.bd3(a.p3(13)); - w.bd3(a.p3(14)); - w.bd3(a.p3(15)); - } - 0x18 => { - let a = r.sub("AcDb2LineAngularDimension"); - w.rd2(a.p2(16)); - w.bd3(a.p3(13)); - w.bd3(a.p3(14)); - w.bd3(a.p3(15)); - w.bd3(defpt); - } - 0x19 => { - let a = r.sub("AcDbRadialDimension"); - w.bd3(defpt); - w.bd3(a.p3(15)); - w.bd(a.f(40)); - } - _ => { - // The far end of the chord (15) first, then its near end (10). - let a = r.sub("AcDbDiametricDimension"); - w.bd3(a.p3(15)); - w.bd3(defpt); - w.bd(a.f(40)); } } w.reference(Ref::HardPointer, dim_style(cx, g.s(3))); diff --git a/crates/io/src/dwg/write/mod.rs b/crates/io/src/dwg/write/mod.rs index 8e70b561..98d0071e 100644 --- a/crates/io/src/dwg/write/mod.rs +++ b/crates/io/src/dwg/write/mod.rs @@ -237,6 +237,7 @@ const STANDARD_CLASSES: &[(&str, &str, &str, u16, bool)] = &[ ("BLOCKROTATEACTION", "AcDbBlockRotationAction", "ObjectDBX Classes", 0, false), ("BLOCKROTATIONGRIP", "AcDbBlockRotationGrip", "ObjectDBX Classes", 0, false), ("BLOCKROTATIONPARAMETER", "AcDbBlockRotationParameter", "ObjectDBX Classes", 0, false), + ("ARC_DIMENSION", "AcDbArcDimension", "ObjectDBX Classes", 1025, true), ("BLOCKSCALEACTION", "AcDbBlockScaleAction", "ObjectDBX Classes", 0, false), ("BLOCKSTRETCHACTION", "AcDbBlockStretchAction", "ObjectDBX Classes", 0, false), ("BLOCKUSERPARAMETER", "AcDbBlockUserParameter", "ObjectDBX Classes", 0, false), @@ -250,6 +251,7 @@ const STANDARD_CLASSES: &[(&str, &str, &str, u16, bool)] = &[ ("DIMASSOC", "AcDbDimAssoc", "AcDbDimAssoc", 0, false), ("HELIX", "AcDbHelix", "ObjectDBX Classes", 4095, true), ("IMAGE", "AcDbRasterImage", "ISM", 127, true), + ("LARGE_RADIAL_DIMENSION", "AcDbRadialDimensionLarge", "ObjectDBX Classes", 1025, true), ("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false), ("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false), ("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false), diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index f26846c6..0ae08a2e 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -472,13 +472,6 @@ pub(crate) fn assoc_xdata(assoc: &[DimAssoc]) -> Vec { v } -/// An arc-length dimension as DraftCraft xdata: `1000 ARCLEN`, `1002 {`, the arc centre as an xdata -/// point (`1010`/`1020`/`1030`), `1002 }`. The record itself stays a standard aligned dimension -/// (DXF has no arc-length DIMENSION type), so other programs still read it. -pub(crate) fn arclen_xdata(center: draftcraft_geom::Vec3) -> Vec { - vec![Tag::s(1000, "ARCLEN"), Tag::s(1002, "{"), Tag::f(1010, center.x), Tag::f(1020, center.y), Tag::f(1030, center.z), Tag::s(1002, "}")] -} - /// Dimension marks as DraftCraft xdata (`1000 MARKS`, `1002 {`, items, `1002 }`): `1000 JOGLINE` /// and a point; `1000 JOGGED`, the centre and the jog point; `1000 BREAK`, a point, `1040` size /// and `1070` auto; `1000 INSPECT`, `1070` shape, `1000` label and `1000` rate. Points are @@ -512,6 +505,17 @@ pub(crate) fn marks_xdata(m: &draftcraft_doc::DimMarks) -> Vec { out } +/// The marks a record's own groups hold (a jogged radius, an arc-length dimension's flags) with +/// those DraftCraft's extended data adds. +pub(crate) fn merge_marks(native: draftcraft_doc::DimMarks, mut extra: draftcraft_doc::DimMarks) -> draftcraft_doc::DimMarks { + if native.jogged.is_some() { + extra.jogged = native.jogged; + } + extra.arc_partial |= native.arc_partial; + extra.arc_leader |= native.arc_leader; + extra +} + /// The marks written by [`marks_xdata`] (no oblique angle); empty for other writers. Damaged /// items are skipped. pub(crate) fn read_marks(tags: &[Tag]) -> draftcraft_doc::DimMarks { @@ -551,7 +555,9 @@ pub(crate) fn read_marks(tags: &[Tag]) -> draftcraft_doc::DimMarks { m } -/// The arc centre written by [`arclen_xdata`]; None for other dimensions and other writers. +/// The arc centre DraftCraft wrote as extended data on an aligned dimension before arc-length +/// dimensions were written as AutoCAD's ARC_DIMENSION (`1000 ARCLEN`, `1002 {`, a 1010 point, +/// `1002 }`); None for other dimensions and other writers. pub(crate) fn read_arclen(tags: &[Tag]) -> Option { let list = xdata_list(xdata(tags, APP), "ARCLEN"); let g = |c: i32| list.iter().find(|t| t.code == c).map(Tag::f64).filter(|v| v.is_finite()); diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 85746a82..0b58316c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -238,7 +238,8 @@ pub(crate) fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]); i += 1 + len; let app = up(&first.str()); - let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")); + let own = OWN_APPS.contains(&app.as_str()) + || (app == "ACAD" && matches!(kind, "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" | "DIMSTYLE")); if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS { continue; } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 77bb025e..122e3ee0 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -198,28 +198,60 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef clip: None, }) } - "DIMENSION" => { + "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" => { let ty = t.i(70).unwrap_or(0) & 0x0f; - let kind = match ty { - 0 => DimKind::Linear { rotation: t.fd(50, 0.0).to_radians() }, - 1 => DimKind::Aligned, - 2 => DimKind::Angular, - 3 => DimKind::Diameter, - 4 => DimKind::Radius, - 5 => DimKind::Angular3P, - 6 => DimKind::Ordinate { x_type: t.i(70).unwrap_or(0) & 64 != 0 }, - 8 => DimKind::ArcLength, - _ => DimKind::Aligned, + // The groups of the type's own subclass: the arc-length and jogged radius + // dimensions reuse 70, 71 and 40 there with meanings of their own. + let own = |marker: &str| T(tags.iter().position(|g| g.code == 100 && g.str() == marker).and_then(|i| tags.get(i + 1..)).unwrap_or(&[])); + let mut marks = draftcraft_doc::DimMarks::default(); + let (mut p13, mut p14, mut p15) = (t.p(13), t.p(14), t.p(15)); + let kind = match kind { + "ARC_DIMENSION" => { + let a = own("AcDbArcDimension"); + (p13, p14, p15) = (a.p(13), a.p(14), a.p(15)); + // DraftCraft draws the arc counter-clockwise from p13 to p14; the file + // gives the arc's start and end angles (40, 41) beside its two points. + let c = p15.xy(); + let off = |p: Vec3, angle: f64| { + draftcraft_geom::norm_angle(c.angle_to(p.xy()) - angle).min(draftcraft_geom::norm_angle(angle - c.angle_to(p.xy()))) + }; + if let Some(start) = a.f(40).filter(|v| v.is_finite()) + && off(p14, start) < off(p13, start) + { + std::mem::swap(&mut p13, &mut p14); + } + marks.arc_partial = a.i(70).unwrap_or(0) != 0; + marks.arc_leader = a.i(71).unwrap_or(0) != 0; + DimKind::ArcLength + } + "LARGE_RADIAL_DIMENSION" => { + let a = own("AcDbRadialDimensionLarge"); + p15 = a.p(15); + marks.jogged = Some(draftcraft_doc::JoggedRadius { center: a.p(13), jog: a.p(14) }); + (p13, p14) = (Vec3::ZERO, Vec3::ZERO); + DimKind::Radius + } + _ => match ty { + 0 => DimKind::Linear { rotation: t.fd(50, 0.0).to_radians() }, + 1 => DimKind::Aligned, + 2 => DimKind::Angular, + 3 => DimKind::Diameter, + 4 => DimKind::Radius, + 5 => DimKind::Angular3P, + 6 => DimKind::Ordinate { x_type: t.i(70).unwrap_or(0) & 64 != 0 }, + 8 => DimKind::ArcLength, + _ => DimKind::Aligned, + }, }; EntityKind::Dimension(Dimension { kind, defpt: t.p(10), // The text midpoint is the one OCS point of a DIMENSION. text_mid: if c.extrusion.z < 0.0 { ocs(&c, t.p(11)) } else { t.p(11) }, - p13: t.p(13), - p14: t.p(14), - p15: t.p(15), - p16: t.p(16), + p13, + p14, + p15, + p16: if kind == DimKind::ArcLength { Vec3::ZERO } else { t.p(16) }, text: mtext_dxf::decode_line(&t.s(1).unwrap_or_default()), style: t.s(3).unwrap_or_else(|| "Standard".into()), measurement: t.fd(42, 0.0), @@ -229,7 +261,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef insertion_point: t.p(12), overrides: Default::default(), assoc: Vec::new(), - marks: Default::default(), + marks, }) } "LEADER" => EntityKind::Leader(Leader { @@ -502,14 +534,14 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option { /// needs the file's handle maps. pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) { match (kind, k) { - ("DIMENSION", EntityKind::Dimension(dm)) => { + ("DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION", EntityKind::Dimension(dm)) => { dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes); dm.assoc = crate::dxf_ext::read_assoc(tags); if let Some(center) = crate::dxf_ext::read_arclen(tags) { dm.kind = DimKind::ArcLength; dm.p15 = center; } - dm.marks = crate::dxf_ext::read_marks(tags); + dm.marks = crate::dxf_ext::merge_marks(std::mem::take(&mut dm.marks), crate::dxf_ext::read_marks(tags)); // Group 52: the extension lines' angle relative to the dimension line (DIMEDIT Oblique). let base = match dm.kind { DimKind::Linear { rotation } => Some(rotation), diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index 3183d021..570cc763 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -59,7 +59,7 @@ pub(crate) fn encode_line(s: &str) -> String { /// has its own and is left alone. AutoLISP's entget and entmake/entmod use it. pub(crate) fn map_text_groups(kind: &str, tags: &mut [Tag], f: fn(&str) -> String) { let kind = kind.to_ascii_uppercase(); - if !matches!(kind.as_str(), "TEXT" | "ATTRIB" | "ATTDEF" | "DIMENSION") { + if !matches!(kind.as_str(), "TEXT" | "ATTRIB" | "ATTDEF" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION") { return; } for t in tags.iter_mut().take_while(|t| t.code != 101) { diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 62dcb6cc..45a35dd2 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -39,13 +39,15 @@ pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) { w.s(1002, "}"); } let mut ours = Vec::new(); - if matches!(dm.kind, DimKind::ArcLength) { - ours.extend(dxf_ext::arclen_xdata(dm.p15)); - } if !dm.assoc.is_empty() { ours.extend(dxf_ext::assoc_xdata(&dm.assoc)); } - ours.extend(dxf_ext::marks_xdata(&dm.marks)); + // A jogged radius is its own type, which holds the jog. + let mut marks = dm.marks.clone(); + if matches!(dm.kind, DimKind::Radius) { + marks.jogged = None; + } + ours.extend(dxf_ext::marks_xdata(&marks)); if !ours.is_empty() { w.s(1001, dxf_ext::APP); w.xdata(ours); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 14079fcd..3631ffdf 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -389,9 +389,18 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b } } +/// The DXF type of a dimension: AutoCAD's own types for an arc length and a jogged radius. +pub(super) fn dimension_type(dm: &draftcraft_doc::Dimension) -> &'static str { + match dm.kind { + DimKind::ArcLength => "ARC_DIMENSION", + DimKind::Radius if dm.marks.jogged.is_some() => "LARGE_RADIAL_DIMENSION", + _ => "DIMENSION", + } +} + fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { if let EntityKind::Dimension(dm) = &e.kind { - w.s(0, "DIMENSION"); + w.s(0, dimension_type(dm)); common_x(w, e, owner, paper, "AcDbDimension", cx.assoc.get(&e.handle)); let bname = cx.dim_blocks.get(&e.handle).cloned().or_else(|| dm.block.clone()).unwrap_or_default(); w.s(2, bname); @@ -410,11 +419,12 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper DimKind::Aligned => 1, DimKind::Angular => 2, DimKind::Diameter => 3, + DimKind::Radius if dm.marks.jogged.is_some() => 9, DimKind::Radius => 4, DimKind::Angular3P => 5, DimKind::Ordinate { x_type } => 6 | if x_type { 64 } else { 0 }, - // Written as aligned, marked by DraftCraft xdata (see `dim_xdata`). - DimKind::ArcLength => 1, + // The values AutoCAD gives its arc-length and jogged radius dimensions. + DimKind::ArcLength => 5, }; w.i(70, ty | 32 | if dm.user_text_pos { 128 } else { 0 }); // The actual measurement (read-only in DXF): AutoLISP's entget shows it. @@ -435,13 +445,37 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper oblique_52(w, dm, rotation); w.s(100, "AcDbRotatedDimension"); } - DimKind::Aligned | DimKind::ArcLength => { + DimKind::Aligned => { w.s(100, "AcDbAlignedDimension"); w.p(13, dm.p13); w.p(14, dm.p14); - if matches!(dm.kind, DimKind::Aligned) { - oblique_52(w, dm, (dm.p14.xy() - dm.p13.xy()).angle()); - } + oblique_52(w, dm, (dm.p14.xy() - dm.p13.xy()).angle()); + } + DimKind::ArcLength => { + // The arc's two points, its centre, whether it measures part of the arc, the + // start and end angles counter-clockwise from p13 to p14, whether it has a + // leader, and the two points again, as AutoCAD writes them. + let c = dm.p15.xy(); + let start = draftcraft_geom::norm_angle(c.angle_to(dm.p13.xy())); + let sweep = draftcraft_geom::norm_angle(c.angle_to(dm.p14.xy()) - start); + w.s(100, "AcDbArcDimension"); + w.p(13, dm.p13); + w.p(14, dm.p14); + w.p(15, dm.p15); + w.i(70, i64::from(dm.marks.arc_partial)); + w.f(40, start); + w.f(41, start + sweep); + w.i(71, i64::from(dm.marks.arc_leader)); + w.p(16, dm.p13); + w.p(17, dm.p14); + } + DimKind::Radius if dm.marks.jogged.is_some() => { + let j = dm.marks.jogged.clone().unwrap_or_default(); + w.s(100, "AcDbRadialDimensionLarge"); + w.p(13, j.center); + w.p(14, j.jog); + w.p(15, dm.p15); + w.f(40, 0.0); } DimKind::Radius => { w.s(100, "AcDbRadialDimension"); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 2b4a3eb0..ddc6bf5c 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -344,6 +344,13 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { if cx.native_mleader() && every.iter().any(|e| matches!(e.kind, EntityKind::MLeader(_))) { classes.push(("MULTILEADER", "AcDbMLeader", 1025, true)); } + let dims = |name: &str| every.iter().any(|e| matches!(&e.kind, EntityKind::Dimension(dm) if super::entity::dimension_type(dm) == name)); + if dims("ARC_DIMENSION") { + classes.push(("ARC_DIMENSION", "AcDbArcDimension", 1025, true)); + } + if dims("LARGE_RADIAL_DIMENSION") { + classes.push(("LARGE_RADIAL_DIMENSION", "AcDbRadialDimensionLarge", 1025, true)); + } if every.iter().any(|e| matches!(e.kind, EntityKind::Wipeout(_))) { classes.push(("WIPEOUT", "AcDbWipeout", 127, true)); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index fcf9d7be..edf3577b 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1881,6 +1881,19 @@ fn wipeout_boundary_keeps_its_orientation() { assert_eq!(&got[..3], &boundary[..]); } +/// The dimensions of a drawing, in order. +fn dims_of(d: &Drawing) -> Vec { + d.model.iter().filter_map(|e| if let EntityKind::Dimension(x) = &e.kind { Some(x.clone()) } else { None }).collect() +} + +/// The groups of the first record of DXF type `kind` in a DXF text. +fn record_of(text: &str, kind: &str) -> Vec<(i32, String)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let pairs: Vec<(i32, String)> = lines.chunks(2).filter_map(|p| Some((p.first()?.parse().ok()?, p.get(1)?.to_string()))).collect(); + let start = pairs.iter().position(|p| *p == (0, kind.to_string())).unwrap_or_else(|| panic!("no {kind} in {text}")); + pairs[start..].iter().skip(1).take_while(|p| p.0 != 0).cloned().collect() +} + #[test] fn arc_length_dimension_keeps_its_kind_and_centre_on_roundtrip() { let mut d = Drawing::new_metric(); @@ -1889,9 +1902,19 @@ fn arc_length_dimension_keeps_its_kind_and_centre_on_roundtrip() { al.p15 = Vec3::new(5.0, 5.0, 0.0); let h = d.add(&Space::Model, Default::default(), EntityKind::Dimension(al)).unwrap(); let text = write_dxf(&d); - // A standard aligned DIMENSION record (type 1 | 32), so other programs can read it. + // AutoCAD's own record: an ARC_DIMENSION of type 5 | 32, its arc in its own subclass, the + // angles counter-clockwise from p13 to p14, and no DraftCraft data for the centre. + let rec = record_of(&text, "ARC_DIMENSION"); + let after = |marker: &str| rec.iter().skip_while(|p| **p != (100, marker.to_string())).skip(1).cloned().collect::>(); + assert!(rec.contains(&(70, "37".into())), "{rec:?}"); + let arc = after("AcDbArcDimension"); + let f = |code: i32| arc.iter().find(|p| p.0 == code).map(|p| p.1.parse::().unwrap()); + assert_eq!((f(15), f(25)), (Some(5.0), Some(5.0))); + assert_eq!((f(40), f(41)), (Some(0.0), Some(std::f64::consts::FRAC_PI_2))); + assert_eq!((f(70), f(71)), (Some(0.0), Some(0.0))); + assert!(!text.contains("ARCLEN"), "{text}"); let lines: Vec<&str> = text.lines().map(str::trim).collect(); - assert!(lines.windows(2).any(|w| w == ["70", "33"]) && !lines.windows(2).any(|w| w == ["70", "40"]), "{text}"); + assert!(lines.windows(4).any(|w| w == ["1", "ARC_DIMENSION", "2", "AcDbArcDimension"]), "the class is declared"); let back = read_dxf(text.as_bytes()).unwrap(); match &back.entity(h).unwrap().kind { EntityKind::Dimension(x) => { @@ -1900,12 +1923,84 @@ fn arc_length_dimension_keeps_its_kind_and_centre_on_roundtrip() { } _ => panic!("not a dimension"), } - // And through DWG. - let back = read(&write(&d, "t.dwg").unwrap(), "t.dwg").unwrap(); - let dims: Vec<_> = back.model.iter().filter_map(|e| if let EntityKind::Dimension(x) = &e.kind { Some(x.clone()) } else { None }).collect(); + // And through DWG, in every version. + for v in Version::ALL { + let dims = dims_of(&read(&write_dwg_own(&d, v).unwrap().0, "t.dwg").unwrap()); + assert_eq!(dims.len(), 1); + assert!(matches!(dims[0].kind, DimKind::ArcLength), "{v:?}: {:?}", dims[0].kind); + assert!((dims[0].p15 - Vec3::new(5.0, 5.0, 0.0)).len() < 1e-9, "{v:?}"); + assert!((dims[0].p13 - Vec3::new(15.0, 5.0, 0.0)).len() < 1e-9, "{v:?}"); + } +} + +/// A partial arc-length dimension with a leader, and a jogged radius, keep what makes them so +/// through DXF and every DWG version; the jogged radius is AutoCAD's LARGE_RADIAL_DIMENSION. +#[test] +fn partial_arc_length_and_jogged_radius_survive_dxf_and_dwg() { + let mut d = Drawing::new_metric(); + let mut al = dim(DimKind::ArcLength, Vec3::new(9.659258, 2.588190, 0.0), Vec3::new(2.588190, 9.659258, 0.0)); + al.defpt = Vec3::new(14.0, 14.0, 0.0); + al.marks.arc_partial = true; + al.marks.arc_leader = true; + d.add(&Space::Model, Default::default(), EntityKind::Dimension(al.clone())).unwrap(); + let mut jr = dim(DimKind::Radius, Vec3::ZERO, Vec3::ZERO); + jr.defpt = Vec3::new(30.0, 0.0, 0.0); + jr.p15 = Vec3::new(33.0, 4.0, 0.0); + jr.marks.jogged = Some(JoggedRadius { center: Vec3::new(45.0, 10.0, 0.0), jog: Vec3::new(39.0, 6.0, 0.0) }); + d.add(&Space::Model, Default::default(), EntityKind::Dimension(jr.clone())).unwrap(); + let text = write_dxf(&d); + let rec = record_of(&text, "LARGE_RADIAL_DIMENSION"); + assert!(rec.contains(&(100, "AcDbRadialDimensionLarge".into())) && rec.contains(&(70, "41".into())), "{rec:?}"); + assert!(!text.contains("JOGGED"), "the jog is the record's own, not DraftCraft data"); + let check = |what: &str, back: &Drawing| { + let dims = dims_of(back); + assert_eq!(dims.len(), 2, "{what}"); + assert!(matches!(dims[0].kind, DimKind::ArcLength), "{what}"); + assert!(dims[0].marks.arc_partial && dims[0].marks.arc_leader, "{what}"); + assert!((dims[0].p13 - al.p13).len() < 1e-9 && (dims[0].p14 - al.p14).len() < 1e-9, "{what}"); + assert!(matches!(dims[1].kind, DimKind::Radius), "{what}"); + assert_eq!(dims[1].marks.jogged, jr.marks.jogged, "{what}"); + assert!((dims[1].p15 - jr.p15).len() < 1e-9, "{what}"); + }; + check("dxf", &read_dxf(text.as_bytes()).unwrap()); + for v in Version::ALL { + check(&format!("{v:?}"), &read(&write_dwg_own(&d, v).unwrap().0, "t.dwg").unwrap()); + } +} + +/// AutoCAD's arc-length dimension of part of an arc gives its two points in either order, with +/// the arc's start and end angles; DraftCraft draws from the point at the start angle. Records in +/// the DXF Reference's layout, as AutoCAD 2027 writes them. +#[test] +fn autocad_arc_length_and_jogged_radius_records_are_read() { + let body = |kind: &str, flags: i32, own: &str| { + format!( + "0\nSECTION\n2\nENTITIES\n0\n{kind}\n5\n1F0\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n280\n0\n2\n\n10\n17.0\n20\n14.0\n30\n0.0\n11\n16.0\n21\n16.0\n31\n0.0\n70\n{flags}\n71\n5\n42\n10.47\n3\nStandard\n{own}0\nENDSEC\n0\nEOF\n" + ) + }; + let arc = "100\nAcDbArcDimension\n13\n2.588\n23\n9.659\n33\n0.0\n14\n9.659\n24\n2.588\n34\n0.0\n15\n0.0\n25\n0.0\n35\n0.0\n70\n1\n40\n0.2618\n41\n1.309\n71\n1\n16\n2.588\n26\n9.659\n36\n0.0\n17\n9.659\n27\n2.588\n37\n0.0\n"; + let dims = dims_of(&read_dxf(body("ARC_DIMENSION", 37, arc).as_bytes()).unwrap()); + assert_eq!(dims.len(), 1); + let a = &dims[0]; + assert!(matches!(a.kind, DimKind::ArcLength) && a.marks.arc_partial && a.marks.arc_leader); + assert_eq!((a.p13.xy(), a.p14.xy()), (Vec2::new(9.659, 2.588), Vec2::new(2.588, 9.659)), "the point at 15° first"); + let large = "100\nAcDbRadialDimensionLarge\n13\n45.0\n23\n10.0\n33\n0.0\n14\n38.9\n24\n6.1\n34\n0.0\n15\n33.9\n25\n3.1\n35\n0.0\n40\n0.0\n"; + let dims = dims_of(&read_dxf(body("LARGE_RADIAL_DIMENSION", 169, large).as_bytes()).unwrap()); + assert_eq!(dims.len(), 1); + assert!(matches!(dims[0].kind, DimKind::Radius) && dims[0].user_text_pos); + assert_eq!(dims[0].p15.xy(), Vec2::new(33.9, 3.1)); + assert_eq!(dims[0].marks.jogged, Some(JoggedRadius { center: Vec3::new(45.0, 10.0, 0.0), jog: Vec3::new(38.9, 6.1, 0.0) })); +} + +/// A file DraftCraft wrote before arc-length dimensions were AutoCAD's ARC_DIMENSION: an aligned +/// dimension with the centre in DraftCraft's extended data still opens as one. +#[test] +fn an_older_draftcraft_arc_length_dimension_still_reads() { + let text = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n0\nAPPID\n2\nDRAFTCRAFT\n70\n0\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nDIMENSION\n5\n1F0\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n\n10\n0.0\n20\n12.0\n30\n0.0\n11\n0.0\n21\n0.0\n31\n0.0\n70\n33\n3\nStandard\n100\nAcDbAlignedDimension\n13\n10.0\n23\n0.0\n33\n0.0\n14\n0.0\n24\n10.0\n34\n0.0\n1001\nDRAFTCRAFT\n1000\nARCLEN\n1002\n{\n1010\n0.0\n1020\n0.0\n1030\n0.0\n1002\n}\n0\nENDSEC\n0\nEOF\n"; + let dims = dims_of(&read_dxf(text.as_bytes()).unwrap()); assert_eq!(dims.len(), 1); assert!(matches!(dims[0].kind, DimKind::ArcLength), "{:?}", dims[0].kind); - assert!((dims[0].p15 - Vec3::new(5.0, 5.0, 0.0)).len() < 1e-9); + assert_eq!(dims[0].p15, Vec3::ZERO); } /// Two gradient hatches (true colours, shifted, rotated; index colours, centered) and a plain diff --git a/crates/io/tests/it/dwg_direct.rs b/crates/io/tests/it/dwg_direct.rs index 908c5dd0..751859da 100644 --- a/crates/io/tests/it/dwg_direct.rs +++ b/crates/io/tests/it/dwg_direct.rs @@ -680,7 +680,16 @@ fn dimensions_drawing() -> draftcraft_doc::Drawing { let mut aligned = dim(DimKind::Aligned, p(32.0, 6.0), p(28.0, 8.0), p(20.0, 0.0), p(30.0, 4.0), Vec3::ZERO, Vec3::ZERO); aligned.text = "<> typ.".into(); aligned.user_text_pos = true; + // An arc-length dimension of part of an arc of radius 5 about (100, 0), with a leader; a + // jogged radius of a circle of radius 5 about (120, 0). + let mut arc = dim(DimKind::ArcLength, p(107.0, 3.0), p(104.0, 6.0), p(104.33, 2.5), p(102.5, 4.33), p(100.0, 0.0), Vec3::ZERO); + arc.marks.arc_partial = true; + arc.marks.arc_leader = true; + let mut jogged = dim(DimKind::Radius, p(120.0, 0.0), p(123.0, 3.0), Vec3::ZERO, Vec3::ZERO, p(123.54, 3.54), Vec3::ZERO); + jogged.marks.jogged = Some(JoggedRadius { center: p(135.0, 10.0), jog: p(129.0, 6.0) }); let kinds = vec![ + arc, + jogged, linear, aligned, dim(DimKind::Angular, p(45.0, 8.0), p(46.0, 9.0), p(40.0, 0.0), p(48.0, 0.0), p(40.0, 0.0), p(46.0, 6.0)), @@ -707,7 +716,7 @@ fn every_kind_of_dimension_reads_as_its_dxf_reads_it() { let reference = via_dxf(&source, version); let dims = |d: &draftcraft_doc::Drawing| d.model.iter().filter(|e| matches!(e.kind, EntityKind::Dimension(_))).cloned().collect::>(); let (got, want) = (dims(&d), dims(&reference)); - assert_eq!(want.len(), 8, "{version:?}"); + assert_eq!(want.len(), 10, "{version:?}"); assert_eq!(got.len(), want.len(), "{version:?}: unread {}", unread.summary()); for (ge, we) in got.iter().zip(&want) { let (mut g, mut w) = (serde_json::to_value(ge.as_ref()).unwrap(), serde_json::to_value(we.as_ref()).unwrap()); @@ -1605,3 +1614,105 @@ fn a_2000_attribute_chain_ends_before_its_seqend() { assert!(seqends >= 2, "the drawing's block references carry attributes"); assert_eq!(draftcraft_io::read(&bytes, "t.dwg").unwrap().model.len(), d.model.len()); } + +/// An arc-length dimension and a jogged radius are AutoCAD's ARC_DIMENSION and +/// LARGE_RADIAL_DIMENSION in a DWG file, their fields after the common dimension data in the order +/// AutoCAD 2027's own 2000 and 2018 files hold them (observed black-box): the dimension arc +/// point, the arc's two points, its centre, the partial flag, the start and end angles, the leader +/// flag and the two points again; the centre, the point on the circle, the leader length, the +/// overriding centre and the jog. +#[test] +fn arc_length_and_jogged_radius_dimensions_are_laid_out_as_autocad_writes_them() { + use draftcraft_doc::{DimKind, Dimension, Drawing, EntityKind, JoggedRadius, Space}; + use draftcraft_dwg::DwgVersion as DV; + use draftcraft_geom::Vec3; + use draftcraft_io::{Version, write_dwg_own}; + let base = Dimension { + kind: DimKind::ArcLength, + defpt: Vec3::new(14.0, 0.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::new(10.0, 0.0, 0.0), + p14: Vec3::new(0.0, 10.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: None, + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let mut d = Drawing::new_metric(); + let mut arc = base.clone(); + arc.marks.arc_partial = true; + d.add(&Space::Model, Default::default(), EntityKind::Dimension(arc)).unwrap(); + let mut jr = base; + jr.kind = DimKind::Radius; + jr.defpt = Vec3::new(30.0, 0.0, 0.0); + jr.p15 = Vec3::new(35.0, 0.0, 0.0); + jr.marks.jogged = Some(JoggedRadius { center: Vec3::new(45.0, 10.0, 0.0), jog: Vec3::new(39.0, 6.0, 0.0) }); + d.add(&Space::Model, Default::default(), EntityKind::Dimension(jr)).unwrap(); + for v in [Version::R2000, Version::R2018] { + let bytes = write_dwg_own(&d, v).unwrap().0; + let file = DwgFile::open(&bytes).unwrap(); + let mut seen = Vec::new(); + for o in file.objects().filter(|o| o.is_entity) { + let mut r = file.read_object(&o).unwrap(); + if !matches!(o.type_name.as_str(), "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION") { + continue; + } + seen.push(o.type_name.clone()); + // The common dimension data. + if r.version() >= DV::R2010 { + r.rc().unwrap(); + } + r.bd3().unwrap(); + r.rd2().unwrap(); + r.bd().unwrap(); + r.rc().unwrap(); + r.text().unwrap(); + for _ in 0..2 { + r.bd().unwrap(); + } + r.bd3().unwrap(); + r.bd().unwrap(); + r.bs().unwrap(); + r.bs().unwrap(); + r.bd().unwrap(); + r.bd().unwrap(); + if r.version() >= DV::R2007 { + for _ in 0..3 { + r.b().unwrap(); + } + } + r.rd2().unwrap(); + if o.type_name == "ARC_DIMENSION" { + assert_eq!(r.bd3().unwrap(), [14.0, 0.0, 0.0], "{v:?}: the dimension arc point"); + assert_eq!(r.bd3().unwrap(), [10.0, 0.0, 0.0]); + assert_eq!(r.bd3().unwrap(), [0.0, 10.0, 0.0]); + assert_eq!(r.bd3().unwrap(), [0.0, 0.0, 0.0], "the centre"); + assert!(r.b().unwrap(), "partial"); + assert_eq!(r.bd().unwrap(), 0.0); + assert!((r.bd().unwrap() - std::f64::consts::FRAC_PI_2).abs() < 1e-12); + assert!(!r.b().unwrap(), "no leader"); + assert_eq!(r.bd3().unwrap(), [10.0, 0.0, 0.0]); + assert_eq!(r.bd3().unwrap(), [0.0, 10.0, 0.0]); + } else { + assert_eq!(r.bd3().unwrap(), [30.0, 0.0, 0.0], "{v:?}: the centre"); + assert_eq!(r.bd3().unwrap(), [35.0, 0.0, 0.0]); + assert_eq!(r.bd().unwrap(), 0.0); + assert_eq!(r.bd3().unwrap(), [45.0, 10.0, 0.0]); + assert_eq!(r.bd3().unwrap(), [39.0, 6.0, 0.0]); + } + assert_eq!(r.remaining_bits(), 0, "{v:?} {}: nothing after", o.type_name); + } + assert_eq!(seen, ["ARC_DIMENSION", "LARGE_RADIAL_DIMENSION"], "{v:?}"); + let back = draftcraft_io::read(&bytes, "t.dwg").unwrap(); + let kinds: Vec<_> = back.model.iter().filter_map(|e| if let EntityKind::Dimension(x) = &e.kind { Some(x.kind) } else { None }).collect(); + assert_eq!(kinds, [DimKind::ArcLength, DimKind::Radius]); + } +} diff --git a/docs/dwg-handoff.md b/docs/dwg-handoff.md index bc95b2b3..4b497ea4 100644 --- a/docs/dwg-handoff.md +++ b/docs/dwg-handoff.md @@ -91,8 +91,6 @@ and the note says saving over the file would lose it. - 3DSOLID, REGION and BODY whose description is binary (AutoCAD 2004 and later files) or in the data store (2013 and later). Text ones (AutoCAD 2000 files, DraftCraft's own) are kept. - MESH (subdivision meshes) and SHAPE (a shape from an SHX file: its name needs the file). -- ARC_DIMENSION and LARGE_RADIAL_DIMENSION are read as far as the drawing has a place for them - (see "Decisions open" in `dwg.md`). **Behaviour that is not kept** diff --git a/docs/dwg-writer-handoff.md b/docs/dwg-writer-handoff.md index 3df762bb..6906cac5 100644 --- a/docs/dwg-writer-handoff.md +++ b/docs/dwg-writer-handoff.md @@ -21,9 +21,7 @@ starts from the head of PR #15 (which contains `main` at f6f72215). AutoCAD's universal-time variables, and AutoCAD's variable dictionary when the drawing has none. - `cargo test -p draftcraft-io --no-fail-fast`: all pass (the `it` suite 578, 21 ignored), and `cargo test -p draftcraft-dwg` (101). -- **Not verified in AutoCAD itself.** A nested session was set up to open the files in the - user's AutoCAD 2027 with computer use, and access to AutoCAD was refused twice; AutoCAD may be - blocked in the app's Computer use settings. What stands in for it is below. +- **Verified in AutoCAD 2027**: see "What is left", item 1, for the files and versions opened. ## How it is built @@ -95,7 +93,11 @@ set; an AutoCAD 2018 MTEXT ends with a null reference. dimensions 2000, tables 2010, attributes and annotation 2000), after four fixes: anonymous blocks stored unnumbered (`*D`, `*T`), the `AcDbSavedByObjectVersion` extended data on visual styles up to 2013, an empty VX table in 2000 files, and SEQENDs left out of the 2000 entity - chain. The image files were not checked. + chain. Since then, also with no recovery and AUDIT 0: mi201 2018, dimensions 2018 (with arc + length and jogged radius dimensions, which AutoCAD lists as its own types), hatches 2007 and + 2018 (patterns, gradients, solid fill with a hole), mlines 2013, regions 2007, viewports 2007 + and 2018 (the layout viewports show the model). AutoCAD's own save of our mi201 2018 file + reads in DraftCraft the same as ours. The image files were not checked. 2. Dynamic-block parameters and actions made in the Block Editor are written to DWG: the Block Editor keeps the evaluation graph's node list (`rebuild_graph` in `crates/doc/src/dynblock/author.rs`), and `crates/engine/tests/dynblock_authoring.rs` saves diff --git a/docs/dwg.md b/docs/dwg.md index 2d7b7e12..883d0683 100644 --- a/docs/dwg.md +++ b/docs/dwg.md @@ -105,12 +105,11 @@ DraftCraft writes every version itself, and acadrust is gone. What remains: | 18 | acadrust removed | done | | 19 | Dynamic-block parameters and actions made in the Block Editor written to DWG | done | -Decisions open: - -- **ARC_DIMENSION and LARGE_RADIAL_DIMENSION**: the drawing has no place for an arc-length - dimension's leader and partial flag or a jogged radius's jog, and the writer can't write either - type back; the DXF reader keeps both as raw records. Raw carry (step 12), or new dimension kinds - in the drawing and the writer. +ARC_DIMENSION and LARGE_RADIAL_DIMENSION are read and written in DXF and DWG as AutoCAD 2027 +writes them (its 2000 and 2018 files and its DXF): an arc-length dimension is `DimKind::ArcLength` +with its partial and leader flags in `DimMarks`, a jogged radius `DimKind::Radius` with +`DimMarks::jogged`. Their DWG fields are pinned by +`arc_length_and_jogged_radius_dimensions_are_laid_out_as_autocad_writes_them`. Not yet confirmed against a file AutoCAD saved (an AutoCAD drawing with them would settle each):