diff --git a/NOTICE b/NOTICE index 083dcc98..82be3108 100644 --- a/NOTICE +++ b/NOTICE @@ -1,6 +1,8 @@ DraftCraft™ Copyright (c) 2026 Skryx Dev and WithShalom Studios. Portions Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. +The DWG reader and writer (crates/dwg: read, write, records, bits, crc, lz77) come from BlackCAD +(https://github.com/withshalom/blackcad), Copyright (c) 2026 WithShalom Studios, MIT OR Apache-2.0. Licensed under the MIT License or the Apache License, Version 2.0, at your option (LICENSE-MIT, LICENSE-APACHE). @@ -15,7 +17,8 @@ Third-party material Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the Mozilla Public License 2.0 and is used unmodified as a separate library (crates/dwg). Its source -is available from crates.io and the repository above. +is available from crates.io and the repository above. DraftCraft's own DWG reader and writer don't +use it; it is the fallback for files they don't cover yet (crates/dwg/src/acadrust). DraftCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code. diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml index 3d3f23aa..71fecb4b 100644 --- a/crates/dwg/Cargo.toml +++ b/crates/dwg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "draftcraft-dwg" -description = "DraftCraft DWG bridge: converts DWG to and from DXF bytes using the acadrust crate (MPL-2.0, used unmodified)" +description = "DraftCraft's DWG codec: reads R13–2018 DWG into object records and writes 2018 DWG (from BlackCAD), with the acadrust crate (MPL-2.0, used unmodified) as a fallback" version.workspace = true edition.workspace = true license.workspace = true @@ -11,11 +11,13 @@ workspace = true [dependencies] log = { workspace = true } -# The same targets as build.rs's `no_dwg_bridge` leave acadrust out: wasm32, and FreeBSD aarch64, -# where acadrust 0.6.6 passed a `*const c_char` (u8 there) to its own `*const i8` sysctlbyname. +# The same target as build.rs's `no_acadrust` leaves acadrust out: FreeBSD aarch64, where +# acadrust 0.6.6 passed a `*const c_char` (u8 there) to its own `*const i8` sysctlbyname. +# wasm32 builds it: acadrust uses `web-time` for its clocks and runs its parallel stages +# sequentially there, and it memory-maps files only on native targets. # A commit of acadrust's main branch, not a release: 0.6.8 and older write 2004–2018 DWG files that # AutoCAD refuses (their section map has no empty first entry; acadrust issue #281, fixed by PR #280). # Go back to a crates.io version (also in crates/io/Cargo.toml) once one includes that fix. -[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dependencies] +[target.'cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))'.dependencies] # MPL-2.0: used as an unmodified dependency only (see plan/adr/0001 and NOTICE). acadrust = { git = "https://github.com/hakanaktt/acadrust", rev = "008c6391bbb5deb7baf4bd44495b7b1cfc53eceb" } diff --git a/crates/dwg/build.rs b/crates/dwg/build.rs index e97782ab..40c14077 100644 --- a/crates/dwg/build.rs +++ b/crates/dwg/build.rs @@ -1,12 +1,12 @@ -//! Sets `no_dwg_bridge` on the targets built without acadrust (see Cargo.toml): the DWG functions +//! Sets `no_acadrust` on the target built without acadrust (see Cargo.toml): the DWG functions //! there return an error that says to use DXF. fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo::rustc-check-cfg=cfg(no_dwg_bridge)"); + println!("cargo::rustc-check-cfg=cfg(no_acadrust)"); let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - if arch == "wasm32" || (os == "freebsd" && arch == "aarch64") { - println!("cargo::rustc-cfg=no_dwg_bridge"); + if os == "freebsd" && arch == "aarch64" { + println!("cargo::rustc-cfg=no_acadrust"); } } diff --git a/crates/dwg/src/acadrust/mod.rs b/crates/dwg/src/acadrust/mod.rs new file mode 100644 index 00000000..bc496f8f --- /dev/null +++ b/crates/dwg/src/acadrust/mod.rs @@ -0,0 +1,1321 @@ +//! DWG through the acadrust crate (MPL-2.0, used unmodified): DWG converted to DXF bytes and back, +//! guarded from the outside (size limits, `catch_unwind`, and a child process on desktop builds). +//! DraftCraft's own reader and writer are the crate root's [`crate::read`] and [`crate::write`]; +//! this module is the fallback for what they don't cover yet. + +use crate::{Limits, VERSIONS, mb}; + +#[cfg(not(no_acadrust))] +pub mod worker; +#[cfg(not(no_acadrust))] +pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_noted, serve_if_asked, use_own_worker, use_worker}; + +#[cfg(not(no_acadrust))] +mod convert { + use std::io::{Cursor, Write}; + use std::panic::AssertUnwindSafe; + + use super::{Limits, mb}; + + /// Read DWG bytes and return an ASCII DXF rendition, within [`Limits::DEFAULT`]. + pub fn dwg_to_dxf(bytes: &[u8]) -> Result, String> { + dwg_to_dxf_with(bytes, Limits::DEFAULT) + } + + /// [`dwg_to_dxf`] with explicit limits. Both are checked before the expensive step they + /// guard: the input size before the DWG reader runs, the DXF size while it is written, so a + /// runaway conversion stops at the limit instead of filling memory first. + pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result, String> { + dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf) + } + + /// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in + /// failsafe mode: an object record it can't decode is skipped instead of failing the whole + /// file, and the notes say how many were skipped and of which types, so a partial read never + /// passes for a complete one. + pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + if bytes.len() > limits.max_dwg_bytes { + return Err(format!("DWG: the file is {}, larger than the {} DraftCraft opens", mb(bytes.len() as u64), mb(limits.max_dwg_bytes as u64))); + } + let outcome = std::panic::catch_unwind(|| { + acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats() + }) + .map_err(|_| "the DWG reader failed on this file".to_string())? + .map_err(|e| format!("DWG: {e}"))?; + // Failsafe skips records, not whole files: when the objects stream itself couldn't be + // read (a damaged header or section map, or not a DWG at all), nothing was read. + if !outcome.stats.record_stream_read { + let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string()); + return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string()))); + } + let mut notes = read_notes(&outcome.stats); + let mut doc = outcome.document; + let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; + if orphans > 0 { + let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; + notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); + } + let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false }; + let written = std::panic::catch_unwind(AssertUnwindSafe(|| { + acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)?; + mtext_contents(&doc, &mut out) + })) + .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; + if out.exceeded { + return Err(format!( + "DWG: converting this {} file produced more than {} of drawing data (the limit); \ + the file is probably damaged, or uses objects the DWG reader misreads", + mb(bytes.len() as u64), + mb(limits.max_dxf_bytes as u64) + )); + } + written.map_err(|e| format!("DWG→DXF: {e}"))?; + Ok((add_header_vars(out.buf, &doc.header), notes)) + } + + /// acadrust 0.6.6's ASCII writer treats a caret followed by a literal space as already + /// escaped, and turns line feeds into paragraph codes. Serialize affected MTEXT contents + /// from the native values instead, using its lossless string writer. All other groups, + /// including embedded-object data, remain byte-for-byte as the DXF writer emitted them. + fn mtext_contents(doc: &acadrust::CadDocument, out: &mut CappedWriter) -> acadrust::Result<()> { + use acadrust::io::dxf::{DxfStreamWriter, DxfTextWriter}; + let contents: std::collections::HashMap<_, _> = doc + .entities() + .filter_map(|e| match e { + acadrust::EntityType::MText(t) if t.value.contains(['^', '\t', '\n']) => Some((t.common.handle.value(), t.value.as_str())), + _ => None, + }) + .collect(); + if contents.is_empty() { + return Ok(()); + } + let dxf = std::mem::take(&mut out.buf); + let mut lines = dxf.split_inclusive(|b| *b == b'\n'); + let (mut mtext, mut text, mut written) = (false, None, false); + while let Some(code) = lines.next() { + let value = lines.next().ok_or_else(|| std::io::Error::other("incomplete DWG bridge DXF pair"))?; + match code.trim_ascii() { + b"0" => { + mtext = value.trim_ascii() == b"MTEXT"; + text = None; + written = false; + } + b"5" if mtext => { + text = std::str::from_utf8(value.trim_ascii()).ok().and_then(|s| u64::from_str_radix(s, 16).ok()).and_then(|h| contents.get(&h)); + } + b"101" => mtext = false, + b"1" | b"3" if mtext && text.is_some() => { + if let Some(&text) = text + && !written + { + let mut writer = DxfTextWriter::new(&mut *out); + if doc.version < acadrust::DxfVersion::AC1021 + && let Some(encoding) = acadrust::io::dxf::code_page::encoding_from_code_page(&doc.header.code_page) + { + writer.set_encoding(encoding); + } + // Each character can expand to two caret-escape characters. Keep + // those pairs together and each group within 250 characters. + let mut rest = text; + while let Some((end, _)) = rest.char_indices().nth(125) { + let (chunk, tail) = rest.split_at(end); + writer.write_xrecord_string(3, chunk)?; + rest = tail; + } + writer.write_xrecord_string(1, rest)?; + written = true; + } + continue; + } + _ => {} + } + out.write_all(code)?; + out.write_all(value)?; + } + Ok(()) + } + + #[cfg(test)] + #[test] + fn mtext_contents_keeps_other_groups_and_the_output_limit() -> acadrust::Result<()> { + for version in [acadrust::DxfVersion::AC1015, acadrust::DxfVersion::AC1032] { + let mut doc = acadrust::CadDocument::new(); + doc.version = version; + doc.header.code_page = "ANSI_1252".into(); + let mut t = acadrust::MText::with_value("é ^ C", acadrust::Vector3::ZERO); + t.common.handle = acadrust::Handle::new(0x10); + doc.add_entity(acadrust::EntityType::MText(Box::new(t)))?; + // Only the MTEXT's own 1/3 groups change. The embedded object's groups and the + // following TEXT record must survive byte-for-byte, including their spaces. + let prefix = b" 0\r\nMTEXT\r\n 5\r\n10\r\n 8\r\n0\r\n"; + let suffix = b"101\r\nEmbedded Object\r\n 1\r\n^ embedded\r\n 3\r\n^ tail\r\n 0\r\nTEXT\r\n 1\r\n^ plain\r\n"; + let raw = [prefix.as_slice(), b" 3\r\nold\r\n 1\r\ntext\r\n", suffix.as_slice()].concat(); + let mut out = CappedWriter { buf: raw.clone(), limit: 4096, exceeded: false }; + mtext_contents(&doc, &mut out)?; + let value: &[u8] = if version == acadrust::DxfVersion::AC1015 { b"\xe9 ^ C" } else { "é ^ C".as_bytes() }; + assert_eq!(out.buf, [prefix.as_slice(), b" 1\r\n", value, b"\r\n", suffix.as_slice()].concat()); + let mut limited = CappedWriter { buf: raw, limit: 1, exceeded: false }; + assert!(mtext_contents(&doc, &mut limited).is_err()); + assert!(limited.exceeded); + } + Ok(()) + } + + /// Most record types named in the skipped-records note. + const NOTE_TYPES: usize = 6; + + /// The note on object records a failsafe read skipped: how many, and how many of each type + /// (most first), or nothing when the read was complete. + pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec { + let skipped = stats.skipped_source_records; + if skipped == 0 { + return Vec::new(); + } + let label = |t: Option<&str>| match t.map(str::parse::) { + Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string), + Some(Err(_)) => t.unwrap_or_default().to_string(), + None => "unknown".to_string(), + }; + let mut by_type: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) { + *by_type.entry(label(d.record_type.as_deref())).or_default() += 1; + } + let mut types: Vec<(String, usize)> = by_type.into_iter().collect(); + types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let mut list: Vec = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect(); + if types.len() > NOTE_TYPES { + list.push(format!("{} more types", types.len() - NOTE_TYPES)); + } + let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() }; + let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" }; + let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") }; + let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) }; + vec![format!( + "DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \ + saving over the original file would lose {them}" + )] + } + + /// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are + /// numbered per file). + fn type_name(code: i16) -> Option<&'static str> { + Some(match code { + 1 => "TEXT", + 2 => "ATTRIB", + 3 => "ATTDEF", + 4 => "BLOCK", + 5 => "ENDBLK", + 6 => "SEQEND", + 7 => "INSERT", + 8 => "MINSERT", + 10..=14 => "VERTEX", + 15 | 16 | 29 | 30 => "POLYLINE", + 17 => "ARC", + 18 => "CIRCLE", + 19 => "LINE", + 20..=26 => "DIMENSION", + 27 => "POINT", + 28 => "3DFACE", + 31 => "SOLID", + 32 => "TRACE", + 33 => "SHAPE", + 34 => "VIEWPORT", + 35 => "ELLIPSE", + 36 => "SPLINE", + 37 => "REGION", + 38 => "3DSOLID", + 39 => "BODY", + 40 => "RAY", + 41 => "XLINE", + 42 => "DICTIONARY", + 43 => "OLEFRAME", + 44 => "MTEXT", + 45 => "LEADER", + 46 => "TOLERANCE", + 47 => "MLINE", + 48 => "BLOCK_CONTROL", + 49 => "BLOCK_RECORD", + 50 => "LAYER_CONTROL", + 51 => "LAYER", + 52 => "STYLE_CONTROL", + 53 => "STYLE", + 56 => "LTYPE_CONTROL", + 57 => "LTYPE", + 60 => "VIEW_CONTROL", + 61 => "VIEW", + 62 => "UCS_CONTROL", + 63 => "UCS", + 64 => "VPORT_CONTROL", + 65 => "VPORT", + 66 => "APPID_CONTROL", + 67 => "APPID", + 68 => "DIMSTYLE_CONTROL", + 69 => "DIMSTYLE", + 70 => "VX_CONTROL", + 71 => "VX_TABLE_RECORD", + 72 => "GROUP", + 73 => "MLINESTYLE", + 74 => "OLE2FRAME", + 77 => "LWPOLYLINE", + 78 => "HATCH", + 79 => "XRECORD", + 80 => "ACDBPLACEHOLDER", + 82 => "LAYOUT", + _ => return None, + }) + } + + /// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's + /// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's + /// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose + /// cells already carry merges are left alone. Each range's first cell gets the span; the + /// cells it covers are marked merged with no span of their own, as DraftCraft's DXF writer does. + fn table_merges(doc: &mut acadrust::CadDocument) { + table_merges_within(doc, MAX_MERGE_CELLS); + } + + /// The most table cells [`table_merges`] visits in one document: each range is capped, but + /// can cover rows × cols cells, so the total is bounded too. + const MAX_MERGE_CELLS: usize = 1 << 24; + + /// A table cell's own text height only when the file says it overrides the table style's. + /// acadrust's DXF writer writes a cell style's height (group 140) whenever the cell has a + /// style record, even a default 0.18 with no override flag, and DraftCraft reads a 140 as an + /// override (#2501). The override is the cell style's TEXT_HEIGHT property flag or the + /// content's format override bit 128; without either the height is cleared (0 is no + /// override), so the table style's height applies. + fn table_cell_heights(doc: &mut acadrust::CadDocument) { + use acadrust::entities::table::CellStylePropertyFlags; + const CONTENT_TEXT_HEIGHT: i32 = 128; + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Table(t) = e else { continue }; + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + // The first content's own height (group 144) when its format override sets bit 128. + // DraftCraft keeps one height for the cell's text, so a later content's override + // must not stand in for the first content's. + let content_height = cell + .contents + .first() + .filter(|c| c.format_override_flags & CONTENT_TEXT_HEIGHT != 0) + .map(|c| c.text_height) + .filter(|h| h.is_finite() && *h > 0.0); + if let Some(h) = content_height { + // DraftCraft reads only the style's height (group 140), so carry it there. + cell.style.get_or_insert_with(acadrust::entities::table::CellStyle::new).text_height = h; + continue; + } + // A style overrides through its property flags or, in newer files, its override + // flags; anything else is the writer's default and is cleared. + if let Some(style) = cell.style.as_mut() + && !style.property_flags.contains(CellStylePropertyFlags::TEXT_HEIGHT) + && style.override_flags & CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32 == 0 + { + style.text_height = 0.0; + } + } + } + } + + /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN + /// components were dropped. The document comes from a third-party reader and is hostile. + fn post_process(doc: &mut acadrust::CadDocument) -> usize { + super::fail_in_test("post_process"); + current_style_names(doc); + table_merges(doc); + table_cell_heights(doc); + table_style_rows(doc, false); + keep_sort_handles(doc); + drop_orphaned_dgn_components(doc) + } + + /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). + fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { + std::panic::catch_unwind(f).map_err(|_| ()) + } + + /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is + /// left unmerged. Returns the cells visited. + fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { + let mut left = budget; + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Table(t) = e else { continue }; + if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) { + continue; + } + let (rows, cols) = (t.rows.len(), t.columns.len()); + // A real table has at most one merge per cell; more ranges than that come from a + // damaged file and would only make this rows × cols × ranges. + let max_ranges = rows.saturating_mul(cols).min(1 << 16); + for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::>() { + // Clamp to the table: the ranges come from the file. + let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1))); + if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { + continue; + } + let area = (bottom - r.top_row + 1).saturating_mul(right - r.left_col + 1); + if area > left { + continue; + } + left -= area; + let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX); + for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) { + for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) { + cell.merged = 1; + let first = (ri, ci) == (r.top_row, r.left_col); + cell.merge_width = if first { span(right - r.left_col) } else { 0 }; + cell.merge_height = if first { span(bottom - r.top_row) } else { 0 }; + } + } + } + } + budget - left + } + + /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF + /// writer renumbers them past every entity handle, but an entity left out of a table sorts by + /// its own handle, so after renumbering it would draw below every listed entity (#2410). Giving + /// the table its codes verbatim makes the writer emit them unchanged. + fn keep_sort_handles(doc: &mut acadrust::CadDocument) { + use acadrust::objects::ObjectType; + let version = doc.version; + for o in doc.objects.values_mut() { + let ObjectType::SortEntitiesTable(t) = o else { continue }; + let hex = |h: acadrust::types::Handle| format!("{:X}", h.value()); + let mut codes = + vec![(5, hex(t.handle)), (330, hex(t.owner_handle)), (100, "AcDbSortentsTable".to_string()), (330, hex(t.block_owner_handle))]; + for e in t.entries() { + codes.push((331, hex(e.entity_handle))); + codes.push((5, hex(e.sort_handle))); + } + t.raw_dxf_codes = Some(codes); + t.raw_dxf_version = Some(version); + } + } + + /// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps + /// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while + /// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields + /// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written; + /// otherwise the flags are copied into the fields after one is read. Older versions store + /// both and are left alone. + fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) { + use acadrust::objects::{ObjectType, TableStyleFlags}; + if doc.version < acadrust::DxfVersion::AC1024 { + return; + } + for o in doc.objects.values_mut() { + let ObjectType::TableStyle(s) = o else { continue }; + for (bit, suppressed) in + [(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)] + { + if to_flags { + s.flags.set(bit, *suppressed); + } else { + *suppressed = s.flags.contains(bit); + } + } + } + } + + /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, + /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as + /// DraftCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, + /// acadrust 0.6.6 reads and writes itself. + fn dimension_flags(doc: &mut acadrust::CadDocument) { + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Dimension(d) = e else { continue }; + d.base_mut().dwg_flags_byte |= 0x02; + } + } + + /// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses + /// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of + /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE + /// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053 + /// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file + /// didn't open at all. No definition that was read refers to them (a definition the reader + /// skipped can't use them either) and DraftCraft doesn't draw DGN line styles, so nothing + /// visible is lost. + /// Every component a definition reaches (directly, or through compound and point + /// components) is kept, as are the definitions; dictionary entries that named a dropped + /// component go with it. Returns how many were left out. + fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize { + use acadrust::objects::{DgnLineStyleData, ObjectType}; + use std::collections::{HashMap, HashSet}; + // Each component's references, and the definitions' root components to start from. + let mut refs: HashMap> = HashMap::new(); + let mut stack: Vec = Vec::new(); + for (h, o) in &doc.objects { + let ObjectType::DgnLineStyle(ls) = o else { continue }; + match &ls.data { + DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component), + DgnLineStyleData::Component { component, .. } => { + refs.insert(*h, component.references()); + } + DgnLineStyleData::Registered { .. } => {} + } + } + if refs.is_empty() { + return 0; + } + // Each component is visited once, so cycles and shared subtrees end. + let mut used: HashSet = HashSet::new(); + while let Some(h) = stack.pop() { + if let Some(r) = refs.get(&h) + && used.insert(h) + { + stack.extend(r.iter().copied()); + } + } + let orphans: HashSet = refs.into_keys().filter(|h| !used.contains(h)).collect(); + if orphans.is_empty() { + return 0; + } + doc.objects.retain(|h, _| !orphans.contains(h)); + doc.dgn_ls_components.retain(|h, _| !orphans.contains(h)); + for o in doc.objects.values_mut() { + let ObjectType::Dictionary(d) = o else { continue }; + if d.entries.iter().any(|(_, e)| orphans.contains(e)) { + d.entries.retain(|(_, e)| !orphans.contains(e)); + let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect(); + d.hard_owner_entries.retain(|k| keys.contains(k.as_str())); + } + } + orphans.len() + } + + /// Leave out what acadrust can't write as this DWG version: other programs' custom entities + /// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file + /// for one of them (0.6.3 left them out); DraftCraft already tells the user which entity types + /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many + /// records of each DXF type were left out, so a save can say so. + fn drop_unwritable(doc: &mut acadrust::CadDocument) -> super::Unwritten { + let version = doc.version; + let mut dropped = super::Unwritten::new(); + let mut count = |name: &str| { + let n = dropped.entry(name.trim().to_ascii_uppercase()).or_insert(0); + *n = n.saturating_add(1); + }; + let unwritable: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Unknown(u) + if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => + { + count(&u.dxf_name); + Some(u.common.handle) + } + _ => None, + }) + .collect(); + for h in &unwritable { + doc.remove_entity(*h); + } + let objects: Vec = doc + .objects + .iter() + .filter_map(|(h, o)| match o { + acadrust::objects::ObjectType::Unknown { type_name, raw_dwg_data, raw_dwg_version, .. } + if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => + { + count(type_name); + Some(*h) + } + _ => None, + }) + .collect(); + for h in &objects { + doc.objects.remove(h); + } + dropped + } + + /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of + /// the HEADER section: (name, group code, value). + fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] { + [ + // DWG holds radians; `$ANGBASE` is in degrees. + ("$ANGBASE", 50, h.angle_base.to_degrees().to_string()), + ("$ANGDIR", 70, h.angle_direction.to_string()), + ("$FILLETRAD", 40, h.fillet_radius.to_string()), + ("$CHAMFERA", 40, h.chamfer_distance_a.to_string()), + ("$CHAMFERB", 40, h.chamfer_distance_b.to_string()), + ("$ELEVATION", 40, h.elevation.to_string()), + ("$THICKNESS", 40, h.thickness.to_string()), + ] + } + + /// Add the [`unwritten_header_vars`] to the HEADER section of acadrust's DXF text, before its + /// ENDSEC; a variable the writer already wrote is left alone. Text of another layout than + /// acadrust's (` 0\r\nSECTION\r\n 2\r\nHEADER\r\n` … ` 0\r\nENDSEC\r\n`) is returned unchanged. + fn add_header_vars(mut dxf: Vec, h: &acadrust::document::HeaderVariables) -> Vec { + const START: &[u8] = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n"; + const END: &[u8] = b"\r\n 0\r\nENDSEC\r\n"; + if !dxf.starts_with(START) { + return dxf; + } + let Some(end) = dxf.windows(END.len()).position(|w| w == END).map(|p| p + 2) else { return dxf }; + let section = dxf.get(..end).unwrap_or_default(); + let mut add = String::new(); + for (name, code, value) in unwritten_header_vars(h) { + let written = section.windows(name.len() + 2).any(|w| w.starts_with(name.as_bytes()) && w.ends_with(b"\r\n")); + if !written && value.parse::().is_ok_and(f64::is_finite) { + add.push_str(&format!(" 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n")); + } + } + dxf.splice(end..end, add.into_bytes()); + dxf + } + + /// Collects the DXF text and fails the write once it would grow past `limit`. + struct CappedWriter { + buf: Vec, + limit: usize, + exceeded: bool, + } + + impl Write for CappedWriter { + fn write(&mut self, b: &[u8]) -> std::io::Result { + // Sticky: once over, every later write fails too. + if self.exceeded || self.buf.len().saturating_add(b.len()) > self.limit { + self.exceeded = true; + return Err(std::io::Error::other("DXF size limit reached")); + } + self.buf.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// Oldest DWG version written; older DXF input is written as this version. + const MIN_DWG_VERSION: acadrust::DxfVersion = acadrust::DxfVersion::AC1018; + + /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 + /// (AC1018). + pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { + convert(dxf, None).map(|(dwg, _)| dwg) + } + + /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), + /// whatever version the DXF declares. + pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { + dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) + } + + /// [`dxf_to_dwg_as`], also returning what the DWG writer left out: how many records of each + /// DXF type it can't write (other programs' custom entities and objects that the DWG reader + /// didn't read from a DWG of this version), empty when the DWG keeps everything. + pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { + let v = match version.trim().to_ascii_uppercase().as_str() { + "AC1015" => acadrust::DxfVersion::AC1015, + "AC1018" => acadrust::DxfVersion::AC1018, + "AC1021" => acadrust::DxfVersion::AC1021, + "AC1024" => acadrust::DxfVersion::AC1024, + "AC1027" => acadrust::DxfVersion::AC1027, + "AC1032" => acadrust::DxfVersion::AC1032, + _ => return Err(super::unsupported(version)), + }; + convert(dxf, Some(v)) + } + + /// The current dimension and text styles' names from their handles: a DWG stores the + /// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG + /// lost its current dimension style (#1051). + fn current_style_names(doc: &mut acadrust::CadDocument) { + let h = doc.header.current_dimstyle_handle; + if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) { + doc.header.current_dimstyle_name = n; + } + let h = doc.header.current_text_style_handle; + if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) { + doc.header.current_text_style_name = n; + } + } + + /// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the + /// handle read with it needn't be the style's in the document, in which case the DWG writer + /// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051). + fn current_dimstyle(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_dimstyle_name.clone(); + if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) { + doc.header.current_dimstyle_handle = h; + } + } + + /// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]: + /// the handle read with the DXF needn't be the style's in the document, in which case the DWG + /// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650). + fn current_text_style(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_text_style_name.clone(); + if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) { + doc.header.current_text_style_handle = h; + } + } + + /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG + /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in + /// the document, so the drawing reopened with layer "0" current (#2252). + fn current_layer(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_layer_name.clone(); + // The table's own lookup compares Unicode case-insensitively ("Survey_Ä" = "Survey_ä"). + if let Some(layer) = doc.layers.get(&name) { + doc.header.current_layer_handle = layer.handle; + } + } + + fn convert(dxf: &[u8], version: Option) -> Result<(Vec, super::Unwritten), String> { + // Reject a pathologically large DXF before handing it to the third-party decoder, which + // allocates tables and section buffers from the input's declared sizes and cannot be + // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder + // runs inside `catch_unwind` so a decode failure is reported rather than crashing. + if dxf.len() > Limits::DEFAULT.max_dxf_bytes { + return Err(format!( + "DXF: the input is {}, larger than the {} DraftCraft converts to DWG", + mb(dxf.len() as u64), + mb(Limits::DEFAULT.max_dxf_bytes as u64) + )); + } + let data = dxf.to_vec(); + let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) + .map_err(|_| "the DXF→DWG conversion failed".to_string())? + .map_err(|e| format!("DXF: {e}"))?; + match version { + Some(v) => doc.version = v, + // Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG + // has no true colours, transparency, table styles or gradients. The DXF stays R2000; + // only the DWG is newer. + None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, + None => {} + } + // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. + let unwritten = guarded(AssertUnwindSafe(|| { + super::fail_in_test("convert"); + other_layout_owners(&mut doc); + table_style_rows(&mut doc, true); + dimension_flags(&mut doc); + let unwritten = drop_unwritable(&mut doc); + current_dimstyle(&mut doc); + add_variable_dictionary(&mut doc); + current_text_style(&mut doc); + current_layer(&mut doc); + unwritten + })) + .map_err(|_| "the DXF to DWG conversion failed on this file".to_string())?; + let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) + .map_err(|_| "the DWG writer failed on this drawing".to_string())? + .map_err(|e| format!("DWG write: {e}"))?; + Ok((dwg, unwritten)) + } + + /// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the + /// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive). + const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary"; + + /// A style or scale name, or `default` when the drawing has none. + fn name_or_default(name: &str, default: &str) -> String { + let name = name.trim(); + if name.is_empty() { default.to_string() } else { name.to_string() } + } + + /// A drawing variable's value as text, or `default` when the header holds a value the + /// variable doesn't accept (a hostile file can put any integer in it). + fn variable_value(value: i16, valid: &[i16], default: i16) -> String { + if valid.contains(&value) { value.to_string() } else { default.to_string() } + } + + /// Add the drawing variables dictionary AutoCAD always writes into the named object + /// dictionary, with the variables it keeps there, when the drawing has none (#1813). + /// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported + /// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such + /// dictionary either, as DraftCraft's and ezdxf's writers don't make one. AutoCAD's AC1032 DWGs + /// read there without it, so newer output is left as it was, and a dictionary the drawing + /// does have keeps its own entries and values. + fn add_variable_dictionary(doc: &mut acadrust::CadDocument) { + use acadrust::objects::{Dictionary, DictionaryVariable, ObjectType}; + if doc.version >= acadrust::DxfVersion::AC1032 { + return; + } + let root_handle = doc.header.named_objects_dict_handle; + match doc.objects.get(&root_handle) { + Some(ObjectType::Dictionary(root)) => { + if root.get(VARIABLE_DICTIONARY).is_some() { + return; + } + } + _ => return, + } + // The variables AutoCAD writes for a drawing with default styles and a 1:1 annotation + // scale. DIMASSOC and HIDETEXT keep the drawing's own header values; LAYEREVAL and + // LAYERNOTIFY have no DXF header variable. + let variables = [ + ("CMLEADERSTYLE", name_or_default(&doc.header.current_mleader_style_name, "Standard")), + ("CTABLESTYLE", name_or_default(&doc.header.current_table_style_name, "Standard")), + ("CANNOSCALE", name_or_default(&doc.header.current_annotation_scale, "1:1")), + ("DIMASSOC", variable_value(doc.header.dimension_associativity, &[0, 1, 2], 2)), + ("HIDETEXT", variable_value(doc.header.hide_text, &[0, 1], 1)), + ("LAYEREVAL", "0".to_string()), + ("LAYERNOTIFY", "0".to_string()), + ]; + let dictionary_handle = doc.allocate_handle(); + let mut dictionary = Dictionary::new(); + dictionary.handle = dictionary_handle; + dictionary.owner = root_handle; + for (name, value) in variables { + let handle = doc.allocate_handle(); + let mut variable = DictionaryVariable::new(name, &value); + variable.handle = handle; + variable.owner_handle = dictionary_handle; + dictionary.add_entry(name, handle); + doc.objects.insert(handle, ObjectType::DictionaryVariable(variable)); + } + doc.objects.insert(dictionary_handle, ObjectType::Dictionary(dictionary)); + if let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&root_handle) { + root.add_entry(VARIABLE_DICTIONARY, dictionary_handle); + } + } + + /// Entities of a layout other than the one in `*Paper_Space` are written owned by their block + /// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1, + /// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a + /// second layout landed on the first one, and the second stayed empty (#1057). + fn other_layout_owners(doc: &mut acadrust::CadDocument) { + let others: std::collections::HashSet = doc + .block_records + .iter() + .filter(|br| { + let n = br.name.to_ascii_uppercase(); + n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit()) + }) + .map(|br| br.handle) + .collect(); + if others.is_empty() { + return; + } + for e in doc.entities_mut() { + let c = e.common_mut(); + if others.contains(&c.owner_handle) { + c.entity_mode = Some(0); + } + } + } + + #[cfg(test)] + mod post_tests { + use super::*; + use acadrust::entities::{CellRange, EntityType, Table}; + + fn doc_with_table(rows: usize, cols: usize, ranges: usize) -> acadrust::CadDocument { + let mut t = Table::new(acadrust::types::Vector3::new(0.0, 0.0, 0.0), rows, cols); + t.merged_ranges = (0..ranges).map(|_| CellRange::new(0, 0, rows - 1, cols - 1)).collect(); + let mut doc = acadrust::CadDocument::new(); + assert!(doc.add_entity(EntityType::Table(Box::new(t))).is_ok()); + doc + } + + /// Overlapping whole-table ranges can't make the merge pass visit more than its budget (#1934). + #[test] + fn merge_work_is_bounded_by_the_cell_budget() { + let mut doc = doc_with_table(10, 10, 50); + assert_eq!(table_merges_within(&mut doc, 250), 200, "two whole-table ranges fit, the rest are skipped"); + let mut doc = doc_with_table(10, 10, 1); + assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); + } + + /// A height marked only in the style's override flags (as newer files store it) is kept, + /// and the same height with no flag at all is cleared (review on #2588). Tested on the + /// read document because acadrust's DWG writer doesn't write the override flags. + #[test] + fn a_style_override_flag_keeps_the_cell_height() { + use acadrust::entities::table::{CellStyle, CellStylePropertyFlags}; + let height = |override_flags: i32| { + let mut doc = doc_with_table(1, 1, 0); + for e in doc.entities_mut() { + if let EntityType::Table(t) = e { + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + let mut s = CellStyle::new(); + s.text_height = 0.5; + s.override_flags = override_flags; + cell.style = Some(s); + } + } + } + table_cell_heights(&mut doc); + doc.entities().find_map(|e| match e { + EntityType::Table(t) => t.rows.first()?.cells.first()?.style.as_ref().map(|s| s.text_height), + _ => None, + }) + }; + assert_eq!(height(CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32), Some(0.5)); + assert_eq!(height(0), Some(0.0)); + } + + /// A panic in the post-read fix-ups is an error, not a crash (#1934). + #[test] + fn a_panic_in_post_processing_is_an_error() { + #[allow(clippy::panic)] + let r = guarded(AssertUnwindSafe(|| -> usize { panic!("boom") })); + assert!(r.is_err()); + assert_eq!(guarded(|| 3), Ok(3)); + } + } +} + +#[cfg(not(no_acadrust))] +pub use convert::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_noted}; + +/// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer +/// can't write. +pub type Unwritten = std::collections::BTreeMap; + +// Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The +// stage then panics on entry, so a test through the public API shows whether it is guarded. +#[cfg(all(test, not(no_acadrust)))] +thread_local! { + static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. +#[cfg(not(no_acadrust))] +#[allow(clippy::panic)] +fn fail_in_test(_stage: &str) { + #[cfg(test)] + if PANIC_IN.with(|p| p.get()) == Some(_stage) { + panic!("test-forced panic in {_stage}"); + } +} + +/// The error for a DWG version DraftCraft can't write. +#[cfg_attr(no_acadrust, allow(dead_code))] +fn unsupported(version: &str) -> String { + let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect(); + format!("DWG version `{version}` can't be written (DraftCraft writes {})", list.join(", ")) +} + +/// Which build has no DWG bridge, for the stubs' errors. +#[cfg(no_acadrust)] +const NO_BRIDGE_BUILD: &str = "FreeBSD aarch64"; + +/// There's no worker without a bridge. +#[cfg(no_acadrust)] +pub const WORKER_ARG: &str = "--dwg-worker"; +#[cfg(no_acadrust)] +pub fn serve_if_asked() -> Option { + None +} +#[cfg(no_acadrust)] +pub fn use_own_worker() {} +#[cfg(no_acadrust)] +pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + dwg_to_dxf_noted(bytes, limits) +} +#[cfg(no_acadrust)] +pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { + dxf_to_dwg_as(dxf, version) +} +#[cfg(no_acadrust)] +pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, Unwritten), String> { + dxf_to_dwg_noted(dxf, version) +} + +#[cfg(no_acadrust)] +pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_acadrust)] +pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec, Vec), String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_acadrust)] +pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result, String> { + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_acadrust)] +pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_acadrust)] +pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_acadrust)] +pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{is_dwg, version}; + + /// The DXF of an empty drawing, enough for the bridge to make a small DWG. + #[cfg(not(no_acadrust))] + const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; + + /// Makes `stage` panic on the current thread until dropped. + #[cfg(not(no_acadrust))] + struct PanicIn; + + #[cfg(not(no_acadrust))] + impl PanicIn { + fn at(stage: &'static str) -> Self { + PANIC_IN.with(|p| p.set(Some(stage))); + Self + } + } + + #[cfg(not(no_acadrust))] + impl Drop for PanicIn { + fn drop(&mut self) { + PANIC_IN.with(|p| p.set(None)); + } + } + + /// The public read reports a panic in the post-read fix-ups as an error: this fails if the + /// `guarded` call around `post_process` is taken out (#2402). + #[cfg(not(no_acadrust))] + #[test] + fn reading_a_dwg_survives_a_panic_in_post_processing() { + let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); + assert!(dwg_to_dxf(&dwg).is_ok(), "the DWG reads without the forced panic"); + let _panic = PanicIn::at("post_process"); + let err = dwg_to_dxf(&dwg).unwrap_err(); + assert!(err.contains("the DWG post-processing failed on this file"), "{err}"); + } + + /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). + #[cfg(not(no_acadrust))] + #[test] + fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { + let _panic = PanicIn::at("convert"); + let err = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap_err(); + assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); + } + + #[test] + fn detects_magic() { + assert!(is_dwg(b"AC1032\0\0\0\0")); + assert!(!is_dwg(b" 0\r\nSECTION")); + assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018")); + } + + /// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not + /// Standard: the DXF names the style, and the handle read with it was Standard's (#1650). + #[cfg(not(no_acadrust))] + #[test] + fn current_text_style_reaches_the_dwg() { + let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n"; + let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n"; + let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n"); + let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n"); + let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); + let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle); + assert!(romans.is_some(), "ROMANS is missing from the DWG"); + assert_eq!(Some(doc.header.current_text_style_handle), romans); + } + + #[test] + fn garbage_is_an_error_not_a_crash() { + assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err()); + assert!(dwg_to_dxf(b"").is_err()); + } + + #[cfg(not(no_acadrust))] + #[test] + fn dxf_to_dwg_rejects_garbage_without_crashing() { + // The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures + // rather than crashing (and rejects oversized input before decoding). + assert!(dxf_to_dwg(b"not a dxf file").is_err()); + assert!(dxf_to_dwg(b"").is_err()); + } + + /// A DXF with one DIMENSION per (text, group 70, subclass, points) row. + #[cfg(not(no_acadrust))] + fn dims_dxf(dims: &[(&str, i64, &str, &[(i32, [f64; 2])])]) -> String { + let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); + for (text, flags, sub, pts) in dims { + s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n"; + s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); + for (code, [x, y]) in pts.iter() { + s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); + } + } + s + " 0\nENDSEC\n 0\nEOF\n" + } + + /// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set: + /// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common + /// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way + /// as the writer can't hide a wrong byte. + #[cfg(not(no_acadrust))] + #[test] + fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() { + let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])]; + let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])]; + let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])]; + let kinds = [ + (0, "AcDbAlignedDimension", linear), + (1, "AcDbAlignedDimension", linear), + (4, "AcDbRadialDimension", radius), + (2, "AcDb2LineAngularDimension", angular), + ]; + let mut dims = Vec::new(); + for (ty, sub, pts) in kinds { + dims.push(("HOME", ty | 32, sub, pts)); + dims.push(("MOVED", ty | 32 | 128, sub, pts)); + } + let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); + let mut seen = Vec::new(); + for e in doc.entities() { + let acadrust::entities::EntityType::Dimension(d) = e else { continue }; + let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte); + seen.push((text.to_string(), byte & 0x03)); + assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type); + let default_pos = text == "HOME"; + assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type); + } + for text in ["HOME", "MOVED"] { + assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}"); + } + + // And DraftCraft reads its own DWG back as it wrote it: 128 only on the moved texts. + let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap(); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let mut flags = Vec::new(); + for rec in lines.chunks(2).collect::>().split(|p| p.first() == Some(&"0")) { + let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied()); + if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) { + flags.push((text, v.parse::().unwrap_or(-1) & 128)); + } + } + assert_eq!(flags.len(), 8, "{flags:?}"); + assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}"); + } + + /// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369). + #[cfg(not(no_acadrust))] + fn dxf_handles(dxf: &str) -> std::collections::HashSet { + let lines: Vec<&str> = dxf.lines().collect(); + lines + .chunks(2) + .filter_map(|p| match p { + [c, v] if matches!(c.trim().parse::(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(), + _ => None, + }) + .collect() + } + + /// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN + /// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a + /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and + /// their dictionary entries with them; the definition and every component it reaches — + /// through compound and point components, around a cycle — are kept. + #[cfg(not(no_acadrust))] + #[test] + fn orphaned_dgn_line_style_components_are_left_out() { + use acadrust::objects::*; + let mut doc = acadrust::CadDocument::new(); + let container = doc.allocate_handle(); + let nod = doc.header.named_objects_dict_handle; + let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") }; + root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container)); + let pattern = || DgnLsStrokePattern { + has_iteration_limit: false, + is_single_segment: false, + iteration_limit: 0, + auto_phase: 0.0, + phase: 0.0, + phase_mode: DgnLsPhaseMode::Distance, + strokes: vec![DgnLsStroke { + is_dash: true, + bypass_corner: false, + can_be_scaled: true, + invert_at_origin: false, + invert_at_end: false, + length: 2.5, + start_width: 0.0, + end_width: 0.0, + width_mode: 0, + cap_mode: 0, + }], + }; + let kind = |c: &DgnLsComponentData| match c { + DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol, + DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound, + DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke, + DgnLsComponentData::Point(_) => DgnLsComponentType::Point, + DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal, + }; + let compound = |of: &[acadrust::Handle]| { + DgnLsComponentData::Compound(DgnLsCompoundComponent { + entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(), + }) + }; + let mut entries = Vec::new(); + let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| { + entries.push((format!("{:X}", h.value()), h)); + let reactors = vec![container]; + doc.objects + .insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data })); + }; + let component = |c: DgnLsComponentData| DgnLineStyleData::Component { + kind: kind(&c), + description: "dash".into(), + version: 1, + component_uid: [7; 16], + scale: 1.0, + property_flags: 0, + component: c, + properties: vec![], + }; + let h: Vec = (0..9).map(|_| doc.allocate_handle()).collect(); + let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") }; + put( + &mut doc, + def, + DgnLineStyleData::Definition { + description: "{ dash }".into(), + version: 1, + style_number: 1, + component_uid: [1; 16], + is_continuous: false, + unit_definition: 1.0, + unit_scale: 1.0, + units_type: 0, + is_element: false, + is_physical: false, + is_scale_independent: false, + is_snappable: false, + root_component: root, + undecoded_fields: None, + properties: vec![], + }, + ); + // Used: def → root → {stroke, point → shared, back → root (a cycle)}. + put(&mut doc, root, component(compound(&[stroke, point, back]))); + put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern()))); + put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] }))); + put(&mut doc, back, component(compound(&[root]))); + put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern()))); + // Orphans: an internal component, and two compounds that refer to each other and to a + // used component (which stays). + let pattern_internal = + DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 }; + put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal))); + put(&mut doc, orphan, component(compound(&[orphan_cycle, shared]))); + put(&mut doc, orphan_cycle, component(compound(&[orphan]))); + let mut dict = Dictionary::new(); + dict.handle = container; + dict.owner = nod; + dict.entries = entries; + doc.objects.insert(container, ObjectType::Dictionary(dict)); + let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + + let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); + let dxf = String::from_utf8(dxf).unwrap(); + let handles = dxf_handles(&dxf); + for kept in [def, root, stroke, point, back, shared] { + assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value()); + } + for gone in [internal, orphan, orphan_cycle] { + assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value()); + } + let lines: Vec<&str> = dxf.lines().collect(); + let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect(); + assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}"); + assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}"); + assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); + } + + /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three + /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD + /// read past the object and refused every DWG DraftCraft wrote with a dynamic block that scales + /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also + /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action + /// from DXF is written whole, with the byte AutoCAD writes (0). + #[test] + fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { + use acadrust::objects::*; + let scale_action = |doc: &acadrust::CadDocument| { + doc.objects.values().find_map(|o| match o { + ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), + _ => None, + }) + }; + let mut doc = acadrust::CadDocument::new(); + let h = doc.allocate_handle(); + let conn = |code, name: &str| BlockConnection { code, name: name.into() }; + let mut action = DynamicBlockObject::new("BLOCKSCALEACTION", "AcDbBlockScaleAction"); + action.handle = h; + action.owner = doc.header.named_objects_dict_handle; + let mut a = BlockBasePointAction::default(); + a.action.action.element.name = "Scale".into(); + a.action.connections = vec![conn(2, "UpdatedBaseX"), conn(2, "UpdatedBaseY")]; + a.action.dependent = true; + a.connections = vec![conn(2, "Scale"), conn(2, "XScale"), conn(2, "YScale")]; + a.dwg_tail_byte = 7; + action.data = DynamicBlockData::ScaleAction(a.clone()); + doc.objects.insert(h, ObjectType::DynamicBlock(action)); + + let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + assert_eq!(scale_action(&back).map(|s| s.dwg_tail_byte), Some(7), "the byte isn't written"); + + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + for version in ["AC1018", "AC1032"] { + let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let read = scale_action(&back).unwrap_or_else(|| panic!("{version}: the scale action wasn't written")); + assert_eq!(read.connections, a.connections, "{version}"); + assert_eq!(read.action.connections, a.action.connections, "{version}"); + assert_eq!(read.dwg_tail_byte, 0, "{version}"); + } + } + + /// Saving says what the DWG writer left out, per type: entities of types acadrust's DXF + /// reader doesn't model (another program's custom entity) can't be written; a drawing the DWG + /// keeps whole reports nothing. + #[cfg(not(no_acadrust))] + #[test] + fn saving_lists_the_types_the_dwg_writer_leaves_out() { + let line = " 0\nLINE\n 8\n0\n100\nAcDbEntity\n100\nAcDbLine\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 11\n10.0\n 21\n0.0\n 31\n0.0\n"; + let widget = " 0\nACME_WIDGET\n 8\n0\n100\nAcDbEntity\n100\nAcmeWidget\n 10\n1.0\n 20\n2.0\n 30\n0.0\n"; + let dxf = |body: &str| { + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{body} 0\nENDSEC\n 0\nEOF\n") + }; + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf(&format!("{line}{widget}{widget}")).as_bytes(), version).unwrap(); + assert!(is_dwg(&dwg), "{version}"); + assert_eq!(unwritten, [("ACME_WIDGET".to_string(), 2)].into_iter().collect::(), "{version}"); + } + let (_, unwritten) = dxf_to_dwg_noted(dxf(line).as_bytes(), "AC1032").unwrap(); + assert!(unwritten.is_empty(), "{unwritten:?}"); + } + + /// An OLE2FRAME, which DraftCraft keeps as its DXF groups without modelling it, is written to + /// the DWG with its data: it isn't in the list of what the writer left out. + #[cfg(not(no_acadrust))] + #[test] + fn ole_frames_are_written_with_their_data() { + let ole = " 0\nOLE2FRAME\n 8\n0\n100\nAcDbEntity\n100\nAcDbOle2Frame\n 70\n2\n 10\n1.0\n 20\n9.0\n 30\n0.0\n 11\n8.0\n 21\n2.0\n 31\n0.0\n 71\n2\n 72\n0\n 73\n1\n 90\n4\n310\nDEADBEEF\n 1\nOLE\n"; + let dxf = + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{ole} 0\nENDSEC\n 0\nEOF\n"); + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf.as_bytes(), version).unwrap(); + assert!(unwritten.is_empty(), "{version} {unwritten:?}"); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let frames: Vec> = back + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Ole2Frame(o) => Some(o.encoded_payload()), + _ => None, + }) + .collect(); + assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); + } + } +} diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/acadrust/worker.rs similarity index 100% rename from crates/dwg/src/worker.rs rename to crates/dwg/src/acadrust/worker.rs diff --git a/crates/dwg/src/bits.rs b/crates/dwg/src/bits.rs new file mode 100644 index 00000000..5a85cf7a --- /dev/null +++ b/crates/dwg/src/bits.rs @@ -0,0 +1,1007 @@ +//! Bit-level reader for DWG bit-coded data. +//! +//! Spec: ODA Open Design Specification for .dwg files v5.4.1, chapter 2 +//! "BIT CODES AND DATA DEFINITIONS" (§2.1–§2.13, verified against the spec +//! text). Bits are consumed most-significant-bit first within each byte. +//! Multi-byte raw values (RS, RL, RD…) are assembled little-endian from +//! bit-aligned bytes. + +use crate::read::error::{Error, Result}; +use crate::records::version::DwgVersion; + +/// A reference to another object as stored in the file: a 4-bit code and +/// the handle (or offset) value. See §2.13. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct HandleRef { + pub code: u8, + pub value: u64, +} + +impl HandleRef { + /// Resolve to an absolute handle. Codes 6, 8, 0xA and 0xC are relative + /// to the handle of the object that contains the reference. + pub fn absolute(self, reference: u64) -> u64 { + match self.code { + 0x6 => reference.wrapping_add(1), + 0x8 => reference.wrapping_sub(1), + 0xA => reference.wrapping_add(self.value), + 0xC => reference.wrapping_sub(self.value), + _ => self.value, + } + } +} + +#[derive(Clone)] +pub struct BitReader<'a> { + data: &'a [u8], + /// Current bit position from the start of `data`. + pos: usize, + /// Exclusive bit limit. Reads past it fail with `Truncated`. + end: usize, +} + +impl<'a> BitReader<'a> { + pub fn new(data: &'a [u8]) -> Self { + BitReader { data, pos: 0, end: data.len() * 8 } + } + + /// A reader over `data` restricted to bits `[start, end)`. + pub fn with_bounds(data: &'a [u8], start: usize, end: usize) -> Self { + let max = data.len() * 8; + let end = end.min(max); + BitReader { data, pos: start.min(end), end } + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + pub fn position(&self) -> usize { + self.pos + } + pub fn end(&self) -> usize { + self.end + } + pub fn remaining(&self) -> usize { + self.end.saturating_sub(self.pos) + } + + pub fn set_position(&mut self, bit: usize) -> Result<()> { + if bit > self.end { + return Err(Error::truncated(format!("seek to bit {bit} past limit {}", self.end))); + } + self.pos = bit; + Ok(()) + } + + /// Narrow (never widen past the data) the readable limit. + pub fn set_end(&mut self, end: usize) { + self.end = end.min(self.data.len() * 8); + if self.pos > self.end { + self.pos = self.end; + } + } + + pub fn align_to_byte(&mut self) { + self.pos = (self.pos + 7) & !7; + if self.pos > self.end { + self.pos = self.end; + } + } + + #[inline] + fn need(&self, n: usize) -> Result<()> { + if self.pos + n > self.end { Err(Error::truncated(format!("need {n} bit(s) at bit {} but limit is {}", self.pos, self.end))) } else { Ok(()) } + } + + pub fn skip_bits(&mut self, n: usize) -> Result<()> { + self.need(n)?; + self.pos += n; + Ok(()) + } + + // ----- raw bit access ------------------------------------------------- + + /// B: a single bit. + #[inline] + pub fn b(&mut self) -> Result { + self.need(1)?; + let byte = self.data[self.pos >> 3]; + let bit = (byte >> (7 - (self.pos & 7))) & 1; + self.pos += 1; + Ok(bit == 1) + } + + /// Read `n` (≤ 64) bits as an unsigned number, first bit most significant. + pub fn bits(&mut self, n: u32) -> Result { + debug_assert!(n <= 64); + self.need(n as usize)?; + let mut v: u64 = 0; + for _ in 0..n { + let byte = self.data[self.pos >> 3]; + let bit = (byte >> (7 - (self.pos & 7))) & 1; + v = (v << 1) | bit as u64; + self.pos += 1; + } + Ok(v) + } + + /// BB: a two-bit code. + #[inline] + pub fn bb(&mut self) -> Result { + Ok(self.bits(2)? as u8) + } + + /// 3B: read bits until a zero bit or until three bits were read (§2.1). + pub fn b3(&mut self) -> Result { + let mut v = 0u8; + for _ in 0..3 { + let bit = self.b()?; + v = (v << 1) | bit as u8; + if !bit { + break; + } + } + Ok(v) + } + + // ----- raw (uncompressed) values -------------------------------------- + + /// RC: raw char, eight bits, bit-aligned. + #[inline] + pub fn rc(&mut self) -> Result { + self.need(8)?; + let shift = self.pos & 7; + let idx = self.pos >> 3; + let v = if shift == 0 { + self.data[idx] + } else { + let hi = self.data[idx] << shift; + let lo = self.data[idx + 1] >> (8 - shift); + hi | lo + }; + self.pos += 8; + Ok(v) + } + + /// RS: raw short, little-endian. + pub fn rs(&mut self) -> Result { + let lo = self.rc()?; + let hi = self.rc()?; + Ok(u16::from_le_bytes([lo, hi])) + } + + /// RL: raw long, little-endian. + pub fn rl(&mut self) -> Result { + let mut b = [0u8; 4]; + for x in &mut b { + *x = self.rc()?; + } + Ok(u32::from_le_bytes(b)) + } + + /// Raw 64-bit little-endian value. + pub fn rll(&mut self) -> Result { + let mut b = [0u8; 8]; + for x in &mut b { + *x = self.rc()?; + } + Ok(u64::from_le_bytes(b)) + } + + /// RD: raw IEEE double, little-endian. + pub fn rd(&mut self) -> Result { + Ok(f64::from_bits(self.rll()?)) + } + + pub fn rd2(&mut self) -> Result<[f64; 2]> { + Ok([self.rd()?, self.rd()?]) + } + + pub fn rd3(&mut self) -> Result<[f64; 3]> { + Ok([self.rd()?, self.rd()?, self.rd()?]) + } + + pub fn raw_bytes(&mut self, n: usize) -> Result> { + self.need(n.saturating_mul(8))?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(self.rc()?); + } + Ok(out) + } + + /// SN: 16-byte sentinel. + pub fn sentinel(&mut self) -> Result<[u8; 16]> { + let mut s = [0u8; 16]; + for x in &mut s { + *x = self.rc()?; + } + Ok(s) + } + + // ----- compressed values --------------------------------------------- + + /// BS: bitshort (§2.2). Returned as the raw 16-bit pattern; cast to + /// `i16` where the field is signed. + pub fn bs(&mut self) -> Result { + match self.bb()? { + 0 => self.rs(), + 1 => Ok(self.rc()? as u16), + 2 => Ok(0), + _ => Ok(256), + } + } + + /// BL: bitlong (§2.3). Cast to `i32` where the field is signed. + pub fn bl(&mut self) -> Result { + match self.bb()? { + 0 => self.rl(), + 1 => Ok(self.rc()? as u32), + 2 => Ok(0), + _ => Err(Error::format(format!("BITLONG code 11 is unused (bit {})", self.pos - 2))), + } + } + + /// BLL: bitlonglong (§2.4). A length l followed by l bytes, least + /// significant first. The spec says the length takes "1-3 bits"; this + /// reads it as a plain three-bit number (0–7). VERIFY against real + /// R2010+ files (used for graphics sizes and REQUIREDVERSIONS). + pub fn bll(&mut self) -> Result { + let len = self.bits(3)? as usize; + let mut v = 0u64; + for i in 0..len { + v |= (self.rc()? as u64) << (8 * i); + } + Ok(v) + } + + /// BD: bitdouble (§2.5). + pub fn bd(&mut self) -> Result { + match self.bb()? { + 0 => self.rd(), + 1 => Ok(1.0), + 2 => Ok(0.0), + _ => Err(Error::format(format!("BITDOUBLE code 11 is unused (bit {})", self.pos - 2))), + } + } + + pub fn bd2(&mut self) -> Result<[f64; 2]> { + Ok([self.bd()?, self.bd()?]) + } + + pub fn bd3(&mut self) -> Result<[f64; 3]> { + Ok([self.bd()?, self.bd()?, self.bd()?]) + } + + /// DD: bitdouble with default (§2.9). + pub fn dd(&mut self, default: f64) -> Result { + match self.bb()? { + 0 => Ok(default), + 1 => { + let mut b = default.to_le_bytes(); + for x in b.iter_mut().take(4) { + *x = self.rc()?; + } + Ok(f64::from_le_bytes(b)) + } + 2 => { + let mut b = default.to_le_bytes(); + b[4] = self.rc()?; + b[5] = self.rc()?; + for x in b.iter_mut().take(4) { + *x = self.rc()?; + } + Ok(f64::from_le_bytes(b)) + } + _ => self.rd(), + } + } + + /// BT: bit thickness (§2.10). + pub fn bt(&mut self, ver: DwgVersion) -> Result { + if ver >= DwgVersion::R2000 && self.b()? { + return Ok(0.0); + } + self.bd() + } + + /// BE: bit extrusion (§2.8). + pub fn be(&mut self, ver: DwgVersion) -> Result<[f64; 3]> { + if ver >= DwgVersion::R2000 && self.b()? { + return Ok([0.0, 0.0, 1.0]); + } + self.bd3() + } + + /// MC, signed form (§2.6): continuation flag 0x80 on every byte, and + /// 0x40 on the final byte negates the value. + pub fn mc_signed(&mut self) -> Result { + let mut value: i64 = 0; + let mut shift = 0u32; + loop { + let b = self.rc()?; + if b & 0x80 != 0 { + if shift > 56 { + return Err(Error::format("modular char too long")); + } + value |= ((b & 0x7F) as i64) << shift; + shift += 7; + } else { + value |= ((b & 0x3F) as i64) << shift; + return Ok(if b & 0x40 != 0 { -value } else { value }); + } + } + } + + /// MC, unsigned form: the final byte keeps all seven data bits. Used + /// where values are never negative (object-map handle deltas, the R2010+ + /// handle-stream size). + pub fn mc_unsigned(&mut self) -> Result { + let mut value: u64 = 0; + let mut shift = 0u32; + loop { + let b = self.rc()?; + if shift > 63 { + return Err(Error::format("modular char too long")); + } + value |= ((b & 0x7F) as u64) << shift; + if b & 0x80 == 0 { + return Ok(value); + } + shift += 7; + } + } + + /// MS: modular short (§2.7). Little-endian 16-bit units, 0x8000 flags + /// continuation, fifteen data bits per unit. + pub fn ms(&mut self) -> Result { + let mut value: u32 = 0; + let mut shift = 0u32; + loop { + let w = self.rs()?; + if shift > 30 { + return Err(Error::format("modular short too long")); + } + value |= ((w & 0x7FFF) as u32) << shift; + if w & 0x8000 == 0 { + return Ok(value); + } + shift += 15; + } + } + + /// H: handle reference (§2.13): 4-bit code, 4-bit byte counter, then the + /// value's bytes most significant first. + pub fn handle(&mut self) -> Result { + let first = self.rc()?; + let code = first >> 4; + let counter = (first & 0x0F) as usize; + if counter > 8 { + return Err(Error::format(format!("handle counter {counter} > 8 at bit {}", self.pos - 8))); + } + let mut value: u64 = 0; + for _ in 0..counter { + value = (value << 8) | self.rc()? as u64; + } + Ok(HandleRef { code, value }) + } + + /// OT: object type (§2.12, R2010+). + pub fn ot(&mut self) -> Result { + match self.bb()? { + 0 => Ok(self.rc()? as u16), + 1 => Ok(self.rc()? as u16 + 0x1F0), + _ => self.rs(), + } + } + + /// T (R13–R2004): BS length then that many 8-bit characters in the + /// drawing's code page. Returned undecoded. + pub fn text8(&mut self) -> Result> { + let len = self.bs()? as usize; + self.raw_bytes(len) + } + + /// TU: BS length (in UTF-16 code units) then UTF-16LE units. + pub fn text16(&mut self) -> Result { + let len = self.bs()? as usize; + self.need(len.saturating_mul(16))?; + let mut units = Vec::with_capacity(len); + for _ in 0..len { + units.push(self.rs()?); + } + while units.last() == Some(&0) { + units.pop(); + } + Ok(String::from_utf16_lossy(&units)) + } +} + +/// Bit-level writer, the mirror of [`BitReader`]: bits go most significant +/// first within each byte, multi-byte raw values little-endian. Each +/// compressed form picks the shortest encoding the reader accepts, which +/// is also the choice AutoCAD makes (checked against AC1032 files written +/// by AutoCAD 2027). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BitWriter { + out: Vec, + /// Number of bits written. + n: usize, +} + +impl BitWriter { + pub fn new() -> Self { + Self::default() + } + + /// Bits written so far. + pub fn position(&self) -> usize { + self.n + } + + /// The bytes, the last one padded with zero bits. + pub fn into_bytes(self) -> Vec { + self.out + } + + pub fn bytes(&self) -> &[u8] { + &self.out + } + + /// B + pub fn b(&mut self, v: bool) { + if self.n.is_multiple_of(8) { + self.out.push(0); + } + if v { + let last = self.out.len() - 1; + self.out[last] |= 0x80 >> (self.n % 8); + } + self.n += 1; + } + + /// `count` (≤ 64) bits of `v`, most significant first. + pub fn bits(&mut self, v: u64, count: u32) { + for i in (0..count).rev() { + self.b((v >> i) & 1 == 1); + } + } + + /// Append every bit another writer holds. + pub fn append(&mut self, other: &BitWriter) { + if self.n.is_multiple_of(8) { + self.out.extend_from_slice(&other.out); + self.n += other.n; + // `other` may end mid-byte: its padding bits are zero, as ours + // would be. + return; + } + let full = other.n / 8; + for &byte in &other.out[..full] { + self.rc(byte); + } + let rest = other.n % 8; + if rest > 0 { + self.bits((other.out[full] >> (8 - rest)) as u64, rest as u32); + } + } + + /// Zero bits up to the next byte boundary. + pub fn pad_to_byte(&mut self) { + self.n = self.out.len() * 8; + } + + /// BB + pub fn bb(&mut self, v: u8) { + self.bits(v as u64 & 3, 2); + } + + /// 3B (§2.1): 0 → "0", 2 → "10", 6 → "110", 7 → "111". + pub fn b3(&mut self, v: u8) { + match v { + 0 => self.b(false), + 2 => self.bits(0b10, 2), + 6 => self.bits(0b110, 3), + _ => self.bits(0b111, 3), + } + } + + /// RC + pub fn rc(&mut self, v: u8) { + if self.n.is_multiple_of(8) { + self.out.push(v); + self.n += 8; + } else { + self.bits(v as u64, 8); + } + } + + /// RS + pub fn rs(&mut self, v: u16) { + for b in v.to_le_bytes() { + self.rc(b); + } + } + + /// RL + pub fn rl(&mut self, v: u32) { + for b in v.to_le_bytes() { + self.rc(b); + } + } + + pub fn rll(&mut self, v: u64) { + for b in v.to_le_bytes() { + self.rc(b); + } + } + + /// RD + pub fn rd(&mut self, v: f64) { + self.rll(v.to_bits()); + } + + pub fn rd2(&mut self, v: [f64; 2]) { + for x in v { + self.rd(x); + } + } + + pub fn rd3(&mut self, v: [f64; 3]) { + for x in v { + self.rd(x); + } + } + + pub fn raw_bytes(&mut self, bytes: &[u8]) { + for &b in bytes { + self.rc(b); + } + } + + /// BS (§2.2): 0 and 256 in two bits, 1–255 in a byte. + pub fn bs(&mut self, v: u16) { + match v { + 0 => self.bb(2), + 256 => self.bb(3), + 1..=255 => { + self.bb(1); + self.rc(v as u8); + } + _ => { + self.bb(0); + self.rs(v); + } + } + } + + /// BL (§2.3). + pub fn bl(&mut self, v: u32) { + match v { + 0 => self.bb(2), + 1..=255 => { + self.bb(1); + self.rc(v as u8); + } + _ => { + self.bb(0); + self.rl(v); + } + } + } + + /// BLL (§2.4), with the length as three bits, as [`BitReader::bll`] + /// reads it. + pub fn bll(&mut self, v: u64) { + let len = (8 - v.leading_zeros() as usize / 8).min(7); + let len = if v == 0 { 0 } else { len }; + self.bits(len as u64, 3); + for i in 0..len { + self.rc((v >> (8 * i)) as u8); + } + } + + /// BD (§2.5): 1.0 and 0.0 in two bits (exactly those values, so a + /// negative zero keeps its sign). + pub fn bd(&mut self, v: f64) { + if v.to_bits() == 1.0f64.to_bits() { + self.bb(1); + } else if v.to_bits() == 0 { + self.bb(2); + } else { + self.bb(0); + self.rd(v); + } + } + + pub fn bd2(&mut self, v: [f64; 2]) { + for x in v { + self.bd(x); + } + } + + pub fn bd3(&mut self, v: [f64; 3]) { + for x in v { + self.bd(x); + } + } + + /// DD (§2.9): only the bytes that differ from `default`. + pub fn dd(&mut self, v: f64, default: f64) { + let b = v.to_le_bytes(); + let d = default.to_le_bytes(); + if b == d { + self.bb(0); + } else if b[4..] == d[4..] { + self.bb(1); + self.raw_bytes(&b[..4]); + } else if b[6..] == d[6..] { + self.bb(2); + self.rc(b[4]); + self.rc(b[5]); + self.raw_bytes(&b[..4]); + } else { + self.bb(3); + self.rd(v); + } + } + + /// BT (§2.10). + pub fn bt(&mut self, v: f64, ver: DwgVersion) { + if ver >= DwgVersion::R2000 { + if v.to_bits() == 0 { + self.b(true); + return; + } + self.b(false); + } + self.bd(v); + } + + /// BE (§2.8). + pub fn be(&mut self, v: [f64; 3], ver: DwgVersion) { + if ver >= DwgVersion::R2000 { + if v[0].to_bits() == 0 && v[1].to_bits() == 0 && v[2].to_bits() == 1.0f64.to_bits() { + self.b(true); + return; + } + self.b(false); + } + self.bd3(v); + } + + /// MC, signed form (§2.6). + pub fn mc_signed(&mut self, v: i64) { + let neg = v < 0; + let mut m = v.unsigned_abs(); + loop { + if m < 0x40 { + self.rc(m as u8 | if neg { 0x40 } else { 0 }); + return; + } + self.rc((m & 0x7F) as u8 | 0x80); + m >>= 7; + } + } + + /// MC, unsigned form: the last byte keeps all seven data bits. + pub fn mc_unsigned(&mut self, mut v: u64) { + loop { + if v < 0x80 { + self.rc(v as u8); + return; + } + self.rc((v & 0x7F) as u8 | 0x80); + v >>= 7; + } + } + + /// MS (§2.7). + pub fn ms(&mut self, mut v: u32) { + loop { + if v < 0x8000 { + self.rs(v as u16); + return; + } + self.rs((v & 0x7FFF) as u16 | 0x8000); + v >>= 15; + } + } + + /// H (§2.13): the code, then the value in as few bytes as it needs, + /// most significant first. + pub fn handle(&mut self, code: u8, value: u64) { + let len = if value == 0 { 0 } else { 8 - value.leading_zeros() as usize / 8 }; + self.rc((code << 4) | len as u8); + for i in (0..len).rev() { + self.rc((value >> (8 * i)) as u8); + } + } + + /// OT (§2.12, R2010+). + pub fn ot(&mut self, t: u16) { + if t < 0x100 { + self.bb(0); + self.rc(t as u8); + } else if (0x1F0..0x2F0).contains(&t) { + self.bb(1); + self.rc((t - 0x1F0) as u8); + } else { + self.bb(2); + self.rs(t); + } + } + + /// T (R13–R2004): BS length then the bytes. + pub fn text8(&mut self, bytes: &[u8]) { + self.bs(bytes.len() as u16); + self.raw_bytes(bytes); + } + + /// TU: BS length in UTF-16 units (no terminator), then the units. + pub fn text16(&mut self, s: &str) { + let units: Vec = s.encode_utf16().collect(); + self.bs(units.len() as u16); + for u in units { + self.rs(u); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every fixed-size writer form (B, BS, BL, BD, DD) reads back as the value written. + #[test] + fn fixed_forms_round_trip_through_the_reader() { + let mut w = BitWriter::new(); + w.b(true); + let shorts = [0u16, 1, 255, 256, 257, 0xFFFF, 0x8000]; + let longs = [0u32, 1, 255, 256, 0x1234_5678, u32::MAX]; + let doubles = [0.0, 1.0, -0.0, 2.5, -1e300, f64::MIN_POSITIVE]; + for &v in &shorts { + w.bs(v); + } + for &v in &longs { + w.bl(v); + } + for &v in &doubles { + w.bd(v); + } + for (v, d) in [(1.0, 1.0), (1.0000001, 1.0), (120.5, 120.0), (3.0, -7.0)] { + w.dd(v, d); + } + let bytes = w.clone().into_bytes(); + let mut r = BitReader::new(&bytes); + assert!(r.b().unwrap()); + for &v in &shorts { + assert_eq!(r.bs().unwrap(), v); + } + for &v in &longs { + assert_eq!(r.bl().unwrap(), v); + } + for &v in &doubles { + assert_eq!(r.bd().unwrap().to_bits(), f64::to_bits(v)); + } + for (v, d) in [(1.0, 1.0), (1.0000001, 1.0), (120.5, 120.0), (3.0, -7.0)] { + assert_eq!(r.dd(d).unwrap(), v); + } + assert_eq!(r.position(), w.position()); + } + + /// Every variable-size writer form (MC, MS, H, OT, BLL, 3B, BT, BE, TU) reads back as the value written. + #[test] + fn variable_forms_round_trip_through_the_reader() { + let mut w = BitWriter::new(); + for v in [0i64, 63, 64, 100, -100, 4610, -1413, 112_823_273] { + w.mc_signed(v); + } + for v in [0u64, 127, 128, 4610, 1 << 40] { + w.mc_unsigned(v); + } + for v in [0u32, 0x7FFF, 0x8000, 4_650_033] { + w.ms(v); + } + for (c, v) in [(5u8, 0u64), (4, 0x3D0B5), (2, 0xFF), (3, u64::MAX)] { + w.handle(c, v); + } + for t in [0x13u16, 0x1F2, 0x1F4, 0x2EF, 0x300] { + w.ot(t); + } + for v in [0u64, 1, 0xFF, 0x100, 0x12_3456_789A] { + w.bll(v); + } + for v in [0u8, 2, 6, 7] { + w.b3(v); + } + w.bt(0.0, DwgVersion::R2018); + w.bt(0.25, DwgVersion::R2018); + w.be([0.0, 0.0, 1.0], DwgVersion::R2018); + w.be([0.0, 1.0, 0.0], DwgVersion::R2018); + w.text16("Größe Ω"); + let bytes = w.clone().into_bytes(); + let mut r = BitReader::new(&bytes); + for v in [0i64, 63, 64, 100, -100, 4610, -1413, 112_823_273] { + assert_eq!(r.mc_signed().unwrap(), v); + } + for v in [0u64, 127, 128, 4610, 1 << 40] { + assert_eq!(r.mc_unsigned().unwrap(), v); + } + for v in [0u32, 0x7FFF, 0x8000, 4_650_033] { + assert_eq!(r.ms().unwrap(), v); + } + for (c, v) in [(5u8, 0u64), (4, 0x3D0B5), (2, 0xFF), (3, u64::MAX)] { + assert_eq!(r.handle().unwrap(), HandleRef { code: c, value: v }); + } + for t in [0x13u16, 0x1F2, 0x1F4, 0x2EF, 0x300] { + assert_eq!(r.ot().unwrap(), t); + } + for v in [0u64, 1, 0xFF, 0x100, 0x12_3456_789A] { + assert_eq!(r.bll().unwrap(), v); + } + for v in [0u8, 2, 6, 7] { + assert_eq!(r.b3().unwrap(), v); + } + assert_eq!(r.bt(DwgVersion::R2018).unwrap(), 0.0); + assert_eq!(r.bt(DwgVersion::R2018).unwrap(), 0.25); + assert_eq!(r.be(DwgVersion::R2018).unwrap(), [0.0, 0.0, 1.0]); + assert_eq!(r.be(DwgVersion::R2018).unwrap(), [0.0, 1.0, 0.0]); + assert_eq!(r.text16().unwrap(), "Größe Ω"); + assert_eq!(r.position(), w.position()); + } + + /// The spec's worked examples come out bit for bit. + #[test] + fn writer_matches_the_spec_examples() { + let mut w = BitWriter::new(); + for v in [257u16, 0, 256, 15, 0] { + w.bs(v); + } + assert_eq!(w.position(), 34); + assert_eq!(w.into_bytes(), bits_to_bytes("0000000001000000011011010000111110")); + let mut w = BitWriter::new(); + w.mc_signed(4610); + assert_eq!(w.into_bytes(), [0b1000_0010, 0b0010_0100]); + let mut w = BitWriter::new(); + w.mc_signed(-1413); + assert_eq!(w.into_bytes(), [0b1000_0101, 0b0100_1011]); + let mut w = BitWriter::new(); + w.ms(4_650_033); + assert_eq!(w.into_bytes(), [0b0011_0001, 0b1111_0100, 0b1000_1101, 0b0000_0000]); + let mut w = BitWriter::new(); + w.handle(5, 0x5E7); + assert_eq!(w.into_bytes(), [0x52, 0x05, 0xE7]); + } + + #[test] + fn appending_keeps_every_bit() { + let mut a = BitWriter::new(); + a.bits(0b101, 3); + let mut b = BitWriter::new(); + b.bits(0b1_1001_0101, 9); + a.append(&b); + assert_eq!(a.position(), 12); + assert_eq!(a.into_bytes(), [0b1011_1001, 0b0101_0000]); + let mut a = BitWriter::new(); + a.rc(0xAB); + a.append(&b); + assert_eq!(a.position(), 17); + assert_eq!(a.into_bytes(), [0xAB, 0b1100_1010, 0b1000_0000]); + } + + /// Turn a string of '0'/'1' characters (spaces ignored) into bytes, + /// padding the last byte with zero bits. + fn bits_to_bytes(s: &str) -> Vec { + let bits: Vec = s.chars().filter(|c| *c == '0' || *c == '1').map(|c| (c == '1') as u8).collect(); + let mut out = vec![0u8; bits.len().div_ceil(8)]; + for (i, b) in bits.iter().enumerate() { + out[i / 8] |= b << (7 - (i % 8)); + } + out + } + + // Worked examples printed in the spec, §2.2. + #[test] + fn bitshort_spec_example() { + let data = bits_to_bytes("0000000001000000011011010000111110"); + let mut r = BitReader::new(&data); + assert_eq!(r.bs().unwrap(), 257); + assert_eq!(r.bs().unwrap(), 0); + assert_eq!(r.bs().unwrap(), 256); + assert_eq!(r.bs().unwrap(), 15); + assert_eq!(r.bs().unwrap(), 0); + assert_eq!(r.position(), 34); + } + + // §2.3. + #[test] + fn bitlong_spec_example() { + let data = bits_to_bytes("000000000100000001000000000000000010010000111110"); + let mut r = BitReader::new(&data); + assert_eq!(r.bl().unwrap(), 257); + assert_eq!(r.bl().unwrap(), 0); + assert_eq!(r.bl().unwrap(), 15); + assert_eq!(r.bl().unwrap(), 0); + } + + // §2.6. + #[test] + fn modular_char_spec_examples() { + let mut r = BitReader::new(&[0b1000_0010, 0b0010_0100]); + assert_eq!(r.mc_signed().unwrap(), 4610); + let mut r = BitReader::new(&[0b1110_1001, 0b1001_0111, 0b1110_0110, 0b0011_0101]); + assert_eq!(r.mc_signed().unwrap(), 112_823_273); + let mut r = BitReader::new(&[0b1000_0101, 0b0100_1011]); + assert_eq!(r.mc_signed().unwrap(), -1413); + let mut r = BitReader::new(&[0b1000_0010, 0b0010_0100]); + assert_eq!(r.mc_unsigned().unwrap(), 4610); + } + + // §2.7. + #[test] + fn modular_short_spec_example() { + let mut r = BitReader::new(&[0b0011_0001, 0b1111_0100, 0b1000_1101, 0b0000_0000]); + assert_eq!(r.ms().unwrap(), 4_650_033); + } + + #[test] + fn unaligned_raw_values() { + // One leading zero bit, then RS 0x1234 little-endian (0x34, 0x12). + let data = bits_to_bytes("0 00110100 00010010"); + let mut r = BitReader::new(&data); + assert!(!r.b().unwrap()); + assert_eq!(r.rs().unwrap(), 0x1234); + } + + #[test] + fn bitdouble_and_default() { + // 01 -> 1.0, 10 -> 0.0 + let data = bits_to_bytes("01 10"); + let mut r = BitReader::new(&data); + assert_eq!(r.bd().unwrap(), 1.0); + assert_eq!(r.bd().unwrap(), 0.0); + // DD 00 keeps the default. + let data = bits_to_bytes("00"); + let mut r = BitReader::new(&data); + assert_eq!(r.dd(12.5).unwrap(), 12.5); + // DD 01 patches the low four bytes of the default. + let default: f64 = 2.0; // 0x4000000000000000 + let mut s = String::from("01"); + for b in [0x01u8, 0x00, 0x00, 0x00] { + s.push_str(&format!("{b:08b}")); + } + let data = bits_to_bytes(&s); + let mut r = BitReader::new(&data); + let v = r.dd(default).unwrap(); + assert_eq!(v.to_bits(), 0x4000_0000_0000_0001); + } + + #[test] + fn handle_reference() { + // code 5, counter 2, value 0x01A3 + let mut r = BitReader::new(&[0x52, 0x01, 0xA3]); + let h = r.handle().unwrap(); + assert_eq!(h, HandleRef { code: 5, value: 0x01A3 }); + assert_eq!(HandleRef { code: 6, value: 0 }.absolute(0x10), 0x11); + assert_eq!(HandleRef { code: 0xC, value: 3 }.absolute(0x10), 0x0D); + } + + #[test] + fn triplet() { + let data = bits_to_bytes("0 10 110 111"); + let mut r = BitReader::new(&data); + assert_eq!(r.b3().unwrap(), 0); + assert_eq!(r.b3().unwrap(), 2); + assert_eq!(r.b3().unwrap(), 6); + assert_eq!(r.b3().unwrap(), 7); + } + + #[test] + fn truncation_is_an_error_not_a_panic() { + let mut r = BitReader::new(&[0xFF]); + assert!(r.rs().is_err()); + let mut r = BitReader::new(&[]); + assert!(r.b().is_err()); + } +} diff --git a/crates/dwg/src/crc.rs b/crates/dwg/src/crc.rs new file mode 100644 index 00000000..e04a272d --- /dev/null +++ b/crates/dwg/src/crc.rs @@ -0,0 +1,120 @@ +//! Checksums used by DWG files. +//! +//! Spec §2.14 "CRCS" and §4.2 "Section page checksum" (verified against the +//! spec text). The spec calls the first one an "8-bit CRC" because it walks +//! the data a byte at a time; the value itself is 16 bits. Its table is the +//! reflected 0xA001 polynomial table, which is generated here rather than +//! copied. + +const fn make_crc16_table() -> [u16; 256] { + let mut table = [0u16; 256]; + let mut i = 0; + while i < 256 { + let mut c = i as u16; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xA001 } else { c >> 1 }; + k += 1; + } + table[i] = c; + i += 1; + } + table +} + +const fn make_crc32_table() -> [u32; 256] { + let mut table = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut c = i as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 }; + k += 1; + } + table[i] = c; + i += 1; + } + table +} + +static CRC16_TABLE: [u16; 256] = make_crc16_table(); +static CRC32_TABLE: [u32; 256] = make_crc32_table(); + +/// The DWG "8-bit CRC" (16-bit result). Seeds seen in the spec: 0xC0C1 for +/// sections and objects, 0 for the R13–R15 file header. +pub fn crc16(seed: u16, data: &[u8]) -> u16 { + let mut crc = seed; + for &b in data { + crc = (crc >> 8) ^ CRC16_TABLE[((crc ^ b as u16) & 0xFF) as usize]; + } + crc +} + +/// The 32-bit CRC used from R2004 (R18) on. Standard reflected CRC-32 with +/// a caller-supplied seed; seed 0 gives the common CRC-32 value. +pub fn crc32(seed: u32, data: &[u8]) -> u32 { + let mut crc = !seed; + for &b in data { + crc = (crc >> 8) ^ CRC32_TABLE[((crc ^ b as u32) & 0xFF) as usize]; + } + !crc +} + +/// Section page checksum (§4.2): an Adler-style running sum with a seed. +pub fn page_checksum(seed: u32, data: &[u8]) -> u32 { + let mut sum1 = seed & 0xFFFF; + let mut sum2 = seed >> 16; + for chunk in data.chunks(0x15B0) { + for &b in chunk { + sum1 += b as u32; + sum2 += sum1; + } + sum1 %= 0xFFF1; + sum2 %= 0xFFF1; + } + (sum2 << 16) | (sum1 & 0xFFFF) +} + +/// XOR applied to the R13–R15 file-header CRC, by number of section +/// locator records (§3.2.6). +pub fn file_header_crc_xor(records: u32) -> u16 { + match records { + 3 => 0xA598, + 4 => 0x8101, + 5 => 0x3CC4, + 6 => 0x8461, + _ => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc16_table_matches_spec_prefix() { + // First entries as printed in §2.14.1. + let expected: [u16; 16] = + [0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440]; + assert_eq!(&CRC16_TABLE[..16], &expected); + } + + #[test] + fn crc32_table_matches_spec_prefix() { + assert_eq!(&CRC32_TABLE[..4], &[0x0000_0000, 0x7707_3096, 0xEE0E_612C, 0x9909_51BA]); + } + + #[test] + fn standard_check_values() { + // CRC-16/ARC and CRC-32 check values for "123456789". + assert_eq!(crc16(0, b"123456789"), 0xBB3D); + assert_eq!(crc32(0, b"123456789"), 0xCBF4_3926); + } + + #[test] + fn page_checksum_matches_adler_with_seed_one() { + // With seed 1 this is exactly Adler-32; "Wikipedia" -> 0x11E60398. + assert_eq!(page_checksum(1, b"Wikipedia"), 0x11E6_0398); + } +} diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 57a9777c..4e3e1a9c 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -1,29 +1,29 @@ -//! DWG support through a DXF bridge. +//! DraftCraft's DWG codec. //! -//! DWG files are read with the `acadrust` crate (MPL-2.0, used unmodified as a dependency) and -//! converted to DXF bytes, which DraftCraft's own DXF reader maps to its document model; saving -//! goes the other way. Keeping the dependency behind this byte-level API isolates it: nothing -//! else in DraftCraft depends on its types. Native targets only (it memory-maps files). +//! - [`read`]: DWG files from R13 to AutoCAD 2018 and later (except 2007) into the [`records`] of +//! their objects, which `draftcraft-io` maps straight into the drawing. +//! - [`write`]: AutoCAD 2018 (AC1032) DWG files from records. +//! - [`bits`], [`crc`], [`lz77`]: the format's primitives, shared by both. +//! - [`acadrust`]: DWG through the acadrust crate (MPL-2.0, used unmodified), converted to and from +//! DXF bytes: the fallback for what the reader and writer don't cover yet. //! -//! # Guardrails around the third-party decoder -//! -//! The decoder allocates tables and section buffers from sizes a (possibly damaged or hostile) -//! file declares, and once it starts it cannot be interrupted (an allocation failure aborts the -//! process, which `catch_unwind` cannot recover). Because the dependency is used unmodified, this -//! crate guards it from the outside: -//! -//! - Both directions reject oversized input *before* the decoder runs ([`Limits::max_dwg_bytes`] -//! for DWG→DXF, [`Limits::max_dxf_bytes`] for DXF→DWG), and the DWG→DXF output is capped while -//! it is written (`CappedWriter`). -//! - The reader and writer run inside `catch_unwind`, so a decode failure is reported instead of -//! crashing. -//! -//! These bound the input- and output-size variants. A small file that declares a huge internal -//! table or section can still make the dependency allocate before any size is known, so the app -//! runs both directions in a child process ([`worker`]): what that kills is the child. +//! The reader, writer and records come from BlackCAD (, +//! MIT OR Apache-2.0), written from the Open Design Alliance's public DWG specification. +//! This crate depends on no other workspace crate. + #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod acadrust; +pub mod bits; +pub mod crc; +pub mod lz77; +pub mod read; +pub mod records; +pub mod write; + +pub use read::{DwgVersion, read_bytes}; + /// DWG version codes we can write. pub const VERSIONS: &[(&str, &str)] = &[("AC1015", "2000"), ("AC1018", "2004"), ("AC1021", "2007"), ("AC1024", "2010"), ("AC1027", "2013"), ("AC1032", "2018")]; @@ -56,1323 +56,8 @@ impl Limits { } /// A byte count in megabytes for messages ("9.9 MB", "1024 MB"). -#[cfg_attr(no_dwg_bridge, allow(dead_code))] -fn mb(n: u64) -> String { +#[cfg_attr(no_acadrust, allow(dead_code))] +pub(crate) fn mb(n: u64) -> String { let m = n as f64 / f64::from(1u32 << 20); if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } } - -#[cfg(not(no_dwg_bridge))] -pub mod worker; -#[cfg(not(no_dwg_bridge))] -pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_noted, serve_if_asked, use_own_worker, use_worker}; - -#[cfg(not(no_dwg_bridge))] -mod native { - use std::io::{Cursor, Write}; - use std::panic::AssertUnwindSafe; - - use super::{Limits, mb}; - - /// Read DWG bytes and return an ASCII DXF rendition, within [`Limits::DEFAULT`]. - pub fn dwg_to_dxf(bytes: &[u8]) -> Result, String> { - dwg_to_dxf_with(bytes, Limits::DEFAULT) - } - - /// [`dwg_to_dxf`] with explicit limits. Both are checked before the expensive step they - /// guard: the input size before the DWG reader runs, the DXF size while it is written, so a - /// runaway conversion stops at the limit instead of filling memory first. - pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result, String> { - dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf) - } - - /// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in - /// failsafe mode: an object record it can't decode is skipped instead of failing the whole - /// file, and the notes say how many were skipped and of which types, so a partial read never - /// passes for a complete one. - pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { - if bytes.len() > limits.max_dwg_bytes { - return Err(format!("DWG: the file is {}, larger than the {} DraftCraft opens", mb(bytes.len() as u64), mb(limits.max_dwg_bytes as u64))); - } - let outcome = std::panic::catch_unwind(|| { - acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats() - }) - .map_err(|_| "the DWG reader failed on this file".to_string())? - .map_err(|e| format!("DWG: {e}"))?; - // Failsafe skips records, not whole files: when the objects stream itself couldn't be - // read (a damaged header or section map, or not a DWG at all), nothing was read. - if !outcome.stats.record_stream_read { - let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string()); - return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string()))); - } - let mut notes = read_notes(&outcome.stats); - let mut doc = outcome.document; - let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; - if orphans > 0 { - let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; - notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); - } - let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false }; - let written = std::panic::catch_unwind(AssertUnwindSafe(|| { - acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)?; - mtext_contents(&doc, &mut out) - })) - .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; - if out.exceeded { - return Err(format!( - "DWG: converting this {} file produced more than {} of drawing data (the limit); \ - the file is probably damaged, or uses objects the DWG reader misreads", - mb(bytes.len() as u64), - mb(limits.max_dxf_bytes as u64) - )); - } - written.map_err(|e| format!("DWG→DXF: {e}"))?; - Ok((add_header_vars(out.buf, &doc.header), notes)) - } - - /// acadrust 0.6.6's ASCII writer treats a caret followed by a literal space as already - /// escaped, and turns line feeds into paragraph codes. Serialize affected MTEXT contents - /// from the native values instead, using its lossless string writer. All other groups, - /// including embedded-object data, remain byte-for-byte as the DXF writer emitted them. - fn mtext_contents(doc: &acadrust::CadDocument, out: &mut CappedWriter) -> acadrust::Result<()> { - use acadrust::io::dxf::{DxfStreamWriter, DxfTextWriter}; - let contents: std::collections::HashMap<_, _> = doc - .entities() - .filter_map(|e| match e { - acadrust::EntityType::MText(t) if t.value.contains(['^', '\t', '\n']) => Some((t.common.handle.value(), t.value.as_str())), - _ => None, - }) - .collect(); - if contents.is_empty() { - return Ok(()); - } - let dxf = std::mem::take(&mut out.buf); - let mut lines = dxf.split_inclusive(|b| *b == b'\n'); - let (mut mtext, mut text, mut written) = (false, None, false); - while let Some(code) = lines.next() { - let value = lines.next().ok_or_else(|| std::io::Error::other("incomplete DWG bridge DXF pair"))?; - match code.trim_ascii() { - b"0" => { - mtext = value.trim_ascii() == b"MTEXT"; - text = None; - written = false; - } - b"5" if mtext => { - text = std::str::from_utf8(value.trim_ascii()).ok().and_then(|s| u64::from_str_radix(s, 16).ok()).and_then(|h| contents.get(&h)); - } - b"101" => mtext = false, - b"1" | b"3" if mtext && text.is_some() => { - if let Some(&text) = text - && !written - { - let mut writer = DxfTextWriter::new(&mut *out); - if doc.version < acadrust::DxfVersion::AC1021 - && let Some(encoding) = acadrust::io::dxf::code_page::encoding_from_code_page(&doc.header.code_page) - { - writer.set_encoding(encoding); - } - // Each character can expand to two caret-escape characters. Keep - // those pairs together and each group within 250 characters. - let mut rest = text; - while let Some((end, _)) = rest.char_indices().nth(125) { - let (chunk, tail) = rest.split_at(end); - writer.write_xrecord_string(3, chunk)?; - rest = tail; - } - writer.write_xrecord_string(1, rest)?; - written = true; - } - continue; - } - _ => {} - } - out.write_all(code)?; - out.write_all(value)?; - } - Ok(()) - } - - #[cfg(test)] - #[test] - fn mtext_contents_keeps_other_groups_and_the_output_limit() -> acadrust::Result<()> { - for version in [acadrust::DxfVersion::AC1015, acadrust::DxfVersion::AC1032] { - let mut doc = acadrust::CadDocument::new(); - doc.version = version; - doc.header.code_page = "ANSI_1252".into(); - let mut t = acadrust::MText::with_value("é ^ C", acadrust::Vector3::ZERO); - t.common.handle = acadrust::Handle::new(0x10); - doc.add_entity(acadrust::EntityType::MText(Box::new(t)))?; - // Only the MTEXT's own 1/3 groups change. The embedded object's groups and the - // following TEXT record must survive byte-for-byte, including their spaces. - let prefix = b" 0\r\nMTEXT\r\n 5\r\n10\r\n 8\r\n0\r\n"; - let suffix = b"101\r\nEmbedded Object\r\n 1\r\n^ embedded\r\n 3\r\n^ tail\r\n 0\r\nTEXT\r\n 1\r\n^ plain\r\n"; - let raw = [prefix.as_slice(), b" 3\r\nold\r\n 1\r\ntext\r\n", suffix.as_slice()].concat(); - let mut out = CappedWriter { buf: raw.clone(), limit: 4096, exceeded: false }; - mtext_contents(&doc, &mut out)?; - let value: &[u8] = if version == acadrust::DxfVersion::AC1015 { b"\xe9 ^ C" } else { "é ^ C".as_bytes() }; - assert_eq!(out.buf, [prefix.as_slice(), b" 1\r\n", value, b"\r\n", suffix.as_slice()].concat()); - let mut limited = CappedWriter { buf: raw, limit: 1, exceeded: false }; - assert!(mtext_contents(&doc, &mut limited).is_err()); - assert!(limited.exceeded); - } - Ok(()) - } - - /// Most record types named in the skipped-records note. - const NOTE_TYPES: usize = 6; - - /// The note on object records a failsafe read skipped: how many, and how many of each type - /// (most first), or nothing when the read was complete. - pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec { - let skipped = stats.skipped_source_records; - if skipped == 0 { - return Vec::new(); - } - let label = |t: Option<&str>| match t.map(str::parse::) { - Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string), - Some(Err(_)) => t.unwrap_or_default().to_string(), - None => "unknown".to_string(), - }; - let mut by_type: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) { - *by_type.entry(label(d.record_type.as_deref())).or_default() += 1; - } - let mut types: Vec<(String, usize)> = by_type.into_iter().collect(); - types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); - let mut list: Vec = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect(); - if types.len() > NOTE_TYPES { - list.push(format!("{} more types", types.len() - NOTE_TYPES)); - } - let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() }; - let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" }; - let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") }; - let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) }; - vec![format!( - "DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \ - saving over the original file would lose {them}" - )] - } - - /// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are - /// numbered per file). - fn type_name(code: i16) -> Option<&'static str> { - Some(match code { - 1 => "TEXT", - 2 => "ATTRIB", - 3 => "ATTDEF", - 4 => "BLOCK", - 5 => "ENDBLK", - 6 => "SEQEND", - 7 => "INSERT", - 8 => "MINSERT", - 10..=14 => "VERTEX", - 15 | 16 | 29 | 30 => "POLYLINE", - 17 => "ARC", - 18 => "CIRCLE", - 19 => "LINE", - 20..=26 => "DIMENSION", - 27 => "POINT", - 28 => "3DFACE", - 31 => "SOLID", - 32 => "TRACE", - 33 => "SHAPE", - 34 => "VIEWPORT", - 35 => "ELLIPSE", - 36 => "SPLINE", - 37 => "REGION", - 38 => "3DSOLID", - 39 => "BODY", - 40 => "RAY", - 41 => "XLINE", - 42 => "DICTIONARY", - 43 => "OLEFRAME", - 44 => "MTEXT", - 45 => "LEADER", - 46 => "TOLERANCE", - 47 => "MLINE", - 48 => "BLOCK_CONTROL", - 49 => "BLOCK_RECORD", - 50 => "LAYER_CONTROL", - 51 => "LAYER", - 52 => "STYLE_CONTROL", - 53 => "STYLE", - 56 => "LTYPE_CONTROL", - 57 => "LTYPE", - 60 => "VIEW_CONTROL", - 61 => "VIEW", - 62 => "UCS_CONTROL", - 63 => "UCS", - 64 => "VPORT_CONTROL", - 65 => "VPORT", - 66 => "APPID_CONTROL", - 67 => "APPID", - 68 => "DIMSTYLE_CONTROL", - 69 => "DIMSTYLE", - 70 => "VX_CONTROL", - 71 => "VX_TABLE_RECORD", - 72 => "GROUP", - 73 => "MLINESTYLE", - 74 => "OLE2FRAME", - 77 => "LWPOLYLINE", - 78 => "HATCH", - 79 => "XRECORD", - 80 => "ACDBPLACEHOLDER", - 82 => "LAYOUT", - _ => return None, - }) - } - - /// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's - /// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's - /// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose - /// cells already carry merges are left alone. Each range's first cell gets the span; the - /// cells it covers are marked merged with no span of their own, as DraftCraft's DXF writer does. - fn table_merges(doc: &mut acadrust::CadDocument) { - table_merges_within(doc, MAX_MERGE_CELLS); - } - - /// The most table cells [`table_merges`] visits in one document: each range is capped, but - /// can cover rows × cols cells, so the total is bounded too. - const MAX_MERGE_CELLS: usize = 1 << 24; - - /// A table cell's own text height only when the file says it overrides the table style's. - /// acadrust's DXF writer writes a cell style's height (group 140) whenever the cell has a - /// style record, even a default 0.18 with no override flag, and DraftCraft reads a 140 as an - /// override (#2501). The override is the cell style's TEXT_HEIGHT property flag or the - /// content's format override bit 128; without either the height is cleared (0 is no - /// override), so the table style's height applies. - fn table_cell_heights(doc: &mut acadrust::CadDocument) { - use acadrust::entities::table::CellStylePropertyFlags; - const CONTENT_TEXT_HEIGHT: i32 = 128; - for e in doc.entities_mut() { - let acadrust::entities::EntityType::Table(t) = e else { continue }; - for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { - // The first content's own height (group 144) when its format override sets bit 128. - // DraftCraft keeps one height for the cell's text, so a later content's override - // must not stand in for the first content's. - let content_height = cell - .contents - .first() - .filter(|c| c.format_override_flags & CONTENT_TEXT_HEIGHT != 0) - .map(|c| c.text_height) - .filter(|h| h.is_finite() && *h > 0.0); - if let Some(h) = content_height { - // DraftCraft reads only the style's height (group 140), so carry it there. - cell.style.get_or_insert_with(acadrust::entities::table::CellStyle::new).text_height = h; - continue; - } - // A style overrides through its property flags or, in newer files, its override - // flags; anything else is the writer's default and is cleared. - if let Some(style) = cell.style.as_mut() - && !style.property_flags.contains(CellStylePropertyFlags::TEXT_HEIGHT) - && style.override_flags & CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32 == 0 - { - style.text_height = 0.0; - } - } - } - } - - /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN - /// components were dropped. The document comes from a third-party reader and is hostile. - fn post_process(doc: &mut acadrust::CadDocument) -> usize { - super::fail_in_test("post_process"); - current_style_names(doc); - table_merges(doc); - table_cell_heights(doc); - table_style_rows(doc, false); - keep_sort_handles(doc); - drop_orphaned_dgn_components(doc) - } - - /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). - fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { - std::panic::catch_unwind(f).map_err(|_| ()) - } - - /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is - /// left unmerged. Returns the cells visited. - fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { - let mut left = budget; - for e in doc.entities_mut() { - let acadrust::entities::EntityType::Table(t) = e else { continue }; - if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) { - continue; - } - let (rows, cols) = (t.rows.len(), t.columns.len()); - // A real table has at most one merge per cell; more ranges than that come from a - // damaged file and would only make this rows × cols × ranges. - let max_ranges = rows.saturating_mul(cols).min(1 << 16); - for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::>() { - // Clamp to the table: the ranges come from the file. - let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1))); - if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { - continue; - } - let area = (bottom - r.top_row + 1).saturating_mul(right - r.left_col + 1); - if area > left { - continue; - } - left -= area; - let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX); - for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) { - for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) { - cell.merged = 1; - let first = (ri, ci) == (r.top_row, r.left_col); - cell.merge_width = if first { span(right - r.left_col) } else { 0 }; - cell.merge_height = if first { span(bottom - r.top_row) } else { 0 }; - } - } - } - } - budget - left - } - - /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF - /// writer renumbers them past every entity handle, but an entity left out of a table sorts by - /// its own handle, so after renumbering it would draw below every listed entity (#2410). Giving - /// the table its codes verbatim makes the writer emit them unchanged. - fn keep_sort_handles(doc: &mut acadrust::CadDocument) { - use acadrust::objects::ObjectType; - let version = doc.version; - for o in doc.objects.values_mut() { - let ObjectType::SortEntitiesTable(t) = o else { continue }; - let hex = |h: acadrust::types::Handle| format!("{:X}", h.value()); - let mut codes = - vec![(5, hex(t.handle)), (330, hex(t.owner_handle)), (100, "AcDbSortentsTable".to_string()), (330, hex(t.block_owner_handle))]; - for e in t.entries() { - codes.push((331, hex(e.entity_handle))); - codes.push((5, hex(e.sort_handle))); - } - t.raw_dxf_codes = Some(codes); - t.raw_dxf_version = Some(version); - } - } - - /// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps - /// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while - /// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields - /// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written; - /// otherwise the flags are copied into the fields after one is read. Older versions store - /// both and are left alone. - fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) { - use acadrust::objects::{ObjectType, TableStyleFlags}; - if doc.version < acadrust::DxfVersion::AC1024 { - return; - } - for o in doc.objects.values_mut() { - let ObjectType::TableStyle(s) = o else { continue }; - for (bit, suppressed) in - [(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)] - { - if to_flags { - s.flags.set(bit, *suppressed); - } else { - *suppressed = s.flags.contains(bit); - } - } - } - } - - /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, - /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as - /// DraftCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, - /// acadrust 0.6.6 reads and writes itself. - fn dimension_flags(doc: &mut acadrust::CadDocument) { - for e in doc.entities_mut() { - let acadrust::entities::EntityType::Dimension(d) = e else { continue }; - d.base_mut().dwg_flags_byte |= 0x02; - } - } - - /// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses - /// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of - /// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE - /// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053 - /// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file - /// didn't open at all. No definition that was read refers to them (a definition the reader - /// skipped can't use them either) and DraftCraft doesn't draw DGN line styles, so nothing - /// visible is lost. - /// Every component a definition reaches (directly, or through compound and point - /// components) is kept, as are the definitions; dictionary entries that named a dropped - /// component go with it. Returns how many were left out. - fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize { - use acadrust::objects::{DgnLineStyleData, ObjectType}; - use std::collections::{HashMap, HashSet}; - // Each component's references, and the definitions' root components to start from. - let mut refs: HashMap> = HashMap::new(); - let mut stack: Vec = Vec::new(); - for (h, o) in &doc.objects { - let ObjectType::DgnLineStyle(ls) = o else { continue }; - match &ls.data { - DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component), - DgnLineStyleData::Component { component, .. } => { - refs.insert(*h, component.references()); - } - DgnLineStyleData::Registered { .. } => {} - } - } - if refs.is_empty() { - return 0; - } - // Each component is visited once, so cycles and shared subtrees end. - let mut used: HashSet = HashSet::new(); - while let Some(h) = stack.pop() { - if let Some(r) = refs.get(&h) - && used.insert(h) - { - stack.extend(r.iter().copied()); - } - } - let orphans: HashSet = refs.into_keys().filter(|h| !used.contains(h)).collect(); - if orphans.is_empty() { - return 0; - } - doc.objects.retain(|h, _| !orphans.contains(h)); - doc.dgn_ls_components.retain(|h, _| !orphans.contains(h)); - for o in doc.objects.values_mut() { - let ObjectType::Dictionary(d) = o else { continue }; - if d.entries.iter().any(|(_, e)| orphans.contains(e)) { - d.entries.retain(|(_, e)| !orphans.contains(e)); - let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect(); - d.hard_owner_entries.retain(|k| keys.contains(k.as_str())); - } - } - orphans.len() - } - - /// Leave out what acadrust can't write as this DWG version: other programs' custom entities - /// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file - /// for one of them (0.6.3 left them out); DraftCraft already tells the user which entity types - /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many - /// records of each DXF type were left out, so a save can say so. - fn drop_unwritable(doc: &mut acadrust::CadDocument) -> super::Unwritten { - let version = doc.version; - let mut dropped = super::Unwritten::new(); - let mut count = |name: &str| { - let n = dropped.entry(name.trim().to_ascii_uppercase()).or_insert(0); - *n = n.saturating_add(1); - }; - let unwritable: Vec = doc - .entities() - .filter_map(|e| match e { - acadrust::entities::EntityType::Unknown(u) - if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => - { - count(&u.dxf_name); - Some(u.common.handle) - } - _ => None, - }) - .collect(); - for h in &unwritable { - doc.remove_entity(*h); - } - let objects: Vec = doc - .objects - .iter() - .filter_map(|(h, o)| match o { - acadrust::objects::ObjectType::Unknown { type_name, raw_dwg_data, raw_dwg_version, .. } - if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => - { - count(type_name); - Some(*h) - } - _ => None, - }) - .collect(); - for h in &objects { - doc.objects.remove(h); - } - dropped - } - - /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of - /// the HEADER section: (name, group code, value). - fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] { - [ - // DWG holds radians; `$ANGBASE` is in degrees. - ("$ANGBASE", 50, h.angle_base.to_degrees().to_string()), - ("$ANGDIR", 70, h.angle_direction.to_string()), - ("$FILLETRAD", 40, h.fillet_radius.to_string()), - ("$CHAMFERA", 40, h.chamfer_distance_a.to_string()), - ("$CHAMFERB", 40, h.chamfer_distance_b.to_string()), - ("$ELEVATION", 40, h.elevation.to_string()), - ("$THICKNESS", 40, h.thickness.to_string()), - ] - } - - /// Add the [`unwritten_header_vars`] to the HEADER section of acadrust's DXF text, before its - /// ENDSEC; a variable the writer already wrote is left alone. Text of another layout than - /// acadrust's (` 0\r\nSECTION\r\n 2\r\nHEADER\r\n` … ` 0\r\nENDSEC\r\n`) is returned unchanged. - fn add_header_vars(mut dxf: Vec, h: &acadrust::document::HeaderVariables) -> Vec { - const START: &[u8] = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n"; - const END: &[u8] = b"\r\n 0\r\nENDSEC\r\n"; - if !dxf.starts_with(START) { - return dxf; - } - let Some(end) = dxf.windows(END.len()).position(|w| w == END).map(|p| p + 2) else { return dxf }; - let section = dxf.get(..end).unwrap_or_default(); - let mut add = String::new(); - for (name, code, value) in unwritten_header_vars(h) { - let written = section.windows(name.len() + 2).any(|w| w.starts_with(name.as_bytes()) && w.ends_with(b"\r\n")); - if !written && value.parse::().is_ok_and(f64::is_finite) { - add.push_str(&format!(" 9\r\n{name}\r\n{code:>3}\r\n{value}\r\n")); - } - } - dxf.splice(end..end, add.into_bytes()); - dxf - } - - /// Collects the DXF text and fails the write once it would grow past `limit`. - struct CappedWriter { - buf: Vec, - limit: usize, - exceeded: bool, - } - - impl Write for CappedWriter { - fn write(&mut self, b: &[u8]) -> std::io::Result { - // Sticky: once over, every later write fails too. - if self.exceeded || self.buf.len().saturating_add(b.len()) > self.limit { - self.exceeded = true; - return Err(std::io::Error::other("DXF size limit reached")); - } - self.buf.extend_from_slice(b); - Ok(b.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - - /// Oldest DWG version written; older DXF input is written as this version. - const MIN_DWG_VERSION: acadrust::DxfVersion = acadrust::DxfVersion::AC1018; - - /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 - /// (AC1018). - pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { - convert(dxf, None).map(|(dwg, _)| dwg) - } - - /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), - /// whatever version the DXF declares. - pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { - dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) - } - - /// [`dxf_to_dwg_as`], also returning what the DWG writer left out: how many records of each - /// DXF type it can't write (other programs' custom entities and objects that the DWG reader - /// didn't read from a DWG of this version), empty when the DWG keeps everything. - pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { - let v = match version.trim().to_ascii_uppercase().as_str() { - "AC1015" => acadrust::DxfVersion::AC1015, - "AC1018" => acadrust::DxfVersion::AC1018, - "AC1021" => acadrust::DxfVersion::AC1021, - "AC1024" => acadrust::DxfVersion::AC1024, - "AC1027" => acadrust::DxfVersion::AC1027, - "AC1032" => acadrust::DxfVersion::AC1032, - _ => return Err(super::unsupported(version)), - }; - convert(dxf, Some(v)) - } - - /// The current dimension and text styles' names from their handles: a DWG stores the - /// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG - /// lost its current dimension style (#1051). - fn current_style_names(doc: &mut acadrust::CadDocument) { - let h = doc.header.current_dimstyle_handle; - if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) { - doc.header.current_dimstyle_name = n; - } - let h = doc.header.current_text_style_handle; - if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) { - doc.header.current_text_style_name = n; - } - } - - /// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the - /// handle read with it needn't be the style's in the document, in which case the DWG writer - /// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051). - fn current_dimstyle(doc: &mut acadrust::CadDocument) { - let name = doc.header.current_dimstyle_name.clone(); - if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) { - doc.header.current_dimstyle_handle = h; - } - } - - /// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]: - /// the handle read with the DXF needn't be the style's in the document, in which case the DWG - /// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650). - fn current_text_style(doc: &mut acadrust::CadDocument) { - let name = doc.header.current_text_style_name.clone(); - if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) { - doc.header.current_text_style_handle = h; - } - } - - /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG - /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in - /// the document, so the drawing reopened with layer "0" current (#2252). - fn current_layer(doc: &mut acadrust::CadDocument) { - let name = doc.header.current_layer_name.clone(); - // The table's own lookup compares Unicode case-insensitively ("Survey_Ä" = "Survey_ä"). - if let Some(layer) = doc.layers.get(&name) { - doc.header.current_layer_handle = layer.handle; - } - } - - fn convert(dxf: &[u8], version: Option) -> Result<(Vec, super::Unwritten), String> { - // Reject a pathologically large DXF before handing it to the third-party decoder, which - // allocates tables and section buffers from the input's declared sizes and cannot be - // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder - // runs inside `catch_unwind` so a decode failure is reported rather than crashing. - if dxf.len() > Limits::DEFAULT.max_dxf_bytes { - return Err(format!( - "DXF: the input is {}, larger than the {} DraftCraft converts to DWG", - mb(dxf.len() as u64), - mb(Limits::DEFAULT.max_dxf_bytes as u64) - )); - } - let data = dxf.to_vec(); - let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) - .map_err(|_| "the DXF→DWG conversion failed".to_string())? - .map_err(|e| format!("DXF: {e}"))?; - match version { - Some(v) => doc.version = v, - // Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG - // has no true colours, transparency, table styles or gradients. The DXF stays R2000; - // only the DWG is newer. - None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, - None => {} - } - // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. - let unwritten = guarded(AssertUnwindSafe(|| { - super::fail_in_test("convert"); - other_layout_owners(&mut doc); - table_style_rows(&mut doc, true); - dimension_flags(&mut doc); - let unwritten = drop_unwritable(&mut doc); - current_dimstyle(&mut doc); - add_variable_dictionary(&mut doc); - current_text_style(&mut doc); - current_layer(&mut doc); - unwritten - })) - .map_err(|_| "the DXF to DWG conversion failed on this file".to_string())?; - let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) - .map_err(|_| "the DWG writer failed on this drawing".to_string())? - .map_err(|e| format!("DWG write: {e}"))?; - Ok((dwg, unwritten)) - } - - /// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the - /// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive). - const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary"; - - /// A style or scale name, or `default` when the drawing has none. - fn name_or_default(name: &str, default: &str) -> String { - let name = name.trim(); - if name.is_empty() { default.to_string() } else { name.to_string() } - } - - /// A drawing variable's value as text, or `default` when the header holds a value the - /// variable doesn't accept (a hostile file can put any integer in it). - fn variable_value(value: i16, valid: &[i16], default: i16) -> String { - if valid.contains(&value) { value.to_string() } else { default.to_string() } - } - - /// Add the drawing variables dictionary AutoCAD always writes into the named object - /// dictionary, with the variables it keeps there, when the drawing has none (#1813). - /// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported - /// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such - /// dictionary either, as DraftCraft's and ezdxf's writers don't make one. AutoCAD's AC1032 DWGs - /// read there without it, so newer output is left as it was, and a dictionary the drawing - /// does have keeps its own entries and values. - fn add_variable_dictionary(doc: &mut acadrust::CadDocument) { - use acadrust::objects::{Dictionary, DictionaryVariable, ObjectType}; - if doc.version >= acadrust::DxfVersion::AC1032 { - return; - } - let root_handle = doc.header.named_objects_dict_handle; - match doc.objects.get(&root_handle) { - Some(ObjectType::Dictionary(root)) => { - if root.get(VARIABLE_DICTIONARY).is_some() { - return; - } - } - _ => return, - } - // The variables AutoCAD writes for a drawing with default styles and a 1:1 annotation - // scale. DIMASSOC and HIDETEXT keep the drawing's own header values; LAYEREVAL and - // LAYERNOTIFY have no DXF header variable. - let variables = [ - ("CMLEADERSTYLE", name_or_default(&doc.header.current_mleader_style_name, "Standard")), - ("CTABLESTYLE", name_or_default(&doc.header.current_table_style_name, "Standard")), - ("CANNOSCALE", name_or_default(&doc.header.current_annotation_scale, "1:1")), - ("DIMASSOC", variable_value(doc.header.dimension_associativity, &[0, 1, 2], 2)), - ("HIDETEXT", variable_value(doc.header.hide_text, &[0, 1], 1)), - ("LAYEREVAL", "0".to_string()), - ("LAYERNOTIFY", "0".to_string()), - ]; - let dictionary_handle = doc.allocate_handle(); - let mut dictionary = Dictionary::new(); - dictionary.handle = dictionary_handle; - dictionary.owner = root_handle; - for (name, value) in variables { - let handle = doc.allocate_handle(); - let mut variable = DictionaryVariable::new(name, &value); - variable.handle = handle; - variable.owner_handle = dictionary_handle; - dictionary.add_entry(name, handle); - doc.objects.insert(handle, ObjectType::DictionaryVariable(variable)); - } - doc.objects.insert(dictionary_handle, ObjectType::Dictionary(dictionary)); - if let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&root_handle) { - root.add_entry(VARIABLE_DICTIONARY, dictionary_handle); - } - } - - /// Entities of a layout other than the one in `*Paper_Space` are written owned by their block - /// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1, - /// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a - /// second layout landed on the first one, and the second stayed empty (#1057). - fn other_layout_owners(doc: &mut acadrust::CadDocument) { - let others: std::collections::HashSet = doc - .block_records - .iter() - .filter(|br| { - let n = br.name.to_ascii_uppercase(); - n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit()) - }) - .map(|br| br.handle) - .collect(); - if others.is_empty() { - return; - } - for e in doc.entities_mut() { - let c = e.common_mut(); - if others.contains(&c.owner_handle) { - c.entity_mode = Some(0); - } - } - } - - #[cfg(test)] - mod post_tests { - use super::*; - use acadrust::entities::{CellRange, EntityType, Table}; - - fn doc_with_table(rows: usize, cols: usize, ranges: usize) -> acadrust::CadDocument { - let mut t = Table::new(acadrust::types::Vector3::new(0.0, 0.0, 0.0), rows, cols); - t.merged_ranges = (0..ranges).map(|_| CellRange::new(0, 0, rows - 1, cols - 1)).collect(); - let mut doc = acadrust::CadDocument::new(); - assert!(doc.add_entity(EntityType::Table(Box::new(t))).is_ok()); - doc - } - - /// Overlapping whole-table ranges can't make the merge pass visit more than its budget (#1934). - #[test] - fn merge_work_is_bounded_by_the_cell_budget() { - let mut doc = doc_with_table(10, 10, 50); - assert_eq!(table_merges_within(&mut doc, 250), 200, "two whole-table ranges fit, the rest are skipped"); - let mut doc = doc_with_table(10, 10, 1); - assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); - } - - /// A height marked only in the style's override flags (as newer files store it) is kept, - /// and the same height with no flag at all is cleared (review on #2588). Tested on the - /// read document because acadrust's DWG writer doesn't write the override flags. - #[test] - fn a_style_override_flag_keeps_the_cell_height() { - use acadrust::entities::table::{CellStyle, CellStylePropertyFlags}; - let height = |override_flags: i32| { - let mut doc = doc_with_table(1, 1, 0); - for e in doc.entities_mut() { - if let EntityType::Table(t) = e { - for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { - let mut s = CellStyle::new(); - s.text_height = 0.5; - s.override_flags = override_flags; - cell.style = Some(s); - } - } - } - table_cell_heights(&mut doc); - doc.entities().find_map(|e| match e { - EntityType::Table(t) => t.rows.first()?.cells.first()?.style.as_ref().map(|s| s.text_height), - _ => None, - }) - }; - assert_eq!(height(CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32), Some(0.5)); - assert_eq!(height(0), Some(0.0)); - } - - /// A panic in the post-read fix-ups is an error, not a crash (#1934). - #[test] - fn a_panic_in_post_processing_is_an_error() { - #[allow(clippy::panic)] - let r = guarded(AssertUnwindSafe(|| -> usize { panic!("boom") })); - assert!(r.is_err()); - assert_eq!(guarded(|| 3), Ok(3)); - } - } -} - -#[cfg(not(no_dwg_bridge))] -pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_noted}; - -/// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer -/// can't write. -pub type Unwritten = std::collections::BTreeMap; - -// Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The -// stage then panics on entry, so a test through the public API shows whether it is guarded. -#[cfg(all(test, not(no_dwg_bridge)))] -thread_local! { - static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. -#[cfg(not(no_dwg_bridge))] -#[allow(clippy::panic)] -fn fail_in_test(_stage: &str) { - #[cfg(test)] - if PANIC_IN.with(|p| p.get()) == Some(_stage) { - panic!("test-forced panic in {_stage}"); - } -} - -/// The error for a DWG version DraftCraft can't write. -#[cfg_attr(no_dwg_bridge, allow(dead_code))] -fn unsupported(version: &str) -> String { - let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect(); - format!("DWG version `{version}` can't be written (DraftCraft writes {})", list.join(", ")) -} - -/// Which build has no DWG bridge, for the stubs' errors. -#[cfg(no_dwg_bridge)] -const NO_BRIDGE_BUILD: &str = if cfg!(target_arch = "wasm32") { "web" } else { "FreeBSD aarch64" }; - -/// There's no worker without a bridge. -#[cfg(no_dwg_bridge)] -pub const WORKER_ARG: &str = "--dwg-worker"; -#[cfg(no_dwg_bridge)] -pub fn serve_if_asked() -> Option { - None -} -#[cfg(no_dwg_bridge)] -pub fn use_own_worker() {} -#[cfg(no_dwg_bridge)] -pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { - dwg_to_dxf_noted(bytes, limits) -} -#[cfg(no_dwg_bridge)] -pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { - dxf_to_dwg_as(dxf, version) -} -#[cfg(no_dwg_bridge)] -pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, Unwritten), String> { - dxf_to_dwg_noted(dxf, version) -} - -#[cfg(no_dwg_bridge)] -pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { - Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} -#[cfg(no_dwg_bridge)] -pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec, Vec), String> { - Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} -#[cfg(no_dwg_bridge)] -pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result, String> { - Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} -#[cfg(no_dwg_bridge)] -pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { - Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} -#[cfg(no_dwg_bridge)] -pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { - Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} -#[cfg(no_dwg_bridge)] -pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { - Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The DXF of an empty drawing, enough for the bridge to make a small DWG. - #[cfg(not(no_dwg_bridge))] - const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; - - /// Makes `stage` panic on the current thread until dropped. - #[cfg(not(no_dwg_bridge))] - struct PanicIn; - - #[cfg(not(no_dwg_bridge))] - impl PanicIn { - fn at(stage: &'static str) -> Self { - PANIC_IN.with(|p| p.set(Some(stage))); - Self - } - } - - #[cfg(not(no_dwg_bridge))] - impl Drop for PanicIn { - fn drop(&mut self) { - PANIC_IN.with(|p| p.set(None)); - } - } - - /// The public read reports a panic in the post-read fix-ups as an error: this fails if the - /// `guarded` call around `post_process` is taken out (#2402). - #[cfg(not(no_dwg_bridge))] - #[test] - fn reading_a_dwg_survives_a_panic_in_post_processing() { - let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); - assert!(dwg_to_dxf(&dwg).is_ok(), "the DWG reads without the forced panic"); - let _panic = PanicIn::at("post_process"); - let err = dwg_to_dxf(&dwg).unwrap_err(); - assert!(err.contains("the DWG post-processing failed on this file"), "{err}"); - } - - /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). - #[cfg(not(no_dwg_bridge))] - #[test] - fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { - let _panic = PanicIn::at("convert"); - let err = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap_err(); - assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); - } - - #[test] - fn detects_magic() { - assert!(is_dwg(b"AC1032\0\0\0\0")); - assert!(!is_dwg(b" 0\r\nSECTION")); - assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018")); - } - - /// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not - /// Standard: the DXF names the style, and the handle read with it was Standard's (#1650). - #[cfg(not(no_dwg_bridge))] - #[test] - fn current_text_style_reaches_the_dwg() { - let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n"; - let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n"; - let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n"); - let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n"); - let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap(); - let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); - let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle); - assert!(romans.is_some(), "ROMANS is missing from the DWG"); - assert_eq!(Some(doc.header.current_text_style_handle), romans); - } - - #[test] - fn garbage_is_an_error_not_a_crash() { - assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err()); - assert!(dwg_to_dxf(b"").is_err()); - } - - #[cfg(not(no_dwg_bridge))] - #[test] - fn dxf_to_dwg_rejects_garbage_without_crashing() { - // The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures - // rather than crashing (and rejects oversized input before decoding). - assert!(dxf_to_dwg(b"not a dxf file").is_err()); - assert!(dxf_to_dwg(b"").is_err()); - } - - /// A DXF with one DIMENSION per (text, group 70, subclass, points) row. - #[cfg(not(no_dwg_bridge))] - fn dims_dxf(dims: &[(&str, i64, &str, &[(i32, [f64; 2])])]) -> String { - let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); - for (text, flags, sub, pts) in dims { - s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n"; - s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n"); - for (code, [x, y]) in pts.iter() { - s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20); - } - } - s + " 0\nENDSEC\n 0\nEOF\n" - } - - /// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set: - /// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common - /// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way - /// as the writer can't hide a wrong byte. - #[cfg(not(no_dwg_bridge))] - #[test] - fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() { - let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])]; - let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])]; - let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])]; - let kinds = [ - (0, "AcDbAlignedDimension", linear), - (1, "AcDbAlignedDimension", linear), - (4, "AcDbRadialDimension", radius), - (2, "AcDb2LineAngularDimension", angular), - ]; - let mut dims = Vec::new(); - for (ty, sub, pts) in kinds { - dims.push(("HOME", ty | 32, sub, pts)); - dims.push(("MOVED", ty | 32 | 128, sub, pts)); - } - let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap(); - let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); - let mut seen = Vec::new(); - for e in doc.entities() { - let acadrust::entities::EntityType::Dimension(d) = e else { continue }; - let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte); - seen.push((text.to_string(), byte & 0x03)); - assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type); - let default_pos = text == "HOME"; - assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type); - } - for text in ["HOME", "MOVED"] { - assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}"); - } - - // And DraftCraft reads its own DWG back as it wrote it: 128 only on the moved texts. - let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap(); - let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); - let mut flags = Vec::new(); - for rec in lines.chunks(2).collect::>().split(|p| p.first() == Some(&"0")) { - let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied()); - if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) { - flags.push((text, v.parse::().unwrap_or(-1) & 128)); - } - } - assert_eq!(flags.len(), 8, "{flags:?}"); - assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}"); - } - - /// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369). - #[cfg(not(no_dwg_bridge))] - fn dxf_handles(dxf: &str) -> std::collections::HashSet { - let lines: Vec<&str> = dxf.lines().collect(); - lines - .chunks(2) - .filter_map(|p| match p { - [c, v] if matches!(c.trim().parse::(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(), - _ => None, - }) - .collect() - } - - /// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN - /// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a - /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and - /// their dictionary entries with them; the definition and every component it reaches — - /// through compound and point components, around a cycle — are kept. - #[cfg(not(no_dwg_bridge))] - #[test] - fn orphaned_dgn_line_style_components_are_left_out() { - use acadrust::objects::*; - let mut doc = acadrust::CadDocument::new(); - let container = doc.allocate_handle(); - let nod = doc.header.named_objects_dict_handle; - let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") }; - root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container)); - let pattern = || DgnLsStrokePattern { - has_iteration_limit: false, - is_single_segment: false, - iteration_limit: 0, - auto_phase: 0.0, - phase: 0.0, - phase_mode: DgnLsPhaseMode::Distance, - strokes: vec![DgnLsStroke { - is_dash: true, - bypass_corner: false, - can_be_scaled: true, - invert_at_origin: false, - invert_at_end: false, - length: 2.5, - start_width: 0.0, - end_width: 0.0, - width_mode: 0, - cap_mode: 0, - }], - }; - let kind = |c: &DgnLsComponentData| match c { - DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol, - DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound, - DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke, - DgnLsComponentData::Point(_) => DgnLsComponentType::Point, - DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal, - }; - let compound = |of: &[acadrust::Handle]| { - DgnLsComponentData::Compound(DgnLsCompoundComponent { - entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(), - }) - }; - let mut entries = Vec::new(); - let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| { - entries.push((format!("{:X}", h.value()), h)); - let reactors = vec![container]; - doc.objects - .insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data })); - }; - let component = |c: DgnLsComponentData| DgnLineStyleData::Component { - kind: kind(&c), - description: "dash".into(), - version: 1, - component_uid: [7; 16], - scale: 1.0, - property_flags: 0, - component: c, - properties: vec![], - }; - let h: Vec = (0..9).map(|_| doc.allocate_handle()).collect(); - let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") }; - put( - &mut doc, - def, - DgnLineStyleData::Definition { - description: "{ dash }".into(), - version: 1, - style_number: 1, - component_uid: [1; 16], - is_continuous: false, - unit_definition: 1.0, - unit_scale: 1.0, - units_type: 0, - is_element: false, - is_physical: false, - is_scale_independent: false, - is_snappable: false, - root_component: root, - undecoded_fields: None, - properties: vec![], - }, - ); - // Used: def → root → {stroke, point → shared, back → root (a cycle)}. - put(&mut doc, root, component(compound(&[stroke, point, back]))); - put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern()))); - put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] }))); - put(&mut doc, back, component(compound(&[root]))); - put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern()))); - // Orphans: an internal component, and two compounds that refer to each other and to a - // used component (which stays). - let pattern_internal = - DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 }; - put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal))); - put(&mut doc, orphan, component(compound(&[orphan_cycle, shared]))); - put(&mut doc, orphan_cycle, component(compound(&[orphan]))); - let mut dict = Dictionary::new(); - dict.handle = container; - dict.owner = nod; - dict.entries = entries; - doc.objects.insert(container, ObjectType::Dictionary(dict)); - let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); - - let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); - let dxf = String::from_utf8(dxf).unwrap(); - let handles = dxf_handles(&dxf); - for kept in [def, root, stroke, point, back, shared] { - assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value()); - } - for gone in [internal, orphan, orphan_cycle] { - assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value()); - } - let lines: Vec<&str> = dxf.lines().collect(); - let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect(); - assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}"); - assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}"); - assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); - } - - /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three - /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD - /// read past the object and refused every DWG DraftCraft wrote with a dynamic block that scales - /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also - /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action - /// from DXF is written whole, with the byte AutoCAD writes (0). - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { - use acadrust::objects::*; - let scale_action = |doc: &acadrust::CadDocument| { - doc.objects.values().find_map(|o| match o { - ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), - _ => None, - }) - }; - let mut doc = acadrust::CadDocument::new(); - let h = doc.allocate_handle(); - let conn = |code, name: &str| BlockConnection { code, name: name.into() }; - let mut action = DynamicBlockObject::new("BLOCKSCALEACTION", "AcDbBlockScaleAction"); - action.handle = h; - action.owner = doc.header.named_objects_dict_handle; - let mut a = BlockBasePointAction::default(); - a.action.action.element.name = "Scale".into(); - a.action.connections = vec![conn(2, "UpdatedBaseX"), conn(2, "UpdatedBaseY")]; - a.action.dependent = true; - a.connections = vec![conn(2, "Scale"), conn(2, "XScale"), conn(2, "YScale")]; - a.dwg_tail_byte = 7; - action.data = DynamicBlockData::ScaleAction(a.clone()); - doc.objects.insert(h, ObjectType::DynamicBlock(action)); - - let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); - let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); - assert_eq!(scale_action(&back).map(|s| s.dwg_tail_byte), Some(7), "the byte isn't written"); - - let mut dxf = Vec::new(); - acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); - for version in ["AC1018", "AC1032"] { - let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); - let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); - let read = scale_action(&back).unwrap_or_else(|| panic!("{version}: the scale action wasn't written")); - assert_eq!(read.connections, a.connections, "{version}"); - assert_eq!(read.action.connections, a.action.connections, "{version}"); - assert_eq!(read.dwg_tail_byte, 0, "{version}"); - } - } - - /// Saving says what the DWG writer left out, per type: entities of types acadrust's DXF - /// reader doesn't model (another program's custom entity) can't be written; a drawing the DWG - /// keeps whole reports nothing. - #[cfg(not(no_dwg_bridge))] - #[test] - fn saving_lists_the_types_the_dwg_writer_leaves_out() { - let line = " 0\nLINE\n 8\n0\n100\nAcDbEntity\n100\nAcDbLine\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 11\n10.0\n 21\n0.0\n 31\n0.0\n"; - let widget = " 0\nACME_WIDGET\n 8\n0\n100\nAcDbEntity\n100\nAcmeWidget\n 10\n1.0\n 20\n2.0\n 30\n0.0\n"; - let dxf = |body: &str| { - format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{body} 0\nENDSEC\n 0\nEOF\n") - }; - for version in ["AC1015", "AC1018", "AC1032"] { - let (dwg, unwritten) = dxf_to_dwg_noted(dxf(&format!("{line}{widget}{widget}")).as_bytes(), version).unwrap(); - assert!(is_dwg(&dwg), "{version}"); - assert_eq!(unwritten, [("ACME_WIDGET".to_string(), 2)].into_iter().collect::(), "{version}"); - } - let (_, unwritten) = dxf_to_dwg_noted(dxf(line).as_bytes(), "AC1032").unwrap(); - assert!(unwritten.is_empty(), "{unwritten:?}"); - } - - /// An OLE2FRAME, which DraftCraft keeps as its DXF groups without modelling it, is written to - /// the DWG with its data: it isn't in the list of what the writer left out. - #[cfg(not(no_dwg_bridge))] - #[test] - fn ole_frames_are_written_with_their_data() { - let ole = " 0\nOLE2FRAME\n 8\n0\n100\nAcDbEntity\n100\nAcDbOle2Frame\n 70\n2\n 10\n1.0\n 20\n9.0\n 30\n0.0\n 11\n8.0\n 21\n2.0\n 31\n0.0\n 71\n2\n 72\n0\n 73\n1\n 90\n4\n310\nDEADBEEF\n 1\nOLE\n"; - let dxf = - format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{ole} 0\nENDSEC\n 0\nEOF\n"); - for version in ["AC1015", "AC1018", "AC1032"] { - let (dwg, unwritten) = dxf_to_dwg_noted(dxf.as_bytes(), version).unwrap(); - assert!(unwritten.is_empty(), "{version} {unwritten:?}"); - let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); - let frames: Vec> = back - .entities() - .filter_map(|e| match e { - acadrust::entities::EntityType::Ole2Frame(o) => Some(o.encoded_payload()), - _ => None, - }) - .collect(); - assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); - } - } -} diff --git a/crates/dwg/src/lz77.rs b/crates/dwg/src/lz77.rs new file mode 100644 index 00000000..25248b3e --- /dev/null +++ b/crates/dwg/src/lz77.rs @@ -0,0 +1,618 @@ +//! Compressor and decompressor for the R2004-family page compression +//! (AC1018, AC1024, AC1027, AC1032). +//! +//! Spec §4.7 "Compression" (verified against the spec text). The stream +//! starts with a literal length, then alternates copy opcodes (a back +//! reference into the output) with literal runs, and ends with opcode 0x11. +//! A back reference copies `compressedBytes` bytes starting `compOffset + 1` +//! bytes behind the current output position; overlapping copies are legal. +//! +//! [`compress`] is original work, used for DWG pages and the native `.cad` +//! format alike. The spec leaves room the decoder in AutoCAD does not +//! accept, so the compressor writes only what AutoCAD's own streams use, +//! observed across its MI-201 files from 2004 to 2018 (black-box: the +//! files, not its code): +//! +//! - every stream ends `11 00 00`, the end opcode followed by a zero two +//! byte offset; the spec mentions only the `11`; +//! - no copy is shorter than four bytes (no `0x4X` near opcode, no `0x21`); +//! - far copies (more than 0x4000 back) use `0x12`–`0x16` for four to +//! eight bytes and `0x10` with a count beyond that, never `0x18`–`0x1F`, +//! which the spec reads as lengths 10–17 but AutoCAD never writes. +//! +//! Its tests check every output by decompressing it again. + +use crate::read::error::{Error, Result}; + +// --------------------------------------------------------------------------- +// Compressor +// --------------------------------------------------------------------------- + +/// Largest back-reference distance the opcode forms can express +/// (far form: offset 0x3FFF + 14-bit field, distance = offset + 1). +const MAX_DISTANCE: usize = 0x3FFF + 0x3FFF + 1; +/// The shortest copy AutoCAD writes, in every form. +const MIN_MATCH: usize = 4; +/// The longest far copy AutoCAD writes with a length in the opcode +/// (`0x16`); longer ones take `0x10` and a count. +const FAR_SHORT_MAX: usize = 8; +/// What ends a stream: the end opcode and a zero two byte offset. +pub(crate) const END: [u8; 3] = [0x11, 0x00, 0x00]; +const HASH_BITS: u32 = 15; +const MAX_CHAIN: usize = 48; +const GOOD_ENOUGH: usize = 128; + +/// Unbounded count: 0x00 bytes add 0xFF each, the first non-zero byte ends +/// the value. `v` must be at least 1. +fn put_long(out: &mut Vec, mut v: usize) { + debug_assert!(v >= 1); + while v > 0xFF { + out.push(0); + v -= 0xFF; + } + out.push(v as u8); +} + +/// Literal run header for `n >= 4` literals. +fn put_literal_length(out: &mut Vec, n: usize) { + debug_assert!(n >= 4); + if n <= 0x12 { + out.push((n - 3) as u8); + } else { + out.push(0); + put_long(out, n - 0x12); + } +} + +/// Emit a copy opcode. Returns the index of the byte whose low two bits +/// carry the trailing literal count (filled in later, 0 by default). +fn put_copy(out: &mut Vec, len: usize, distance: usize) -> usize { + debug_assert!(len >= MIN_MATCH); + let offset = distance - 1; + if offset <= 0x3FF && len <= 14 { + let at = out.len(); + out.push((((len + 1) << 4) | ((offset & 3) << 2)) as u8); + out.push((offset >> 2) as u8); + return at; + } + let raw = if offset <= 0x3FFF { + if len <= 33 { + out.push((0x1E + len) as u8); + } else { + out.push(0x20); + put_long(out, len - 0x21); + } + offset + } else { + if len <= FAR_SHORT_MAX { + out.push(0x10 | (len - 2) as u8); + } else { + // 0x10 + count gives 10 or more; a nine-byte copy is cut to + // eight before it gets here. + debug_assert!(len >= 10); + out.push(0x10); + put_long(out, len - 9); + } + offset - 0x3FFF + }; + let at = out.len(); + out.push(((raw & 0x3F) << 2) as u8); + out.push((raw >> 6) as u8); + at +} + +/// Compress `src` into the §4.7 opcode stream. Returns `None` for inputs of +/// 1–3 bytes, which the format cannot express (the first literal run must +/// be at least four bytes); store those uncompressed. +pub fn compress(src: &[u8]) -> Option> { + let n = src.len(); + if n == 0 { + return Some(END.to_vec()); + } + if n < 4 { + return None; + } + let mut out = Vec::with_capacity(n / 2 + 16); + let hash_size = 1usize << HASH_BITS; + let mut head = vec![usize::MAX; hash_size]; + let mut prev = vec![usize::MAX; n]; + let hash = |p: usize| -> usize { + let v = (src[p] as u32) | ((src[p + 1] as u32) << 8) | ((src[p + 2] as u32) << 16); + (v.wrapping_mul(0x9E37_79B1) >> (32 - HASH_BITS)) as usize + }; + let insert = |p: usize, head: &mut Vec, prev: &mut Vec| { + if p + 3 <= n { + let h = hash(p); + prev[p] = head[h]; + head[h] = p; + } + }; + + let mut lit_start = 0usize; + // Byte holding the previous copy's literal-count bits, once a copy exists. + let mut last_copy: Option = None; + let mut pos = 0usize; + + let flush = |out: &mut Vec, last_copy: Option, lits: &[u8]| { + if lits.is_empty() { + return; + } + match last_copy { + Some(at) if lits.len() <= 3 => { + out[at] |= lits.len() as u8; + } + _ => put_literal_length(out, lits.len()), + } + out.extend_from_slice(lits); + }; + + while pos < n { + let mut best_len = 0usize; + let mut best_dist = 0usize; + // The opening literal run must be at least four bytes long. + if pos + 3 <= n && (last_copy.is_some() || pos >= 4) { + let mut cand = head[hash(pos)]; + let mut chain = 0; + while cand != usize::MAX && chain < MAX_CHAIN { + let dist = pos - cand; + if dist > MAX_DISTANCE { + break; + } + let mut l = 0; + while pos + l < n && src[cand + l] == src[pos + l] { + l += 1; + } + if l >= MIN_MATCH && l > best_len { + best_len = l; + best_dist = dist; + if l >= GOOD_ENOUGH { + break; + } + } + cand = prev[cand]; + chain += 1; + } + } + if best_len == FAR_SHORT_MAX + 1 && best_dist > 0x4000 { + best_len = FAR_SHORT_MAX; + } + if best_len > 0 { + flush(&mut out, last_copy, &src[lit_start..pos]); + last_copy = Some(put_copy(&mut out, best_len, best_dist)); + for p in pos..pos + best_len { + insert(p, &mut head, &mut prev); + } + pos += best_len; + lit_start = pos; + } else { + insert(pos, &mut head, &mut prev); + pos += 1; + } + } + flush(&mut out, last_copy, &src[lit_start..n]); + out.extend_from_slice(&END); + Some(out) +} + +// --------------------------------------------------------------------------- +// Decompressor +// --------------------------------------------------------------------------- + +struct Input<'a> { + src: &'a [u8], + pos: usize, +} + +impl Input<'_> { + fn byte(&mut self) -> Result { + let b = *self.src.get(self.pos).ok_or_else(|| Error::truncated(format!("compressed data ends at byte {}", self.pos)))?; + self.pos += 1; + Ok(b) + } + + /// Literal length (§4.7): 0x01–0x0F → value + 3; 0x00 → 0x0F plus + /// 0xFF for every further zero byte plus the first non-zero byte, + 3. + fn literal_length(&mut self, first: u8) -> Result { + if first != 0 { + return Ok(first as usize + 3); + } + let mut total = 0x0Fusize; + loop { + let b = self.byte()?; + if b == 0 { + total += 0xFF; + } else { + total += b as usize; + return Ok(total + 3); + } + } + } + + /// Long compression offset (§4.7): a non-zero byte is used as is; each + /// 0x00 adds 0xFF and the first non-zero byte ends the value. + fn long_count(&mut self) -> Result { + let mut total = 0usize; + loop { + let b = self.byte()?; + if b == 0 { + total += 0xFF; + } else { + return Ok(total + b as usize); + } + } + } + + /// Two byte offset (§4.7). Returns (offset, literal count 0–3). + fn two_byte_offset(&mut self) -> Result<(usize, usize)> { + let first = self.byte()?; + let second = self.byte()?; + let offset = ((first >> 2) as usize) | ((second as usize) << 6); + Ok((offset, (first & 0x03) as usize)) + } +} + +/// Decompress one page. `expected` is the decompressed size recorded in the +/// page header; producing more than that is treated as corruption. +pub fn decompress(src: &[u8], expected: usize) -> Result> { + // `expected` comes from the file; grow as data arrives instead of + // trusting it for one large allocation. + let mut out: Vec = Vec::with_capacity(expected.min(src.len().saturating_mul(8)).min(1 << 20)); + let mut inp = Input { src, pos: 0 }; + + let copy_literals = |inp: &mut Input, out: &mut Vec, n: usize| -> Result<()> { + if out.len() + n > expected { + return Err(Error::format(format!("literal run of {n} bytes overflows page size {expected}"))); + } + let end = inp.pos + n; + let bytes = inp.src.get(inp.pos..end).ok_or_else(|| Error::truncated(format!("literal run of {n} bytes at {} runs past input", inp.pos)))?; + out.extend_from_slice(bytes); + inp.pos = end; + Ok(()) + }; + + let mut op = inp.byte()?; + if op & 0xF0 == 0 { + let n = inp.literal_length(op)?; + copy_literals(&mut inp, &mut out, n)?; + op = inp.byte()?; + } + + loop { + if op == 0x11 { + break; + } + let (count, offset, literals) = match op { + 0x10 => { + let count = inp.long_count()? + 9; + let (off, lit) = inp.two_byte_offset()?; + (count, off + 0x3FFF, lit) + } + 0x12..=0x1F => { + let count = (op & 0x0F) as usize + 2; + let (off, lit) = inp.two_byte_offset()?; + (count, off + 0x3FFF, lit) + } + 0x20 => { + let count = inp.long_count()? + 0x21; + let (off, lit) = inp.two_byte_offset()?; + (count, off, lit) + } + 0x21..=0x3F => { + let count = op as usize - 0x1E; + let (off, lit) = inp.two_byte_offset()?; + (count, off, lit) + } + 0x40..=0xFF => { + let count = ((op & 0xF0) >> 4) as usize - 1; + let op2 = inp.byte()?; + let off = ((op2 as usize) << 2) | (((op & 0x0C) >> 2) as usize); + (count, off, (op & 0x03) as usize) + } + _ => return Err(Error::format(format!("unexpected opcode {op:#04x} at compressed byte {}", inp.pos - 1))), + }; + + let distance = offset + 1; + if distance > out.len() { + return Err(Error::format(format!("back reference {distance} bytes behind output of {} bytes", out.len()))); + } + if out.len() + count > expected { + return Err(Error::format(format!("copy of {count} bytes overflows page size {expected}"))); + } + let start = out.len() - distance; + for k in 0..count { + let b = out[start + k]; + out.push(b); + } + + if literals > 0 { + copy_literals(&mut inp, &mut out, literals)?; + op = inp.byte()?; + } else { + op = inp.byte()?; + if op & 0xF0 == 0 { + let n = inp.literal_length(op)?; + copy_literals(&mut inp, &mut out, n)?; + op = inp.byte()?; + } + } + } + Ok(out) +} + +/// One copy in a stream: its opcode, length and distance back. +#[cfg(test)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Copy { + pub op: u8, + pub len: usize, + pub distance: usize, +} + +/// The copies of a stream, in order, and the bytes after its end opcode. +#[cfg(test)] +pub(crate) fn copies(src: &[u8]) -> Result<(Vec, Vec)> { + let mut inp = Input { src, pos: 0 }; + let mut out = Vec::new(); + let mut produced = 0usize; + let mut op = inp.byte()?; + if op & 0xF0 == 0 { + let n = inp.literal_length(op)?; + inp.pos += n; + produced += n; + op = inp.byte()?; + } + while op != 0x11 { + let (len, offset, mut literals) = match op { + 0x10 => (inp.long_count()? + 9, inp.two_byte_offset().map(|(o, l)| (o + 0x3FFF, l))?), + 0x12..=0x1F => ((op & 0x0F) as usize + 2, inp.two_byte_offset().map(|(o, l)| (o + 0x3FFF, l))?), + 0x20 => (inp.long_count()? + 0x21, inp.two_byte_offset()?), + 0x21..=0x3F => (op as usize - 0x1E, inp.two_byte_offset()?), + 0x40..=0xFF => { + let op2 = inp.byte()?; + (((op & 0xF0) >> 4) as usize - 1, (((op2 as usize) << 2) | (((op & 0x0C) >> 2) as usize), (op & 3) as usize)) + } + _ => return Err(Error::format(format!("opcode {op:#04x}"))), + } + .flatten(); + out.push(Copy { op, len, distance: offset + 1 }); + produced += len; + if literals == 0 { + let b = inp.byte()?; + if b & 0xF0 == 0 { + literals = inp.literal_length(b)?; + } else { + inp.pos -= 1; + } + } + inp.pos += literals; + produced += literals; + op = inp.byte()?; + } + let _ = produced; + Ok((out, src[inp.pos..].to_vec())) +} + +#[cfg(test)] +trait Flatten { + fn flatten(self) -> (usize, usize, usize); +} +#[cfg(test)] +impl Flatten for (usize, (usize, usize)) { + fn flatten(self) -> (usize, usize, usize) { + (self.0, self.1.0, self.1.1) + } +} + +/// Whether a stream keeps to what AutoCAD writes (see the module notes). +/// Returns the first departure. +#[cfg(test)] +pub(crate) fn autocad_form(src: &[u8]) -> std::result::Result<(), String> { + let (copies, tail) = copies(src).map_err(|e| e.message)?; + if tail != [0, 0] { + return Err(format!("stream ends 11 {tail:02x?}, not 11 00 00")); + } + for c in copies { + if c.len < MIN_MATCH { + return Err(format!("copy of {} bytes (opcode {:#04x})", c.len, c.op)); + } + if (0x17..=0x1F).contains(&c.op) { + return Err(format!("far opcode {:#04x}", c.op)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn literal_only() { + // 0x05 -> 8 literals (spec example: 0x05 = 0x08), then terminator. + let mut src = vec![0x05]; + src.extend_from_slice(b"ABCDEFGH"); + src.push(0x11); + assert_eq!(decompress(&src, 8).unwrap(), b"ABCDEFGH"); + } + + #[test] + fn long_literal_length() { + // Spec example: 0x00 0x02 = 0x14 literals. + let payload: Vec = (0u8..0x14).collect(); + let mut src = vec![0x00, 0x02]; + src.extend_from_slice(&payload); + src.push(0x11); + assert_eq!(decompress(&src, 0x14).unwrap(), payload); + } + + #[test] + fn short_back_reference() { + // "abcd", then opcode 0x4C: count ((0x40 & 0xF0) >> 4) - 1 = 3, + // offset (0 << 2) | ((0x4C & 0x0C) >> 2) = 3 -> copy 3 bytes from 4 + // back; literal count 0, so the next byte is read as a literal length + // or opcode (0x11 ends). + let src = [0x01, b'a', b'b', b'c', b'd', 0x4C, 0x00, 0x11]; + assert_eq!(decompress(&src, 7).unwrap(), b"abcdabc"); + } + + #[test] + fn two_byte_offset_with_trailing_literal() { + // Four literals "xyz?", then opcode 0x22 (count 0x22 - 0x1E = 4) with + // two-byte offset bytes 0x0D 0x00: offset = (0x0D >> 2) | (0 << 6) = 3 + // (distance 4), literal count = 0x0D & 3 = 1 -> one literal '!'. + let src = [0x01, b'x', b'y', b'z', b'?', 0x22, 0x0D, 0x00, b'!', 0x11]; + assert_eq!(decompress(&src, 9).unwrap(), b"xyz?xyz?!"); + } + + #[test] + fn long_compression_count() { + // Opcode 0x20 with long count byte 0x01 -> 0x01 + 0x21 = 34 bytes, + // distance 1 (offset 0): a run of the last literal. + let src = [0x01, b'a', b'b', b'c', b'd', 0x20, 0x01, 0x00, 0x00, 0x11]; + let out = decompress(&src, 4 + 34).unwrap(); + assert_eq!(&out[..4], b"abcd"); + assert!(out[4..].iter().all(|&b| b == b'd')); + assert_eq!(out.len(), 38); + } + + #[test] + fn corrupt_reference_is_error() { + let src = [0x01, b'a', b'b', b'c', b'd', 0x4C, 0xFF, 0x11]; + assert!(decompress(&src, 100).is_err()); + assert!(decompress(&[], 10).is_err()); + } +} + +#[cfg(test)] +mod compressor { + use super::{END, autocad_form, compress, decompress}; + + fn rng(seed: &mut u64) -> u64 { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + *seed + } + + #[test] + fn writes_only_the_forms_autocad_writes() { + let mut seed = 0x5EED_u64; + let block: Vec = (0..40_000).map(|_| rng(&mut seed) as u8).collect(); + let mut data = Vec::new(); + data.extend_from_slice(&block[..20_000]); + // Far copies of every length from 3 to 20, each after fresh bytes. + for len in 3..=20 { + data.extend_from_slice(&block[20_000 + len * 50..20_000 + len * 50 + 40]); + data.extend_from_slice(&block[len * 300..len * 300 + len]); + } + // Near copies of 3 bytes. + data.extend_from_slice(b"abc1abc2abc3abc4"); + data.extend_from_slice(&vec![0u8; 0x7400 - data.len() % 0x7400]); + for chunk in data.chunks(0x7400) { + let c = compress(chunk).unwrap(); + assert_eq!(decompress(&c, chunk.len()).unwrap(), chunk); + autocad_form(&c).unwrap(); + } + for n in 4..80 { + let v: Vec = (0..n).map(|i| (i % 7) as u8).collect(); + autocad_form(&compress(&v).unwrap()).unwrap(); + } + // The checker catches what the compressor used to write. + let mut bare = vec![0x05]; + bare.extend_from_slice(b"ABCDEFGH"); + bare.push(0x11); + assert!(autocad_form(&bare).is_err()); + let three = [0x01, b'a', b'b', b'c', b'd', 0x4C, 0x00, 0x11, 0, 0]; + assert!(autocad_form(&three).is_err()); + } + + fn roundtrip(data: &[u8]) { + let c = compress(data).expect("compressible length"); + let d = decompress(&c, data.len()).expect("decompress own output"); + assert_eq!(d, data, "roundtrip failed for {} bytes", data.len()); + } + + #[test] + fn tiny_inputs() { + assert_eq!(compress(&[]).unwrap(), END.to_vec()); + assert!(compress(b"a").is_none()); + assert!(compress(b"abc").is_none()); + for n in 4..64 { + roundtrip(&vec![b'q'; n]); + let v: Vec = (0..n as u8).collect(); + roundtrip(&v); + } + } + + #[test] + fn all_opcode_forms() { + let mut seed = 0xDEAD_BEEF_u64; + let block: Vec = (0..40_000).map(|_| rng(&mut seed) as u8).collect(); + // Near short, near long (two-byte), far (> 0x4000) and very long runs. + let mut data = Vec::new(); + data.extend_from_slice(&block[..2000]); + data.extend_from_slice(&block[100..110]); // 0x40 form + data.extend_from_slice(&block[..300]); // near two-byte, long count + data.extend_from_slice(&block[2000..22_000]); + data.extend_from_slice(&block[..12]); // far, short + data.extend_from_slice(&block[500..900]); // far, long + data.extend_from_slice(&vec![7u8; 5000]); // overlapping run + data.extend_from_slice(&block[22_000..]); + roundtrip(&data); + let c = compress(&data).unwrap(); + assert!(c.len() < data.len()); + } + + #[test] + fn random_and_structured() { + let mut seed = 0x0123_4567_89AB_CDEF_u64; + for round in 0..300 { + let len = 4 + (rng(&mut seed) % 5000) as usize; + let alphabet = 1 + (rng(&mut seed) % 255) as u8; + let data: Vec = (0..len) + .map(|i| { + let r = rng(&mut seed); + if round % 3 == 0 { + (r % alphabet as u64) as u8 + } else { + // Repetitive text-like content. + b"LINE 10 20 30 LAYER 0 "[(i + (r as usize % 3)) % 22] + } + }) + .collect(); + roundtrip(&data); + } + } + + #[test] + fn literal_counts_after_copies() { + // Copies followed by 1, 2, 3, 4 and 19+ literals. + let mut data = b"abcdefgh".to_vec(); + for k in [1usize, 2, 3, 4, 5, 18, 19, 20, 300] { + data.extend_from_slice(b"abcdefgh"); + data.extend((0..k).map(|i| 200u8.wrapping_add((i * 7 + k) as u8))); + } + roundtrip(&data); + } +} + +#[cfg(test)] +mod robustness { + #[test] + fn random_input_does_not_panic() { + let mut x: u64 = 0x1234_5678_9ABC_DEF1; + for _ in 0..20_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let len = (x % 300) as usize; + let src: Vec = (0..len) + .map(|i| { + let v = x.rotate_left((i % 64) as u32) as u8; + v ^ (i as u8) + }) + .collect(); + let _ = super::decompress(&src, 0x7400); + } + } +} diff --git a/crates/dwg/src/read/classes.rs b/crates/dwg/src/read/classes.rs new file mode 100644 index 00000000..e7534320 --- /dev/null +++ b/crates/dwg/src/read/classes.rs @@ -0,0 +1,229 @@ +//! AcDb:Classes — custom object classes (type codes 500 and up). +//! +//! Written from knowledge of the spec, chapter 10. VERIFY against the spec +//! PDF and real files. + +use super::section::{self, CLASSES_END, CLASSES_START}; +use super::streams::{Streams, string_stream}; +use super::version::DwgVersion as V; +use super::version::DwgVersion; +use crate::bits::BitReader; +use crate::read::error::{Error, Result}; +use crate::read::model::ClassDef; + +pub(crate) fn parse(data: &[u8], ver: DwgVersion, maintenance: u8, codepage: u16) -> Result<(Vec, Vec)> { + let mut notes = Vec::new(); + let wrapped = section::unwrap(data, &CLASSES_START, &CLASSES_END, ver, maintenance)?; + if !wrapped.end_found { + notes.push("classes: end sentinel not found where expected".to_string()); + } + let body = wrapped.body; + if ver < V::R2007 { + let s = Streams { ver, codepage, dat: BitReader::new(body), strs: None, hdl: None }; + return Ok((read_records(s)?, notes)); + } + // R2007+: an RL bit size, then records whose strings sit in a string + // stream ending at that bit. Which origin the bit size counts from is + // not confirmed, so try both and keep the one that parses cleanly. + if body.len() < 4 { + return Err(Error::truncated("classes body too short")); + } + let bitsize = u32::from_le_bytes([body[0], body[1], body[2], body[3]]) as usize; + let mut last_err = Error::format("no class layout matched"); + for endbit in [bitsize, bitsize + 32] { + if endbit == 0 || endbit > body.len() * 8 { + continue; + } + let strs = match string_stream(body, endbit) { + Ok(Some((sr, _))) => Some(sr), + Ok(None) => None, + Err(e) => { + last_err = e; + continue; + } + }; + let mut dat = BitReader::with_bounds(body, 32, endbit); + dat.set_end(endbit); + let s = Streams { ver, codepage, dat, strs, hdl: None }; + match read_records(s) { + Ok(list) if list.iter().all(plausible) => return Ok((list, notes)), + Ok(_) => last_err = Error::format("class records implausible"), + Err(e) => last_err = e, + } + } + Err(last_err) +} + +fn plausible(c: &ClassDef) -> bool { + c.number >= 500 + && (c.item_class_id == 0x1F2 || c.item_class_id == 0x1F3) + && !c.dxf_name.is_empty() + && c.dxf_name.chars().all(|ch| ch.is_ascii_graphic()) +} + +fn read_records(mut s: Streams) -> Result> { + let ver = s.ver; + let mut expected: Option = None; + if ver >= V::R2004 { + let max_num = s.dat.bs()? as usize; + let _zero1 = s.dat.rc()?; + let _zero2 = s.dat.rc()?; + let _flag = s.dat.b()?; + expected = Some(max_num.saturating_sub(499)); + } + let mut out = Vec::new(); + loop { + if let Some(n) = expected { + if out.len() >= n { + break; + } + } else if s.dat.remaining() < 13 { + break; + } + let mut c = ClassDef { number: s.dat.bs()?, proxy_flags: s.dat.bs()?, ..Default::default() }; + c.app_name = s.tv()?; + c.cpp_name = s.tv()?; + c.dxf_name = s.tv()?; + c.was_zombie = s.dat.b()?; + c.item_class_id = s.dat.bs()?; + if ver >= V::R2004 { + c.instance_count = s.dat.bl()?; + // BL, as spec §5.8 gives them for R2007, not BS as §10.2 does: + // real AC1018 and AC1032 files both parse only this way (a + // maintenance number of 377 shows it). + c.dwg_version = s.dat.bl()?; + c.maintenance_version = s.dat.bl()?; + let _unknown1 = s.dat.bl()?; + let _unknown2 = s.dat.bl()?; + } + if c.number < 500 && expected.is_none() { + // Padding or garbage after the last record. + break; + } + out.push(c); + if out.len() > 65_535 { + return Err(Error::format("class count runaway")); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct W { + bytes: Vec, + bits: usize, + } + impl W { + fn bit(&mut self, v: bool) { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + if v { + *self.bytes.last_mut().unwrap() |= 0x80 >> (self.bits % 8); + } + self.bits += 1; + } + fn n(&mut self, v: u64, count: u32) { + for i in (0..count).rev() { + self.bit(v >> i & 1 != 0); + } + } + fn rc(&mut self, v: u8) { + self.n(v as u64, 8); + } + fn rs(&mut self, v: u16) { + self.rc(v as u8); + self.rc((v >> 8) as u8); + } + fn rl(&mut self, v: u32) { + self.rs(v as u16); + self.rs((v >> 16) as u16); + } + fn bs(&mut self, v: u16) { + match v { + 0 => self.n(0b10, 2), + 256 => self.n(0b11, 2), + 1..=255 => { + self.n(0b01, 2); + self.rc(v as u8); + } + _ => { + self.n(0b00, 2); + self.rs(v); + } + } + } + fn bl(&mut self, v: u32) { + match v { + 0 => self.n(0b10, 2), + 1..=255 => { + self.n(0b01, 2); + self.rc(v as u8); + } + _ => { + self.n(0b00, 2); + self.rl(v); + } + } + } + fn tu(&mut self, s: &str) { + let units: Vec = s.encode_utf16().collect(); + self.bs(units.len() as u16); + for u in units { + self.rs(u); + } + } + } + + /// An R2007+ classes section laid out as an AC1032 file saved by + /// AutoCAD LT 2026 has it: the class's DWG and maintenance versions are + /// BL (spec §5.8), not BS (§10.2); 377 does not fit a BS read here. + #[test] + fn r2007_plus_class_versions_are_bitlongs() { + let names = ["ObjectDBX Classes", "AcDbDetailViewStyle", "ACDBDETAILVIEWSTYLE"]; + let mut w = W::default(); + w.rl(0); // bit size, patched below + w.bs(500); // maximum class number + w.rc(0); + w.rc(0); + w.bit(true); + w.bs(500); + w.bs(0x401); + w.bit(false); // was a zombie + w.bs(0x1F3); + w.bl(1); // objects of this class + w.bl(33); // DWG version + w.bl(377); // maintenance version + w.bl(0); + w.bl(0); + let strings_start = w.bits; + for s in names { + w.tu(s); + } + let size = (w.bits - strings_start) as u16; + w.rs(size); + w.bit(true); // string stream present + let endbit = w.bits as u32; + w.bytes[..4].copy_from_slice(&endbit.to_le_bytes()); + let body = w.bytes; + + let mut sec = CLASSES_START.to_vec(); + sec.extend_from_slice(&(body.len() as u32).to_le_bytes()); + sec.extend_from_slice(&0u32.to_le_bytes()); // high size (R2018) + sec.extend_from_slice(&body); + sec.extend_from_slice(&[0, 0]); // CRC + sec.extend_from_slice(&CLASSES_END); + + let (list, _) = parse(&sec, V::R2018, 0, 30).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].number, 500); + assert_eq!(list[0].app_name, names[0]); + assert_eq!(list[0].cpp_name, names[1]); + assert_eq!(list[0].dxf_name, names[2]); + assert_eq!(list[0].item_class_id, 0x1F3); + } +} diff --git a/crates/dwg/src/read/container.rs b/crates/dwg/src/read/container.rs new file mode 100644 index 00000000..d1cab037 --- /dev/null +++ b/crates/dwg/src/read/container.rs @@ -0,0 +1,24 @@ +//! Version-independent view of the sections the reader needs. + +use crate::read::model::{Diagnostic, SectionInfo}; + +pub(crate) struct Container { + pub maintenance: u8, + pub codepage: u16, + /// Header section bytes, starting at its start sentinel. + pub header: Option>, + /// Classes section bytes, starting at its start sentinel. + pub classes: Option>, + /// Object map bytes. + pub handles: Vec, + /// Bytes that object-map locations index into: the whole file for + /// R13–R15, the AcDb:AcDbObjects section for R2004+. + pub objects: Vec, + pub sections: Vec, + /// The other named sections of an R2004-family file (AcDb:SummaryInfo, + /// AcDb:Preview, AcDb:AuxHeader, …), decompressed, in section-map + /// order. Sections that could not be read are left out. Empty for + /// R13–R15. + pub others: Vec<(String, Vec)>, + pub notes: Vec, +} diff --git a/crates/dwg/src/read/eed.rs b/crates/dwg/src/read/eed.rs new file mode 100644 index 00000000..25444be0 --- /dev/null +++ b/crates/dwg/src/read/eed.rs @@ -0,0 +1,580 @@ +//! Extended entity data (EED): the per-application data DXF calls XDATA. +//! +//! Spec: ODA Open Design Specification for .dwg files v5.4.1, chapter 28 +//! "Extended Entity Data (Extended Object Data)", checked against the spec +//! text. Its place in every object, right after the object's own handle, +//! is from §20.1 and §20.4.1 (also checked). Layout, repeated until a +//! length of zero: +//! +//! ```text +//! BS length of this application's data, in bytes +//! H the application's APPID table record +//! … that many bytes of items: a one-byte code (DXF group − 1000), +//! then the value, with no bit coding +//! ``` +//! +//! Three points the spec leaves open, and how this module handles them: +//! +//! - **Byte order of the 8-byte handles in items 3 and 5.** The spec says +//! to read them "as usual for handles" (most significant byte first, as +//! in §2.13), but also that all data is little-endian unless stated +//! otherwise (§2). Items are read most significant first, then +//! [`resolve`] checks which order makes the drawing's 1003 and 1005 +//! values point at existing layers and objects, and keeps that one, as +//! the object map reader does with its two readings. +//! - **8-bit strings (R13–R2004)** carry a code page, a "2-byte short" with +//! no byte order given. Real R14, 2000 and 2004 files store it most +//! significant byte first (00 1E for code page 30), so it is read that +//! way, and least significant first is accepted too. Only ANSI_1252 is +//! decoded (code page 30, or 1252), exactly, one character per byte; +//! strings in any other code page are kept as bytes. +//! - **Terminators.** The spec describes none, so strings are kept exactly, +//! including any NUL characters. Real files will show whether AutoCAD +//! counts a terminating NUL. + +use super::version::DwgVersion; +use crate::bits::BitReader; +use crate::read::error::{Error, Result}; +use crate::read::geom::Vec3; +use crate::read::model::{Diagnostic, Handle, Object, ObjectKind, Severity, XData, XDataApp, XValue}; +use crate::read::text; +use std::collections::{BTreeMap, BTreeSet}; + +/// DWG type codes this module looks for: APPID (67, §20.4.66) and LAYER +/// (51, §20.4.54). +const APPID: u16 = 0x43; +const LAYER: u16 = 0x33; + +/// Read the extended data at the reader's position and leave the reader +/// just past the terminating zero length. Applications are returned by +/// handle; [`resolve`] names them once every object is loaded. `own` +/// is the object's handle, for references stored relative to it. +pub(crate) fn read(dat: &mut BitReader, ver: DwgVersion, own: u64) -> Result> { + let mut out = Vec::new(); + loop { + let size = dat.bs()? as usize; + if size == 0 { + return Ok(out); + } + let app = dat.handle()?.absolute(own); + let data = dat.raw_bytes(size)?; + out.push(XData { app: XDataApp::Handle(Handle(app)), items: items(&data, ver) }); + } +} + +/// Decode one application's items. An item that cannot be decoded ends +/// the list with an [`XValue::Undecoded`] holding the rest of the bytes, so +/// nothing is lost. +pub(crate) fn items(data: &[u8], ver: DwgVersion) -> Vec { + let mut out = Vec::new(); + let mut p = 0usize; + while p < data.len() { + let start = p; + match item(data, &mut p, ver) { + Ok(v) => out.push(v), + Err(_) => { + out.push(XValue::Undecoded { version: ver, data: data[start..].to_vec() }); + break; + } + } + } + out +} + +fn take<'a>(data: &'a [u8], p: &mut usize, n: usize) -> Result<&'a [u8]> { + let end = p + .checked_add(n) + .filter(|&e| e <= data.len()) + .ok_or_else(|| Error::truncated(format!("extended data item needs {n} bytes at byte {p} of {}", data.len())))?; + let s = &data[*p..end]; + *p = end; + Ok(s) +} + +fn fixed(data: &[u8], p: &mut usize) -> Result<[u8; N]> { + let mut a = [0u8; N]; + a.copy_from_slice(take(data, p, N)?); + Ok(a) +} + +fn real(data: &[u8], p: &mut usize) -> Result { + Ok(f64::from_le_bytes(fixed::<8>(data, p)?)) +} + +/// Items 3 and 5: eight bytes, read most significant first (see the +/// module notes; [`resolve`] may reverse them for the whole drawing). +fn handle8(data: &[u8], p: &mut usize) -> Result { + Ok(Handle(u64::from_be_bytes(fixed::<8>(data, p)?))) +} + +/// DWG code page numbers for Windows-1252: 30 in the DWG numbering (as the +/// file header's DWGCODEPAGE uses), 1252 in Windows' own. +fn is_cp1252(codepage: u16) -> bool { + matches!(codepage, 30 | 1252) +} + +fn string(data: &[u8], p: &mut usize, ver: DwgVersion) -> Result { + if ver >= DwgVersion::R2007 { + // RS length in characters, then UTF-16LE. + let n = u16::from_le_bytes(fixed::<2>(data, p)?) as usize; + let bytes = take(data, p, n * 2)?; + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + String::from_utf16(&units).map_err(|_| Error::format("group 1000: invalid UTF-16")) + } else { + // RC length, RS code page, then that many 8-bit characters. + let n = fixed::<1>(data, p)?[0] as usize; + let raw = fixed::<2>(data, p)?; + let (be, le) = (u16::from_be_bytes(raw), u16::from_le_bytes(raw)); + let codepage = if !is_cp1252(be) && is_cp1252(le) { le } else { be }; + let bytes = take(data, p, n)?; + if !is_cp1252(codepage) { + return Err(Error::new(crate::read::error::ErrorKind::Unsupported, format!("group 1000: code page {codepage} is not decoded"))); + } + Ok(text::decode_cp1252_exact(bytes)) + } +} + +fn item(data: &[u8], p: &mut usize, ver: DwgVersion) -> Result { + let code = fixed::<1>(data, p)?[0]; + Ok(match code { + 0 => XValue::Str(string(data, p, ver)?), + 2 => match fixed::<1>(data, p)?[0] { + 0 => XValue::Open, + 1 => XValue::Close, + b => return Err(Error::format(format!("group 1002: value {b}"))), + }, + 3 => XValue::Layer(handle8(data, p)?), + 4 => { + let n = fixed::<1>(data, p)?[0] as usize; + XValue::Bytes(take(data, p, n)?.to_vec()) + } + 5 => XValue::Handle(handle8(data, p)?), + 10..=13 => { + let v = Vec3::new(real(data, p)?, real(data, p)?, real(data, p)?); + match code { + 10 => XValue::Point(v), + 11 => XValue::Position(v), + 12 => XValue::Displacement(v), + _ => XValue::Direction(v), + } + } + 40..=42 => { + let x = real(data, p)?; + match code { + 40 => XValue::Real(x), + 41 => XValue::Distance(x), + _ => XValue::ScaleFactor(x), + } + } + 70 => XValue::Int16(i16::from_le_bytes(fixed::<2>(data, p)?)), + 71 => XValue::Int32(i32::from_le_bytes(fixed::<4>(data, p)?)), + // 1 (group 1001) is not valid inside the data, per the spec. + c => return Err(Error::format(format!("extended data item code {c} (group {})", 1000 + c as u32))), + }) +} + +/// Finish the extended data once every object is loaded: settle the byte +/// order of item 3 and 5 handles, name each application from its APPID +/// record, and report what could not be resolved. +pub(crate) fn resolve(objects: &mut BTreeMap, diagnostics: &mut Vec) { + let names: BTreeMap = objects + .iter() + .filter_map(|(h, o)| match &o.kind { + ObjectKind::NamedRecord(r) if o.type_code == APPID => Some((*h, r.name.clone())), + _ => None, + }) + .collect(); + let layers: BTreeSet = objects.iter().filter(|(_, o)| o.type_code == LAYER).map(|(h, _)| *h).collect(); + + // Which byte order makes the handles point at something: layers for + // 1003, any object for 1005. + let (mut refs, mut as_read, mut reversed) = (0usize, 0usize, 0usize); + for o in objects.values() { + for it in o.xdata.iter().flat_map(|x| &x.items) { + let (h, is_layer) = match it { + XValue::Layer(h) => (*h, true), + XValue::Handle(h) => (*h, false), + _ => continue, + }; + if h.is_null() { + continue; + } + let hit = |k: Handle| { + if is_layer { layers.contains(&k) } else { objects.contains_key(&k) } + }; + refs += 1; + as_read += hit(h) as usize; + reversed += hit(Handle(h.0.swap_bytes())) as usize; + } + } + let swap = reversed > as_read; + + let (mut carriers, mut blocks, mut unnamed, mut undecoded) = (0usize, 0usize, 0usize, 0usize); + let (mut layer_refs, mut stray_layer_refs) = (0usize, 0usize); + for o in objects.values_mut() { + if !o.xdata.is_empty() { + carriers += 1; + } + for x in &mut o.xdata { + blocks += 1; + if let XDataApp::Handle(h) = x.app { + match names.get(&h) { + Some(n) => x.app = XDataApp::Name(n.clone()), + None => unnamed += 1, + } + } + for it in &mut x.items { + match it { + XValue::Layer(h) | XValue::Handle(h) if swap => *h = Handle(h.0.swap_bytes()), + _ => {} + } + match it { + XValue::Layer(h) => { + layer_refs += 1; + if !layers.contains(h) { + stray_layer_refs += 1; + } + } + XValue::Undecoded { .. } => undecoded += 1, + _ => {} + } + } + } + } + + let mut note = |severity, message: String| diagnostics.push(Diagnostic { severity, message }); + if blocks > 0 { + note(Severity::Info, format!("extended data: {blocks} application blocks on {carriers} objects")); + } + if refs > 0 { + let (order, hits) = if swap { ("least", reversed) } else { ("most", as_read) }; + note( + if hits == 0 { Severity::Warning } else { Severity::Info }, + format!( + "extended data: handles (1003, 1005) read {order} significant byte first; \ + {hits} of {refs} point at objects in the drawing" + ), + ); + } + if unnamed > 0 { + note( + Severity::Warning, + format!( + "extended data: {unnamed} blocks refer to an application record that is \ + missing or unreadable; kept by handle" + ), + ); + } + if undecoded > 0 { + note(Severity::Warning, format!("extended data: {undecoded} blocks only partly decoded; the rest is kept as bytes")); + } + if stray_layer_refs > 0 { + note( + Severity::Warning, + format!( + "extended data: {stray_layer_refs} of {layer_refs} layer references (1003) do not \ + point at a LAYER" + ), + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::model::NamedRecord; + + /// Writes DWG bit codes most significant bit first, for building test + /// input (the reader side is `BitReader`). + #[derive(Default)] + struct BitWriter { + buf: Vec, + bits: usize, + } + + impl BitWriter { + fn bit(&mut self, b: bool) { + if self.bits.is_multiple_of(8) { + self.buf.push(0); + } + if b { + self.buf[self.bits / 8] |= 0x80 >> (self.bits % 8); + } + self.bits += 1; + } + fn bits(&mut self, n: u32, v: u64) { + for i in (0..n).rev() { + self.bit((v >> i) & 1 == 1); + } + } + fn rc(&mut self, v: u8) { + self.bits(8, v as u64); + } + /// BS as in §2.2. + fn bs(&mut self, v: u16) { + match v { + 0 => self.bits(2, 2), + 256 => self.bits(2, 3), + 1..=255 => { + self.bits(2, 1); + self.rc(v as u8); + } + _ => { + self.bits(2, 0); + self.rc(v as u8); + self.rc((v >> 8) as u8); + } + } + } + /// H as in §2.13: code, byte count, bytes most significant first. + fn handle(&mut self, code: u8, v: u64) { + let bytes: Vec = v.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect(); + self.rc((code << 4) | bytes.len() as u8); + for b in bytes { + self.rc(b); + } + } + fn block(&mut self, app: u64, data: &[u8]) { + self.bs(data.len() as u16); + self.handle(5, app); + for b in data { + self.rc(*b); + } + } + } + + fn v3(x: f64, y: f64, z: f64) -> Vec { + [x, y, z].iter().flat_map(|v| v.to_le_bytes()).collect() + } + + /// One item of every code, R13–R2004 string form. + fn every_item_r2004() -> (Vec, Vec) { + let mut d = Vec::new(); + d.extend([0, 4, 30, 0]); + d.extend(b"Test"); + d.extend([2, 0]); + d.extend([3, 0, 0, 0, 0, 0, 0, 0, 0x10]); + d.extend([4, 3, 0xDE, 0xAD, 0xBF]); + d.extend([5, 0, 0, 0, 0, 0, 0, 0x01, 0x2C]); + for (code, v) in [(10u8, 1.0), (11, 2.0), (12, 3.0), (13, 4.0)] { + d.push(code); + d.extend(v3(v, -v, 0.5)); + } + for (code, v) in [(40u8, 1.5), (41, 2.5), (42, 0.25)] { + d.push(code); + d.extend(f64::to_le_bytes(v)); + } + d.push(70); + d.extend((-2i16).to_le_bytes()); + d.push(71); + d.extend(123_456_789i32.to_le_bytes()); + d.extend([2, 1]); + let want = vec![ + XValue::Str("Test".into()), + XValue::Open, + XValue::Layer(Handle(0x10)), + XValue::Bytes(vec![0xDE, 0xAD, 0xBF]), + XValue::Handle(Handle(0x12C)), + XValue::Point(Vec3::new(1.0, -1.0, 0.5)), + XValue::Position(Vec3::new(2.0, -2.0, 0.5)), + XValue::Displacement(Vec3::new(3.0, -3.0, 0.5)), + XValue::Direction(Vec3::new(4.0, -4.0, 0.5)), + XValue::Real(1.5), + XValue::Distance(2.5), + XValue::ScaleFactor(0.25), + XValue::Int16(-2), + XValue::Int32(123_456_789), + XValue::Close, + ]; + (d, want) + } + + #[test] + fn decodes_every_item_code() { + let (d, want) = every_item_r2004(); + assert_eq!(items(&d, DwgVersion::R2004), want); + } + + #[test] + fn strings_are_kept_exactly() { + // R2007+: a character count, then UTF-16LE; a NUL is kept. + let d = [0u8, 4, 0, 0xD8, 0, b'-', 0, b'x', 0, 0, 0]; + assert_eq!(items(&d, DwgVersion::R2018), vec![XValue::Str("Ø-x\0".into())]); + // R13–R2004 in ANSI_1252 (code page 30, or 1252): one character per + // byte, NULs and escapes left as they are. + // The code page is stored most significant byte first in real files + // (00 1E); the other order is accepted too. + for cp in [[0u8, 30], [30, 0]] { + let d = [0u8, 3, cp[0], cp[1], b'4', b'5', 0xB0]; + assert_eq!(items(&d, DwgVersion::R2000), vec![XValue::Str("45°".into())]); + } + // Code page 1252 (0x04E4): "a", NUL, then a literal "\U+0041b". + let mut d = vec![0u8, 10, 0xE4, 0x04]; + d.extend(b"a\0\\U+0041b"); + assert_eq!(items(&d, DwgVersion::R2004), vec![XValue::Str("a\0\\U+0041b".into())]); + // Any other code page is kept as bytes (Shift-JIS here). + let d = vec![0u8, 2, 42, 0, 0x93, 0xFA, 70, 1, 0]; + assert_eq!(items(&d, DwgVersion::R2004), vec![XValue::Undecoded { version: DwgVersion::R2004, data: d.clone() }]); + } + + #[test] + fn undecodable_items_keep_their_bytes() { + let v = DwgVersion::R2004; + // Code 1 (group 1001) is invalid inside the data. + let d = [70u8, 7, 0, 1, 9, 9]; + assert_eq!(items(&d, v), vec![XValue::Int16(7), XValue::Undecoded { version: v, data: vec![1, 9, 9] }]); + // A string longer than the data, a bad brace, an unknown code. + for d in [vec![0u8, 10, 30, 0, b'a'], vec![2u8, 7], vec![99u8, 1, 2], vec![5u8, 0, 0]] { + assert_eq!(items(&d, v), vec![XValue::Undecoded { version: v, data: d.clone() }]); + } + // An unpaired UTF-16 surrogate is kept as bytes, not replaced. + let d = vec![0u8, 1, 0, 0x00, 0xD8]; + assert_eq!(items(&d, DwgVersion::R2010), vec![XValue::Undecoded { version: DwgVersion::R2010, data: d.clone() }]); + } + + #[test] + fn reads_blocks_until_the_zero_length() { + let (d, want) = every_item_r2004(); + let mut w = BitWriter::default(); + w.bits(3, 0b101); // EED rarely starts on a byte boundary + w.block(0x12, &d); + w.block(0x1A3, &[70, 1, 0]); + w.bs(0); + w.bits(5, 0b10011); // what follows in the object + let mut r = BitReader::new(&w.buf); + r.skip_bits(3).unwrap(); + let x = read(&mut r, DwgVersion::R2004, 0x40).unwrap(); + assert_eq!( + x, + vec![ + XData { app: XDataApp::Handle(Handle(0x12)), items: want }, + XData { app: XDataApp::Handle(Handle(0x1A3)), items: vec![XValue::Int16(1)] }, + ] + ); + assert_eq!(r.bits(5).unwrap(), 0b10011); + // No extended data: just the zero length. + let mut w = BitWriter::default(); + w.bs(0); + let mut r = BitReader::new(&w.buf); + assert!(read(&mut r, DwgVersion::R2018, 1).unwrap().is_empty()); + assert_eq!(r.position(), 2); + } + + #[test] + fn truncated_block_is_an_error() { + let mut w = BitWriter::default(); + w.bs(40); + w.handle(5, 0x12); + w.rc(70); + let mut r = BitReader::new(&w.buf); + assert!(read(&mut r, DwgVersion::R2004, 1).is_err()); + } + + fn object(h: u64, code: u16, name: &str, kind: ObjectKind, xdata: Vec) -> Object { + Object { + handle: Handle(h), + type_code: code, + type_name: name.into(), + owner: Handle::NULL, + reactors: vec![], + xdictionary: Handle::NULL, + entity: None, + kind, + offset: 0, + size: 0, + note: None, + raw: None, + xdata, + unknown_tags: vec![], + } + } + + #[test] + fn applications_are_named_from_appid_records() { + let appid = |h, n: &str| object(h, APPID, "APPID", ObjectKind::NamedRecord(NamedRecord { name: n.into() }), vec![]); + let mut objects: BTreeMap = [ + appid(0x12, "ACAD"), + appid(0x13, "AcadAnnotative"), + object(0x10, LAYER, "LAYER", ObjectKind::Unsupported, vec![]), + object( + 0x100, + 0x13, + "LINE", + ObjectKind::Unsupported, + vec![ + XData { app: XDataApp::Handle(Handle(0x13)), items: vec![XValue::Layer(Handle(0x10))] }, + XData { app: XDataApp::Handle(Handle(0x99)), items: vec![XValue::Layer(Handle(0x11))] }, + ], + ), + ] + .into_iter() + .map(|o| (o.handle, o)) + .collect(); + let mut diags = Vec::new(); + resolve(&mut objects, &mut diags); + let line = &objects[&Handle(0x100)]; + assert_eq!(line.xdata[0].app, XDataApp::Name("AcadAnnotative".into())); + assert_eq!(line.xdata[1].app, XDataApp::Handle(Handle(0x99))); + assert!(line.xdata_for("ACADANNOTATIVE").is_some()); + assert!(line.xdata_for("ACAD").is_none()); + let text: Vec<&str> = diags.iter().map(|d| d.message.as_str()).collect(); + assert!(text.iter().any(|m| m.contains("2 application blocks on 1 objects"))); + assert!(text.iter().any(|m| m.contains("1 blocks refer to an application"))); + assert!(text.iter().any(|m| m.contains("1 of 2 layer references"))); + } + + #[test] + fn handle_byte_order_is_settled_by_what_the_handles_point_at() { + let objects_with = |items: Vec| -> BTreeMap { + [ + object(0x10, LAYER, "LAYER", ObjectKind::Unsupported, vec![]), + object(0x100, 0x13, "LINE", ObjectKind::Unsupported, vec![XData { app: XDataApp::Handle(Handle(0x12)), items }]), + ] + .into_iter() + .map(|o| (o.handle, o)) + .collect() + }; + // Bytes written most significant first: kept as read. + let d = [&[3u8, 0, 0, 0, 0, 0, 0, 0, 0x10][..], &[5u8, 0, 0, 0, 0, 0, 0, 0x01, 0x00][..]].concat(); + let mut objects = objects_with(items(&d, DwgVersion::R2004)); + let mut diags = Vec::new(); + resolve(&mut objects, &mut diags); + let want = vec![XValue::Layer(Handle(0x10)), XValue::Handle(Handle(0x100))]; + assert_eq!(objects[&Handle(0x100)].xdata[0].items, want); + assert!(diags.iter().any(|x| x.message.contains("most significant byte first; 2 of 2"))); + // The same values written least significant first: reversed. + let d = [&[3u8, 0x10, 0, 0, 0, 0, 0, 0, 0][..], &[5u8, 0x00, 0x01, 0, 0, 0, 0, 0, 0][..]].concat(); + let mut objects = objects_with(items(&d, DwgVersion::R2004)); + let mut diags = Vec::new(); + resolve(&mut objects, &mut diags); + assert_eq!(objects[&Handle(0x100)].xdata[0].items, want); + assert!(diags.iter().any(|x| x.message.contains("least significant byte first; 2 of 2"))); + // Nothing to go by: kept as read, with a warning. + let d = [5u8, 0, 0, 0, 0, 0, 0, 0x0F, 0xFF]; + let mut objects = objects_with(items(&d, DwgVersion::R2004)); + let mut diags = Vec::new(); + resolve(&mut objects, &mut diags); + assert_eq!(objects[&Handle(0x100)].xdata[0].items, vec![XValue::Handle(Handle(0xFFF))]); + assert!(diags.iter().any(|x| x.severity == Severity::Warning && x.message.contains("0 of 1"))); + } + + #[test] + fn random_input_never_panics() { + let mut s = 0x2545_F491_4F6C_DD1Du64; + let mut next = move || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s + }; + for _ in 0..20_000 { + let n = (next() % 64) as usize; + let d: Vec = (0..n).map(|_| next() as u8).collect(); + for v in [DwgVersion::R2000, DwgVersion::R2018] { + let _ = items(&d, v); + let mut r = BitReader::new(&d); + let _ = read(&mut r, v, 1); + } + } + } +} diff --git a/crates/dwg/src/read/entities.rs b/crates/dwg/src/read/entities.rs new file mode 100644 index 00000000..acc3d874 --- /dev/null +++ b/crates/dwg/src/read/entities.rs @@ -0,0 +1,887 @@ +//! Entity-specific data decoders. +//! +//! Written from knowledge of the spec, chapter 20 "Data section +//! AcDb:AcDbObjects" (per-type layouts). The fetch of the spec text stopped +//! before this chapter, so every layout here must be VERIFIED against the +//! spec PDF and a corpus of real files. Fields marked "uncertain" are the +//! ones most likely to need correction. + +use super::streams::Streams; +use super::version::DwgVersion as V; +use crate::read::error::{Error, Result}; +use crate::read::geom::{Vec2, Vec3}; +use crate::read::model::{ + Arc, Attribute, Circle, ConstructionLine, Dimension, DimensionKind, Ellipse, Face3d, Handle, Hatch, HatchEdge, HatchPath, HatchPatternLine, + Insert, Leader, Line, LwPolyline, MLine, MLineVertex, MText, PaperViewport, Point, Polyline, PolylineKind, RasterImage, Solid, Spline, Text, + Tolerance, Vertex, VertexKind, +}; + +fn v3(a: [f64; 3]) -> Vec3 { + Vec3::from_array(a) +} +fn v2(a: [f64; 2]) -> Vec2 { + Vec2::from_array(a) +} + +pub(crate) fn line(s: &mut Streams) -> Result { + let (start, end) = if s.ver <= V::R14 { + (v3(s.dat.bd3()?), v3(s.dat.bd3()?)) + } else { + let z_zero = s.dat.b()?; + let sx = s.dat.rd()?; + let ex = s.dat.dd(sx)?; + let sy = s.dat.rd()?; + let ey = s.dat.dd(sy)?; + let (sz, ez) = if z_zero { + (0.0, 0.0) + } else { + let sz = s.dat.rd()?; + (sz, s.dat.dd(sz)?) + }; + (Vec3::new(sx, sy, sz), Vec3::new(ex, ey, ez)) + }; + let thickness = s.dat.bt(s.ver)?; + let extrusion = v3(s.dat.be(s.ver)?); + Ok(Line { start, end, thickness, extrusion }) +} + +pub(crate) fn circle(s: &mut Streams) -> Result { + let center = v3(s.dat.bd3()?); + let radius = s.dat.bd()?; + let thickness = s.dat.bt(s.ver)?; + let extrusion = v3(s.dat.be(s.ver)?); + Ok(Circle { center, radius, thickness, extrusion }) +} + +pub(crate) fn arc(s: &mut Streams) -> Result { + let c = circle(s)?; + let start_angle = s.dat.bd()?; + let end_angle = s.dat.bd()?; + Ok(Arc { center: c.center, radius: c.radius, thickness: c.thickness, extrusion: c.extrusion, start_angle, end_angle }) +} + +pub(crate) fn point(s: &mut Streams) -> Result { + let position = v3(s.dat.bd3()?); + let thickness = s.dat.bt(s.ver)?; + let extrusion = v3(s.dat.be(s.ver)?); + let x_axis_angle = s.dat.bd()?; + Ok(Point { position, thickness, extrusion, x_axis_angle }) +} + +pub(crate) fn ellipse(s: &mut Streams) -> Result { + Ok(Ellipse { + center: v3(s.dat.bd3()?), + major_axis: v3(s.dat.bd3()?), + extrusion: v3(s.dat.bd3()?), + axis_ratio: s.dat.bd()?, + start_param: s.dat.bd()?, + end_param: s.dat.bd()?, + }) +} + +pub(crate) fn text(s: &mut Streams) -> Result { + let mut t = Text { width_factor: 1.0, ..Default::default() }; + if s.ver <= V::R14 { + t.elevation = s.dat.bd()?; + t.insertion = v2(s.dat.rd2()?); + t.alignment = v2(s.dat.rd2()?); + t.extrusion = v3(s.dat.bd3()?); + t.thickness = s.dat.bd()?; + t.oblique = s.dat.bd()?; + t.rotation = s.dat.bd()?; + t.height = s.dat.bd()?; + t.width_factor = s.dat.bd()?; + t.value = s.tv()?; + t.generation = s.dat.bs()?; + t.h_align = s.dat.bs()?; + t.v_align = s.dat.bs()?; + } else { + let flags = s.dat.rc()?; + if flags & 0x01 == 0 { + t.elevation = s.dat.rd()?; + } + t.insertion = v2(s.dat.rd2()?); + t.alignment = if flags & 0x02 == 0 { + let x = s.dat.dd(t.insertion.x)?; + let y = s.dat.dd(t.insertion.y)?; + Vec2::new(x, y) + } else { + t.insertion + }; + t.extrusion = v3(s.dat.be(s.ver)?); + t.thickness = s.dat.bt(s.ver)?; + if flags & 0x04 == 0 { + t.oblique = s.dat.rd()?; + } + if flags & 0x08 == 0 { + t.rotation = s.dat.rd()?; + } + t.height = s.dat.rd()?; + if flags & 0x10 == 0 { + t.width_factor = s.dat.rd()?; + } + t.value = s.tv()?; + if flags & 0x20 == 0 { + t.generation = s.dat.bs()?; + } + if flags & 0x40 == 0 { + t.h_align = s.dat.bs()?; + } + if flags & 0x80 == 0 { + t.v_align = s.dat.bs()?; + } + } + Ok(t) +} + +/// ATTRIB (definition = false) and ATTDEF (definition = true). +pub(crate) fn attribute(s: &mut Streams, definition: bool) -> Result { + let text = text(s)?; + if s.ver >= V::R2010 { + let _version = s.dat.rc()?; + } + if s.ver >= V::R2018 { + // Uncertain: attribute type (1 single line, 2/4 multi-line). + let kind = s.dat.rc()?; + if kind > 1 { + return Err(Error::unsupported("multi-line attribute (R2018) not decoded yet")); + } + } + let tag = s.tv()?; + let field_length = s.dat.bs()?; + let flags = s.dat.rc()?; + let lock_position = if s.ver >= V::R2007 { s.dat.b()? } else { false }; + let prompt = if definition { + if s.ver >= V::R2010 { + let _version = s.dat.rc()?; // uncertain + } + s.tv()? + } else { + String::new() + }; + Ok(Attribute { text, tag, prompt, flags, field_length, is_definition: definition, lock_position }) +} + +/// INSERT and MINSERT. Returns the insert and, for R2004+, the number of +/// owned attribute handles that follow in the handle stream. +pub(crate) fn insert(s: &mut Streams, minsert: bool) -> Result<(Insert, u32)> { + let insertion = v3(s.dat.bd3()?); + let scale = if s.ver <= V::R14 { + v3(s.dat.bd3()?) + } else { + match s.dat.bb()? { + 0 => { + let x = s.dat.rd()?; + let y = s.dat.dd(x)?; + let z = s.dat.dd(x)?; + Vec3::new(x, y, z) + } + 1 => { + let y = s.dat.dd(1.0)?; + let z = s.dat.dd(1.0)?; + Vec3::new(1.0, y, z) + } + 2 => { + let x = s.dat.rd()?; + Vec3::new(x, x, x) + } + _ => Vec3::new(1.0, 1.0, 1.0), + } + }; + let rotation = s.dat.bd()?; + let extrusion = v3(s.dat.bd3()?); + let has_attribs = s.dat.b()?; + let owned = if s.ver >= V::R2004 && has_attribs { s.dat.bl()? } else { 0 }; + let array = if minsert { + let cols = s.dat.bs()?; + let rows = s.dat.bs()?; + let col_spacing = s.dat.bd()?; + let row_spacing = s.dat.bd()?; + Some((cols, rows, col_spacing, row_spacing)) + } else { + None + }; + Ok((Insert { insertion, scale, rotation, extrusion, has_attribs, array, ..Default::default() }, owned)) +} + +pub(crate) fn vertex_2d(s: &mut Streams) -> Result { + let flags = s.dat.rc()?; + let point = v3(s.dat.bd3()?); + let sw = s.dat.bd()?; + let (start_width, end_width) = if sw < 0.0 { (-sw, -sw) } else { (sw, s.dat.bd()?) }; + let bulge = s.dat.bd()?; + let id = if s.ver >= V::R2010 { s.dat.bl()? } else { 0 }; + let tangent_dir = s.dat.bd()?; + Ok(Vertex { kind: VertexKind::Vertex2d, flags, point, start_width, end_width, bulge, tangent_dir, id, face: [0; 4] }) +} + +pub(crate) fn vertex_3d(s: &mut Streams, kind: VertexKind) -> Result { + let flags = s.dat.rc()?; + let point = v3(s.dat.bd3()?); + Ok(Vertex { kind, flags, point, ..Default::default() }) +} + +pub(crate) fn vertex_pface_face(s: &mut Streams) -> Result { + let mut face = [0i16; 4]; + for f in &mut face { + *f = s.dat.bs()? as i16; + } + Ok(Vertex { kind: VertexKind::PfaceFace, face, ..Default::default() }) +} + +/// POLYLINE (2D). Returns the owned-object count (R2004+). +pub(crate) fn polyline_2d(s: &mut Streams) -> Result<(Polyline, u32)> { + let flags = s.dat.bs()?; + let curve_type = s.dat.bs()?; + let start_width = s.dat.bd()?; + let end_width = s.dat.bd()?; + let thickness = s.dat.bt(s.ver)?; + let elevation = s.dat.bd()?; + let extrusion = v3(s.dat.be(s.ver)?); + let owned = if s.ver >= V::R2004 { s.dat.bl()? } else { 0 }; + Ok(( + Polyline { kind: PolylineKind::Polyline2d, flags, curve_type, start_width, end_width, thickness, elevation, extrusion, ..Default::default() }, + owned, + )) +} + +/// POLYLINE (3D). +pub(crate) fn polyline_3d(s: &mut Streams) -> Result<(Polyline, u32)> { + let curve_flags = s.dat.rc()?; + let closed_flags = s.dat.rc()?; + let owned = if s.ver >= V::R2004 { s.dat.bl()? } else { 0 }; + Ok(( + Polyline { + kind: PolylineKind::Polyline3d, + flags: (closed_flags as u16 & 1) | 8, + curve_type: curve_flags as u16, + extrusion: Vec3::Z, + ..Default::default() + }, + owned, + )) +} + +/// POLYLINE (PFACE). +pub(crate) fn polyline_pface(s: &mut Streams) -> Result<(Polyline, u32)> { + let _num_verts = s.dat.bs()?; + let _num_faces = s.dat.bs()?; + let owned = if s.ver >= V::R2004 { s.dat.bl()? } else { 0 }; + Ok((Polyline { kind: PolylineKind::PolyfaceMesh, flags: 64, extrusion: Vec3::Z, ..Default::default() }, owned)) +} + +/// POLYLINE (MESH). +pub(crate) fn polyline_mesh(s: &mut Streams) -> Result<(Polyline, u32)> { + let flags = s.dat.bs()?; + let curve_type = s.dat.bs()?; + let _m = s.dat.bs()?; + let _n = s.dat.bs()?; + let _m_density = s.dat.bs()?; + let _n_density = s.dat.bs()?; + let owned = if s.ver >= V::R2004 { s.dat.bl()? } else { 0 }; + Ok((Polyline { kind: PolylineKind::PolygonMesh, flags: flags | 16, curve_type, extrusion: Vec3::Z, ..Default::default() }, owned)) +} + +pub(crate) fn lwpolyline(s: &mut Streams) -> Result { + let flags = s.dat.bs()?; + let mut p = LwPolyline { flags, extrusion: Vec3::Z, ..Default::default() }; + if flags & 4 != 0 { + p.const_width = s.dat.bd()?; + } + if flags & 8 != 0 { + p.elevation = s.dat.bd()?; + } + if flags & 2 != 0 { + p.thickness = s.dat.bd()?; + } + if flags & 1 != 0 { + p.extrusion = v3(s.dat.bd3()?); + } + let n_points = s.dat.bl()?; + let n_bulges = if flags & 16 != 0 { s.dat.bl()? } else { 0 }; + let n_ids = if s.ver >= V::R2010 && flags & 1024 != 0 { s.dat.bl()? } else { 0 }; + let n_widths = if flags & 32 != 0 { s.dat.bl()? } else { 0 }; + + let n_points = s.check_count(n_points, 4, "LWPOLYLINE point")?; + let n_bulges = s.check_count(n_bulges, 2, "LWPOLYLINE bulge")?; + let n_ids = s.check_count(n_ids, 2, "LWPOLYLINE vertex id")?; + let n_widths = s.check_count(n_widths, 4, "LWPOLYLINE width")?; + + p.points.reserve(n_points); + if s.ver <= V::R14 { + for _ in 0..n_points { + p.points.push(v2(s.dat.rd2()?)); + } + } else if n_points > 0 { + let mut prev = v2(s.dat.rd2()?); + p.points.push(prev); + for _ in 1..n_points { + let x = s.dat.dd(prev.x)?; + let y = s.dat.dd(prev.y)?; + prev = Vec2::new(x, y); + p.points.push(prev); + } + } + for _ in 0..n_bulges { + p.bulges.push(s.dat.bd()?); + } + for _ in 0..n_ids { + p.vertex_ids.push(s.dat.bl()?); + } + for _ in 0..n_widths { + let a = s.dat.bd()?; + let b = s.dat.bd()?; + p.widths.push((a, b)); + } + Ok(p) +} + +/// SOLID and TRACE share a layout. +pub(crate) fn solid(s: &mut Streams, is_trace: bool) -> Result { + let thickness = s.dat.bt(s.ver)?; + let elevation = s.dat.bd()?; + let mut corners = [Vec2::ZERO; 4]; + for c in &mut corners { + *c = v2(s.dat.rd2()?); + } + let extrusion = v3(s.dat.be(s.ver)?); + Ok(Solid { thickness, elevation, corners, extrusion, is_trace }) +} + +pub(crate) fn face3d(s: &mut Streams) -> Result { + let mut f = Face3d::default(); + if s.ver <= V::R14 { + for c in &mut f.corners { + *c = v3(s.dat.bd3()?); + } + f.invisible_edges = s.dat.bs()?; + } else { + let no_flags = s.dat.b()?; + let z_zero = s.dat.b()?; + let x = s.dat.rd()?; + let y = s.dat.rd()?; + let z = if z_zero { 0.0 } else { s.dat.rd()? }; + f.corners[0] = Vec3::new(x, y, z); + for i in 1..4 { + let prev = f.corners[i - 1]; + let x = s.dat.dd(prev.x)?; + let y = s.dat.dd(prev.y)?; + let z = s.dat.dd(prev.z)?; + f.corners[i] = Vec3::new(x, y, z); + } + if !no_flags { + f.invisible_edges = s.dat.bs()?; + } + } + Ok(f) +} + +pub(crate) fn spline(s: &mut Streams) -> Result { + let mut sp = Spline::default(); + let mut scenario = s.dat.bl()?; + if s.ver >= V::R2013 { + // Uncertain: R2013 adds spline flags and knot parameterisation. + let flags1 = s.dat.bl()?; + let knot_param = s.dat.bl()?; + if flags1 & 1 != 0 { + scenario = 2; + } + if knot_param == 15 { + scenario = 1; + } + } + sp.degree = s.dat.bl()?; + let mut n_knots = 0; + let mut n_ctrl = 0; + let mut n_fit = 0; + let mut weighted = false; + match scenario { + 2 => { + sp.fit_tolerance = s.dat.bd()?; + sp.start_tangent = v3(s.dat.bd3()?); + sp.end_tangent = v3(s.dat.bd3()?); + n_fit = s.dat.bl()?; + } + 1 => { + sp.rational = s.dat.b()?; + sp.closed = s.dat.b()?; + sp.periodic = s.dat.b()?; + let _knot_tol = s.dat.bd()?; + let _ctrl_tol = s.dat.bd()?; + n_knots = s.dat.bl()?; + n_ctrl = s.dat.bl()?; + weighted = s.dat.b()?; + } + other => return Err(Error::format(format!("unknown spline scenario {other}"))), + } + let n_knots = s.check_count(n_knots, 2, "SPLINE knot")?; + let n_ctrl = s.check_count(n_ctrl, 6, "SPLINE control point")?; + let n_fit = s.check_count(n_fit, 6, "SPLINE fit point")?; + for _ in 0..n_knots { + sp.knots.push(s.dat.bd()?); + } + for _ in 0..n_ctrl { + sp.control_points.push(v3(s.dat.bd3()?)); + if weighted { + sp.weights.push(s.dat.bd()?); + } + } + for _ in 0..n_fit { + sp.fit_points.push(v3(s.dat.bd3()?)); + } + Ok(sp) +} + +pub(crate) fn mtext(s: &mut Streams) -> Result { + let mut m = + MText { insertion: v3(s.dat.bd3()?), extrusion: v3(s.dat.bd3()?), x_axis: v3(s.dat.bd3()?), linespacing_factor: 1.0, ..Default::default() }; + // Reference rectangle: width (DXF 41), then from R2007 its height (46). + // The writer and the field probe of AutoCAD's MTEXT records use this + // order; reading the height first swapped the two. + m.rect_width = s.dat.bd()?; + if s.ver >= V::R2007 { + m.rect_height = s.dat.bd()?; + } + m.text_height = s.dat.bd()?; + m.attachment = s.dat.bs()?; + m.drawing_dir = s.dat.bs()?; + let _ext_height = s.dat.bd()?; + let _ext_width = s.dat.bd()?; + m.contents = s.tv()?; + if s.ver >= V::R2000 { + m.linespacing_exact = s.dat.bs()? == 2; + m.linespacing_factor = s.dat.bd()?; + let _unknown = s.dat.b()?; + } + // R2004+ background fill and R2018 column data follow; not needed for + // display, and the handle stream is read from its own position. + Ok(m) +} + +pub(crate) fn dimension(s: &mut Streams, code: u16) -> Result { + let mut d = Dimension::default(); + if s.ver >= V::R2010 { + let _version = s.dat.rc()?; + } + d.extrusion = v3(s.dat.bd3()?); + d.text_midpoint = v2(s.dat.rd2()?); + d.elevation = s.dat.bd()?; + d.flags = s.dat.rc()?; + d.user_text = s.tv()?; + d.text_rotation = s.dat.bd()?; + d.horizontal_direction = s.dat.bd()?; + d.insert_scale = v3(s.dat.bd3()?); + d.insert_rotation = s.dat.bd()?; + if s.ver >= V::R2000 { + d.attachment = s.dat.bs()?; + let _linespacing_style = s.dat.bs()?; + let _linespacing_factor = s.dat.bd()?; + d.measurement = s.dat.bd()?; + } + if s.ver >= V::R2007 { + let _unknown = s.dat.b()?; + let _flip_arrow1 = s.dat.b()?; + let _flip_arrow2 = s.dat.b()?; + } + d.clone_insertion = v2(s.dat.rd2()?); + match code { + 0x14 => { + d.kind = DimensionKind::Ordinate; + d.pt10 = v3(s.dat.bd3()?); + d.pt13 = v3(s.dat.bd3()?); + d.pt14 = v3(s.dat.bd3()?); + let _flags2 = s.dat.rc()?; + } + 0x15 => { + d.kind = DimensionKind::Linear; + d.pt13 = v3(s.dat.bd3()?); + d.pt14 = v3(s.dat.bd3()?); + d.pt10 = v3(s.dat.bd3()?); + d.ext_line_rotation = s.dat.bd()?; + d.dim_rotation = s.dat.bd()?; + } + 0x16 => { + d.kind = DimensionKind::Aligned; + d.pt13 = v3(s.dat.bd3()?); + d.pt14 = v3(s.dat.bd3()?); + d.pt10 = v3(s.dat.bd3()?); + d.ext_line_rotation = s.dat.bd()?; + } + 0x17 => { + d.kind = DimensionKind::Angular3Pt; + d.pt10 = v3(s.dat.bd3()?); + d.pt13 = v3(s.dat.bd3()?); + d.pt14 = v3(s.dat.bd3()?); + d.pt15 = v3(s.dat.bd3()?); + } + 0x18 => { + d.kind = DimensionKind::Angular2Line; + d.pt16 = v2(s.dat.rd2()?); + d.pt13 = v3(s.dat.bd3()?); + d.pt14 = v3(s.dat.bd3()?); + d.pt15 = v3(s.dat.bd3()?); + d.pt10 = v3(s.dat.bd3()?); + } + 0x19 | 0x1A => { + d.kind = if code == 0x19 { DimensionKind::Radius } else { DimensionKind::Diameter }; + d.pt10 = v3(s.dat.bd3()?); + d.pt15 = v3(s.dat.bd3()?); + d.leader_length = s.dat.bd()?; + } + _ => return Err(Error::format(format!("not a dimension type {code:#x}"))), + } + Ok(d) +} + +/// HATCH. Returns the hatch and the number of boundary-object handles in +/// the handle stream. +pub(crate) fn hatch(s: &mut Streams) -> Result<(Hatch, Vec)> { + let mut h = Hatch::default(); + if s.ver >= V::R2004 { + h.is_gradient = s.dat.bl()? != 0; + let _reserved = s.dat.bl()?; + let _angle = s.dat.bd()?; + let _shift = s.dat.bd()?; + let _single_color = s.dat.bl()?; + let _tint = s.dat.bd()?; + let n_colors = s.dat.bl()?; + let n_colors = s.check_count(n_colors, 20, "gradient color")?; + for _ in 0..n_colors { + let _unknown_double = s.dat.bd()?; + let _unknown_short = s.dat.bs()?; + let _rgb = s.dat.bl()?; + let _ignored = s.dat.rc()?; + } + let _gradient_name = s.tv()?; + } + h.elevation = s.dat.bd()?; + h.extrusion = v3(s.dat.bd3()?); + h.pattern_name = s.tv()?; + h.solid_fill = s.dat.b()?; + h.associative = s.dat.b()?; + let n_paths = s.dat.bl()?; + let n_paths = s.check_count(n_paths, 8, "hatch path")?; + let mut handles: Vec = Vec::with_capacity(n_paths); + let mut derived = false; + for _ in 0..n_paths { + let flags = s.dat.bl()?; + if flags & 4 != 0 { + derived = true; + } + if flags & 2 == 0 { + let n_edges = s.dat.bl()?; + let n_edges = s.check_count(n_edges, 8, "hatch edge")?; + let mut edges = Vec::with_capacity(n_edges); + for _ in 0..n_edges { + let kind = s.dat.rc()?; + let edge = match kind { + 1 => HatchEdge::Line { a: v2(s.dat.rd2()?), b: v2(s.dat.rd2()?) }, + 2 => HatchEdge::Arc { center: v2(s.dat.rd2()?), radius: s.dat.bd()?, start: s.dat.bd()?, end: s.dat.bd()?, ccw: s.dat.b()? }, + 3 => HatchEdge::Ellipse { + center: v2(s.dat.rd2()?), + major: v2(s.dat.rd2()?), + ratio: s.dat.bd()?, + start: s.dat.bd()?, + end: s.dat.bd()?, + ccw: s.dat.b()?, + }, + 4 => { + let degree = s.dat.bl()?; + let rational = s.dat.b()?; + let _periodic = s.dat.b()?; + let n_knots = s.dat.bl()?; + let n_ctrl = s.dat.bl()?; + let n_knots = s.check_count(n_knots, 2, "hatch spline knot")?; + let n_ctrl = s.check_count(n_ctrl, 128, "hatch spline control point")?; + let mut knots = Vec::with_capacity(n_knots); + for _ in 0..n_knots { + knots.push(s.dat.bd()?); + } + let mut control_points = Vec::with_capacity(n_ctrl); + let mut weights = Vec::new(); + for _ in 0..n_ctrl { + control_points.push(v2(s.dat.rd2()?)); + if rational { + weights.push(s.dat.bd()?); + } + } + if s.ver >= V::R2010 { + let n_fit = s.dat.bl()?; + let n_fit = s.check_count(n_fit, 128, "hatch spline fit point")?; + if n_fit > 0 { + for _ in 0..n_fit { + let _fit = s.dat.rd2()?; + } + let _start_tangent = s.dat.rd2()?; + let _end_tangent = s.dat.rd2()?; + } + } + HatchEdge::Spline { degree, knots, control_points, weights } + } + other => return Err(Error::format(format!("unknown hatch edge type {other}"))), + }; + edges.push(edge); + } + h.paths.push(HatchPath::Edges { flags, edges }); + } else { + let has_bulges = s.dat.b()?; + let closed = s.dat.b()?; + let n = s.dat.bl()?; + let n = s.check_count(n, 128, "hatch polyline vertex")?; + let mut vertices = Vec::with_capacity(n); + for _ in 0..n { + let p = v2(s.dat.rd2()?); + let b = if has_bulges { s.dat.bd()? } else { 0.0 }; + vertices.push((p, b)); + } + h.paths.push(HatchPath::Polyline { flags, closed, vertices }); + } + handles.push(s.dat.bl()?); + } + h.style = s.dat.bs()?; + h.pattern_type = s.dat.bs()?; + if !h.solid_fill { + h.pattern_angle = s.dat.bd()?; + h.pattern_scale = s.dat.bd()?; + h.pattern_double = s.dat.b()?; + let n_lines = s.dat.bs()?; + let n_lines = s.check_count(n_lines as u32, 10, "hatch pattern line")?; + for _ in 0..n_lines { + let angle = s.dat.bd()?; + let base = v2(s.dat.bd2()?); + let offset = v2(s.dat.bd2()?); + let n_dashes = s.dat.bs()?; + let n_dashes = s.check_count(n_dashes as u32, 2, "hatch dash")?; + let mut dashes = Vec::with_capacity(n_dashes); + for _ in 0..n_dashes { + dashes.push(s.dat.bd()?); + } + h.pattern_lines.push(HatchPatternLine { angle, base, offset, dashes }); + } + } + if derived { + let _pixel_size = s.dat.bd()?; + } + let n_seeds = s.dat.bl()?; + let n_seeds = s.check_count(n_seeds, 128, "hatch seed point")?; + for _ in 0..n_seeds { + h.seed_points.push(v2(s.dat.rd2()?)); + } + Ok((h, handles)) +} + +/// RAY and XLINE (§20.4.42, §20.4.43): a point and a direction. +pub(crate) fn construction_line(s: &mut Streams) -> Result { + Ok(ConstructionLine { base: v3(s.dat.bd3()?), direction: v3(s.dat.bd3()?) }) +} + +/// LEADER (§20.4.47), up to its handles. +/// TOLERANCE (§20.4.49, checked against the specification text). The +/// text names its text field "BS"; it is a string (DXF 1), read as TV as +/// the specification's own example shows. R13 and R14 store a short, the +/// text height and the gap first; the short is printed as "S", which the +/// example shows to be a bit short. +pub(crate) fn tolerance(s: &mut Streams) -> Result { + let r14 = if s.ver <= V::R14 { Some((s.dat.bs()?, s.dat.bd()?, s.dat.bd()?)) } else { None }; + let insertion = v3(s.dat.bd3()?); + let x_direction = v3(s.dat.bd3()?); + let extrusion = v3(s.dat.bd3()?); + let text = s.tv()?; + Ok(Tolerance { insertion, x_direction, extrusion, text, dimstyle: Handle::NULL, r14 }) +} + +/// MLINE (§20.4.50, checked against the specification text). The style +/// handle comes after. Lists are bounded by the record's size. +pub(crate) fn mline(s: &mut Streams) -> Result { + let scale = s.dat.bd()?; + let justification = s.dat.rc()?; + let base = v3(s.dat.bd3()?); + let extrusion = v3(s.dat.bd3()?); + let flags = s.dat.bs()?; + let lines_in_style = s.dat.rc()?; + let n = s.dat.bs()?; + // A vertex is at least nine doubles' worth of bits (2 each). + let n = s.check_count(u32::from(n), 18, "multiline vertex")?; + let mut vertices = Vec::with_capacity(n); + for _ in 0..n { + let point = v3(s.dat.bd3()?); + let direction = v3(s.dat.bd3()?); + let miter = v3(s.dat.bd3()?); + let mut params = Vec::with_capacity(usize::from(lines_in_style)); + for _ in 0..lines_in_style { + let k = s.dat.bs()?; + let k = s.check_count(u32::from(k), 2, "multiline segment parameter")?; + let mut seg = Vec::with_capacity(k); + for _ in 0..k { + seg.push(s.dat.bd()?); + } + let k = s.dat.bs()?; + let k = s.check_count(u32::from(k), 2, "multiline fill parameter")?; + let mut fill = Vec::with_capacity(k); + for _ in 0..k { + fill.push(s.dat.bd()?); + } + params.push((seg, fill)); + } + vertices.push(MLineVertex { point, direction, miter, params }); + } + Ok(MLine { style: Handle::NULL, scale, justification, base, extrusion, flags, lines_in_style, vertices }) +} + +/// IMAGE and WIPEOUT (AcDbRasterImage, §20.4.80, checked against the +/// specification text; WIPEOUT, which the text doesn't describe, has the +/// same record). The handles (definition, reactor) come after. +pub(crate) fn raster_image(s: &mut Streams) -> Result { + let class_version = s.dat.bl()?; + let insertion = v3(s.dat.bd3()?); + let u = v3(s.dat.bd3()?); + let v = v3(s.dat.bd3()?); + let size = v2(s.dat.rd2()?); + let display = s.dat.bs()?; + let clipping = s.dat.b()?; + let brightness = s.dat.rc()?; + let contrast = s.dat.rc()?; + let fade = s.dat.rc()?; + let clip_inside = if s.ver >= V::R2010 { s.dat.b()? } else { false }; + let clip_type = s.dat.bs()?; + let clip = if clip_type == 1 { + vec![v2(s.dat.rd2()?), v2(s.dat.rd2()?)] + } else { + let n = s.dat.bl()?; + let n = s.check_count(n, 16, "clip vertex")?; + let mut pts = Vec::with_capacity(n); + for _ in 0..n { + pts.push(v2(s.dat.rd2()?)); + } + pts + }; + Ok(RasterImage { + class_version, + insertion, + u, + v, + size, + display, + clipping, + brightness, + contrast, + fade, + clip_inside, + clip_type, + clip, + definition: Handle::NULL, + reactor: Handle::NULL, + }) +} + +pub(crate) fn leader(s: &mut Streams) -> Result { + let unknown_bit = s.dat.b()?; + let annotation_type = s.dat.bs()?; + let path_type = s.dat.bs()?; + let n = s.dat.bl()?; + let n = s.check_count(n, 6, "leader vertex")?; + let mut vertices = Vec::with_capacity(n); + for _ in 0..n { + vertices.push(v3(s.dat.bd3()?)); + } + let origin = v3(s.dat.bd3()?); + let extrusion = v3(s.dat.bd3()?); + let x_direction = v3(s.dat.bd3()?); + let block_offset = v3(s.dat.bd3()?); + let annotation_offset = if s.ver >= V::R14 { v3(s.dat.bd3()?) } else { Vec3::ZERO }; + if s.ver <= V::R14 { + let _dimgap = s.dat.bd()?; + } + let text_height = s.dat.bd()?; + let text_width = s.dat.bd()?; + let hookline_on_x = s.dat.b()?; + let arrowhead = s.dat.b()?; + let mut unknown = (unknown_bit, 0u16, false, false); + if s.ver <= V::R14 { + let _arrowhead_type = s.dat.bs()?; + let _dimasz = s.dat.bd()?; + let _ = (s.dat.b()?, s.dat.b()?, s.dat.bs()?, s.dat.bs()?, s.dat.b()?, s.dat.b()?); + } else { + unknown.1 = s.dat.bs()?; + unknown.2 = s.dat.b()?; + unknown.3 = s.dat.b()?; + } + // DWG keeps no hook line flag: an MTEXT leader whose last segment is + // not along the horizontal direction ends in one. + let hookline = annotation_type == 0 && vertices.len() >= 2 && { + let d = vertices[vertices.len() - 1] - vertices[vertices.len() - 2]; + let x = x_direction.normalized(); + let along = d.dot(x).abs(); + along < d.length() * (1.0 - 1e-9) + }; + Ok(Leader { + vertices, + arrowhead, + spline: path_type == 1, + annotation_type, + hookline_on_x, + hookline, + text_height, + text_width, + origin, + extrusion, + x_direction, + block_offset, + annotation_offset, + annotation: Handle::NULL, + dimstyle: Handle::NULL, + unknown, + }) +} + +/// VIEWPORT (§20.4.38), up to its handles; with the number of frozen +/// layer handles to read. +pub(crate) fn viewport(s: &mut Streams) -> Result<(PaperViewport, u32)> { + let center = v3(s.dat.bd3()?); + let width = s.dat.bd()?; + let height = s.dat.bd()?; + let mut v = PaperViewport::new(center.xy(), width, height, Vec2::ZERO, 1.0, 0); + v.center = center; + v.view_height = height; + let mut frozen = 0; + if s.ver >= V::R2000 { + v.view_target = v3(s.dat.bd3()?); + v.view_direction = v3(s.dat.bd3()?); + v.twist = s.dat.bd()?; + v.view_height = s.dat.bd()?; + v.lens = s.dat.bd()?; + v.front_clip = s.dat.bd()?; + v.back_clip = s.dat.bd()?; + v.snap_angle = s.dat.bd()?; + v.view_center = v2(s.dat.rd2()?); + v.snap_base = v2(s.dat.rd2()?); + v.snap_spacing = v2(s.dat.rd2()?); + v.grid_spacing = v2(s.dat.rd2()?); + v.circle_zoom = s.dat.bs()?; + if s.ver >= V::R2007 { + v.grid_major = s.dat.bs()?; + } + frozen = s.dat.bl()?; + v.status = s.dat.bl()?; + v.style_sheet = s.tv()?; + v.render_mode = s.dat.rc()?; + v.ucs_at_origin = s.dat.b()?; + v.ucs_per_viewport = s.dat.b()?; + v.ucs_origin = v3(s.dat.bd3()?); + v.ucs_x = v3(s.dat.bd3()?); + v.ucs_y = v3(s.dat.bd3()?); + v.ucs_elevation = s.dat.bd()?; + v.ucs_ortho_type = s.dat.bs()?; + if s.ver >= V::R2004 { + v.shade_plot_mode = s.dat.bs()?; + } + if s.ver >= V::R2007 { + v.default_lights = s.dat.b()?; + v.lighting_type = s.dat.rc()?; + v.brightness = s.dat.bd()?; + v.contrast = s.dat.bd()?; + v.ambient = s.cmc()?.0; + } + } + Ok((v, frozen)) +} diff --git a/crates/dwg/src/read/header.rs b/crates/dwg/src/read/header.rs new file mode 100644 index 00000000..ca3a6b4c --- /dev/null +++ b/crates/dwg/src/read/header.rs @@ -0,0 +1,699 @@ +//! AcDb:Header — header variables. +//! +//! Written from knowledge of the spec, chapter 9. The variable list is kept +//! as a table so corrections are one-line edits once it is checked against +//! the spec PDF. The parse is self-validating: it only counts as verified +//! when the control-object and space handles it reads resolve to objects +//! of the right types in the object map. + +use super::section::{self, HEADER_END, HEADER_START}; +use super::streams::{Streams, string_stream}; +use super::version::DwgVersion as V; +use super::version::DwgVersion; +use crate::bits::BitReader; +use crate::read::error::{Error, Result}; +use crate::read::geom::{Vec2, Vec3}; +use crate::read::model::{Handle, HeaderVars}; + +#[derive(Clone, Copy, Debug)] +enum K { + B, + Bs, + Bl, + Bll, + Bd, + Rd2, + Bd3, + Rc, + Tv, + Cmc, + /// Handle (handle stream from R2007). + H, + /// HANDSEED: a handle in the main stream. + Seed, + /// Julian day + milliseconds, two BLs. + Time, +} + +#[derive(Clone, Copy, Debug)] +enum W { + All, + R13R14, + R13R2000, + R2000P, + R2004P, + R2007P, + R2010P, + R2013P, + /// CPSNID: only when CEPSNTYPE == 3. + Cpsnid, +} + +fn applies(w: W, v: DwgVersion, cepsntype: i64) -> bool { + match w { + W::All => true, + W::R13R14 => v <= V::R14, + W::R13R2000 => v <= V::R2000, + W::R2000P => v >= V::R2000, + W::R2004P => v >= V::R2004, + W::R2007P => v >= V::R2007, + W::R2010P => v >= V::R2010, + W::R2013P => v >= V::R2013, + W::Cpsnid => v >= V::R2000 && cepsntype == 3, + } +} + +use K::*; +use W::*; + +/// Header variables in file order (spec chapter 9, from knowledge). +#[rustfmt::skip] +static VARS: &[(&str, K, W)] = &[ + ("REQUIREDVERSIONS", Bll, R2013P), + ("UNKNOWN_BD_412148564080", Bd, All), + ("UNKNOWN_BD_1A", Bd, All), + ("UNKNOWN_BD_1B", Bd, All), + ("UNKNOWN_BD_1C", Bd, All), + ("UNKNOWN_TV_1", Tv, All), + ("UNKNOWN_TV_2", Tv, All), + ("UNKNOWN_TV_3", Tv, All), + ("UNKNOWN_TV_4", Tv, All), + ("UNKNOWN_BL_24", Bl, All), + ("UNKNOWN_BL_0", Bl, All), + ("UNKNOWN_BS_0", Bs, R13R14), + ("CURRENT_VIEWPORT_ENTITY_HEADER", H, R13R2000), + ("DIMASO", B, All), + ("DIMSHO", B, All), + ("DIMSAV", B, R13R14), + ("PLINEGEN", B, All), + ("ORTHOMODE", B, All), + ("REGENMODE", B, All), + ("FILLMODE", B, All), + ("QTEXTMODE", B, All), + ("PSLTSCALE", B, All), + ("LIMCHECK", B, All), + ("BLIPMODE", B, R13R14), + ("UNKNOWN_B_R2004", B, R2004P), + ("USRTIMER", B, All), + ("SKPOLY", B, All), + ("ANGDIR", B, All), + ("SPLFRAME", B, All), + ("ATTREQ", B, R13R14), + ("ATTDIA", B, R13R14), + ("MIRRTEXT", B, All), + ("WORLDVIEW", B, All), + ("WIREFRAME", B, R13R14), + ("TILEMODE", B, All), + ("PLIMCHECK", B, All), + ("VISRETAIN", B, All), + ("DELOBJ", B, R13R14), + ("DISPSILH", B, All), + ("PELLIPSE", B, All), + ("PROXYGRAPHICS", Bs, All), + ("DRAGMODE", Bs, R13R14), + ("TREEDEPTH", Bs, All), + ("LUNITS", Bs, All), + ("LUPREC", Bs, All), + ("AUNITS", Bs, All), + ("AUPREC", Bs, All), + ("OSMODE", Bs, R13R14), + ("ATTMODE", Bs, All), + ("COORDS", Bs, R13R14), + ("PDMODE", Bs, All), + ("PICKSTYLE", Bs, R13R14), + ("UNKNOWN_BL_R2004_1", Bl, R2004P), + ("UNKNOWN_BL_R2004_2", Bl, R2004P), + ("UNKNOWN_BL_R2004_3", Bl, R2004P), + ("USERI1", Bs, All), + ("USERI2", Bs, All), + ("USERI3", Bs, All), + ("USERI4", Bs, All), + ("USERI5", Bs, All), + ("SPLINESEGS", Bs, All), + ("SURFU", Bs, All), + ("SURFV", Bs, All), + ("SURFTYPE", Bs, All), + ("SURFTAB1", Bs, All), + ("SURFTAB2", Bs, All), + ("SPLINETYPE", Bs, All), + ("SHADEDGE", Bs, All), + ("SHADEDIF", Bs, All), + ("UNITMODE", Bs, All), + ("MAXACTVP", Bs, All), + ("ISOLINES", Bs, All), + ("CMLJUST", Bs, All), + ("TEXTQLTY", Bs, All), + ("LTSCALE", Bd, All), + ("TEXTSIZE", Bd, All), + ("TRACEWID", Bd, All), + ("SKETCHINC", Bd, All), + ("FILLETRAD", Bd, All), + ("THICKNESS", Bd, All), + ("ANGBASE", Bd, All), + ("PDSIZE", Bd, All), + ("PLINEWID", Bd, All), + ("USERR1", Bd, All), + ("USERR2", Bd, All), + ("USERR3", Bd, All), + ("USERR4", Bd, All), + ("USERR5", Bd, All), + ("CHAMFERA", Bd, All), + ("CHAMFERB", Bd, All), + ("CHAMFERC", Bd, All), + ("CHAMFERD", Bd, All), + ("FACETRES", Bd, All), + ("CMLSCALE", Bd, All), + ("CELTSCALE", Bd, All), + // The spec lists MENUNAME for R13–R2004 only, but AutoCAD 2027's + // AC1024, AC1027 and AC1032 files store it too: without it every + // later string is read one place early (DXFs of the same drawing + // show $MENU ".", an empty $DIMPOST and the GUIDs where they belong). + ("MENUNAME", Tv, All), + ("TDCREATE", Time, All), + ("TDUPDATE", Time, All), + ("UNKNOWN_BL_R2004_4", Bl, R2004P), + ("UNKNOWN_BL_R2004_5", Bl, R2004P), + ("UNKNOWN_BL_R2004_6", Bl, R2004P), + ("TDINDWG", Time, All), + ("TDUSRTIMER", Time, All), + ("CECOLOR", Cmc, All), + ("HANDSEED", Seed, All), + ("CLAYER", H, All), + ("TEXTSTYLE", H, All), + ("CELTYPE", H, All), + ("CMATERIAL", H, R2007P), + ("DIMSTYLE", H, All), + ("CMLSTYLE", H, All), + ("PSVPSCALE", Bd, R2000P), + ("PINSBASE", Bd3, All), + ("PEXTMIN", Bd3, All), + ("PEXTMAX", Bd3, All), + ("PLIMMIN", Rd2, All), + ("PLIMMAX", Rd2, All), + ("PELEVATION", Bd, All), + ("PUCSORG", Bd3, All), + ("PUCSXDIR", Bd3, All), + ("PUCSYDIR", Bd3, All), + ("PUCSNAME", H, All), + ("PUCSORTHOREF", H, R2000P), + ("PUCSORTHOVIEW", Bs, R2000P), + ("PUCSBASE", H, R2000P), + ("PUCSORGTOP", Bd3, R2000P), + ("PUCSORGBOTTOM", Bd3, R2000P), + ("PUCSORGLEFT", Bd3, R2000P), + ("PUCSORGRIGHT", Bd3, R2000P), + ("PUCSORGFRONT", Bd3, R2000P), + ("PUCSORGBACK", Bd3, R2000P), + ("INSBASE", Bd3, All), + ("EXTMIN", Bd3, All), + ("EXTMAX", Bd3, All), + ("LIMMIN", Rd2, All), + ("LIMMAX", Rd2, All), + ("ELEVATION", Bd, All), + ("UCSORG", Bd3, All), + ("UCSXDIR", Bd3, All), + ("UCSYDIR", Bd3, All), + ("UCSNAME", H, All), + ("UCSORTHOREF", H, R2000P), + ("UCSORTHOVIEW", Bs, R2000P), + ("UCSBASE", H, R2000P), + ("UCSORGTOP", Bd3, R2000P), + ("UCSORGBOTTOM", Bd3, R2000P), + ("UCSORGLEFT", Bd3, R2000P), + ("UCSORGRIGHT", Bd3, R2000P), + ("UCSORGFRONT", Bd3, R2000P), + ("UCSORGBACK", Bd3, R2000P), + ("DIMPOST", Tv, R2000P), + ("DIMAPOST", Tv, R2000P), + ("DIMTOL", B, R13R14), + ("DIMLIM", B, R13R14), + ("DIMTIH", B, R13R14), + ("DIMTOH", B, R13R14), + ("DIMSE1", B, R13R14), + ("DIMSE2", B, R13R14), + ("DIMALT", B, R13R14), + ("DIMTOFL", B, R13R14), + ("DIMSAH", B, R13R14), + ("DIMTIX", B, R13R14), + ("DIMSOXD", B, R13R14), + ("DIMALTD", Rc, R13R14), + ("DIMZIN", Rc, R13R14), + ("DIMSD1", B, R13R14), + ("DIMSD2", B, R13R14), + ("DIMTOLJ", Rc, R13R14), + ("DIMJUST", Rc, R13R14), + ("DIMFIT", Rc, R13R14), + ("DIMUPT", B, R13R14), + ("DIMTZIN", Rc, R13R14), + ("DIMALTZ", Rc, R13R14), + ("DIMALTTZ", Rc, R13R14), + ("DIMTAD", Rc, R13R14), + ("DIMUNIT", Bs, R13R14), + ("DIMAUNIT", Bs, R13R14), + ("DIMDEC", Bs, R13R14), + ("DIMTDEC", Bs, R13R14), + ("DIMALTU", Bs, R13R14), + ("DIMALTTD", Bs, R13R14), + ("DIMTXSTY", H, R13R14), + ("DIMSCALE", Bd, All), + ("DIMASZ", Bd, All), + ("DIMEXO", Bd, All), + ("DIMDLI", Bd, All), + ("DIMEXE", Bd, All), + ("DIMRND", Bd, All), + ("DIMDLE", Bd, All), + ("DIMTP", Bd, All), + ("DIMTM", Bd, All), + ("DIMFXL", Bd, R2007P), + ("DIMJOGANG", Bd, R2007P), + ("DIMTFILL", Bs, R2007P), + ("DIMTFILLCLR", Cmc, R2007P), + ("DIMTOL", B, R2000P), + ("DIMLIM", B, R2000P), + ("DIMTIH", B, R2000P), + ("DIMTOH", B, R2000P), + ("DIMSE1", B, R2000P), + ("DIMSE2", B, R2000P), + ("DIMTAD", Bs, R2000P), + ("DIMZIN", Bs, R2000P), + ("DIMAZIN", Bs, R2000P), + ("DIMARCSYM", Bs, R2007P), + ("DIMTXT", Bd, All), + ("DIMCEN", Bd, All), + ("DIMTSZ", Bd, All), + ("DIMALTF", Bd, All), + ("DIMLFAC", Bd, All), + ("DIMTVP", Bd, All), + ("DIMTFAC", Bd, All), + ("DIMGAP", Bd, All), + ("DIMPOST", Tv, R13R14), + ("DIMAPOST", Tv, R13R14), + ("DIMBLK", Tv, R13R14), + ("DIMBLK1", Tv, R13R14), + ("DIMBLK2", Tv, R13R14), + ("DIMALTRND", Bd, R2000P), + ("DIMALT", B, R2000P), + ("DIMALTD", Bs, R2000P), + ("DIMTOFL", B, R2000P), + ("DIMSAH", B, R2000P), + ("DIMTIX", B, R2000P), + ("DIMSOXD", B, R2000P), + ("DIMCLRD", Cmc, All), + ("DIMCLRE", Cmc, All), + ("DIMCLRT", Cmc, All), + ("DIMADEC", Bs, R2000P), + ("DIMDEC", Bs, R2000P), + ("DIMTDEC", Bs, R2000P), + ("DIMALTU", Bs, R2000P), + ("DIMALTTD", Bs, R2000P), + ("DIMAUNIT", Bs, R2000P), + ("DIMFRAC", Bs, R2000P), + ("DIMLUNIT", Bs, R2000P), + ("DIMDSEP", Bs, R2000P), + ("DIMTMOVE", Bs, R2000P), + ("DIMJUST", Bs, R2000P), + ("DIMSD1", B, R2000P), + ("DIMSD2", B, R2000P), + ("DIMTOLJ", Bs, R2000P), + ("DIMTZIN", Bs, R2000P), + ("DIMALTZ", Bs, R2000P), + ("DIMALTTZ", Bs, R2000P), + ("DIMUPT", B, R2000P), + ("DIMATFIT", Bs, R2000P), + ("DIMFXLON", B, R2007P), + ("DIMTXTDIRECTION", B, R2010P), + ("DIMALTMZF", Bd, R2010P), + ("DIMALTMZS", Tv, R2010P), + ("DIMMZF", Bd, R2010P), + ("DIMMZS", Tv, R2010P), + ("DIMTXSTY", H, R2000P), + ("DIMLDRBLK", H, R2000P), + ("DIMBLK", H, R2000P), + ("DIMBLK1", H, R2000P), + ("DIMBLK2", H, R2000P), + ("DIMLTYPE", H, R2007P), + ("DIMLTEX1", H, R2007P), + ("DIMLTEX2", H, R2007P), + ("DIMLWD", Bs, R2000P), + ("DIMLWE", Bs, R2000P), + ("BLOCK_CONTROL", H, All), + ("LAYER_CONTROL", H, All), + ("STYLE_CONTROL", H, All), + ("LTYPE_CONTROL", H, All), + ("VIEW_CONTROL", H, All), + ("UCS_CONTROL", H, All), + ("VPORT_CONTROL", H, All), + ("APPID_CONTROL", H, All), + ("DIMSTYLE_CONTROL", H, All), + ("VX_CONTROL", H, R13R2000), + ("DICTIONARY_ACAD_GROUP", H, All), + ("DICTIONARY_ACAD_MLINESTYLE", H, All), + ("DICTIONARY_NAMED_OBJECTS", H, All), + ("TSTACKALIGN", Bs, R2000P), + ("TSTACKSIZE", Bs, R2000P), + ("HYPERLINKBASE", Tv, R2000P), + ("STYLESHEET", Tv, R2000P), + ("DICTIONARY_LAYOUTS", H, R2000P), + ("DICTIONARY_PLOTSETTINGS", H, R2000P), + ("DICTIONARY_PLOTSTYLES", H, R2000P), + ("DICTIONARY_MATERIALS", H, R2004P), + ("DICTIONARY_COLORS", H, R2004P), + ("DICTIONARY_VISUALSTYLE", H, R2007P), + ("UNKNOWN_H_R2013", H, R2013P), + ("FLAGS", Bl, R2000P), + ("INSUNITS", Bs, R2000P), + ("CEPSNTYPE", Bs, R2000P), + ("CPSNID", H, Cpsnid), + ("FINGERPRINTGUID", Tv, R2000P), + ("VERSIONGUID", Tv, R2000P), + ("SORTENTS", Rc, R2004P), + ("INDEXCTL", Rc, R2004P), + ("HIDETEXT", Rc, R2004P), + ("XCLIPFRAME", Rc, R2004P), + ("DIMASSOC", Rc, R2004P), + ("HALOGAP", Rc, R2004P), + ("OBSCUREDCOLOR", Bs, R2004P), + ("INTERSECTIONCOLOR", Bs, R2004P), + ("OBSCUREDLTYPE", Rc, R2004P), + ("INTERSECTIONDISPLAY", Rc, R2004P), + ("PROJECTNAME", Tv, R2004P), + ("BLOCK_RECORD_PAPER_SPACE", H, All), + ("BLOCK_RECORD_MODEL_SPACE", H, All), + ("LTYPE_BYLAYER", H, All), + ("LTYPE_BYBLOCK", H, All), + ("LTYPE_CONTINUOUS", H, All), + ("CAMERADISPLAY", B, R2007P), + ("UNKNOWN_BL_R2007_1", Bl, R2007P), + ("UNKNOWN_BL_R2007_2", Bl, R2007P), + ("UNKNOWN_BD_R2007_1", Bd, R2007P), + ("STEPSPERSEC", Bd, R2007P), + ("STEPSIZE", Bd, R2007P), + ("3DDWFPREC", Bd, R2007P), + ("LENSLENGTH", Bd, R2007P), + ("CAMERAHEIGHT", Bd, R2007P), + ("SOLIDHIST", Rc, R2007P), + ("SHOWHIST", Rc, R2007P), + ("PSOLWIDTH", Bd, R2007P), + ("PSOLHEIGHT", Bd, R2007P), + ("LOFTANG1", Bd, R2007P), + ("LOFTANG2", Bd, R2007P), + ("LOFTMAG1", Bd, R2007P), + ("LOFTMAG2", Bd, R2007P), + ("LOFTPARAM", Bs, R2007P), + ("LOFTNORMALS", Rc, R2007P), + ("LATITUDE", Bd, R2007P), + ("LONGITUDE", Bd, R2007P), + ("NORTHDIRECTION", Bd, R2007P), + ("TIMEZONE", Bl, R2007P), + ("LIGHTGLYPHDISPLAY", Rc, R2007P), + ("TILEMODELIGHTSYNCH", Rc, R2007P), + ("DWFFRAME", Rc, R2007P), + ("DGNFRAME", Rc, R2007P), + ("UNKNOWN_B_R2007", B, R2007P), + ("INTERFERECOLOR", Cmc, R2007P), + ("INTERFEREOBJVS", H, R2007P), + ("INTERFEREVPVS", H, R2007P), + ("DRAGVS", H, R2007P), + ("CSHADOW", Rc, R2007P), + ("UNKNOWN_BD_R2007_2", Bd, R2007P), +]; + +#[derive(Debug, Clone, PartialEq)] +enum Val { + Bool(bool), + Int(i64), + Real(f64), + P2(Vec2), + P3(Vec3), + Text(String), + Handle(u64), + Color(crate::read::model::Color), +} + +impl Val { + fn display(&self) -> String { + match self { + Val::Bool(b) => b.to_string(), + Val::Int(i) => i.to_string(), + Val::Real(f) => format!("{f}"), + Val::P2(p) => format!("({}, {})", p.x, p.y), + Val::P3(p) => format!("({}, {}, {})", p.x, p.y, p.z), + Val::Text(t) => format!("{t:?}"), + Val::Handle(h) => format!("#{h:X}"), + Val::Color(c) => color_text(*c), + } + } +} + +fn read_value(s: &mut Streams, k: K) -> Result { + Ok(match k { + K::B => Val::Bool(s.dat.b()?), + K::Bs => Val::Int(s.dat.bs()? as i16 as i64), + K::Bl => Val::Int(s.dat.bl()? as i32 as i64), + K::Bll => Val::Int(s.dat.bll()? as i64), + K::Bd => Val::Real(s.dat.bd()?), + K::Rd2 => Val::P2(Vec2::from_array(s.dat.rd2()?)), + K::Bd3 => Val::P3(Vec3::from_array(s.dat.bd3()?)), + K::Rc => Val::Int(s.dat.rc()? as i64), + K::Tv => Val::Text(s.tv()?), + K::Cmc => { + let (color, index) = s.cmc()?; + if s.ver < V::R2004 { + Val::Int(index as i64) + } else { + // From R2004 the colour is in the method word; the index + // field alone reads 0 for every colour. + Val::Color(color) + } + } + K::H => Val::Handle(s.h()?.value), + K::Seed => Val::Handle(s.dat.handle()?.value), + K::Time => { + let day = s.dat.bl()? as i64; + let ms = s.dat.bl()? as i64; + Val::Real(day as f64 + ms as f64 / 86_400_000.0) + } + }) +} + +/// A CmColor as the header's display text keeps it: `BYLAYER`, +/// `BYBLOCK`, an ACI number, `RGB(r,g,b)` or `NONE`. Read back by +/// [`crate::read::hvars`]. +pub(crate) fn color_text(c: crate::read::model::Color) -> String { + use crate::read::model::Color; + match c { + Color::ByLayer => "BYLAYER".into(), + Color::ByBlock => "BYBLOCK".into(), + Color::Index(i) => i.to_string(), + Color::Rgb(r, g, b) => format!("RGB({r},{g},{b})"), + Color::None => "NONE".into(), + } +} + +/// The variable list, for writers: name, kind and versions. +pub(crate) fn vars() -> impl Iterator bool)> { + VARS.iter().map(|&(name, k, w)| { + let applies_fn: fn(DwgVersion, i64) -> bool = match w { + W::All => |_, _| true, + W::R13R14 => |v, _| v <= V::R14, + W::R13R2000 => |v, _| v <= V::R2000, + W::R2000P => |v, _| v >= V::R2000, + W::R2004P => |v, _| v >= V::R2004, + W::R2007P => |v, _| v >= V::R2007, + W::R2010P => |v, _| v >= V::R2010, + W::R2013P => |v, _| v >= V::R2013, + W::Cpsnid => |v, c| v >= V::R2000 && c == 3, + }; + let kind = match k { + K::B => VarKind::B, + K::Bs => VarKind::Bs, + K::Bl => VarKind::Bl, + K::Bll => VarKind::Bll, + K::Bd => VarKind::Bd, + K::Rd2 => VarKind::Rd2, + K::Bd3 => VarKind::Bd3, + K::Rc => VarKind::Rc, + K::Tv => VarKind::Tv, + K::Cmc => VarKind::Cmc, + K::H => VarKind::H, + K::Seed => VarKind::Seed, + K::Time => VarKind::Time, + }; + (name, kind, applies_fn) + }) +} + +/// How a header variable is stored (see the spec, chapter 9). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum VarKind { + B, + Bs, + Bl, + Bll, + Bd, + Rd2, + Bd3, + Rc, + Tv, + Cmc, + H, + Seed, + Time, +} + +/// Read all variables in order. +fn read_all(mut s: Streams) -> Result<(Vec<(&'static str, Val)>, usize)> { + let mut out = Vec::with_capacity(VARS.len()); + let mut cepsntype = 0i64; + for &(name, k, w) in VARS { + if !applies(w, s.ver, cepsntype) { + continue; + } + let v = read_value(&mut s, k).map_err(|e| e.context(format!("header variable {name}")))?; + if name == "CEPSNTYPE" + && let Val::Int(i) = v + { + cepsntype = i; + } + out.push((name, v)); + } + Ok((out, s.dat.position())) +} + +/// Object types the header's control handles must point at. +const EXPECTED_TYPES: &[(&str, u16)] = &[ + ("BLOCK_CONTROL", 0x30), + ("LAYER_CONTROL", 0x32), + ("STYLE_CONTROL", 0x34), + ("LTYPE_CONTROL", 0x38), + ("VIEW_CONTROL", 0x3C), + ("UCS_CONTROL", 0x3E), + ("VPORT_CONTROL", 0x40), + ("APPID_CONTROL", 0x42), + ("DIMSTYLE_CONTROL", 0x44), + ("BLOCK_RECORD_PAPER_SPACE", 0x31), + ("BLOCK_RECORD_MODEL_SPACE", 0x31), +]; + +fn validate(vals: &[(&'static str, Val)], type_of: &dyn Fn(u64) -> Option) -> std::result::Result<(), String> { + for &(name, expected) in EXPECTED_TYPES { + let h = vals.iter().find_map(|(n, v)| match v { + Val::Handle(h) if *n == name => Some(*h), + _ => None, + }); + match h { + None => return Err(format!("{name} not read")), + Some(h) => match type_of(h) { + Some(t) if t == expected => {} + Some(t) => return Err(format!("{name} #{h:X} is type {t:#X}, expected {expected:#X}")), + None => return Err(format!("{name} #{h:X} not in object map")), + }, + } + } + Ok(()) +} + +fn to_header(vals: Vec<(&'static str, Val)>, verified: bool, note: String) -> HeaderVars { + let mut hv = HeaderVars { verified, note, ..Default::default() }; + for (name, v) in &vals { + match (*name, v) { + ("INSUNITS", Val::Int(i)) => hv.insunits = u16::try_from(*i).ok(), + ("EXTMIN", Val::P3(p)) => hv.extmin = Some(*p), + ("EXTMAX", Val::P3(p)) => hv.extmax = Some(*p), + ("LIMMIN", Val::P2(p)) => hv.limmin = Some(*p), + ("LIMMAX", Val::P2(p)) => hv.limmax = Some(*p), + ("INSBASE", Val::P3(p)) => hv.insbase = Some(*p), + ("LTSCALE", Val::Real(f)) => hv.ltscale = Some(*f), + ("TEXTSIZE", Val::Real(f)) => hv.textsize = Some(*f), + ("CELTSCALE", Val::Real(f)) => hv.celtscale = Some(*f), + ("LUNITS", Val::Int(i)) => hv.lunits = u16::try_from(*i).ok(), + ("LUPREC", Val::Int(i)) => hv.luprec = u16::try_from(*i).ok(), + ("AUNITS", Val::Int(i)) => hv.aunits = u16::try_from(*i).ok(), + ("AUPREC", Val::Int(i)) => hv.auprec = u16::try_from(*i).ok(), + ("ANGBASE", Val::Real(f)) => hv.angbase = Some(*f), + ("ANGDIR", Val::Bool(b)) => hv.angdir = Some(*b as u16), + ("TEXTSTYLE", Val::Handle(h)) => hv.textstyle = Handle(*h), + ("CELTYPE", Val::Handle(h)) => hv.celtype = Handle(*h), + ("DIMSTYLE", Val::Handle(h)) => hv.dimstyle = Handle(*h), + ("DIMSTYLE_CONTROL", Val::Handle(h)) => hv.dimstyle_control = Handle(*h), + ("HANDSEED", Val::Handle(h)) => hv.handseed = Some(*h), + ("CLAYER", Val::Handle(h)) => hv.clayer = Handle(*h), + ("BLOCK_CONTROL", Val::Handle(h)) => hv.block_control = Handle(*h), + ("LAYER_CONTROL", Val::Handle(h)) => hv.layer_control = Handle(*h), + ("STYLE_CONTROL", Val::Handle(h)) => hv.style_control = Handle(*h), + ("LTYPE_CONTROL", Val::Handle(h)) => hv.linetype_control = Handle(*h), + ("BLOCK_RECORD_MODEL_SPACE", Val::Handle(h)) => hv.model_space = Handle(*h), + ("BLOCK_RECORD_PAPER_SPACE", Val::Handle(h)) => hv.paper_space = Handle(*h), + ("DICTIONARY_NAMED_OBJECTS", Val::Handle(h)) => hv.named_objects_dict = Handle(*h), + _ => {} + } + } + hv.raw = vals.iter().map(|(n, v)| (n.to_string(), v.display())).collect(); + hv +} + +/// Parse the header section. Never fails outright: an unreadable header +/// yields `HeaderVars { verified: false, note }`. +pub(crate) fn parse(data: &[u8], ver: DwgVersion, maintenance: u8, codepage: u16, type_of: &dyn Fn(u64) -> Option) -> HeaderVars { + match parse_inner(data, ver, maintenance, codepage, type_of) { + Ok(h) => h, + Err(e) => HeaderVars { verified: false, note: e.to_string(), ..Default::default() }, + } +} + +fn parse_inner(data: &[u8], ver: DwgVersion, maintenance: u8, codepage: u16, type_of: &dyn Fn(u64) -> Option) -> Result { + let wrapped = section::unwrap(data, &HEADER_START, &HEADER_END, ver, maintenance)?; + let body = wrapped.body; + if ver < V::R2007 { + let s = Streams { ver, codepage, dat: BitReader::new(body), strs: None, hdl: None }; + let (vals, _end) = read_all(s)?; + return Ok(match validate(&vals, type_of) { + Ok(()) => to_header(vals, true, String::new()), + Err(why) => to_header(vals, false, format!("header not verified: {why}")), + }); + } + // R2007+: main, string and handle streams. The layout of the leading + // bit-size field is not confirmed; try the plausible origins. + if body.len() < 4 { + return Err(Error::truncated("header body too short")); + } + let bitsize = u32::from_le_bytes([body[0], body[1], body[2], body[3]]) as usize; + let mut notes = Vec::new(); + let mut best: Option> = None; + for (label, main_start, endbit) in + [("bitsize from body start", 32usize, bitsize), ("bitsize after field", 32usize, bitsize + 32), ("no bitsize field", 0usize, body.len() * 8)] + { + if endbit == 0 || endbit > body.len() * 8 || main_start >= endbit { + notes.push(format!("{label}: out of range")); + continue; + } + let strs = match string_stream(body, endbit) { + Ok(Some((sr, _))) => Some(sr), + Ok(None) => None, + Err(e) => { + notes.push(format!("{label}: {e}")); + continue; + } + }; + let hdl = BitReader::with_bounds(body, endbit, body.len() * 8); + let dat = BitReader::with_bounds(body, main_start, endbit); + let s = Streams { ver, codepage, dat, strs, hdl: Some(hdl) }; + match read_all(s) { + Ok((vals, _)) => match validate(&vals, type_of) { + Ok(()) => return Ok(to_header(vals, true, format!("layout: {label}"))), + Err(why) => { + notes.push(format!("{label}: {why}")); + if best.is_none() { + best = Some(vals); + } + } + }, + Err(e) => notes.push(format!("{label}: {e}")), + } + } + let note = format!("header not verified ({})", notes.join("; ")); + Ok(match best { + Some(vals) => to_header(vals, false, note), + None => HeaderVars { verified: false, note, ..Default::default() }, + }) +} diff --git a/crates/dwg/src/read/hvars.rs b/crates/dwg/src/read/hvars.rs new file mode 100644 index 00000000..f62c10ff --- /dev/null +++ b/crates/dwg/src/read/hvars.rs @@ -0,0 +1,240 @@ +//! Typed access to a drawing's header variables, for the writers. +//! +//! The reader keeps every variable it read as display text, in file order +//! (`HeaderVars::raw`), and the variables the core uses as typed fields. +//! A writer asks here by DWG variable name: the typed field wins when the +//! drawing has it (an edit may have changed it), then the stored text, +//! then the caller's default. Drawings started in this program have no +//! stored text, so every lookup has a default. + +use super::version::DwgVersion; +use crate::read::geom::{Vec2, Vec3}; +use crate::read::model::{Color, Drawing, Handle}; +use std::collections::HashMap; + +/// A drawing's header variables by DWG name (see the module docs). +pub struct Hv<'a> { + d: &'a Drawing, + raw: HashMap<&'a str, &'a str>, +} + +/// Undo the `{:?}` quoting the reader stores strings with. +fn unquote(s: &str) -> Option { + let inner = s.strip_prefix('"')?.strip_suffix('"')?; + let mut out = String::with_capacity(inner.len()); + let mut it = inner.chars(); + while let Some(c) = it.next() { + if c != '\\' { + out.push(c); + continue; + } + match it.next()? { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + '0' => out.push('\0'), + '\\' => out.push('\\'), + '"' => out.push('"'), + '\'' => out.push('\''), + 'u' => { + if it.next()? != '{' { + return None; + } + let mut hex = String::new(); + for c in it.by_ref() { + if c == '}' { + break; + } + hex.push(c); + } + out.push(char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?); + } + _ => return None, + } + } + Some(out) +} + +fn floats(s: &str) -> Option> { + let inner = s.trim().strip_prefix('(')?.strip_suffix(')')?; + inner.split(',').map(|p| p.trim().parse::().ok()).collect() +} + +impl<'a> Hv<'a> { + pub fn new(d: &'a Drawing) -> Self { + let mut raw: HashMap<&'a str, &'a str> = d.header.raw.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + // Readers before 0.2.1 skipped MENUNAME in R2007+ files, so every + // string variable after the four unknown ones carries the value of + // the one before it, and the last string was not read. + if d.version >= DwgVersion::R2007 && !raw.contains_key("MENUNAME") && raw.contains_key("DIMPOST") { + let names: Vec<&'static str> = super::header::vars() + .filter(|(n, k, applies)| { + *k == super::header::VarKind::Tv && applies(d.version, 0) && !n.starts_with("UNKNOWN_TV") && *n != "MENUNAME" + }) + .map(|(n, _, _)| n) + .collect(); + let values: Vec<&'a str> = names.iter().map(|n| raw.get(n).copied().unwrap_or("\"\"")).collect(); + raw.insert("MENUNAME", values[0]); + for (i, n) in names.iter().enumerate() { + raw.insert(n, values.get(i + 1).copied().unwrap_or("\"\"")); + } + } + Hv { d, raw } + } + + fn raw(&self, name: &str) -> Option<&str> { + self.raw.get(name).copied() + } + + pub fn real(&self, name: &str, default: f64) -> f64 { + let h = &self.d.header; + let typed = match name { + "LTSCALE" => h.ltscale, + "TEXTSIZE" => h.textsize, + "CELTSCALE" => h.celtscale, + "ANGBASE" => h.angbase, + _ => None, + }; + typed.or_else(|| self.raw(name)?.parse().ok()).unwrap_or(default) + } + + pub fn int(&self, name: &str, default: i64) -> i64 { + let h = &self.d.header; + let typed = match name { + "INSUNITS" => h.insunits, + "MEASUREMENT" => h.measurement, + "LUNITS" => h.lunits, + "LUPREC" => h.luprec, + "AUNITS" => h.aunits, + "AUPREC" => h.auprec, + _ => None, + }; + if let Some(v) = typed { + return v as i64; + } + match self.raw(name) { + Some("true") => 1, + Some("false") => 0, + Some(t) => t.parse().unwrap_or(default), + None => default, + } + } + + pub fn bool(&self, name: &str, default: bool) -> bool { + if name == "ANGDIR" + && let Some(v) = self.d.header.angdir + { + return v != 0; + } + match self.raw(name) { + Some("true") => true, + Some("false") => false, + Some(t) => t.parse::().map(|v| v != 0).unwrap_or(default), + None => default, + } + } + + pub fn p2(&self, name: &str, default: Vec2) -> Vec2 { + let h = &self.d.header; + let typed = match name { + "LIMMIN" => h.limmin, + "LIMMAX" => h.limmax, + _ => None, + }; + typed + .or_else(|| { + let v = floats(self.raw(name)?)?; + (v.len() == 2).then(|| Vec2::new(v[0], v[1])) + }) + .unwrap_or(default) + } + + pub fn p3(&self, name: &str, default: Vec3) -> Vec3 { + let h = &self.d.header; + let typed = match name { + "EXTMIN" => h.extmin, + "EXTMAX" => h.extmax, + "INSBASE" => h.insbase, + _ => None, + }; + typed + .or_else(|| { + let v = floats(self.raw(name)?)?; + (v.len() == 3).then(|| Vec3::new(v[0], v[1], v[2])) + }) + .unwrap_or(default) + } + + pub fn text(&self, name: &str, default: &str) -> String { + if name == "HYPERLINKBASE" && !self.d.header.properties.hyperlink_base.is_empty() { + return self.d.header.properties.hyperlink_base.clone(); + } + self.raw(name).and_then(unquote).unwrap_or_else(|| default.to_string()) + } + + /// A handle variable; NULL when unknown. + pub fn handle(&self, name: &str) -> Handle { + let h = &self.d.header; + let typed = match name { + "CLAYER" => h.clayer, + "TEXTSTYLE" => h.textstyle, + "CELTYPE" => h.celtype, + "DIMSTYLE" => h.dimstyle, + "BLOCK_CONTROL" => h.block_control, + "LAYER_CONTROL" => h.layer_control, + "STYLE_CONTROL" => h.style_control, + "LTYPE_CONTROL" => h.linetype_control, + "DIMSTYLE_CONTROL" => h.dimstyle_control, + "BLOCK_RECORD_MODEL_SPACE" => self.d.model_space(), + "BLOCK_RECORD_PAPER_SPACE" => self.d.paper_space(), + "DICTIONARY_NAMED_OBJECTS" => h.named_objects_dict, + _ => Handle::NULL, + }; + if !typed.is_null() { + return typed; + } + self.raw(name).and_then(|t| t.strip_prefix('#')).and_then(|t| u64::from_str_radix(t, 16).ok()).map(Handle).unwrap_or(Handle::NULL) + } + + /// A CmColor variable. Files the reader saved before it kept these + /// whole stored only the index field, which reads 0 for every colour + /// from R2004 on; such a value is unknown and gives `default`. + pub fn color(&self, name: &str, default: Color) -> Color { + match self.raw(name) { + Some("BYLAYER") => Color::ByLayer, + Some("BYBLOCK") => Color::ByBlock, + Some("NONE") => Color::None, + Some(t) if t.starts_with("RGB(") => { + let v: Vec = t[4..t.len() - 1].split(',').filter_map(|p| p.trim().parse().ok()).collect(); + if v.len() == 3 { Color::Rgb(v[0], v[1], v[2]) } else { default } + } + Some(t) => match t.parse::() { + Ok(0) if self.d.version >= DwgVersion::R2004 => default, + Ok(i) => Color::from_aci(i), + Err(_) => default, + }, + None => default, + } + } + + /// A date: Julian day plus fraction. + pub fn time(&self, name: &str, default: f64) -> f64 { + self.raw(name).and_then(|t| t.parse().ok()).unwrap_or(default) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Header variables read from a drawing made from a template are tried + // in cad-core (tests/dwg_header_vars.rs), which has the templates. + + #[test] + fn stored_text_reads_back() { + assert_eq!(unquote("\"m\"").as_deref(), Some("m")); + assert_eq!(unquote("\"\"").as_deref(), Some("")); + assert_eq!(unquote(r#""a\"b\\c\u{b0}""#).as_deref(), Some("a\"b\\c°")); + assert_eq!(floats("(1, -2.5, 1e20)"), Some(vec![1.0, -2.5, 1e20])); + } +} diff --git a/crates/dwg/src/read/mod.rs b/crates/dwg/src/read/mod.rs new file mode 100644 index 00000000..24e369f7 --- /dev/null +++ b/crates/dwg/src/read/mod.rs @@ -0,0 +1,327 @@ +//! BlackCAD's DWG reader and writer. +//! +//! Reading: [`read_bytes`] turns a DWG file of any version from R13 to +//! AutoCAD 2018 and later (AC1012–AC1032) into a [`Drawing`], except +//! AutoCAD 2007–2009 (AC1021), whose container is not implemented yet. +//! Writing: [`write::to_bytes`] writes a drawing as an AutoCAD 2018 +//! (AC1032) file. +//! +//! The drawing is `cad-model`'s database, re-exported here as +//! [`cad_model`]. +//! +//! Reading, step by step: detect the version → extract sections from the +//! container +//! (R13–R15 flat, or R2004-family paged) → classes → object map → decode +//! every object → header variables (validated against the objects). +//! +//! Each object is decoded in isolation: a failure is recorded on that +//! object and the rest of the drawing still loads. + +// A file is only a claim: no input reaches a panic. Tests may unwrap. +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +pub use crate::records::version; +pub(crate) use crate::records::{error, geom, model, text}; + +pub mod nongraphic; + +pub(crate) mod classes; +pub(crate) mod container; +pub(crate) mod eed; +pub(crate) mod entities; +pub(crate) mod header; +pub mod hvars; +pub(crate) mod object; +pub(crate) mod objmap; +#[cfg(test)] +mod probe; +pub(crate) mod r2000; +pub(crate) mod r2004; +pub(crate) mod section; +pub(crate) mod streams; +pub(crate) mod styles; +pub(crate) mod tables; + +pub use version::DwgVersion; + +/// The name of one of DWG's fixed object types (`LINE` for 0x13), or `None` +/// for class-defined and unknown type numbers. +pub fn fixed_type_name(code: u16) -> Option<&'static str> { + object::fixed_type(code).map(|(name, _)| name) +} + +use crate::read::error::{Error, ErrorKind, Result}; +use crate::read::model::{Diagnostic, Drawing, DrawingIndex, EntityCommon, Handle, HeaderVars, Object, ObjectKind, Properties, Severity}; +use std::collections::BTreeMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::Path; + +/// Read a DWG file from disk. +pub fn read_file(path: impl AsRef) -> Result { + let bytes = std::fs::read(path.as_ref()).map_err(|e| Error::new(ErrorKind::Io, format!("{}: {e}", path.as_ref().display())))?; + read_bytes(&bytes) +} + +/// Identify a DWG file's version from its first six bytes. +pub fn sniff_version(bytes: &[u8]) -> Option { + DwgVersion::from_magic(bytes) +} + +/// Read a DWG file from memory. +pub fn read_bytes(bytes: &[u8]) -> Result { + let ver = DwgVersion::from_magic(bytes).ok_or_else(|| { + let tag: String = bytes.iter().take(6).map(|&b| if b.is_ascii_graphic() { b as char } else { '?' }).collect(); + Error::new(ErrorKind::NotDwg, format!("unrecognised version tag {tag:?}")) + })?; + let container = match ver { + DwgVersion::R13 | DwgVersion::R14 | DwgVersion::R2000 => r2000::read(bytes, ver)?, + DwgVersion::R2004 | DwgVersion::R2010 | DwgVersion::R2013 | DwgVersion::R2018 => r2004::read(bytes, ver)?, + DwgVersion::R2007 => { + return Err(Error::new( + ErrorKind::UnsupportedVersion, + "AC1021 (AutoCAD 2007–2009) uses its own container, which is not implemented yet; \ + save the drawing as 2004 or 2010-and-later format", + )); + } + }; + let mut diagnostics = container.notes; + let maintenance = container.maintenance; + let codepage = container.codepage; + let warn = |d: &mut Vec, sev: Severity, msg: String| d.push(Diagnostic { severity: sev, message: msg }); + + // Classes. + let classes = match &container.classes { + Some(data) => match classes::parse(data, ver, maintenance, codepage) { + Ok((list, notes)) => { + for n in notes { + warn(&mut diagnostics, Severity::Info, n); + } + list + } + Err(e) => { + warn(&mut diagnostics, Severity::Warning, format!("classes: {e}")); + Vec::new() + } + }, + None => { + warn(&mut diagnostics, Severity::Warning, "no classes section".into()); + Vec::new() + } + }; + + // Object map, choosing between the two readings of the delta reset. + let entries = choose_object_map(&container.handles, ver, &container.objects, &mut diagnostics)?; + + // Objects. + let ctx = object::DecodeCtx { ver, codepage, classes: &classes }; + let mut objects: BTreeMap = BTreeMap::new(); + let mut out_of_range = 0usize; + let mut mismatched = 0usize; + for e in &entries { + if e.handle == 0 { + continue; + } + if e.location < 0 || e.location as usize >= container.objects.len() { + out_of_range += 1; + continue; + } + let off = e.location as usize; + let decoded = catch_unwind(AssertUnwindSafe(|| object::decode(&ctx, &container.objects, off))); + let obj = match decoded { + Ok(Ok(o)) => { + if o.handle.0 != e.handle { + mismatched += 1; + } + o + } + Ok(Err(err)) => failed(&ctx, &container.objects, e.handle, off, err.to_string()), + Err(_) => failed(&ctx, &container.objects, e.handle, off, "decoder panicked (bug)".into()), + }; + let mut obj = obj; + // Keep the record's bytes when the model cannot hold all of it: + // undecoded objects, and table records kept by name only (VPORT, + // DIMSTYLE, VIEW, UCS, APPID), so the native file loses nothing + // a DWG writer needs. + if !obj.kind.is_decoded() || matches!(obj.kind, ObjectKind::NamedRecord(_)) { + obj.raw = object::raw(ver, &container.objects, off).ok(); + } + objects.insert(Handle(e.handle), obj); + } + if out_of_range > 0 { + warn(&mut diagnostics, Severity::Warning, format!("{out_of_range} object map entries point outside the object data")); + } + if mismatched > 0 { + warn(&mut diagnostics, Severity::Warning, format!("{mismatched} objects carry a handle different from their map entry")); + } + eed::resolve(&mut objects, &mut diagnostics); + let failed_count = objects.values().filter(|o| matches!(o.kind, ObjectKind::Failed(_))).count(); + if failed_count > 0 { + warn(&mut diagnostics, Severity::Warning, format!("{failed_count} of {} objects failed to decode", objects.len())); + } + + // Header variables, validated against the decoded objects. + let type_of = |h: u64| objects.get(&Handle(h)).map(|o| o.type_code); + let header = match &container.header { + Some(data) => header::parse(data, ver, maintenance, codepage, &type_of), + None => HeaderVars { note: "no header section".into(), ..Default::default() }, + }; + if !header.verified { + warn(&mut diagnostics, Severity::Info, format!("header: {}", header.note)); + } + + let mut header = header; + if let Some((_, s)) = container.others.iter().find(|(n, _)| n == "AcDb:SummaryInfo") + && let Some(p) = summary_info(s, ver >= DwgVersion::R2007) + { + header.properties = p; + } + // MEASUREMENT (imperial or metric) is not a header variable in DWG + // but the last field of AcDb:Template. + if let Some((_, s)) = container.others.iter().find(|(n, _)| n == "AcDb:Template") + && let Some(m) = template_measurement(s) + { + header.measurement = Some(m); + } + + let mut drawing = Drawing { + version: ver, + maintenance_version: maintenance, + codepage, + header, + classes, + objects: objects.into(), + sections: container.sections, + diagnostics, + index: DrawingIndex::default(), + }; + nongraphic::promote(&mut drawing); + drawing.rebuild_index(); + drawing.number_viewports(); + Ok(drawing) +} + +/// MEASUREMENT from AcDb:Template (spec chapter 22): the section's last +/// short, after the template description, which AutoCAD leaves empty (it +/// writes `01 00 00 00` before it). 0 is imperial, 1 metric; anything else +/// is not believed. R13–R15 files have no such section and keep the +/// default. +fn template_measurement(s: &[u8]) -> Option { + let at = s.len().checked_sub(2)?; + let m = u16::from_le_bytes([*s.get(at)?, *s.get(at + 1)?]); + (m <= 1).then_some(m) +} + +/// One string of AcDb:SummaryInfo: RS length counting the terminating 0, +/// then UTF-16 units (R2007+) or 8-bit characters. +fn summary_text(s: &[u8], p: &mut usize, wide: bool) -> Option { + let n = u16::from_le_bytes(s.get(*p..*p + 2)?.try_into().ok()?) as usize; + *p += 2; + let t = if wide { + let b = s.get(*p..*p + 2 * n)?; + *p += 2 * n; + let units: Vec = b.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&units) + } else { + let b = s.get(*p..*p + n)?; + *p += n; + b.iter().map(|&c| c as char).collect() + }; + Some(t.trim_end_matches('\0').to_string()) +} + +/// AcDb:SummaryInfo (spec chapter 13): eight strings, three dates the +/// header also holds, then custom properties as name and value pairs. +/// `None` if it does not parse. +fn summary_info(s: &[u8], wide: bool) -> Option { + let mut p = 0usize; + let mut f = Vec::with_capacity(8); + for _ in 0..8 { + f.push(summary_text(s, &mut p, wide)?); + } + let mut props = Properties { + title: f[0].clone(), + subject: f[1].clone(), + author: f[2].clone(), + keywords: f[3].clone(), + comments: f[4].clone(), + last_saved_by: f[5].clone(), + revision: f[6].clone(), + hyperlink_base: f[7].clone(), + ..Default::default() + }; + p += 24; + let count = u16::from_le_bytes(s.get(p..p + 2)?.try_into().ok()?) as usize; + p += 2; + for _ in 0..count.min(1024) { + let k = summary_text(s, &mut p, wide)?; + let v = summary_text(s, &mut p, wide)?; + props.custom.push((k, v)); + } + Some(props) +} + +fn failed(ctx: &object::DecodeCtx, data: &[u8], handle: u64, offset: usize, message: String) -> Object { + let (type_code, type_name, is_entity) = match object::peek(ctx.ver, data, offset) { + Ok((_, code)) => { + let (name, ent) = object::classify(code, ctx.classes); + (code, name, ent) + } + Err(_) => (0, "?".to_string(), false), + }; + Object { + handle: Handle(handle), + type_code, + type_name, + owner: Handle::NULL, + reactors: Vec::new(), + xdictionary: Handle::NULL, + entity: if is_entity { Some(EntityCommon::default()) } else { None }, + kind: ObjectKind::Failed(message), + offset, + size: 0, + note: None, + raw: None, + xdata: Vec::new(), + unknown_tags: Vec::new(), + } +} + +/// Parse the object map both ways and keep the reading whose entries agree +/// with the handles stored in the objects themselves. +fn choose_object_map(handles: &[u8], ver: DwgVersion, objects: &[u8], diagnostics: &mut Vec) -> Result> { + let score = |entries: &[objmap::MapEntry]| -> (usize, usize) { + if entries.is_empty() { + return (0, 0); + } + let step = (entries.len() / 64).max(1); + let mut hit = 0; + let mut tried = 0; + for e in entries.iter().step_by(step) { + tried += 1; + if e.location >= 0 + && let Ok((h, _)) = object::peek(ver, objects, e.location as usize) + && h == e.handle + { + hit += 1; + } + } + (hit, tried) + }; + let reset = objmap::parse(handles, true); + let running = objmap::parse(handles, false); + match (reset, running) { + (Ok(a), Ok(b)) => { + let (sa, ta) = score(&a); + let (sb, tb) = score(&b); + let (chosen, label, s, t) = if sb > sa { (b, "running", sb, tb) } else { (a, "per-block reset", sa, ta) }; + let sev = if t > 0 && s * 10 >= t * 9 { Severity::Info } else { Severity::Warning }; + diagnostics.push(Diagnostic { + severity: sev, + message: format!("object map: {} entries, {label} reading, {s}/{t} sampled handles match", chosen.len()), + }); + Ok(chosen) + } + (Ok(a), Err(_)) | (Err(_), Ok(a)) => Ok(a), + (Err(e), Err(_)) => Err(e.context("object map")), + } +} diff --git a/crates/dwg/src/read/nongraphic.rs b/crates/dwg/src/read/nongraphic.rs new file mode 100644 index 00000000..29f4ed4d --- /dev/null +++ b/crates/dwg/src/read/nongraphic.rs @@ -0,0 +1,869 @@ +//! Non-graphical objects the drawing model keeps only as their original +//! DWG records (`Object::raw`): dictionaries, extension records, layouts, +//! scales and the like. The DXF writer turns them into DXF records, and +//! the DWG writer looks up the drawing's defaults (plot style, material) +//! through them. +//! +//! Layouts from the ODA specification, chapter 20, checked against the +//! objects of an AC1032 file written by AutoCAD 2027 and the DXF AutoCAD +//! saved of the same drawing (corpus/mosaiciron-mi201): +//! DICTIONARY §20.4.44, DICTIONARYWDFLT §20.4.45, MLINESTYLE §20.4.73, +//! DICTIONARYVAR §20.4.74, LAYOUT §20.4.84, SCALE §20.4.92, XRECORD +//! §20.4.104. ACDBPLACEHOLDER stores nothing of its own. + +use super::object::{self, DecodeCtx}; +use super::streams::Streams; +use super::version::DwgVersion as V; +use crate::read::error::{Error, Result}; +use crate::read::geom::{Vec2, Vec3}; +use crate::read::model::{ClassDef, Color, Drawing, Groups, Handle, Object, ObjectKind}; +pub use crate::read::model::{ + Dictionary, DimStyleRecord, DimVars, Layout, MLineElement, MLineStyle, NonGraphic, PlotSettings, Scale, Vport, XRecord, XrValue, +}; + +/// Decode an object kept as its DWG record, when its type is one of the +/// above. `None` for other types; an error when the record does not fit +/// the layout. +pub fn decode(o: &Object, classes: &[ClassDef], codepage: u16) -> Option> { + if let ObjectKind::NonGraphic(n) = &o.kind { + return Some(Ok(n.clone())); + } + let raw = o.raw.as_ref()?; + let kind = match o.type_name.as_str() { + "DICTIONARY" | "ACDBDICTIONARYWDFLT" => 0, + "XRECORD" => 1, + "ACDBPLACEHOLDER" => 2, + "DICTIONARYVAR" => 3, + "SCALE" => 4, + "LAYOUT" => 5, + "MLINESTYLE" => 6, + _ => return None, + }; + let buf = object::raw_buffer(raw); + let ctx = DecodeCtx { ver: raw.version, codepage, classes }; + Some((|| { + let mut op = object::open(&ctx, &buf, 0)?; + let wdflt = op.type_name == "ACDBDICTIONARYWDFLT"; + // Type data first, then the handles: common ones, then the type's. + let partial = match kind { + 0 => Partial::Dict(dictionary_data(&mut op.s)?), + 1 => Partial::XRec(xrecord_data(&mut op.s)?), + 2 => Partial::Done(NonGraphic::Placeholder), + 3 => { + let schema = op.s.dat.rc()?; + let value = op.s.tv()?; + Partial::Done(NonGraphic::DictionaryVar { schema, value }) + } + 4 => Partial::Done(NonGraphic::Scale(Scale { + flag: op.s.dat.bs()?, + name: op.s.tv()?, + paper_units: op.s.dat.bd()?, + drawing_units: op.s.dat.bd()?, + unit_scale: op.s.dat.b()?, + })), + 5 => Partial::Layout(Box::new(layout_data(&mut op.s)?)), + _ => Partial::MLine(mlinestyle_data(&mut op.s)?), + }; + let _ = object::common_handles(&mut op)?; + let own = op.handle; + let s = &mut op.s; + Ok(match partial { + Partial::Done(n) => n, + Partial::Dict((mut d, names)) => { + for name in names { + let h = Handle(s.h_abs(own)?); + d.entries.push((name, h)); + } + if wdflt { + d.default = Some(Handle(s.h_abs(own)?)); + } + NonGraphic::Dictionary(d) + } + Partial::XRec(x) => NonGraphic::XRecord(x), + Partial::Layout(mut l) => { + if s.ver >= V::R2004 { + l.plot.plot_view = Handle(s.h_abs(own)?); + } + if s.ver >= V::R2007 { + l.plot.visual_style = Handle(s.h_abs(own)?); + } + l.block = Handle(s.h_abs(own)?); + l.last_viewport = Handle(s.h_abs(own)?); + l.base_ucs = Handle(s.h_abs(own)?); + l.named_ucs = Handle(s.h_abs(own)?); + let n = l.viewports.len(); + l.viewports.clear(); + for _ in 0..n { + l.viewports.push(Handle(s.h_abs(own)?)); + } + NonGraphic::Layout(l) + } + Partial::MLine(mut m) => { + if s.ver >= V::R2018 { + for e in &mut m.elements { + e.linetype = Handle(s.h_abs(own)?); + } + } + NonGraphic::MLineStyle(m) + } + }) + })()) +} + +enum Partial { + Done(NonGraphic), + Dict((Dictionary, Vec)), + XRec(XRecord), + Layout(Box), + MLine(MLineStyle), +} + +fn dictionary_data(s: &mut Streams) -> Result<(Dictionary, Vec)> { + let n = s.dat.bl()?; + if s.ver == V::R14 { + let _unknown = s.dat.rc()?; + } + let (cloning, hard_owner) = if s.ver >= V::R2000 { (s.dat.bs()?, s.dat.rc()?) } else { (0, 0) }; + let n = s.check_handle_count(n, "dictionary entry")?; + let mut names = Vec::with_capacity(n); + for _ in 0..n { + names.push(s.tv()?); + } + Ok((Dictionary { cloning, hard_owner, entries: Vec::new(), default: None }, names)) +} + +/// The binary form of an XRECORD value, by group code (DXF reference, +/// "Group Code Value Types"; sizes as R2007+ files store them). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum XrType { + Str, + Point, + Real, + Int8, + Int16, + Int32, + Int64, + Bool, + Bytes, + Handle, +} + +/// The binary form of an XRECORD value with this group code, if it has one. +pub fn xr_type(code: u16) -> Option { + use XrType::*; + Some(match code { + 0..=9 | 100..=102 | 300..=309 | 410..=419 | 430..=439 | 470..=479 | 999 | 1000..=1003 => Str, + 10..=18 | 110..=112 | 210 | 1010..=1013 => Point, + 19..=59 | 113..=149 | 211..=239 | 460..=469 | 1014..=1059 => Real, + 60..=79 | 170..=179 | 270..=279 | 370..=389 | 400..=409 | 1060..=1070 => Int16, + 280..=289 => Int8, + 90..=99 | 420..=429 | 440..=459 | 1071 => Int32, + 160..=169 => Int64, + 290..=299 => Bool, + 310..=319 | 1004 => Bytes, + 105 | 320..=369 | 390..=399 | 480..=481 | 1005 => Handle, + _ => return None, + }) +} + +fn xrecord_data(s: &mut Streams) -> Result { + let n = s.dat.bl()? as usize; + if n > s.dat.remaining() / 8 { + return Err(Error::format("XRECORD data runs past the record")); + } + let bytes = s.dat.raw_bytes(n)?; + let cloning = if s.ver >= V::R2000 { s.dat.bs()? } else { 0 }; + let items = xrecord_items(&bytes, s.ver)?; + Ok(XRecord { cloning, items }) +} + +/// `b` as the bytes of an `N`-byte little-endian number. The callers take +/// exactly `N` bytes; were any missing, they would read as zero. +fn le(b: &[u8]) -> [u8; N] { + let mut a = [0u8; N]; + for (x, y) in a.iter_mut().zip(b) { + *x = *y; + } + a +} + +fn xrecord_items(d: &[u8], ver: V) -> Result> { + let mut p = 0usize; + let mut out = Vec::new(); + let take = |p: &mut usize, n: usize| -> Result<&[u8]> { + let s = d.get(*p..*p + n).ok_or_else(|| Error::format("XRECORD value runs past its data"))?; + *p += n; + Ok(s) + }; + while p < d.len() { + let code = u16::from_le_bytes(le(take(&mut p, 2)?)); + let t = xr_type(code).ok_or_else(|| Error::format(format!("XRECORD group code {code} not known")))?; + let f64_at = |b: &[u8]| f64::from_le_bytes(le(b)); + let v = match t { + XrType::Str => { + if ver.has_string_stream() { + let len = u16::from_le_bytes(le(take(&mut p, 2)?)) as usize; + let units: Vec = take(&mut p, len * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + XrValue::Str(String::from_utf16_lossy(&units)) + } else { + let len = take(&mut p, 1)?[0] as usize; + let _codepage = take(&mut p, 1)?; + XrValue::Str(crate::read::text::decode_ansi(take(&mut p, len)?, 30)) + } + } + XrType::Point => { + let b = take(&mut p, 24)?; + XrValue::Point(Vec3::new(f64_at(&b[..8]), f64_at(&b[8..16]), f64_at(&b[16..]))) + } + XrType::Real => XrValue::Real(f64_at(take(&mut p, 8)?)), + XrType::Int8 => XrValue::Int8(take(&mut p, 1)?[0] as i8), + XrType::Int16 => XrValue::Int16(i16::from_le_bytes(le(take(&mut p, 2)?))), + XrType::Int32 => XrValue::Int32(i32::from_le_bytes(le(take(&mut p, 4)?))), + XrType::Int64 => XrValue::Int64(i64::from_le_bytes(le(take(&mut p, 8)?))), + XrType::Bool => XrValue::Bool(take(&mut p, 1)?[0] != 0), + XrType::Bytes => { + let len = take(&mut p, 1)?[0] as usize; + XrValue::Bytes(take(&mut p, len)?.to_vec()) + } + XrType::Handle => XrValue::Handle(Handle(u64::from_le_bytes(le(take(&mut p, 8)?)))), + }; + out.push((code, v)); + } + Ok(out) +} + +fn v2(a: [f64; 2]) -> Vec2 { + Vec2::from_array(a) +} +fn v3(a: [f64; 3]) -> Vec3 { + Vec3::from_array(a) +} + +fn layout_data(s: &mut Streams) -> Result { + let mut p = PlotSettings { page_setup_name: s.tv()?, printer: s.tv()?, flags: s.dat.bs()?, ..Default::default() }; + for m in &mut p.margins { + *m = s.dat.bd()?; + } + p.paper_width = s.dat.bd()?; + p.paper_height = s.dat.bd()?; + p.paper_size = s.tv()?; + p.origin = v2(s.dat.bd2()?); + p.paper_units = s.dat.bs()?; + p.rotation = s.dat.bs()?; + p.plot_type = s.dat.bs()?; + p.window_min = v2(s.dat.bd2()?); + p.window_max = v2(s.dat.bd2()?); + if s.ver <= V::R2000 { + let _view_name = s.tv()?; + } + p.real_world_units = s.dat.bd()?; + p.drawing_units = s.dat.bd()?; + p.style_sheet = s.tv()?; + p.scale_type = s.dat.bs()?; + p.scale_factor = s.dat.bd()?; + p.image_origin = v2(s.dat.bd2()?); + if s.ver >= V::R2004 { + p.shade_plot_mode = s.dat.bs()?; + p.shade_plot_res_level = s.dat.bs()?; + p.shade_plot_custom_dpi = s.dat.bs()?; + } + let mut l = Layout { + plot: p, + name: s.tv()?, + tab_order: s.dat.bl()?, + flags: s.dat.bs()?, + ucs_origin: v3(s.dat.bd3()?), + limmin: v2(s.dat.rd2()?), + limmax: v2(s.dat.rd2()?), + insbase: v3(s.dat.bd3()?), + ucs_x: v3(s.dat.bd3()?), + ucs_y: v3(s.dat.bd3()?), + elevation: s.dat.bd()?, + ortho_type: s.dat.bs()?, + extmin: v3(s.dat.bd3()?), + extmax: v3(s.dat.bd3()?), + ..Default::default() + }; + if s.ver >= V::R2004 { + // The spec gives an RL; AutoCAD 2027's AC1032 layouts store a BL + // (only that reading ends where their strings begin). + let n = s.dat.bl()?; + let n = s.check_handle_count(n, "layout viewport")?; + l.viewports = vec![Handle::NULL; n]; + } + Ok(l) +} + +/// DWG keeps the MLINESTYLE flag bits in a different order from DXF 70. +const MLINE_FLAG_BITS: [(u16, u16); 8] = [(1, 2), (2, 1), (16, 16), (32, 64), (64, 32), (256, 256), (512, 1024), (1024, 512)]; + +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()?; + let flags = mline_flags_to_dxf(s.dat.bs()?); + let (fill_color, _) = s.cmc()?; + let start_angle = s.dat.bd()?; + let end_angle = s.dat.bd()?; + let n = s.dat.rc()? as usize; + let mut elements = Vec::with_capacity(n); + for _ in 0..n { + let offset = s.dat.bd()?; + let (color, _) = s.cmc()?; + let linetype_index = if s.ver < V::R2018 { s.dat.bs()? as i16 } else { 0 }; + elements.push(MLineElement { offset, color, linetype: Handle::NULL, linetype_index }); + } + Ok(MLineStyle { name, description, flags, fill_color, start_angle, end_angle, elements }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn corpus() -> Option { + let p = std::path::PathBuf::from(std::env::var_os("MI201_CORPUS")?).join("mi201-r2018.dwg"); + std::fs::read(p).ok().map(|b| super::super::read_bytes(&b).unwrap()) + } + + /// Every dictionary, extension record, layout, scale and style of the + /// AutoCAD 2027 file decodes, and the values match what AutoCAD's own + /// DXF of the drawing shows. + #[test] + fn autocad_objects_decode_as_its_dxf_shows() { + let Some(d) = corpus() else { return }; + let mut counts = std::collections::BTreeMap::<&str, usize>::new(); + for o in d.objects.values() { + match decode(o, &d.classes, d.codepage) { + None => {} + Some(Ok(_)) => *counts.entry(o.type_name.as_str()).or_default() += 1, + Some(Err(e)) => panic!("{} {:X}: {e}", o.type_name, o.handle.0), + } + } + assert_eq!(counts["DICTIONARY"], 19); + assert_eq!(counts["XRECORD"], 20); + assert_eq!(counts["SCALE"], 17); + assert_eq!(counts["LAYOUT"], 2); + let get = |h: u64| decode(&d.objects[&Handle(h)], &d.classes, d.codepage).unwrap().unwrap(); + // The named object dictionary. + match get(0x3F) { + NonGraphic::Dictionary(dict) => { + assert!(dict.entries.iter().any(|e| e == &("ACAD_GROUP".to_string(), Handle(0x3E)))); + assert!(dict.entries.iter().any(|e| e == &("ACAD_LAYOUT".to_string(), Handle(0x3D0C9)))); + } + other => panic!("{other:?}"), + } + match get(0x3D094) { + NonGraphic::Dictionary(dict) => { + assert_eq!(dict.entries, vec![("Normal".to_string(), Handle(0x3D095))]); + assert_eq!(dict.default, Some(Handle(0x3D095))); + } + other => panic!("{other:?}"), + } + match get(0x3D0EA) { + NonGraphic::XRecord(x) => { + assert_eq!(x.cloning, 1); + assert_eq!(x.items, vec![(300, XrValue::Str("ACD".into())), (300, XrValue::Str("2027".into())), (300, XrValue::Str(String::new())),]); + } + other => panic!("{other:?}"), + } + match get(0x3D0A2) { + NonGraphic::XRecord(x) => { + assert_eq!(x.items, vec![(270, XrValue::Int16(1)), (271, XrValue::Int16(1))]); + } + other => panic!("{other:?}"), + } + match get(0x3D0E7) { + NonGraphic::Layout(l) => { + assert_eq!(l.name, "Model"); + assert_eq!(l.block, Handle(0x17)); + assert_eq!(l.last_viewport, Handle(0x3)); + } + other => panic!("{other:?}"), + } + match get(0x3D0CD) { + NonGraphic::MLineStyle(m) => { + assert_eq!(m.name, "STANDARD"); + assert_eq!(m.elements.len(), 2); + assert_eq!(m.elements[0].linetype, Handle(0x6)); + assert_eq!(m.elements[0].offset, 0.5); + } + other => panic!("{other:?}"), + } + } +} + +/// The dimension variables the header holds (the current style's values +/// unless overridden). +pub fn dim_vars_from_header(hv: &super::hvars::Hv) -> DimVars { + let r = |n: &str, d: f64| hv.real(n, d); + let i = |n: &str, d: i64| hv.int(n, d) as u16; + let b = |n: &str, d: bool| hv.bool(n, d); + DimVars { + post: hv.text("DIMPOST", ""), + apost: hv.text("DIMAPOST", ""), + scale: r("DIMSCALE", 1.0), + asz: r("DIMASZ", 0.18), + exo: r("DIMEXO", 0.0625), + dli: r("DIMDLI", 0.38), + exe: r("DIMEXE", 0.18), + rnd: r("DIMRND", 0.0), + dle: r("DIMDLE", 0.0), + tp: r("DIMTP", 0.0), + tm: r("DIMTM", 0.0), + fxl: r("DIMFXL", 1.0), + jogang: r("DIMJOGANG", std::f64::consts::FRAC_PI_4), + tfill: i("DIMTFILL", 0), + tfillclr: hv.color("DIMTFILLCLR", Color::ByBlock), + tol: b("DIMTOL", false), + lim: b("DIMLIM", false), + tih: b("DIMTIH", true), + toh: b("DIMTOH", true), + se1: b("DIMSE1", false), + se2: b("DIMSE2", false), + tad: i("DIMTAD", 0), + zin: i("DIMZIN", 0), + azin: i("DIMAZIN", 0), + arcsym: i("DIMARCSYM", 0), + txt: r("DIMTXT", 0.18), + cen: r("DIMCEN", 0.09), + tsz: r("DIMTSZ", 0.0), + altf: r("DIMALTF", 25.4), + lfac: r("DIMLFAC", 1.0), + tvp: r("DIMTVP", 0.0), + tfac: r("DIMTFAC", 1.0), + gap: r("DIMGAP", 0.09), + altrnd: r("DIMALTRND", 0.0), + alt: b("DIMALT", false), + altd: i("DIMALTD", 2), + tofl: b("DIMTOFL", false), + sah: b("DIMSAH", false), + tix: b("DIMTIX", false), + soxd: b("DIMSOXD", false), + clrd: hv.color("DIMCLRD", Color::ByBlock), + clre: hv.color("DIMCLRE", Color::ByBlock), + clrt: hv.color("DIMCLRT", Color::ByBlock), + adec: i("DIMADEC", 0), + dec: i("DIMDEC", 4), + tdec: i("DIMTDEC", 4), + altu: i("DIMALTU", 2), + alttd: i("DIMALTTD", 2), + aunit: i("DIMAUNIT", 0), + frac: i("DIMFRAC", 0), + lunit: i("DIMLUNIT", 2), + dsep: i("DIMDSEP", b'.' as i64), + tmove: i("DIMTMOVE", 0), + just: i("DIMJUST", 0), + sd1: b("DIMSD1", false), + sd2: b("DIMSD2", false), + tolj: i("DIMTOLJ", 1), + tzin: i("DIMTZIN", 0), + altz: i("DIMALTZ", 0), + alttz: i("DIMALTTZ", 0), + upt: b("DIMUPT", false), + fit: i("DIMATFIT", 3), + fxlon: b("DIMFXLON", false), + txtdirection: b("DIMTXTDIRECTION", false), + altmzf: r("DIMALTMZF", 100.0), + altmzs: hv.text("DIMALTMZS", ""), + mzf: r("DIMMZF", 100.0), + mzs: hv.text("DIMMZS", ""), + lwd: hv.int("DIMLWD", -2) as i16, + lwe: hv.int("DIMLWE", -2) as i16, + flag_bit: false, + txsty: hv.handle("DIMTXSTY"), + ldrblk: hv.handle("DIMLDRBLK"), + blk: hv.handle("DIMBLK"), + blk1: hv.handle("DIMBLK1"), + blk2: hv.handle("DIMBLK2"), + ltype: hv.handle("DIMLTYPE"), + ltex1: hv.handle("DIMLTEX1"), + ltex2: hv.handle("DIMLTEX2"), + } +} + +/// A DIMSTYLE record kept as its DWG bytes: the name, flags and every +/// variable. `None` for R13–R14 records (laid out differently). +pub fn dimstyle(o: &Object, classes: &[ClassDef], codepage: u16) -> Option> { + if let ObjectKind::DimStyleRecord(r) = &o.kind { + return Some(Ok((r.name.clone(), r.vars.clone()))); + } + let raw = o.raw.as_ref()?; + if o.type_code != 0x45 || raw.version < V::R2000 { + return None; + } + let buf = object::raw_buffer(raw); + let ctx = DecodeCtx { ver: raw.version, codepage, classes }; + Some((|| { + let mut op = object::open(&ctx, &buf, 0)?; + let s = &mut op.s; + let name = record_name(s)?; + let ver = s.ver; + let post = s.tv()?; + let apost = s.tv()?; + let (scale, asz, exo, dli, exe, rnd, dle, tp, tm) = + (s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?); + let (mut fxl, mut jogang, mut tfill, mut tfillclr) = (1.0, std::f64::consts::FRAC_PI_4, 0, Color::ByBlock); + if ver >= V::R2007 { + fxl = s.dat.bd()?; + jogang = s.dat.bd()?; + tfill = s.dat.bs()?; + tfillclr = s.cmc()?.0; + } + let (tol, lim, tih, toh, se1, se2) = (s.dat.b()?, s.dat.b()?, s.dat.b()?, s.dat.b()?, s.dat.b()?, s.dat.b()?); + let (tad, zin, azin) = (s.dat.bs()?, s.dat.bs()?, s.dat.bs()?); + let arcsym = if ver >= V::R2007 { s.dat.bs()? } else { 0 }; + let (txt, cen, tsz, altf, lfac, tvp, tfac, gap, altrnd) = + (s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?, s.dat.bd()?); + let alt = s.dat.b()?; + let altd = s.dat.bs()?; + let (tofl, sah, tix, soxd) = (s.dat.b()?, s.dat.b()?, s.dat.b()?, s.dat.b()?); + let clrd = s.cmc()?.0; + let clre = s.cmc()?.0; + let clrt = s.cmc()?.0; + let mut n = [0u16; 10]; + for v in &mut n { + *v = s.dat.bs()?; + } + let [adec, dec, tdec, altu, alttd, aunit, frac, lunit, dsep, tmove] = n; + let just = s.dat.bs()?; + let sd1 = s.dat.b()?; + let sd2 = s.dat.b()?; + let (tolj, tzin, altz, alttz) = (s.dat.bs()?, s.dat.bs()?, s.dat.bs()?, s.dat.bs()?); + let upt = s.dat.b()?; + let fit = s.dat.bs()?; + let fxlon = if ver >= V::R2007 { s.dat.b()? } else { false }; + let (mut txtdirection, mut altmzf, mut altmzs, mut mzf, mut mzs) = (false, 100.0, String::new(), 100.0, String::new()); + if ver >= V::R2010 { + txtdirection = s.dat.b()?; + altmzf = s.dat.bd()?; + altmzs = s.tv()?; + mzf = s.dat.bd()?; + mzs = s.tv()?; + } + let lwd = s.dat.bs()? as i16; + let lwe = s.dat.bs()? as i16; + let flag_bit = s.dat.b()?; + let _ = object::common_handles(&mut op)?; + let own = op.handle; + let s = &mut op.s; + let _xref_block = s.h()?; + let mut h = || -> Result { Ok(Handle(s.h_abs(own)?)) }; + let txsty = h()?; + let (ldrblk, blk, blk1, blk2) = (h()?, h()?, h()?, h()?); + let (mut ltype, mut ltex1, mut ltex2) = (Handle::NULL, Handle::NULL, Handle::NULL); + if ver >= V::R2007 { + ltype = h()?; + ltex1 = h()?; + ltex2 = h()?; + } + Ok(( + name, + DimVars { + post, + apost, + scale, + asz, + exo, + dli, + exe, + rnd, + dle, + tp, + tm, + fxl, + jogang, + tfill, + tfillclr, + tol, + lim, + tih, + toh, + se1, + se2, + tad, + zin, + azin, + arcsym, + txt, + cen, + tsz, + altf, + lfac, + tvp, + tfac, + gap, + altrnd, + alt, + altd, + tofl, + sah, + tix, + soxd, + clrd, + clre, + clrt, + adec, + dec, + tdec, + altu, + alttd, + aunit, + frac, + lunit, + dsep, + tmove, + just, + sd1, + sd2, + tolj, + tzin, + altz, + alttz, + upt, + fit, + fxlon, + txtdirection, + altmzf, + altmzs, + mzf, + mzs, + lwd, + lwe, + flag_bit, + txsty, + ldrblk, + blk, + blk1, + blk2, + ltype, + ltex1, + ltex2, + }, + )) + })()) +} + +/// The common start of a table record: the name and (before R2007) the +/// 64-flag, xref index and xref-dependent bit. +fn record_name(s: &mut Streams) -> Result { + let name = s.tv()?; + if !s.ver.has_string_stream() { + let _flag64 = s.dat.b()?; + } + let _xref_index = s.dat.bs()?; + if !s.ver.has_string_stream() { + let _xdep = s.dat.b()?; + } + Ok(name) +} + +/// A VPORT record kept as its DWG bytes. `None` before R2000. +pub fn vport(o: &Object, classes: &[ClassDef], codepage: u16) -> Option> { + if let ObjectKind::Viewport(v) = &o.kind { + return Some(Ok((**v).clone())); + } + let raw = o.raw.as_ref()?; + if o.type_code != 0x41 || raw.version < V::R2000 { + return None; + } + let buf = object::raw_buffer(raw); + let ctx = DecodeCtx { ver: raw.version, codepage, classes }; + Some((|| { + let mut op = object::open(&ctx, &buf, 0)?; + let s = &mut op.s; + let ver = s.ver; + let name = record_name(s)?; + let view_height = s.dat.bd()?; + let width = s.dat.bd()?; + let center = v2(s.dat.rd2()?); + let target = v3(s.dat.bd3()?); + let direction = v3(s.dat.bd3()?); + let twist = s.dat.bd()?; + let lens = s.dat.bd()?; + let front_clip = s.dat.bd()?; + let back_clip = s.dat.bd()?; + let mode = s.dat.bits(4)? as u16; + // Bits 0–2 are 71's bits 0–2; bit 3 is the opposite of 71's 16. + let mut view_mode = ((mode >> 3) & 1) | (((mode >> 2) & 1) << 1) | (((mode >> 1) & 1) << 2); + if mode & 1 == 0 { + view_mode |= 16; + } + let render_mode = s.dat.rc()?; + let mut v = Vport::looking_at(Vec2::ZERO, Vec2::new(1.0, 1.0)); + if ver >= V::R2007 { + v.default_lights = s.dat.b()?; + v.lighting_type = s.dat.rc()?; + v.brightness = s.dat.bd()?; + v.contrast = s.dat.bd()?; + v.ambient = s.cmc()?.0; + } + v.lower_left = v2(s.dat.rd2()?); + v.upper_right = v2(s.dat.rd2()?); + if s.dat.b()? { + view_mode |= 8; + } + v.circle_zoom = s.dat.bs()?; + v.fast_zoom = s.dat.b()?; + v.ucsicon = s.dat.bits(2)? as u8; + v.grid_on = s.dat.b()?; + v.grid_spacing = v2(s.dat.rd2()?); + v.snap_on = s.dat.b()?; + v.snap_style = s.dat.b()?; + v.snap_isopair = s.dat.bs()?; + v.snap_rotation = s.dat.bd()?; + v.snap_base = v2(s.dat.rd2()?); + v.snap_spacing = v2(s.dat.rd2()?); + v.unknown_bit = s.dat.b()?; + v.ucs_per_viewport = s.dat.b()?; + v.ucs_origin = v3(s.dat.bd3()?); + v.ucs_x = v3(s.dat.bd3()?); + v.ucs_y = v3(s.dat.bd3()?); + v.ucs_elevation = s.dat.bd()?; + v.ucs_ortho_type = s.dat.bs()?; + if ver >= V::R2007 { + v.grid_flags = s.dat.bs()?; + v.grid_major = s.dat.bs()?; + } + let _ = object::common_handles(&mut op)?; + let own = op.handle; + let s = &mut op.s; + let _xref_block = s.h()?; + if ver >= V::R2007 { + v.background = Handle(s.h_abs(own)?); + v.visual_style = Handle(s.h_abs(own)?); + v.sun = Handle(s.h_abs(own)?); + } + v.named_ucs = Handle(s.h_abs(own)?); + v.base_ucs = Handle(s.h_abs(own)?); + Ok(Vport { + name, + view_height, + aspect: if view_height != 0.0 { width / view_height } else { 1.0 }, + center, + target, + direction, + twist, + lens, + front_clip, + back_clip, + view_mode, + render_mode, + ..v + }) + })()) +} + +#[cfg(test)] +mod table_tests { + use super::*; + + fn corpus() -> Option { + let p = std::path::PathBuf::from(std::env::var_os("MI201_CORPUS")?).join("mi201-r2018.dwg"); + std::fs::read(p).ok().map(|b| super::super::read_bytes(&b).unwrap()) + } + + /// The *Active viewport and the Standard dimension style of the + /// AutoCAD 2027 file hold what AutoCAD's DXF of it shows. + #[test] + fn vport_and_dimstyle_records_decode_as_the_dxf_shows() { + let Some(d) = corpus() else { return }; + let v = vport(&d.objects[&Handle(3)], &d.classes, d.codepage).unwrap().unwrap(); + assert_eq!(v.name, "*Active"); + assert!((v.center.x - 129.0894530191407).abs() < 1e-9); + assert!((v.center.y - 39.35701577680084).abs() < 1e-9); + assert!((v.view_height - 16.58941231582867).abs() < 1e-9); + assert!((v.aspect - 1.856966707768187).abs() < 1e-9); + assert_eq!(v.lens, 50.0); + assert_eq!((v.view_mode, v.circle_zoom, v.fast_zoom, v.ucsicon), (0, 100, true, 3)); + assert_eq!(v.snap_spacing, Vec2::new(0.5, 0.5)); + assert_eq!(v.grid_spacing, Vec2::new(0.5, 0.5)); + assert_eq!((v.grid_flags, v.grid_major), (3, 5)); + assert!(v.ucs_per_viewport && v.default_lights); + assert_eq!(v.lighting_type, 1); + assert_eq!(v.visual_style, Handle(0x3D0B5)); + let (name, s) = dimstyle(&d.objects[&Handle(0x15)], &d.classes, d.codepage).unwrap().unwrap(); + assert_eq!(name, "Standard"); + assert_eq!(s.txsty, Handle(0x11)); + assert_eq!((s.asz, s.exo, s.dli, s.txt, s.gap), (0.18, 0.0625, 0.38, 0.18, 0.09)); + assert_eq!((s.dec, s.tdec, s.lunit, s.dsep, s.fit, s.tolj), (4, 4, 2, 46, 3, 1)); + assert_eq!((s.clrd, s.lwd, s.lwe), (Color::ByBlock, -2, -2)); + assert_eq!(s.post, ""); + } +} + +/// Turn objects kept as DWG records into the model's records where they +/// decode: VPORT and DIMSTYLE table records, the non-graphical objects +/// above, and tolerances, multilines, images and wipeouts. Their DWG bytes are then dropped; the DWG writer encodes them +/// again. Objects that do not decode stay as they were. Used by the DWG +/// reader, and by the native reader for files of format 2.1 and earlier. +/// A style object (`Groups::KINDS`) from its DWG record. +pub(crate) fn decode_groups(o: &Object, classes: &[ClassDef], codepage: u16, lookup: &super::styles::Lookup) -> Option> { + if let ObjectKind::NonGraphic(NonGraphic::Groups(g)) = &o.kind { + return Some(Ok(g.clone())); + } + if !Groups::KINDS.contains(&o.type_name.as_str()) { + return None; + } + let raw = o.raw.as_ref()?; + let buf = object::raw_buffer(raw); + let ctx = DecodeCtx { ver: raw.version, codepage, classes }; + let mut op = match object::open(&ctx, &buf, 0) { + Ok(op) => op, + Err(e) => return Some(Err(e)), + }; + if let Err(e) = object::common_handles(&mut op) { + return Some(Err(e)); + } + let own = op.handle; + let kind = op.type_name.clone(); + super::styles::decode(&kind, &mut op.s, own, lookup) +} + +pub fn promote(d: &mut Drawing) { + let (classes, codepage) = (d.classes.clone(), d.codepage); + let lookup = super::styles::Lookup::new(d); + for o in d.objects.values_mut() { + if o.raw.is_none() { + continue; + } + let kind = match (o.type_code, &o.kind) { + (0x41, ObjectKind::NamedRecord(_)) => match vport(o, &classes, codepage) { + Some(Ok(v)) => Some(ObjectKind::Viewport(Box::new(v))), + _ => None, + }, + (0x45, ObjectKind::NamedRecord(_)) => match dimstyle(o, &classes, codepage) { + Some(Ok((name, vars))) => Some(ObjectKind::DimStyleRecord(Box::new(DimStyleRecord { name, vars }))), + _ => None, + }, + // Entities kept as bytes by readers from before their types + // were decoded (tolerances, multilines, images, wipeouts in + // older .cad files): decoded now, when the record fits. + (_, ObjectKind::Unsupported) if matches!(o.type_code, 0x2E | 0x2F) || matches!(o.type_name.as_str(), "IMAGE" | "WIPEOUT") => { + o.raw.as_ref().and_then(|raw| { + let ctx = DecodeCtx { ver: raw.version, codepage, classes: &classes }; + let k = object::decode(&ctx, &object::raw_buffer(raw), 0).ok()?.kind; + matches!(k, ObjectKind::Tolerance(_) | ObjectKind::MLine(_) | ObjectKind::Image(_) | ObjectKind::Wipeout(_)).then_some(k) + }) + } + (_, ObjectKind::Unsupported) => match decode(o, &classes, codepage) { + Some(Ok(n)) => Some(ObjectKind::NonGraphic(n)), + _ => match decode_groups(o, &classes, codepage, &lookup) { + Some(Ok(g)) => Some(ObjectKind::NonGraphic(NonGraphic::Groups(g))), + _ => None, + }, + }, + _ => None, + }; + if let Some(k) = kind { + o.kind = k; + o.raw = None; + } + } +} diff --git a/crates/dwg/src/read/object.rs b/crates/dwg/src/read/object.rs new file mode 100644 index 00000000..6879e1e8 --- /dev/null +++ b/crates/dwg/src/read/object.rs @@ -0,0 +1,1059 @@ +//! Decoding of individual objects: the common object/entity header, the +//! stream split, type dispatch and the handle stream. +//! +//! Written from knowledge of the spec, chapter 20 ("common non-entity +//! object format", "common entity format", "common entity handle data"). +//! VERIFY against the spec PDF and real files. Checked so far: the fields +//! up to and including the extended data (§20.1, §20.4.1), which +//! `eed.rs` decodes (chapter 28). + +use super::eed; +use super::entities; +use super::streams::{Streams, string_stream}; +use super::tables; +use super::version::DwgVersion as V; +use super::version::DwgVersion; +use crate::bits::BitReader; +use crate::read::error::{Error, Result}; +use crate::read::model::{ClassDef, EntityCommon, Handle, LinetypeRef, Object, ObjectKind, RawDwgObject, Space, VertexKind, XData}; + +pub(crate) struct DecodeCtx<'a> { + pub ver: DwgVersion, + pub codepage: u16, + pub classes: &'a [ClassDef], +} + +/// Name and entity/non-entity classification of the fixed object types. +pub(crate) fn fixed_type(code: u16) -> Option<(&'static str, bool)> { + Some(match code { + 0x01 => ("TEXT", true), + 0x02 => ("ATTRIB", true), + 0x03 => ("ATTDEF", true), + 0x04 => ("BLOCK", true), + 0x05 => ("ENDBLK", true), + 0x06 => ("SEQEND", true), + 0x07 => ("INSERT", true), + 0x08 => ("MINSERT", true), + 0x0A => ("VERTEX_2D", true), + 0x0B => ("VERTEX_3D", true), + 0x0C => ("VERTEX_MESH", true), + 0x0D => ("VERTEX_PFACE", true), + 0x0E => ("VERTEX_PFACE_FACE", true), + 0x0F => ("POLYLINE_2D", true), + 0x10 => ("POLYLINE_3D", true), + 0x11 => ("ARC", true), + 0x12 => ("CIRCLE", true), + 0x13 => ("LINE", true), + 0x14 => ("DIMENSION_ORDINATE", true), + 0x15 => ("DIMENSION_LINEAR", true), + 0x16 => ("DIMENSION_ALIGNED", true), + 0x17 => ("DIMENSION_ANG_3PT", true), + 0x18 => ("DIMENSION_ANG_2LN", true), + 0x19 => ("DIMENSION_RADIUS", true), + 0x1A => ("DIMENSION_DIAMETER", true), + 0x1B => ("POINT", true), + 0x1C => ("3DFACE", true), + 0x1D => ("POLYLINE_PFACE", true), + 0x1E => ("POLYLINE_MESH", true), + 0x1F => ("SOLID", true), + 0x20 => ("TRACE", true), + 0x21 => ("SHAPE", true), + 0x22 => ("VIEWPORT", true), + 0x23 => ("ELLIPSE", true), + 0x24 => ("SPLINE", true), + 0x25 => ("REGION", true), + 0x26 => ("3DSOLID", true), + 0x27 => ("BODY", true), + 0x28 => ("RAY", true), + 0x29 => ("XLINE", true), + 0x2A => ("DICTIONARY", false), + 0x2B => ("OLEFRAME", true), + 0x2C => ("MTEXT", true), + 0x2D => ("LEADER", true), + 0x2E => ("TOLERANCE", true), + 0x2F => ("MLINE", true), + 0x30 => ("BLOCK_CONTROL", false), + 0x31 => ("BLOCK_HEADER", false), + 0x32 => ("LAYER_CONTROL", false), + 0x33 => ("LAYER", false), + 0x34 => ("STYLE_CONTROL", false), + 0x35 => ("STYLE", false), + 0x38 => ("LTYPE_CONTROL", false), + 0x39 => ("LTYPE", false), + 0x3C => ("VIEW_CONTROL", false), + 0x3D => ("VIEW", false), + 0x3E => ("UCS_CONTROL", false), + 0x3F => ("UCS", false), + 0x40 => ("VPORT_CONTROL", false), + 0x41 => ("VPORT", false), + 0x42 => ("APPID_CONTROL", false), + 0x43 => ("APPID", false), + 0x44 => ("DIMSTYLE_CONTROL", false), + 0x45 => ("DIMSTYLE", false), + 0x46 => ("VX_CONTROL", false), + 0x47 => ("VX_TABLE_RECORD", false), + 0x48 => ("GROUP", false), + 0x49 => ("MLINESTYLE", false), + 0x4A => ("OLE2FRAME", true), + 0x4B => ("DUMMY", false), + 0x4C => ("LONG_TRANSACTION", true), + 0x4D => ("LWPOLYLINE", true), + 0x4E => ("HATCH", true), + 0x4F => ("XRECORD", false), + 0x50 => ("ACDBPLACEHOLDER", false), + 0x51 => ("VBA_PROJECT", false), + 0x52 => ("LAYOUT", false), + 0x1F2 => ("ACAD_PROXY_ENTITY", true), + 0x1F3 => ("ACAD_PROXY_OBJECT", false), + _ => return None, + }) +} + +/// Name and entity flag for any type code, using the class table for +/// codes 500 and up. +pub(crate) fn classify(code: u16, classes: &[ClassDef]) -> (String, bool) { + if let Some((name, ent)) = fixed_type(code) { + return (name.to_string(), ent); + } + if code >= 500 + && let Some(c) = classes.iter().find(|c| c.number == code) + { + let name = if c.dxf_name.is_empty() { format!("CLASS_{code}") } else { c.dxf_name.clone() }; + return (name, c.is_entity()); + } + (format!("TYPE_{code:#X}"), false) +} + +/// Lightweight look at an object: its own handle and type code. Used to +/// validate the object map before full decoding. +pub(crate) fn peek(ver: DwgVersion, data: &[u8], offset: usize) -> Result<(u64, u16)> { + let mut r = BitReader::new(data); + r.set_position(offset.checked_mul(8).ok_or_else(|| Error::format("offset overflow"))?)?; + let size = r.ms()? as usize; + if ver >= V::R2010 { + let _hsize = r.mc_unsigned()?; + } + let start = r.position() / 8; + let end = start.checked_add(size).ok_or_else(|| Error::format("size overflow"))?; + if end > data.len() || size == 0 { + return Err(Error::truncated(format!("object at {offset} of {size} bytes runs past data"))); + } + let mut dat = BitReader::new(&data[start..end]); + let code = if ver >= V::R2010 { dat.ot()? } else { dat.bs()? }; + if (V::R2000..=V::R2007).contains(&ver) { + let _bitsize = dat.rl()?; + } + let h = dat.handle()?; + Ok((h.value, code)) +} + +/// Common entity fields read from the main stream, kept for the handle +/// stream that follows. +#[derive(Default)] +struct EntityFlags { + entmode: u8, + num_reactors: u32, + xdic_missing: bool, + bylayer_ltype: bool, + no_links: bool, + color_handle: bool, + ltype_flags: u8, + plotstyle_flags: u8, + material_flags: u8, + full_vs: bool, + face_vs: bool, + edge_vs: bool, +} + +/// Extra counts some types need when reading their handles. +enum Pending { + None, + Owned(u32), + Insert { + owned: u32, + }, + Block(tables::BlockHeaderCounts), + Control { + entries: u32, + is_block_control: bool, + }, + Hatch { + /// Boundary object handles of each path. + boundary_handles: Vec, + }, + Viewport { + frozen: u32, + }, +} + +/// An object whose common fields have been read: the streams are +/// positioned at the type-specific data, and the handle stream at the +/// owner reference. +pub(crate) struct Opened<'a> { + pub handle: u64, + pub type_code: u16, + pub type_name: String, + pub is_entity: bool, + pub size: usize, + pub common: Option, + flags: EntityFlags, + pub num_reactors: u32, + pub xdic_missing: bool, + pub xdata: Vec, + pub s: Streams<'a>, +} + +/// Read the common fields of the object whose modular-short size begins +/// at byte `offset` of `data`, up to its type-specific data. +pub(crate) fn open<'a>(ctx: &DecodeCtx, data: &'a [u8], offset: usize) -> Result> { + let ver = ctx.ver; + let mut r = BitReader::new(data); + r.set_position(offset.checked_mul(8).ok_or_else(|| Error::format("offset overflow"))?)?; + let size = r.ms()? as usize; + let hsize = if ver >= V::R2010 { r.mc_unsigned()? as usize } else { 0 }; + let start = r.position() / 8; + let end = start.checked_add(size).ok_or_else(|| Error::format("size overflow"))?; + if end > data.len() || size == 0 { + return Err(Error::truncated(format!("object at {offset} of {size} bytes runs past data"))); + } + let obj = &data[start..end]; + let total_bits = size * 8; + let mut dat = BitReader::new(obj); + + let type_code = if ver >= V::R2010 { dat.ot()? } else { dat.bs()? }; + let mut bitsize = if ver >= V::R2010 { + total_bits.checked_sub(hsize).ok_or_else(|| Error::format(format!("handle stream {hsize} bits > object {total_bits} bits")))? + } else if ver >= V::R2000 { + dat.rl()? as usize + } else { + 0 + }; + let handle = dat.handle()?.value; + let xdata = eed::read(&mut dat, ver, handle)?; + + let (type_name, is_entity) = classify(type_code, ctx.classes); + + let mut flags = EntityFlags::default(); + let mut common: Option = None; + let num_reactors; + let xdic_missing; + if is_entity { + if dat.b()? { + let gsize = if ver >= V::R2010 { dat.bll()? } else { dat.rl()? as u64 }; + let bits = (gsize as usize).checked_mul(8).ok_or_else(|| Error::format("graphics size overflow"))?; + dat.skip_bits(bits)?; + } + if ver <= V::R14 { + bitsize = dat.rl()? as usize; + } + flags.entmode = dat.bb()?; + flags.num_reactors = dat.bl()?; + if ver >= V::R2004 { + flags.xdic_missing = dat.b()?; + } + if ver >= V::R2013 { + let _has_ds_data = dat.b()?; + } + if ver <= V::R14 { + flags.bylayer_ltype = dat.b()?; + } + flags.no_links = if ver <= V::R2000 { dat.b()? } else { true }; + let mut ent = EntityCommon { + space: match flags.entmode { + 1 => Space::Paper, + 2 => Space::Model, + _ => Space::Owned, + }, + linetype_scale: 1.0, + ..Default::default() + }; + // Color: BS index up to R2000, ENC from R2004. + { + let mut tmp = Streams { ver, codepage: ctx.codepage, dat, strs: None, hdl: None }; + let (color, transparency, color_handle) = tmp.enc()?; + dat = tmp.dat; + ent.color = color; + ent.transparency = transparency; + flags.color_handle = color_handle; + } + ent.linetype_scale = dat.bd()?; + if ver >= V::R2000 { + flags.ltype_flags = dat.bb()?; + flags.plotstyle_flags = dat.bb()?; + } + if ver >= V::R2007 { + flags.material_flags = dat.bb()?; + let _shadow = dat.rc()?; + } + if ver >= V::R2010 { + flags.full_vs = dat.b()?; + flags.face_vs = dat.b()?; + flags.edge_vs = dat.b()?; + } + ent.invisible = dat.bs()? & 1 != 0; + if ver >= V::R2000 { + ent.lineweight = dat.rc()?; + } + ent.linetype = if ver <= V::R14 { + if flags.bylayer_ltype { LinetypeRef::ByLayer } else { LinetypeRef::Continuous } + } else { + match flags.ltype_flags { + 0 => LinetypeRef::ByLayer, + 1 => LinetypeRef::ByBlock, + 2 => LinetypeRef::Continuous, + _ => LinetypeRef::Continuous, + } + }; + num_reactors = flags.num_reactors; + xdic_missing = flags.xdic_missing; + common = Some(ent); + } else { + if ver <= V::R14 { + bitsize = dat.rl()? as usize; + } + num_reactors = dat.bl()?; + xdic_missing = if ver >= V::R2004 { dat.b()? } else { false }; + if ver >= V::R2013 { + let _has_ds_data = dat.b()?; + } + } + + if bitsize > total_bits { + return Err(Error::format(format!("data end bit {bitsize} beyond object size {total_bits} ({type_name} {handle:X})"))); + } + + // Split into streams. + let hdl = BitReader::with_bounds(obj, bitsize, total_bits); + let mut strs = None; + let mut data_end = bitsize; + if ver.has_string_stream() { + match string_stream(obj, bitsize)? { + Some((sr, st)) => { + strs = Some(sr); + data_end = st; + } + None => data_end = bitsize.saturating_sub(1), + } + } + // If the common data already ran into the strings, reads now fail and + // the object is reported as failed rather than decoded from garbage. + dat.set_end(data_end); + Ok(Opened { + handle, + type_code, + type_name, + is_entity, + size, + common, + flags, + num_reactors, + xdic_missing, + xdata, + s: Streams { ver, codepage: ctx.codepage, dat, strs, hdl: Some(hdl) }, + }) +} + +/// The common handles: owner, reactors, extension dictionary and, for an +/// entity, its layer, linetype, material and plot style (into `common`). +pub(crate) fn common_handles(o: &mut Opened) -> Result<(u64, Vec, u64)> { + let ver = o.s.ver; + let handle = o.handle; + let s = &mut o.s; + let flags = &o.flags; + let mut owner = 0u64; + let mut reactors = Vec::new(); + let mut xdictionary = 0u64; + if o.is_entity { + let Some(ent) = o.common.as_mut() else { + return Err(Error::format("entity without its common data")); + }; + if flags.entmode == 0 { + owner = s.h_abs(handle)?; + } + let n = s.check_handle_count(o.num_reactors, "reactor")?; + for _ in 0..n { + reactors.push(Handle(s.h_abs(handle)?)); + } + if ver < V::R2004 || !o.xdic_missing { + xdictionary = s.h_abs(handle)?; + } + if ver <= V::R14 { + ent.layer = Handle(s.h_abs(handle)?); + if !flags.bylayer_ltype { + ent.linetype = LinetypeRef::Handle(Handle(s.h_abs(handle)?)); + } + } + if ver <= V::R2000 && !flags.no_links { + let _prev = s.h()?; + let _next = s.h()?; + } + if ver >= V::R2004 && flags.color_handle { + let _color_book = s.h()?; + } + if ver >= V::R2000 { + ent.layer = Handle(s.h_abs(handle)?); + if flags.ltype_flags == 3 { + ent.linetype = LinetypeRef::Handle(Handle(s.h_abs(handle)?)); + } + } + if ver >= V::R2007 && flags.material_flags == 3 { + ent.material = Handle(s.h_abs(handle)?); + } + if ver >= V::R2000 && flags.plotstyle_flags == 3 { + ent.plotstyle = Handle(s.h_abs(handle)?); + } + if ver >= V::R2010 { + for present in [flags.full_vs, flags.face_vs, flags.edge_vs] { + if present { + let _vs = s.h()?; + } + } + } + } else { + owner = s.h_abs(handle)?; + let n = s.check_handle_count(o.num_reactors, "reactor")?; + for _ in 0..n { + reactors.push(Handle(s.h_abs(handle)?)); + } + if ver < V::R2004 || !o.xdic_missing { + xdictionary = s.h_abs(handle)?; + } + } + Ok((owner, reactors, xdictionary)) +} + +/// Decode the object whose modular-short size begins at byte `offset` of +/// `data` (the whole file for R13–R15, the AcDb:AcDbObjects section for +/// R2004+). +pub(crate) fn decode(ctx: &DecodeCtx, data: &[u8], offset: usize) -> Result { + let ver = ctx.ver; + let mut o = open(ctx, data, offset)?; + let handle = o.handle; + let type_code = o.type_code; + + // Type-specific data. + let specific = decode_specific(type_code, &o.type_name, &mut o.s); + // Records whose every data field is read must end exactly where their + // strings begin (R2007+, where that boundary is known). Anything else + // means the layout read here differs from the file's. + let mut fit_note = None; + if ver.has_string_stream() && specific.is_ok() && matches!(type_code, 0x31 | 0x33 | 0x43) && o.s.dat.remaining() != 0 { + fit_note = Some(format!("data: {} bit(s) left before the strings; this version's layout may differ", o.s.dat.remaining())); + } + + // Common handles. + let (mut owner, mut reactors, mut xdictionary) = (0u64, Vec::new(), 0u64); + let mut handle_note: Option = None; + match common_handles(&mut o) { + Ok((a, b, c)) => { + owner = a; + reactors = b; + xdictionary = c; + } + Err(e) => handle_note = Some(format!("common handles: {e}")), + } + + // Types decoded from version 0.6 on (construction lines, leaders, + // viewports; tolerances from 0.13, images and wipeouts from 0.14, + // multilines from 0.15) are + // kept as their bytes whenever the layout read here does not fit the + // record exactly, as they were before. + let newer = matches!(type_code, 0x22 | 0x28 | 0x29 | 0x2D | 0x2E | 0x2F) || matches!(o.type_name.as_str(), "IMAGE" | "WIPEOUT"); + let misfit = newer && (specific.is_err() || (ver.has_string_stream() && o.s.dat.remaining() != 0)); + let kind = match specific { + _ if misfit => ObjectKind::Unsupported, + Ok((mut kind, pending)) => { + if handle_note.is_none() + && let Err(e) = read_specific_handles(&mut kind, pending, &mut o.s, handle) + { + if newer { + kind = ObjectKind::Unsupported; + } else { + handle_note = Some(format!("handles: {e}")); + } + } + kind + } + Err(e) => ObjectKind::Failed(e.to_string()), + }; + if handle_note.is_none() { + handle_note = fit_note; + } + + Ok(Object { + handle: Handle(handle), + type_code, + type_name: o.type_name, + owner: Handle(owner), + reactors, + xdictionary: Handle(xdictionary), + entity: o.common, + kind, + offset, + size: o.size, + note: handle_note, + raw: None, + xdata: o.xdata, + unknown_tags: Vec::new(), + }) +} + +/// A buffer holding `raw` as it sits in an objects section (size, +/// handle-stream size, data and a blank CRC), for [`open`]. +pub(crate) fn raw_buffer(raw: &RawDwgObject) -> Vec { + let mut w = crate::bits::BitWriter::new(); + w.ms(raw.data.len() as u32); + if raw.version >= V::R2010 { + w.mc_unsigned(raw.handle_stream_bits); + } + let mut out = w.into_bytes(); + out.extend_from_slice(&raw.data); + out.extend_from_slice(&[0, 0]); + out +} + +/// The undecoded bytes of the object whose size prefix starts at `offset`, +/// for keeping objects the core cannot decode. +pub(crate) fn raw(ver: DwgVersion, data: &[u8], offset: usize) -> Result { + let mut r = BitReader::new(data); + r.set_position(offset.checked_mul(8).ok_or_else(|| Error::format("offset overflow"))?)?; + let size = r.ms()? as usize; + let hsize = if ver >= V::R2010 { r.mc_unsigned()? } else { 0 }; + let start = r.position() / 8; + let end = start.checked_add(size).ok_or_else(|| Error::format("size overflow"))?; + let bytes = data.get(start..end).ok_or_else(|| Error::truncated("object runs past data"))?; + Ok(RawDwgObject { version: ver, handle_stream_bits: hsize, data: bytes.to_vec() }) +} + +fn decode_specific(code: u16, name: &str, s: &mut Streams) -> Result<(ObjectKind, Pending)> { + use ObjectKind as K; + let r = match code { + 0x01 => (K::Text(entities::text(s)?), Pending::None), + 0x02 => (K::Attribute(entities::attribute(s, false)?), Pending::None), + 0x03 => (K::Attribute(entities::attribute(s, true)?), Pending::None), + 0x04 => (K::BlockBegin { name: s.tv()? }, Pending::None), + 0x05 => (K::BlockEnd, Pending::None), + 0x06 => (K::SeqEnd, Pending::None), + 0x07 | 0x08 => { + let (ins, owned) = entities::insert(s, code == 0x08)?; + (K::Insert(ins), Pending::Insert { owned }) + } + 0x0A => (K::Vertex(entities::vertex_2d(s)?), Pending::None), + 0x0B => (K::Vertex(entities::vertex_3d(s, VertexKind::Vertex3d)?), Pending::None), + 0x0C => (K::Vertex(entities::vertex_3d(s, VertexKind::Mesh)?), Pending::None), + 0x0D => (K::Vertex(entities::vertex_3d(s, VertexKind::PfaceVertex)?), Pending::None), + 0x0E => (K::Vertex(entities::vertex_pface_face(s)?), Pending::None), + 0x0F => { + let (p, owned) = entities::polyline_2d(s)?; + (K::Polyline(p), Pending::Owned(owned)) + } + 0x10 => { + let (p, owned) = entities::polyline_3d(s)?; + (K::Polyline(p), Pending::Owned(owned)) + } + 0x11 => (K::Arc(entities::arc(s)?), Pending::None), + 0x12 => (K::Circle(entities::circle(s)?), Pending::None), + 0x13 => (K::Line(entities::line(s)?), Pending::None), + 0x14..=0x1A => (K::Dimension(entities::dimension(s, code)?), Pending::None), + 0x1B => (K::Point(entities::point(s)?), Pending::None), + 0x1C => (K::Face3d(entities::face3d(s)?), Pending::None), + 0x1D => { + let (p, owned) = entities::polyline_pface(s)?; + (K::Polyline(p), Pending::Owned(owned)) + } + 0x1E => { + let (p, owned) = entities::polyline_mesh(s)?; + (K::Polyline(p), Pending::Owned(owned)) + } + 0x1F | 0x20 => (K::Solid(entities::solid(s, code == 0x20)?), Pending::None), + 0x23 => (K::Ellipse(entities::ellipse(s)?), Pending::None), + 0x24 => (K::Spline(entities::spline(s)?), Pending::None), + 0x2C => (K::MText(entities::mtext(s)?), Pending::None), + 0x28 => (K::Ray(entities::construction_line(s)?), Pending::None), + 0x29 => (K::Xline(entities::construction_line(s)?), Pending::None), + 0x2D => (K::Leader(entities::leader(s)?), Pending::None), + 0x2E => (K::Tolerance(entities::tolerance(s)?), Pending::None), + 0x2F => (K::MLine(entities::mline(s)?), Pending::None), + 0x22 => { + let (v, frozen) = entities::viewport(s)?; + (K::PaperViewport(Box::new(v)), Pending::Viewport { frozen }) + } + 0x4D => (K::LwPolyline(entities::lwpolyline(s)?), Pending::None), + 0x4E => { + let (h, n) = entities::hatch(s)?; + (K::Hatch(h), Pending::Hatch { boundary_handles: n }) + } + 0x30 | 0x32 | 0x34 | 0x38 | 0x3C | 0x3E | 0x40 | 0x42 | 0x44 | 0x46 => { + let (c, n) = tables::control(s)?; + (K::Control(c), Pending::Control { entries: n, is_block_control: code == 0x30 }) + } + 0x31 => { + let (b, counts) = tables::block_header(s)?; + (K::BlockHeader(b), Pending::Block(counts)) + } + 0x33 => (K::Layer(tables::layer(s)?), Pending::None), + 0x35 => (tables::text_style(s)?, Pending::None), + 0x39 => (tables::linetype(s)?, Pending::None), + 0x43 => (K::NamedRecord(tables::appid(s)?), Pending::None), + 0x3D | 0x3F | 0x41 | 0x45 | 0x47 => (K::NamedRecord(tables::named_record(s)?), Pending::None), + c if c >= 500 => match name { + "LWPOLYLINE" => (K::LwPolyline(entities::lwpolyline(s)?), Pending::None), + "IMAGE" => (K::Image(Box::new(entities::raster_image(s)?)), Pending::None), + "WIPEOUT" => (K::Wipeout(Box::new(entities::raster_image(s)?)), Pending::None), + "HATCH" => { + let (h, n) = entities::hatch(s)?; + (K::Hatch(h), Pending::Hatch { boundary_handles: n }) + } + _ => (K::Unsupported, Pending::None), + }, + _ => (K::Unsupported, Pending::None), + }; + Ok(r) +} + +fn read_specific_handles(kind: &mut ObjectKind, pending: Pending, s: &mut Streams, own: u64) -> Result<()> { + let ver = s.ver; + match kind { + ObjectKind::Text(t) => t.style = Handle(s.h_abs(own)?), + ObjectKind::Attribute(a) => a.text.style = Handle(s.h_abs(own)?), + ObjectKind::MText(m) => m.style = Handle(s.h_abs(own)?), + ObjectKind::Insert(ins) => { + ins.block_header = Handle(s.h_abs(own)?); + if ins.has_attribs { + if ver <= V::R2000 { + ins.first_attrib = Handle(s.h_abs(own)?); + ins.last_attrib = Handle(s.h_abs(own)?); + } else if let Pending::Insert { owned } = pending { + let n = s.check_handle_count(owned, "attribute")?; + for _ in 0..n { + ins.attribs.push(Handle(s.h_abs(own)?)); + } + } + ins.seqend = Handle(s.h_abs(own)?); + } + } + ObjectKind::Polyline(p) => { + if ver <= V::R2000 { + p.first_vertex = Handle(s.h_abs(own)?); + p.last_vertex = Handle(s.h_abs(own)?); + } else if let Pending::Owned(owned) = pending { + let n = s.check_handle_count(owned, "vertex")?; + for _ in 0..n { + p.vertices.push(Handle(s.h_abs(own)?)); + } + } + p.seqend = Handle(s.h_abs(own)?); + } + ObjectKind::Dimension(d) => { + d.dimstyle = Handle(s.h_abs(own)?); + d.block = Handle(s.h_abs(own)?); + } + ObjectKind::Leader(l) => { + l.annotation = Handle(s.h_abs(own)?); + l.dimstyle = Handle(s.h_abs(own)?); + } + ObjectKind::Tolerance(t) => t.dimstyle = Handle(s.h_abs(own)?), + ObjectKind::MLine(m) => m.style = Handle(s.h_abs(own)?), + ObjectKind::Image(r) | ObjectKind::Wipeout(r) => { + r.definition = Handle(s.h_abs(own)?); + r.reactor = Handle(s.h_abs(own)?); + } + ObjectKind::PaperViewport(v) => { + if ver <= V::R14 { + let _header = s.h()?; + } else { + if let Pending::Viewport { frozen } = pending { + let n = s.check_handle_count(frozen, "viewport frozen layer")?; + for _ in 0..n { + v.frozen_layers.push(Handle(s.h_abs(own)?)); + } + } + v.clip_boundary = Handle(s.h_abs(own)?); + if ver == V::R2000 { + let _header = s.h()?; + } + v.named_ucs = Handle(s.h_abs(own)?); + v.base_ucs = Handle(s.h_abs(own)?); + if ver >= V::R2007 { + v.background = Handle(s.h_abs(own)?); + v.visual_style = Handle(s.h_abs(own)?); + v.shade_plot = Handle(s.h_abs(own)?); + v.sun = Handle(s.h_abs(own)?); + } + } + } + ObjectKind::Hatch(h) => { + // Boundary object handles, path by path. + if let Pending::Hatch { boundary_handles } = pending { + h.sources.clear(); + for count in boundary_handles { + let n = s.check_handle_count(count, "hatch boundary")?; + let mut path = Vec::with_capacity(n); + for _ in 0..n { + path.push(Handle(s.h_abs(own)?)); + } + h.sources.push(path); + } + if h.sources.iter().all(Vec::is_empty) { + h.sources.clear(); + } + } + } + ObjectKind::Control(c) => { + if let Pending::Control { entries, is_block_control } = pending { + let n = s.check_handle_count(entries, "table entry")?; + for _ in 0..n { + c.entries.push(Handle(s.h_abs(own)?)); + } + if is_block_control { + c.model_space = Handle(s.h_abs(own)?); + c.paper_space = Handle(s.h_abs(own)?); + } + } + } + ObjectKind::BlockHeader(b) => { + if let Pending::Block(counts) = pending { + let _null = s.h()?; + b.block_entity = Handle(s.h_abs(own)?); + if counts.lists_entities { + if ver <= V::R2000 { + b.first_entity = Handle(s.h_abs(own)?); + b.last_entity = Handle(s.h_abs(own)?); + } else { + let n = s.check_handle_count(counts.owned, "block entity")?; + for _ in 0..n { + b.entities.push(Handle(s.h_abs(own)?)); + } + } + } + b.endblk = Handle(s.h_abs(own)?); + if ver >= V::R2000 { + let n = s.check_handle_count(counts.inserts, "block insert")?; + for _ in 0..n { + let _insert = s.h()?; + } + b.layout = Handle(s.h_abs(own)?); + } + } + } + ObjectKind::Layer(l) => { + let _xref_block = s.h()?; + if ver >= V::R2000 { + let _plotstyle = s.h()?; + } + if ver >= V::R2007 { + let _material = s.h()?; + } + l.linetype = Handle(s.h_abs(own)?); + } + ObjectKind::Linetype(l) => { + let _xref_block = s.h()?; + // One shape file or text style per element (§20.4.58). + for e in l.elements.iter_mut() { + e.style = Handle(s.h_abs(own)?); + } + } + _ => {} + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::geom::Vec3; + use crate::read::model::{Groups, XrValue}; + + /// xorshift64* — a tiny deterministic generator for robustness tests. + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn bytes(&mut self, n: usize) -> Vec { + (0..n).map(|_| self.next() as u8).collect() + } + } + + /// The STYLE example printed in the ODA specification (§20.4.56.1), an + /// R14 object, decodes to the values it shows: STANDARD, font txt. + #[test] + fn the_specifications_style_example_decodes() { + let bytes = [ + 0x25, 0x00, 0x4D, 0x40, 0x44, 0x20, 0x20, 0x10, 0x00, 0x09, 0x08, 0x53, 0x54, 0x41, 0x4E, 0x44, 0x41, 0x52, 0x44, 0xC2, 0x60, 0x02, 0x6A, + 0x66, 0x66, 0x66, 0x66, 0x67, 0x24, 0xFD, 0x03, 0x74, 0x78, 0x74, 0x90, 0x40, 0xCC, 0x14, 0x28, 0xEC, 0x6E, + ]; + let ctx = DecodeCtx { ver: V::R14, codepage: 30, classes: &[] }; + let o = decode(&ctx, &bytes, 0).unwrap(); + assert_eq!(o.type_name, "STYLE"); + assert_eq!(o.handle, Handle(0x10)); + match &o.kind { + ObjectKind::TextStyle(t) => { + assert_eq!(t.name, "STANDARD"); + assert_eq!(t.font_file, "txt"); + assert_eq!(t.bigfont_file, ""); + assert_eq!(t.height, 0.0); + assert_eq!(t.width_factor, 1.0); + assert_eq!(t.oblique, 0.0); + assert_eq!(t.last_height, 0.2); + } + other => panic!("{other:?}"), + } + assert_eq!(o.note, None, "handles read cleanly"); + } + + /// The TOLERANCE example printed in the ODA specification (§20.4.49.1), + /// an R14 object (handle 010C). + #[test] + fn the_specifications_tolerance_example_decodes() { + let bytes = [ + 0x65, 0x00, 0x4B, 0x80, 0x80, 0x43, 0x27, 0x18, 0x10, 0x00, 0x05, 0x5B, 0x40, 0x56, 0xBD, 0x1B, 0x81, 0xE8, 0x56, 0x39, 0xF8, 0x15, 0xAF, + 0x46, 0xE0, 0x7A, 0x15, 0x6E, 0x7E, 0x51, 0x19, 0xA0, 0x47, 0x00, 0xC7, 0x13, 0xA0, 0x18, 0x09, 0x38, 0x21, 0x8A, 0x5E, 0xA1, 0x48, 0x13, + 0x54, 0xA5, 0xCF, 0x6B, 0x88, 0xCC, 0xEC, 0x8E, 0x87, 0x6D, 0x4F, 0xA4, 0xA4, 0xAE, 0xCF, 0x6B, 0x88, 0xCC, 0xEC, 0x8E, 0x87, 0x6D, 0xCF, + 0xAC, 0x2E, 0x6C, 0x8C, 0xCF, 0x6B, 0x88, 0xCC, 0xEC, 0x8E, 0x87, 0x6D, 0xAF, 0xA4, 0xA4, 0xAE, 0xC4, 0xA4, 0xAE, 0xC4, 0xA4, 0xAE, 0xC4, + 0xA4, 0xAE, 0xC6, 0x0A, 0x21, 0xF8, 0x20, 0x4C, 0x0A, 0x23, 0xB4, 0x45, 0x2F, + ]; + let ctx = DecodeCtx { ver: V::R14, codepage: 30, classes: &[] }; + let o = decode(&ctx, &bytes, 0).unwrap(); + assert_eq!(o.type_name, "TOLERANCE"); + assert_eq!(o.handle, Handle(0x10C)); + match &o.kind { + ObjectKind::Tolerance(t) => { + assert_eq!(t.text, "{\\Fgdt;j}%%v{\\Fgdt;n}asdf{\\Fgdt;m}%%v%%v%%v%%v"); + assert_eq!(t.r14, Some((0, 0.18, 0.09)), "DIMTXT and DIMGAP's defaults"); + assert!((t.insertion.x - 11.777_355_618_798_37).abs() < 1e-12); + assert!((t.insertion.y - 3.369_785_403_870_281_5).abs() < 1e-12); + assert_eq!(t.x_direction, Vec3::X); + assert_eq!(t.extrusion, Vec3::Z); + assert_eq!(t.dimstyle, Handle(0x1D)); + } + other => panic!("{other:?}"), + } + assert_eq!(o.note, None, "handles read cleanly"); + } + + /// The MLINE example printed in the ODA specification (§20.4.50.1), an + /// R14 object (handle 010D). + #[test] + fn the_specifications_mline_example_decodes() { + let bytes = hex( + "e4004bc0804366c83000055b200461ad1ef213a88a0181933c67d42bc07f528081206461ad1ef213a88a0181933c67d42bc07f13e9cf70de473cc7e4f86a7b9c002f39fc4e86a7b9c002f3df93e9cf70de473cc7f2055204000000000000785fd038dd69b078de3880440a1c33bde105204062c65315c95771f9fb6cf09b58b3ab7f05473cf47b0b79b7e08f921ddcd12f79fc81548118d6ba82c020de77f42750a165460292a013161543da240028101cb194c57255dc7e7f5b3c26d62ceadfc765b3c26d62cea9f820b194c57255dc7f2055204000000000000785fd182887c05087288e4c9188", + ); + let ctx = DecodeCtx { ver: V::R14, codepage: 30, classes: &[] }; + let o = decode(&ctx, &bytes, 0).unwrap(); + assert_eq!((o.type_name.as_str(), o.handle), ("MLINE", Handle(0x10D))); + assert_eq!(o.note, None, "handles read cleanly"); + let ObjectKind::MLine(m) = &o.kind else { panic!("{:?}", o.kind) }; + // A three-vertex multiline in a two-element style (STANDARD, one + // unit apart), top justified, open: unit directions, miters at + // right angles to the first and last segments, each element's + // start along the miter (0, then 1 unit or more at the bend). + assert_eq!((m.scale, m.justification, m.flags, m.lines_in_style), (1.0, 0, 1, 2)); + assert_eq!(m.style, Handle(0x1C)); + assert_eq!(m.base, m.vertices[0].point); + assert_eq!(m.vertices.len(), 3); + for v in &m.vertices { + assert!((v.direction.length() - 1.0).abs() < 1e-12); + assert!((v.miter.length() - 1.0).abs() < 1e-12); + assert_eq!(v.params.len(), 2); + assert!(v.params.iter().all(|(seg, fill)| seg.len() == 2 && fill.is_empty())); + } + assert!(m.vertices[0].direction.dot(m.vertices[0].miter).abs() < 1e-12); + assert_eq!(m.vertices[0].params[1].0, vec![-1.0, 0.0]); + assert!((m.vertices[1].params[1].0[0] + 1.188_965_882_476_041_6).abs() < 1e-12); + assert!((m.vertices[2].point.x - 10.510_839_768_060_261).abs() < 1e-12); + } + + /// The raster examples printed in the ODA specification, R14 objects + /// whose classes are numbered as in the file they came from: IMAGE + /// (§20.4.80.1, class 1F9), IMAGEDEF (§20.4.81.1, 1F7), IMAGEDEF_REACTOR + /// (§20.4.82.1, 1F8) and RASTERVARIABLES (§20.4.91.1, 1F5). + fn raster_example(name: &str) -> (Vec, Vec) { + let (hex_bytes, number, entity) = match name { + "IMAGE" => ( + "09013e40405b6c600000046000000008000004200000003000000028000006b56e620baae102000372c563f8d8aa000000000000000006b56e620baae102000372c563f8d8ca000000000000000006b56e620baae112000372c563f8d8ca000000000000000006b56e620baae112000372c563f8d8aa000000000000000006b56e620baae102000372c563f8d8aa000000000000000006d038000280db46b56e620baae1020000dcb158fe362a810000000000001007f4000000000053109e0000000000001007f0000000000003020000000000000302020e32320040400000000000382fc00000000000382fc0000000003817d000000000003817d0105ecc1443f0416843545acc5b3f0d2a", + 0x1F9, + true, + ), + "IMAGEDEF" => ( + "4e003dc0405ae3b02000040a0000000000006040000000000000604046d0ce9715d2539395171199585d1a195c95195e1d1d5c994b989b5c205e25d4eb0752bac7fe25d4eb0752bac7f0082d482d8611e823", + 0x1F7, + false, + ), + "IMAGEDEF_REACTOR" => ("0c003e00405b2500000009026030a113", 0x1F8, false), + _ => ("11003d404056a66000000406405019010430c0dcd2", 0x1F5, false), + }; + let classes = vec![ClassDef { number, dxf_name: name.into(), item_class_id: if entity { 0x1F2 } else { 0x1F3 }, ..Default::default() }]; + (hex(hex_bytes), classes) + } + + #[test] + fn the_specifications_image_example_decodes() { + let (bytes, classes) = raster_example("IMAGE"); + let ctx = DecodeCtx { ver: V::R14, codepage: 30, classes: &classes }; + let o = decode(&ctx, &bytes, 0).unwrap(); + assert_eq!((o.type_name.as_str(), o.handle), ("IMAGE", Handle(0x6D))); + assert_eq!(o.note, None, "handles read cleanly"); + let ObjectKind::Image(r) = &o.kind else { panic!("{:?}", o.kind) }; + // A 128 × 128 pixel image, 1/128 unit a pixel, unclipped: its clip + // rectangle is the whole image, pixel centres at whole numbers. + assert_eq!(r.size, crate::read::geom::Vec2::new(128.0, 128.0)); + assert_eq!(r.u, Vec3::new(0.0078125, 0.0, 0.0)); + assert!((r.v.y - 0.0078125).abs() < 1e-15 && r.v.x.abs() < 1e-15); + assert!((r.insertion.x - 8.180_582_100_138_889).abs() < 1e-12); + assert!((r.insertion.y - 5.276_854_222_199_745).abs() < 1e-12); + assert_eq!((r.clip_type, r.clipping), (1, false)); + assert_eq!(r.clip, vec![crate::read::geom::Vec2::new(-0.5, -0.5), crate::read::geom::Vec2::new(127.5, 127.5)]); + assert_eq!((r.display, r.brightness, r.contrast, r.fade), (7, 50, 50, 0)); + assert_eq!(r.definition, Handle(0x6B), "its IMAGEDEF, the next example"); + assert_eq!(r.reactor, Handle(0x6C), "its IMAGEDEF_REACTOR"); + } + + /// Decodes a spec example of an object kept as DXF groups. + fn groups_example(name: &str) -> Groups { + let (bytes, classes) = raster_example(name); + let ver = V::R14; + let mut o = decode(&DecodeCtx { ver, codepage: 30, classes: &classes }, &bytes, 0).unwrap(); + assert_eq!(o.type_name, name); + o.raw = Some(raw(ver, &bytes, 0).unwrap()); + let lookup = crate::read::styles::Lookup::empty(); + match crate::read::nongraphic::decode_groups(&o, &classes, 30, &lookup) { + Some(Ok(g)) => g, + other => panic!("{other:?}"), + } + } + + #[test] + fn the_specifications_image_object_examples_decode() { + use crate::read::geom::Vec3 as P; + let def = groups_example("IMAGEDEF"); + assert_eq!( + def.items, + vec![ + (100, XrValue::Str("AcDbRasterImageDef".into())), + (90, XrValue::Int32(0)), + (1, XrValue::Str("C:\\WINNT\\FeatherTexture.bmp".into())), + (10, XrValue::Point(P::new(128.0, 128.0, 0.0))), + (11, XrValue::Point(P::new(0.352858149123434, 0.352858149123434, 0.0))), + (280, XrValue::Int8(1)), + (281, XrValue::Int8(2)), + ], + "128 × 128 pixels, loaded, centimetres" + ); + let reactor = groups_example("IMAGEDEF_REACTOR"); + assert_eq!(reactor.items, vec![(100, XrValue::Str("AcDbRasterImageDefReactor".into())), (90, XrValue::Int32(2))]); + let vars = groups_example("RASTERVARIABLES"); + assert_eq!( + vars.items, + vec![ + (100, XrValue::Str("AcDbRasterVariables".into())), + (90, XrValue::Int32(0)), + (70, XrValue::Int16(1)), + (71, XrValue::Int16(1)), + (72, XrValue::Int16(0)), + ], + "frame shown, high quality, no units" + ); + } + + /// An R2010+ object as it sits in the objects section: its size (MS), + /// its handle-stream size in bits (MC), then the object. + fn frame(handle_bits: u16, body: &[u8]) -> Vec { + let n = body.len() as u16; + assert!(n < 0x8000); + let mut out = vec![n as u8, (n >> 8) as u8]; + if handle_bits < 0x80 { + out.push(handle_bits as u8); + } else { + out.push((handle_bits & 0x7F) as u8 | 0x80); + out.push((handle_bits >> 7) as u8); + } + out.extend_from_slice(body); + out.extend_from_slice(&[0, 0]); // CRC (not checked here) + out + } + + fn hex(s: &str) -> Vec { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect() + } + + /// Table records from an AC1032 file saved by AutoCAD LT 2026 (generic + /// records: layer "0", application "ACAD", the paper-space block). From + /// R2007 a table record stores no 64-flag and no xref-dependent bit + /// (see `tables::record_common_flags`); read with them, none of these + /// decodes. Each must also end exactly where its strings begin. + #[test] + fn r2018_table_records_from_a_real_file() { + let ctx = DecodeCtx { ver: V::R2018, codepage: 30, classes: &[] }; + let appid = frame(27, &hex("10c044aa8010441004300410044004a00a084a87")); + let o = decode(&ctx, &appid, 0).unwrap(); + assert_eq!(o.handle, Handle(0x12)); + assert_eq!(o.owner, Handle(0x9)); + assert_eq!(o.note, None); + match &o.kind { + ObjectKind::NamedRecord(r) => assert_eq!(r.name, "ACAD"), + other => panic!("{other:?}"), + } + + let layer = frame(101, &hex("0cc044288f0038070000c300404c0006802820463cca0a21ea330a22ca1f")); + let o = decode(&ctx, &layer, 0).unwrap(); + assert_eq!(o.handle, Handle(0x10)); + assert_eq!(o.note, None); + match &o.kind { + ObjectKind::Layer(l) => { + assert_eq!(l.name, "0"); + assert_eq!(l.color, crate::read::model::Color::Index(7)); + assert!(!l.off && !l.frozen && !l.locked && l.plot); + assert_eq!(l.flags, 0x3F0); + assert_eq!(l.linetype, Handle(0x16)); + } + other => panic!("{other:?}"), + } + + let block = frame(77, &hex("0c40562a815401500430a80140018401c0019401c8017c014c01c00184018c019402b38028202a062b462b6a2b3f")); + let o = decode(&ctx, &block, 0).unwrap(); + assert_eq!(o.handle, Handle(0x58)); + assert_eq!(o.note, None); + match &o.kind { + ObjectKind::BlockHeader(b) => { + assert_eq!(b.name, "*Paper_Space"); + assert!(b.entities.is_empty()); + assert_eq!(b.base_point, crate::read::geom::Vec3::ZERO); + } + other => panic!("{other:?}"), + } + } + + /// Random bytes must produce errors or objects, never a panic. This + /// exercises every decoder path reachable from random type codes. + #[test] + fn random_objects_do_not_panic() { + let classes = vec![ + ClassDef { number: 500, dxf_name: "LWPOLYLINE".into(), item_class_id: 0x1F2, ..Default::default() }, + ClassDef { number: 501, dxf_name: "IMAGE".into(), item_class_id: 0x1F2, ..Default::default() }, + ClassDef { number: 502, dxf_name: "WIPEOUT".into(), item_class_id: 0x1F2, ..Default::default() }, + ]; + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + for ver in [V::R14, V::R2000, V::R2004, V::R2007, V::R2010, V::R2013, V::R2018] { + let ctx = DecodeCtx { ver, codepage: 30, classes: &classes }; + for i in 0..4000 { + let len = 4 + (rng.next() % 600) as usize; + let mut buf = rng.bytes(len); + // Plant a plausible size and a known type code half the time + // so decoding gets past the header into type-specific code. + if i % 2 == 0 && len > 8 { + let size = (len - 4) as u16 & 0x7FFF; + buf[0] = size as u8; + buf[1] = (size >> 8) as u8; + } + let _ = decode(&ctx, &buf, 0); + let _ = peek(ver, &buf, 0); + } + } + } +} diff --git a/crates/dwg/src/read/objmap.rs b/crates/dwg/src/read/objmap.rs new file mode 100644 index 00000000..b3bc16ce --- /dev/null +++ b/crates/dwg/src/read/objmap.rs @@ -0,0 +1,78 @@ +//! The object map (AcDb:Handles): handle → object location. +//! +//! Written from knowledge of the spec, chapter 23. The map is a series of +//! blocks, each starting with a big-endian 16-bit size (which counts the +//! two size bytes but not the trailing two-byte CRC), holding pairs of +//! modular chars: handle delta (never negative) and location delta +//! (signed). A block of size 2 ends the map. +//! +//! Whether the running handle/location restart at zero in every block is +//! not confirmed, so both readings are produced and the caller keeps the +//! one whose entries match the objects' own handles. + +use crate::bits::BitReader; +use crate::read::error::{Error, Result}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct MapEntry { + pub handle: u64, + pub location: i64, +} + +pub(crate) fn parse(data: &[u8], reset_per_block: bool) -> Result> { + let mut out = Vec::new(); + let mut pos = 0usize; + let mut last_handle: u64 = 0; + let mut last_loc: i64 = 0; + let mut blocks = 0usize; + while pos + 2 <= data.len() { + let size = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize; + if size <= 2 { + break; + } + let body_end = pos + size; + if body_end > data.len() { + return Err(Error::truncated(format!("object map block at {pos} claims {size} bytes, only {} left", data.len() - pos))); + } + if reset_per_block { + last_handle = 0; + last_loc = 0; + } + let mut r = BitReader::with_bounds(data, (pos + 2) * 8, body_end * 8); + while r.remaining() >= 16 { + let dh = r.mc_unsigned()?; + let dl = r.mc_signed()?; + last_handle = last_handle.wrapping_add(dh); + last_loc = last_loc.wrapping_add(dl); + out.push(MapEntry { handle: last_handle, location: last_loc }); + } + pos = body_end + 2; // skip the CRC + blocks += 1; + if blocks > 10_000_000 { + return Err(Error::format("object map block runaway")); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_blocks_with_reset() { + // Block 1 (size 7 = 2 size bytes + 5 data bytes): (+1, +100), (+2, +20). + // 100 has bit 0x40 set, so as a signed MC it takes two bytes: E4 00. + // Block 2 (size 5): (+5, +300) with 300 = AC 02. Each block is + // followed by a two-byte CRC; a size-2 block ends the map. + let data = [ + 0x00, 0x07, 0x01, 0xE4, 0x00, 0x02, 0x14, 0xAA, 0xBB, // block 1 + CRC + 0x00, 0x05, 0x05, 0xAC, 0x02, 0xCC, 0xDD, // block 2 + CRC + 0x00, 0x02, // end + ]; + let reset = parse(&data, true).unwrap(); + assert_eq!(reset, vec![MapEntry { handle: 1, location: 100 }, MapEntry { handle: 3, location: 120 }, MapEntry { handle: 5, location: 300 },]); + let running = parse(&data, false).unwrap(); + assert_eq!(running[2], MapEntry { handle: 8, location: 420 }); + } +} diff --git a/crates/dwg/src/read/probe.rs b/crates/dwg/src/read/probe.rs new file mode 100644 index 00000000..8735aafa --- /dev/null +++ b/crates/dwg/src/read/probe.rs @@ -0,0 +1,313 @@ +//! Study aids for files other programs wrote: run with +//! `cargo test -p cad-core probe -- --ignored --nocapture`. + +use super::r2004; +use std::path::PathBuf; + +fn corpus(name: &str) -> Option> { + let p = PathBuf::from(std::env::var_os("MI201_CORPUS")?).join(name); + std::fs::read(p).ok() +} + +pub(crate) fn hex_dump(bytes: &[u8]) -> String { + let mut o = String::new(); + for (i, chunk) in bytes.chunks(16).enumerate() { + o.push_str(&format!("{:06x} ", i * 16)); + for b in chunk { + o.push_str(&format!("{b:02x} ")); + } + o.push_str(" "); + for &b in chunk { + o.push(if b.is_ascii_graphic() || b == b' ' { b as char } else { '.' }); + } + o.push('\n'); + } + o +} + +#[test] +#[ignore] +fn probe_container_layout() { + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + println!("{}", r2004::describe(&file)); + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + for (name, bytes) in &c.others { + println!("== {name} ({} bytes)\n{}", bytes.len(), hex_dump(&bytes[..bytes.len().min(2048)])); + } + println!("== handles ({} bytes)\n{}", c.handles.len(), hex_dump(&c.handles)); +} + +/// Every object of the 2018 file: type, handle, size, and the handle +/// references in its handle stream as (code, value). +#[test] +#[ignore] +fn probe_object_handles() { + use crate::bits::BitReader; + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + let d = super::read_bytes(&file).unwrap(); + println!("objects section starts {:02x?}", &c.objects[..8]); + for o in d.objects.values() { + let data = &c.objects; + let mut r = BitReader::new(data); + r.set_position(o.offset * 8).unwrap(); + let size = r.ms().unwrap() as usize; + let hsize = r.mc_unsigned().unwrap() as usize; + let start = r.position() / 8; + let obj = &data[start..start + size]; + let crc = &data[start + size..start + size + 2]; + let bitsize = size * 8 - hsize; + let mut h = BitReader::with_bounds(obj, bitsize, size * 8); + let mut refs = Vec::new(); + while h.remaining() >= 8 { + match h.handle() { + Ok(x) => refs.push(format!("{:X}.{:X}", x.code, x.value)), + Err(_) => break, + } + } + // string stream flag + let mut f = BitReader::new(obj); + f.set_position(bitsize - 1).unwrap(); + let has_strings = f.b().unwrap(); + println!( + "{:6X} {:22} off {:5} size {:4} hbits {:4} strs {} crc {:02x?} refs [{}]", + o.handle.0, + o.type_name, + o.offset, + size, + hsize, + has_strings as u8, + crc, + refs.join(" ") + ); + } +} + +/// Header and classes sections: ends, sizes and CRC checks. +#[test] +#[ignore] +fn probe_header_classes() { + use crate::crc::crc16; + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + for (name, s) in [("header", c.header.unwrap()), ("classes", c.classes.unwrap())] { + let n = s.len(); + println!("== {name}: {n} bytes\nstart:\n{}end:\n{}", hex_dump(&s[..64]), hex_dump(&s[n - 48..])); + let size = u32::from_le_bytes(s[16..20].try_into().unwrap()) as usize; + let hi = u32::from_le_bytes(s[20..24].try_into().unwrap()); + println!("size {size} hi {hi}; body+crc+sentinel = {}", 24 + size + 2 + 16); + let crc_at = 24 + size; + let stored = u16::from_le_bytes([s[crc_at], s[crc_at + 1]]); + for (label, from) in [("from size", 16usize), ("from body", 24)] { + println!(" crc {label}: {:04x} (stored {stored:04x})", crc16(0xC0C1, &s[from..crc_at])); + } + let bitsize = u32::from_le_bytes(s[24..28].try_into().unwrap()); + println!(" first RL of body (bitsize?) {bitsize} = {} bytes + {} bits; body bits {}", bitsize / 8, bitsize % 8, size * 8); + } +} + +/// The string stream of a few objects: BS length and the UTF-16 units. +#[test] +#[ignore] +fn probe_string_streams() { + use super::streams::string_stream; + use crate::bits::BitReader; + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + for off in [11054usize, 11090, 10031, 11286, 11645] { + let data = &c.objects; + let mut r = BitReader::new(data); + r.set_position(off * 8).unwrap(); + let size = r.ms().unwrap() as usize; + let hsize = r.mc_unsigned().unwrap() as usize; + let start = r.position() / 8; + let obj = &data[start..start + size]; + let endbit = size * 8 - hsize; + let (mut s, st) = string_stream(obj, endbit).unwrap().unwrap(); + let mut out = Vec::new(); + while s.remaining() >= 2 { + let len = s.bs().unwrap() as usize; + let mut units = Vec::new(); + for _ in 0..len { + units.push(s.rs().unwrap()); + } + out.push(format!("len {len} {:?}", String::from_utf16_lossy(&units))); + if s.remaining() < 2 { + break; + } + } + println!("obj at {off}: strings start bit {st}, endbit {endbit}: {}", out.join(" | ")); + } +} + +#[test] +#[ignore] +fn probe_nongraphic() { + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let d = super::read_bytes(&file).unwrap(); + for o in d.objects.values() { + if let Some(r) = super::nongraphic::decode(o, &d.classes, d.codepage) { + println!("{:X} {} owner {:X} reactors {:?} xdic {:X}: {:?}", o.handle.0, o.type_name, o.owner.0, o.reactors, o.xdictionary.0, r); + } + } +} + +/// Page checksums, padding and the bytes after the system pages, as +/// AutoCAD wrote them. +#[test] +#[ignore] +fn probe_page_details() { + use crate::crc::page_checksum; + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let u32_at = |o: usize| u32::from_le_bytes(file[o..o + 4].try_into().unwrap()); + let magic = r2004::magic_sequence(0x100); + println!("0xEC..0x100 == magic[0xEC..0x100]: {}", file[0xEC..0x100] == magic[0xEC..0x100]); + // Data pages (address, from the layout probe). + for a in [0x100usize, 0x1a0, 0x13e0, 0x14a0, 0x4760] { + let m = 0x4164_536Bu32 ^ a as u32; + let mut hdr: Vec = (0..8).flat_map(|i| (u32_at(a + i * 4) ^ m).to_le_bytes()).collect(); + let size = u32::from_le_bytes(hdr[8..12].try_into().unwrap()) as usize; + let stored_h = u32::from_le_bytes(hdr[24..28].try_into().unwrap()); + let stored_d = u32::from_le_bytes(hdr[28..32].try_into().unwrap()); + let data = &file[a + 32..a + 32 + size]; + let dsum = page_checksum(0, data); + hdr[24..28].fill(0); + let hsum = page_checksum(dsum, &hdr); + let mut hdr0 = hdr.clone(); + hdr0[28..32].fill(0); + let hsum0 = page_checksum(dsum, &hdr0); + let end = a + 32 + size; + let page = u32::from_le_bytes(hdr[12..16].try_into().unwrap()) as usize; + let pad = &file[end..a + page]; + let pos = magic.windows(pad.len().max(1)).position(|w| w == pad); + println!( + "page {a:#x}: data sum {dsum:#x} stored {stored_d:#x}; header sum {hsum:#x} (with data sum field) {hsum0:#x} (zeroed) stored {stored_h:#x}; pad {} bytes {:02x?} found in magic at {:?}", + pad.len(), + pad, + pos + ); + } + for a in [0x4b20usize, 0x4d40] { + let comp = u32_at(a + 8) as usize; + let end = a + 20 + comp; + println!("system page {a:#x}: after data {:02x?}", &file[end..(end + 40).min(file.len())]); + } +} + +#[test] +#[ignore] +fn probe_other_containers() { + for name in ["mi201-r2004.dwg", "mi201-r2010.dwg", "mi201-r2013.dwg"] { + let Some(file) = corpus(name) else { continue }; + println!("===== {name}\n{}", r2004::describe(&file)); + } +} + +/// What fills each data page past its section's content. +#[test] +#[ignore] +fn probe_page_padding() { + use crate::lz77; + let Some(file) = corpus("mi201-r2018.dwg") else { return }; + let u32_at = |o: usize| u32::from_le_bytes(file[o..o + 4].try_into().unwrap()); + // (address, section size, compressed) + for (a, size, comp) in [ + (0x100usize, 0x4e, false), + (0x1a0, 0x545, false), + (0x9c0, 0x2ce, false), + (0xce0, 0x522, false), + (0x1280, 0xcc, true), + (0x13e0, 0x10, true), + (0x14a0, 0x474d, true), + (0x3ca0, 0x59, true), + (0x3d80, 6, true), + (0x3e40, 0x232, true), + (0x4120, 0x546, true), + (0x4660, 0x81, true), + (0x4760, 0x36c, true), + ] { + let m = 0x4164_536Bu32 ^ a as u32; + let ds = (u32_at(a + 8) ^ m) as usize; + let body = &file[a + 32..a + 32 + ds]; + let data = if comp { lz77::decompress(body, 0x10_0000).unwrap() } else { body.to_vec() }; + let tail = &data[size.min(data.len())..]; + let nz = tail.iter().filter(|&&b| b != 0).count(); + println!( + "page {a:#x}: stored {ds:#x}, decompressed {:#x}, content {size:#x}, tail {} bytes, nonzero {nz}; tail starts {:02x?}", + data.len(), + tail.len(), + &tail[..tail.len().min(24)] + ); + if comp && a == 0x3d80 { + println!(" compressed bytes {:02x?}", body); + } + } +} + +/// `DWGFILE=path cargo test probe_describe_file -- --ignored --nocapture` +#[test] +#[ignore] +fn probe_describe_file() { + let Ok(p) = std::env::var("DWGFILE") else { return }; + let file = std::fs::read(p).unwrap(); + println!("{}", r2004::describe(&file)); + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + for (name, bytes) in &c.others { + println!("== {name} ({} bytes)\n{}", bytes.len(), hex_dump(&bytes[..bytes.len().min(256)])); + } +} + +/// `DWG=path cargo test probe_any -- --ignored --nocapture` +#[test] +#[ignore] +fn probe_any() { + let Ok(p) = std::env::var("DWG") else { return }; + let file = std::fs::read(p).unwrap(); + println!("{}", r2004::describe(&file)); + let c = r2004::read(&file, super::DwgVersion::R2018).unwrap(); + for (name, bytes) in &c.others { + println!("== {name} ({} bytes)\n{}", bytes.len(), hex_dump(&bytes[..bytes.len().min(512)])); + } + let h = c.header.as_ref().unwrap(); + println!("== header first 32 {:02x?}\n last 40 {:02x?}", &h[..32], &h[h.len() - 40..]); + println!("== objects first 16 {:02x?} len {}", &c.objects[..16], c.objects.len()); +} + +#[test] +#[ignore] +fn probe_header_tails() { + use crate::bits::BitReader; + for (name, ver) in [ + ("mi201-r2004.dwg", super::DwgVersion::R2004), + ("mi201-r2010.dwg", super::DwgVersion::R2010), + ("mi201-r2013.dwg", super::DwgVersion::R2013), + ("mi201-r2018.dwg", super::DwgVersion::R2018), + ] { + let Some(file) = corpus(name) else { continue }; + let c = r2004::read(&file, ver).unwrap(); + let s = c.header.as_ref().unwrap(); + let size = u32::from_le_bytes(s[16..20].try_into().unwrap()) as usize; + let off = if ver >= super::DwgVersion::R2010 { 24 } else { 20 }; + let body = &s[off..off + size]; + if ver < super::DwgVersion::R2007 { + println!("{name}: size {size}, last 16 {:02x?}", &body[size - 16..]); + continue; + } + let endbit = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize; + let mut r = BitReader::with_bounds(body, endbit, size * 8); + let mut refs = Vec::new(); + while r.remaining() >= 8 { + match r.handle() { + Ok(h) if h.code <= 5 => refs.push(format!("{:X}.{:X}", h.code, h.value)), + _ => break, + } + } + println!("{name}: size {size} endbit {endbit}, {} refs, last refs {:?}", refs.len(), &refs[refs.len().saturating_sub(4)..]); + let mut t = r.clone(); + let mut tail = String::new(); + while t.remaining() > 0 { + tail.push(if t.b().unwrap() { '1' } else { '0' }); + } + println!(" tail {} bits {tail}", tail.len()); + } +} diff --git a/crates/dwg/src/read/r2000.rs b/crates/dwg/src/read/r2000.rs new file mode 100644 index 00000000..dc02f11b --- /dev/null +++ b/crates/dwg/src/read/r2000.rs @@ -0,0 +1,75 @@ +//! R13–R15 container (AC1012, AC1014, AC1015): a flat file with a table +//! of section locators at the start. +//! +//! Spec §3 "R13-R15 DWG FILE FORMAT ORGANIZATION" (verified against the +//! spec text). + +use super::container::Container; +use super::section::FILE_HEADER_END; +use super::version::DwgVersion; +use crate::crc::{crc16, file_header_crc_xor}; +use crate::read::error::{Error, Result}; +use crate::read::model::{Diagnostic, SectionInfo, Severity}; + +fn u16_at(d: &[u8], o: usize) -> Option { + Some(u16::from_le_bytes(d.get(o..o + 2)?.try_into().ok()?)) +} +fn u32_at(d: &[u8], o: usize) -> Option { + Some(u32::from_le_bytes(d.get(o..o + 4)?.try_into().ok()?)) +} + +pub(crate) fn read(file: &[u8], _ver: DwgVersion) -> Result { + let short = || Error::truncated("file header is incomplete"); + let maintenance = *file.get(0x0B).ok_or_else(short)?; + let codepage = u16_at(file, 0x13).ok_or_else(short)?; + let n = u32_at(file, 0x15).ok_or_else(short)? as usize; + if n == 0 || n > 64 { + return Err(Error::format(format!("implausible section-locator count {n}"))); + } + let mut notes = Vec::new(); + let mut records = Vec::with_capacity(n); + for i in 0..n { + let base = 0x19 + i * 9; + let number = *file.get(base).ok_or_else(short)?; + let seeker = u32_at(file, base + 1).ok_or_else(short)? as usize; + let size = u32_at(file, base + 5).ok_or_else(short)? as usize; + records.push((number, seeker, size)); + } + let crc_pos = 0x19 + n * 9; + if let Some(stored) = u16_at(file, crc_pos) { + let computed = crc16(0, &file[..crc_pos]) ^ file_header_crc_xor(n as u32); + if computed != stored { + notes.push(Diagnostic { severity: Severity::Info, message: format!("file header CRC {stored:#06X} != computed {computed:#06X}") }); + } + } + if file.get(crc_pos + 2..crc_pos + 18) != Some(&FILE_HEADER_END[..]) { + notes.push(Diagnostic { severity: Severity::Warning, message: "file header end sentinel not found".into() }); + } + + let slice = |number: u8| -> Option> { + let &(_, seeker, size) = records.iter().find(|r| r.0 == number)?; + let end = seeker.checked_add(size)?; + file.get(seeker..end).map(|s| s.to_vec()) + }; + let name = |number: u8| match number { + 0 => "Header", + 1 => "Classes", + 2 => "Object map", + 3 => "Special table", + 4 => "Template", + _ => "Unknown", + }; + let sections = records + .iter() + .map(|&(num, _, size)| SectionInfo { + name: format!("{} (record {num})", name(num)), + size: size as u64, + pages: 1, + compressed: false, + encrypted: false, + }) + .collect(); + + let handles = slice(2).ok_or_else(|| Error::format("object map locator (record 2) missing or out of range"))?; + Ok(Container { maintenance, codepage, header: slice(0), classes: slice(1), handles, objects: file.to_vec(), sections, others: Vec::new(), notes }) +} diff --git a/crates/dwg/src/read/r2004.rs b/crates/dwg/src/read/r2004.rs new file mode 100644 index 00000000..b1774405 --- /dev/null +++ b/crates/dwg/src/read/r2004.rs @@ -0,0 +1,416 @@ +//! R2004-family container (AC1018, AC1024, AC1027, AC1032): an encrypted +//! file header, a page map, a section map and compressed data pages. +//! +//! Spec §4.1–§4.7 (verified against the spec text). R2010, R2013 and R2018 +//! use the same container (spec chapters 6–8). + +use super::container::Container; +use super::version::DwgVersion; +use crate::crc::{crc32, page_checksum}; +use crate::lz77; +use crate::read::error::{Error, ErrorKind, Result}; +use crate::read::model::{Diagnostic, SectionInfo, Severity}; +use std::collections::HashMap; + +const FILE_ID: &[u8; 12] = b"AcFssFcAJMB\0"; +const PAGE_MAP_TYPE: u32 = 0x4163_0E3B; +const SECTION_MAP_TYPE: u32 = 0x4163_003B; +const DATA_PAGE_TYPE: u32 = 0x4163_043B; +const PAGE_MASK: u32 = 0x4164_536B; +/// Refuse to allocate absurd section sizes from corrupt maps. +const MAX_SECTION: u64 = 2 * 1024 * 1024 * 1024; +/// What all of a file's sections together may declare, as a multiple of the file's size. A +/// section's size is only a claim of its map: a damaged or hostile map can declare gigabytes in +/// a file of a few kilobytes. AutoCAD's own files hold one to three times their size (the MI-201 +/// corpus, 2004 to 2018, measured 1.2 to 3.0), so 64 times leaves room for drawings that compress +/// far better while keeping what a file can make the reader allocate in proportion to the file. +const MAX_EXPANSION: u64 = 64; +/// The least that budget is, so small files are never refused for it. +const MIN_BUDGET: u64 = 64 << 20; + +/// The bytes all of `file`'s sections may decompress to (`MAX_EXPANSION`). +fn section_budget(file: &[u8]) -> u64 { + (file.len() as u64).saturating_mul(MAX_EXPANSION).max(MIN_BUDGET) +} + +fn u32_at(d: &[u8], o: usize) -> Option { + Some(u32::from_le_bytes(d.get(o..o + 4)?.try_into().ok()?)) +} +fn u64_at(d: &[u8], o: usize) -> Option { + Some(u64::from_le_bytes(d.get(o..o + 8)?.try_into().ok()?)) +} + +/// The "magic number sequence" (§4.1): an LCG with seed 1. +pub(crate) fn magic_sequence(len: usize) -> Vec { + let mut seed: u32 = 1; + (0..len) + .map(|_| { + seed = seed.wrapping_mul(0x343FD).wrapping_add(0x269EC3); + (seed >> 16) as u8 + }) + .collect() +} + +struct Page { + address: u64, + size: u32, +} + +#[derive(Debug)] +struct PageRef { + number: i32, + data_size: u32, + start: u64, +} + +#[derive(Debug)] +struct SectionDesc { + name: String, + size: u64, + max_decompressed: u32, + compressed: u32, + encrypted: u32, + pages: Vec, +} + +/// Read a system page (page map or section map) at `addr`. +fn system_page(file: &[u8], addr: u64, notes: &mut Vec) -> Result<(u32, Vec)> { + let a = usize::try_from(addr).map_err(|_| Error::format("page address overflow"))?; + let hdr = file.get(a..a + 20).ok_or_else(|| Error::truncated(format!("system page header at {a:#x} past end of file")))?; + let kind = u32_at(hdr, 0).unwrap_or(0); + let decompressed = u32_at(hdr, 4).unwrap_or(0) as usize; + let compressed = u32_at(hdr, 8).unwrap_or(0) as usize; + let compression = u32_at(hdr, 12).unwrap_or(0); + let stored_checksum = u32_at(hdr, 16).unwrap_or(0); + let body = file.get(a + 20..a + 20 + compressed).ok_or_else(|| Error::truncated(format!("system page data at {a:#x} past end of file")))?; + // §4.3: header checksum (seed 0, checksum field zeroed), then the data + // with that result as the seed. Reported, not enforced. + let mut h = hdr.to_vec(); + h[16..20].fill(0); + let computed = page_checksum(page_checksum(0, &h), body); + if computed != stored_checksum { + notes.push(Diagnostic { + severity: Severity::Info, + message: format!("system page {kind:#010x} at {a:#x}: checksum {stored_checksum:#010x} != computed {computed:#010x}"), + }); + } + let data = + if compression == 2 { lz77::decompress(body, decompressed).map_err(|e| e.context(format!("system page at {a:#x}")))? } else { body.to_vec() }; + Ok((kind, data)) +} + +pub(crate) fn read(file: &[u8], ver: DwgVersion) -> Result { + if file.len() < 0x100 { + return Err(Error::truncated("file is shorter than the R2004 file header")); + } + let maintenance = file[0x0B]; + let codepage = u16::from_le_bytes([file[0x13], file[0x14]]); + let security_flags = u32_at(file, 0x18).unwrap_or(0); + let mut notes = Vec::new(); + if security_flags != 0 { + notes.push(Diagnostic { + severity: Severity::Warning, + message: format!("security flags {security_flags:#x}: the drawing may be password protected"), + }); + } + + // Decrypt the 0x6C-byte header block at 0x80. + let mask = magic_sequence(0x6C); + let mut hdr: Vec = file[0x80..0x80 + 0x6C].iter().zip(&mask).map(|(a, b)| a ^ b).collect(); + if &hdr[..12] != FILE_ID { + return Err(Error::format(format!("{}: encrypted file header did not decode to the expected file ID", ver.magic()))); + } + let stored_crc = u32_at(&hdr, 0x68).unwrap_or(0); + hdr[0x68..0x6C].fill(0); + let computed_crc = crc32(0, &hdr); + if computed_crc != stored_crc { + notes.push(Diagnostic { + severity: Severity::Warning, + message: format!("file header CRC32 {stored_crc:#010x} != computed {computed_crc:#010x}"), + }); + } + let page_map_address = u64_at(&hdr, 0x54).unwrap_or(0) + 0x100; + let section_map_id = u32_at(&hdr, 0x5C).unwrap_or(0) as i32; + + // Page map: page number -> file address. + let (kind, pm) = system_page(file, page_map_address, &mut notes).map_err(|e| e.context("page map"))?; + if kind != PAGE_MAP_TYPE { + return Err(Error::format(format!("page map has type {kind:#010x}, expected {PAGE_MAP_TYPE:#010x}"))); + } + let mut pages: HashMap = HashMap::new(); + let mut addr: u64 = 0x100; + let mut p = 0usize; + while p + 8 <= pm.len() { + let number = u32_at(&pm, p).unwrap_or(0) as i32; + let size = u32_at(&pm, p + 4).unwrap_or(0); + p += 8; + if number < 0 { + p += 16; // gap: parent, left, right, 0 + } else { + pages.insert(number, Page { address: addr, size }); + } + addr += size as u64; + } + + // Section map. + let sm_addr = + pages.get(§ion_map_id).map(|pg| pg.address).ok_or_else(|| Error::format(format!("section map page {section_map_id} not in page map")))?; + let (kind, sm) = system_page(file, sm_addr, &mut notes).map_err(|e| e.context("section map"))?; + if kind != SECTION_MAP_TYPE { + return Err(Error::format(format!("section map has type {kind:#010x}, expected {SECTION_MAP_TYPE:#010x}"))); + } + let n_desc = u32_at(&sm, 0).ok_or_else(|| Error::truncated("section map header"))? as usize; + let mut descs = Vec::new(); + let mut q = 20usize; + for _ in 0..n_desc.min(4096) { + let size = u64_at(&sm, q).ok_or_else(|| Error::truncated("section description"))?; + let page_count = u32_at(&sm, q + 8).unwrap_or(0) as usize; + let max_decompressed = u32_at(&sm, q + 12).unwrap_or(0x7400); + let compressed = u32_at(&sm, q + 20).unwrap_or(2); + let encrypted = u32_at(&sm, q + 28).unwrap_or(0); + let name_bytes = sm.get(q + 32..q + 96).ok_or_else(|| Error::truncated("section name"))?; + let name_len = name_bytes.iter().position(|&b| b == 0).unwrap_or(64); + let name = String::from_utf8_lossy(&name_bytes[..name_len]).into_owned(); + q += 96; + let mut page_refs = Vec::with_capacity(page_count.min(65_536)); + for _ in 0..page_count { + let number = u32_at(&sm, q).ok_or_else(|| Error::truncated("section page record"))? as i32; + let data_size = u32_at(&sm, q + 4).unwrap_or(0); + let start = u64_at(&sm, q + 8).unwrap_or(0); + q += 16; + page_refs.push(PageRef { number, data_size, start }); + } + descs.push(SectionDesc { name, size, max_decompressed, compressed, encrypted, pages: page_refs }); + } + + let sections: Vec = descs + .iter() + .map(|d| SectionInfo { + name: if d.name.is_empty() { "(unnamed)".into() } else { d.name.clone() }, + size: d.size, + pages: d.pages.len() as u32, + compressed: d.compressed == 2, + encrypted: d.encrypted == 1, + }) + .collect(); + + let find = |name: &str| descs.iter().find(|d| d.name == name); + let mut budget = section_budget(file); + let load = |name: &str, notes: &mut Vec, budget: &mut u64| -> Result>> { + match find(name) { + None => Ok(None), + Some(d) => assemble(file, d, &pages, notes, budget).map(Some).map_err(|e| e.context(name)), + } + }; + let header = load("AcDb:Header", &mut notes, &mut budget).unwrap_or_else(|e| { + notes.push(Diagnostic { severity: Severity::Warning, message: e.to_string() }); + None + }); + let classes = load("AcDb:Classes", &mut notes, &mut budget).unwrap_or_else(|e| { + notes.push(Diagnostic { severity: Severity::Warning, message: e.to_string() }); + None + }); + let handles = load("AcDb:Handles", &mut notes, &mut budget)?.ok_or_else(|| Error::format("no AcDb:Handles section"))?; + let objects = load("AcDb:AcDbObjects", &mut notes, &mut budget)?.ok_or_else(|| Error::format("no AcDb:AcDbObjects section"))?; + let mut others = Vec::new(); + for d in &descs { + if d.name.is_empty() || matches!(d.name.as_str(), "AcDb:Header" | "AcDb:Classes" | "AcDb:Handles" | "AcDb:AcDbObjects") { + continue; + } + let mut quiet = Vec::new(); + if let Ok(bytes) = assemble(file, d, &pages, &mut quiet, &mut budget) { + others.push((d.name.clone(), bytes)); + } + } + + Ok(Container { maintenance, codepage, header, classes, handles, objects, sections, others, notes }) +} + +/// A readable account of an R2004-family file's container: the file +/// header fields, the page map and the section map with each page's +/// masked header. For studying files written by other programs. +#[cfg(test)] +pub(crate) fn describe(file: &[u8]) -> String { + use std::fmt::Write; + let mut o = String::new(); + let _ = writeln!(o, "file header bytes 0..0x80: {:02x?}", &file[..0x80]); + let mask = magic_sequence(0x6C); + let hdr: Vec = file[0x80..0xEC].iter().zip(&mask).map(|(a, b)| a ^ b).collect(); + for off in (0x0C..0x6C).step_by(4) { + let _ = writeln!(o, " enc[{off:#04x}] = {:#010x}", u32_at(&hdr, off).unwrap()); + } + let _ = writeln!(o, "bytes 0xEC..0x100: {:02x?}", &file[0xEC..0x100]); + let tail = &file[file.len() - 0x6C..]; + let tail_dec: Vec = tail.iter().zip(&mask).map(|(a, b)| a ^ b).collect(); + let _ = writeln!(o, "trailer header equal to first: {}", tail_dec == hdr); + let pm_addr = u64_at(&hdr, 0x54).unwrap() + 0x100; + let mut notes = Vec::new(); + let (_, pm) = system_page(file, pm_addr, &mut notes).unwrap(); + let _ = writeln!(o, "page map at {pm_addr:#x}, {} bytes, header {:02x?}", pm.len(), &file[pm_addr as usize..pm_addr as usize + 20]); + let mut addr = 0x100u64; + let mut p = 0; + while p + 8 <= pm.len() { + let n = u32_at(&pm, p).unwrap() as i32; + let s = u32_at(&pm, p + 4).unwrap(); + let _ = writeln!(o, " page {n:4} size {s:#7x} at {addr:#8x}"); + p += 8; + if n < 0 { + p += 16; + } + addr += s as u64; + } + let _ = writeln!(o, "file length {:#x}, pages end at {addr:#x}", file.len()); + // Section map. + let sm_id = u32_at(&hdr, 0x5C).unwrap() as i32; + let mut addr = 0x100u64; + let mut p = 0; + let mut page_addr = HashMap::new(); + while p + 8 <= pm.len() { + let n = u32_at(&pm, p).unwrap() as i32; + let s = u32_at(&pm, p + 4).unwrap(); + page_addr.insert(n, addr); + p += if n < 0 { 24 } else { 8 }; + addr += s as u64; + } + let sm_addr = page_addr[&sm_id]; + let (_, sm) = system_page(file, sm_addr, &mut notes).unwrap(); + let _ = writeln!( + o, + "section map page {sm_id} at {sm_addr:#x}, {} bytes, header {:02x?}; first words {:?}", + sm.len(), + &file[sm_addr as usize..sm_addr as usize + 20], + (0..5).map(|i| u32_at(&sm, i * 4).unwrap()).collect::>() + ); + let n_desc = u32_at(&sm, 0).unwrap() as usize; + let mut q = 20; + for _ in 0..n_desc { + let size = u64_at(&sm, q).unwrap(); + let count = u32_at(&sm, q + 8).unwrap(); + let words: Vec = (0..6).map(|i| u32_at(&sm, q + 8 + i * 4).unwrap()).collect(); + let name_bytes = &sm[q + 32..q + 96]; + let len = name_bytes.iter().position(|&b| b == 0).unwrap_or(64); + let _ = writeln!( + o, + " section {:?} size {size:#x} words(count,max,unk,compr,id,enc) {words:?} name-tail nonzero {}", + String::from_utf8_lossy(&name_bytes[..len]), + name_bytes[len..].iter().any(|&b| b != 0) + ); + q += 96; + for _ in 0..count { + let num = u32_at(&sm, q).unwrap() as i32; + let ds = u32_at(&sm, q + 4).unwrap(); + let st = u64_at(&sm, q + 8).unwrap(); + let a = page_addr[&num]; + let m = PAGE_MASK ^ (a as u32); + let w: Vec = (0..8).map(|i| u32_at(file, a as usize + i * 4).unwrap() ^ m).collect(); + let _ = writeln!(o, " page {num} data {ds:#x} start {st:#x} at {a:#x}; header {:x?}", w); + q += 16; + } + } + o.push_str(¬es.iter().map(|n| n.message.clone()).collect::>().join("\n")); + o +} + +/// Reassemble one section from its pages, taking its size from what is left of the file's +/// `budget` (`section_budget`). +fn assemble(file: &[u8], d: &SectionDesc, pages: &HashMap, notes: &mut Vec, budget: &mut u64) -> Result> { + if d.encrypted == 1 { + return Err(Error::new(ErrorKind::Unsupported, "section is encrypted (password-protected drawing)")); + } + if d.size > MAX_SECTION { + return Err(Error::format(format!("section size {} is implausible", d.size))); + } + if d.size > *budget { + return Err(Error::format(format!( + "section size {} is more than a file of {} bytes holds (its sections may hold {} more)", + d.size, + file.len(), + *budget + ))); + } + *budget -= d.size; + let mut buf = vec![0u8; usize::try_from(d.size).map_err(|_| Error::format("section size is implausible"))?]; + for pr in &d.pages { + let page = pages.get(&pr.number).ok_or_else(|| Error::format(format!("page {} not in page map", pr.number)))?; + let a = page.address as usize; + let raw_hdr = file.get(a..a + 32).ok_or_else(|| Error::truncated(format!("data page header at {a:#x} past end of file")))?; + // §4.6: each 32-bit word of the header is XORed with 0x4164536B ^ address. + let m = PAGE_MASK ^ (page.address as u32); + let word = |i: usize| u32::from_le_bytes([raw_hdr[i * 4], raw_hdr[i * 4 + 1], raw_hdr[i * 4 + 2], raw_hdr[i * 4 + 3]]) ^ m; + let page_type = word(0); + if page_type != DATA_PAGE_TYPE { + notes.push(Diagnostic { + severity: Severity::Info, + message: format!("{}: page {} header type {page_type:#010x} unexpected", d.name, pr.number), + }); + } + let header_size = word(2) as usize; + let comp_size = if pr.data_size > 0 { pr.data_size as usize } else { header_size }; + let body = file + .get(a + 32..a + 32 + comp_size) + .ok_or_else(|| Error::truncated(format!("data page {} ({comp_size} bytes at {a:#x}) past end of file", pr.number)))?; + let _ = page.size; + let data = if d.compressed == 2 { + let limit = (d.max_decompressed.max(word(3)) as usize).clamp(1, 0x10_0000); + lz77::decompress(body, limit).map_err(|e| e.context(format!("page {}", pr.number)))? + } else { + body.to_vec() + }; + let start = pr.start as usize; + if start < buf.len() { + let n = data.len().min(buf.len() - start); + buf[start..start + n].copy_from_slice(&data[..n]); + } + } + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn section(size: u64) -> SectionDesc { + SectionDesc { name: "AcDb:AcDbObjects".into(), size, max_decompressed: 0x7400, compressed: 2, encrypted: 0, pages: Vec::new() } + } + + /// A section map's sizes are claims: one larger than the file can hold is refused before + /// anything is allocated for it (a few kilobytes can't make the reader take gigabytes). + #[test] + fn a_section_larger_than_the_file_allows_is_refused_before_allocating() { + let file = [0u8; 1000]; + let mut budget = section_budget(&file); + assert_eq!(budget, MIN_BUDGET); + let e = assemble(&file, §ion(1 << 30), &HashMap::new(), &mut Vec::new(), &mut budget).unwrap_err(); + assert!(e.to_string().contains("more than a file of 1000 bytes holds"), "{e}"); + assert_eq!(budget, MIN_BUDGET, "nothing was taken"); + // A large file's budget grows with it. + assert_eq!(section_budget(&vec![0u8; 2 << 20]), 128 << 20); + } + + /// The budget is shared: many sections can't each claim the whole of it. + #[test] + fn every_section_takes_from_the_same_budget() { + let file = [0u8; 16]; + let mut budget = 100; + assert_eq!(assemble(&file, §ion(60), &HashMap::new(), &mut Vec::new(), &mut budget).unwrap().len(), 60); + assert_eq!(budget, 40); + assert!(assemble(&file, §ion(60), &HashMap::new(), &mut Vec::new(), &mut budget).is_err()); + assert_eq!(assemble(&file, §ion(40), &HashMap::new(), &mut Vec::new(), &mut budget).unwrap().len(), 40); + assert_eq!(budget, 0); + } + + #[test] + fn magic_sequence_starts_as_documented_lcg() { + // seed = 1 * 0x343FD + 0x269EC3 = 0x29E2C0 -> first byte 0x29. + let m = magic_sequence(4); + assert_eq!(m[0], 0x29); + // Recompute independently. + let mut s: u64 = 1; + let mut v = Vec::new(); + for _ in 0..4 { + s = (s * 0x343FD + 0x269EC3) & 0xFFFF_FFFF; + v.push((s >> 16) as u8); + } + assert_eq!(m, v); + } +} diff --git a/crates/dwg/src/read/section.rs b/crates/dwg/src/read/section.rs new file mode 100644 index 00000000..31c04453 --- /dev/null +++ b/crates/dwg/src/read/section.rs @@ -0,0 +1,48 @@ +//! Sentinel-wrapped sections (AcDb:Header, AcDb:Classes): start sentinel, +//! RL size, optional RL high size (R2010+), data, RS CRC, end sentinel. +//! +//! Sentinel byte values from the spec (R13–R15 header §3.2.6 verified; the +//! header/classes sentinels are written from knowledge of chapters 9–10). + +use super::version::DwgVersion; +use crate::read::error::{Error, Result}; + +pub(crate) const HEADER_START: [u8; 16] = [0xCF, 0x7B, 0x1F, 0x23, 0xFD, 0xDE, 0x38, 0xA9, 0x5F, 0x7C, 0x68, 0xB8, 0x4E, 0x6D, 0x33, 0x5F]; +pub(crate) const HEADER_END: [u8; 16] = [0x30, 0x84, 0xE0, 0xDC, 0x02, 0x21, 0xC7, 0x56, 0xA0, 0x83, 0x97, 0x47, 0xB1, 0x92, 0xCC, 0xA0]; +pub(crate) const CLASSES_START: [u8; 16] = [0x8D, 0xA1, 0xC4, 0xB8, 0xC4, 0xA9, 0xF8, 0xC5, 0xC0, 0xDC, 0xF4, 0x5F, 0xE7, 0xCF, 0xB6, 0x8A]; +pub(crate) const CLASSES_END: [u8; 16] = [0x72, 0x5E, 0x3B, 0x47, 0x3B, 0x56, 0x07, 0x3A, 0x3F, 0x23, 0x0B, 0xA0, 0x18, 0x30, 0x49, 0x75]; +/// Ends the R13–R15 file header (§3.2.6, verified). +pub(crate) const FILE_HEADER_END: [u8; 16] = [0x95, 0xA0, 0x4E, 0x28, 0x99, 0x82, 0x1A, 0xE5, 0x5E, 0x41, 0xE0, 0x5F, 0x9D, 0x3A, 0x4D, 0x00]; + +pub(crate) struct Wrapped<'a> { + pub body: &'a [u8], + /// Whether the end sentinel was found where expected. + pub end_found: bool, +} + +/// Find the data body of a sentinel-wrapped section. The optional high +/// size RL (R2010+) is detected by where the end sentinel sits. +pub(crate) fn unwrap<'a>(data: &'a [u8], start: &[u8; 16], end: &[u8; 16], ver: DwgVersion, maintenance: u8) -> Result> { + if data.len() < 20 || &data[..16] != start { + return Err(Error::format("section start sentinel not found")); + } + let size = u32::from_le_bytes([data[16], data[17], data[18], data[19]]) as usize; + let candidates: &[bool] = if ver >= DwgVersion::R2010 { &[true, false] } else { &[false] }; + for &hi in candidates { + let body_start = 20 + if hi { 4 } else { 0 }; + let end_pos = body_start + size + 2; + if data.len() >= end_pos + 16 && &data[end_pos..end_pos + 16] == end { + return Ok(Wrapped { body: &data[body_start..body_start + size], end_found: true }); + } + } + // End sentinel not where expected: fall back to the rule in the spec + // (high size present for R2018, and for R2010/R2013 with maintenance + // version above 3) and clamp. + let hi = ver >= DwgVersion::R2018 || (ver >= DwgVersion::R2010 && maintenance > 3); + let body_start = 20 + if hi { 4 } else { 0 }; + let body_end = (body_start + size).min(data.len()); + if body_start > body_end { + return Err(Error::truncated("section body runs past data")); + } + Ok(Wrapped { body: &data[body_start..body_end], end_found: false }) +} diff --git a/crates/dwg/src/read/streams.rs b/crates/dwg/src/read/streams.rs new file mode 100644 index 00000000..a5d3ffa8 --- /dev/null +++ b/crates/dwg/src/read/streams.rs @@ -0,0 +1,141 @@ +//! The three streams an object (or the R2007+ header) is split into: main +//! data, strings (R2007+) and handles. +//! +//! Written from knowledge of the spec (chapter 20, "common object format", +//! R2007+ string stream). VERIFY against the spec PDF and real files. + +use super::version::DwgVersion; +use crate::bits::{BitReader, HandleRef}; +use crate::read::error::{Error, Result}; +use crate::read::model::Color; +use crate::read::text; + +pub(crate) struct Streams<'a> { + pub ver: DwgVersion, + pub codepage: u16, + pub dat: BitReader<'a>, + /// R2007+ string stream; `None` when the object stores no strings. + pub strs: Option>, + /// Separate handle stream; `None` means handles are inline in `dat` + /// (the R13–R2004 header section). + pub hdl: Option>, +} + +impl<'a> Streams<'a> { + /// TV: 8-bit text in the main stream up to R2004, UTF-16 text in the + /// string stream from R2007. + pub fn tv(&mut self) -> Result { + if self.ver.has_string_stream() { + match self.strs.as_mut() { + Some(s) => s.text16(), + None => Ok(String::new()), + } + } else { + let raw = self.dat.text8()?; + Ok(text::decode_ansi(&raw, self.codepage)) + } + } + + /// Next handle reference from the handle stream (or inline). + pub fn h(&mut self) -> Result { + match self.hdl.as_mut() { + Some(h) => h.handle(), + None => self.dat.handle(), + } + } + + /// Handle resolved against the owning object's handle. + pub fn h_abs(&mut self, own: u64) -> Result { + Ok(self.h()?.absolute(own)) + } + + /// Bits left in the handle stream (or main stream when inline). + pub fn handle_bits_left(&self) -> usize { + match &self.hdl { + Some(h) => h.remaining(), + None => self.dat.remaining(), + } + } + + /// CMC (§2.11): BS index up to R2000; from R2004 a BS index, a BL + /// method+RGB word and a flag byte announcing optional names. + pub fn cmc(&mut self) -> Result<(Color, i16)> { + let index = self.dat.bs()? as i16; + if self.ver < DwgVersion::R2004 { + return Ok((Color::from_aci(index), index)); + } + let word = self.dat.bl()?; + let flags = self.dat.rc()?; + if flags & 1 != 0 { + let _name = self.tv()?; + } + if flags & 2 != 0 { + let _book = self.tv()?; + } + Ok((Color::from_method_word(word, index), index)) + } + + /// ENC entity color (§2.11, R2004+). Returns the color, the raw + /// transparency word if stored, and whether a color-book handle follows + /// in the handle stream. + pub fn enc(&mut self) -> Result<(Color, Option, bool)> { + let raw = self.dat.bs()?; + if self.ver < DwgVersion::R2004 { + return Ok((Color::from_aci(raw as i16), None, false)); + } + let index = (raw & 0x01FF) as i16; + let mut color = Color::from_aci(index); + if raw & 0x8000 != 0 { + let word = self.dat.bl()?; + color = Color::from_method_word(word, index); + } + let transparency = if raw & 0x2000 != 0 { Some(self.dat.bl()?) } else { None }; + Ok((color, transparency, raw & 0x4000 != 0)) + } + + /// Guard against absurd counts read from corrupt data: `n` items, each + /// needing at least `min_bits` in the main stream. + pub fn check_count(&self, n: u32, min_bits: usize, what: &str) -> Result { + let n = n as usize; + if n.saturating_mul(min_bits) > self.dat.remaining() { + return Err(Error::format(format!("{what} count {n} exceeds remaining data ({} bits)", self.dat.remaining()))); + } + Ok(n) + } + + /// Same guard for handle lists. + pub fn check_handle_count(&self, n: u32, what: &str) -> Result { + let n = n as usize; + if n.saturating_mul(8) > self.handle_bits_left() { + return Err(Error::format(format!("{what} handle count {n} exceeds remaining handle data"))); + } + Ok(n) + } +} + +/// Locate the R2007+ string stream that ends just before bit `endbit` of +/// `data`. The bit at `endbit - 1` says whether strings are present; the 16 +/// bits before it hold the stream size in bits, with 0x8000 flagging a +/// further 16-bit high part before that. Returns the string reader and the +/// bit where the strings begin. +pub(crate) fn string_stream(data: &[u8], endbit: usize) -> Result, usize)>> { + if endbit == 0 || endbit > data.len() * 8 { + return Err(Error::format(format!("string stream end bit {endbit} out of range"))); + } + let mut r = BitReader::with_bounds(data, 0, endbit); + r.set_position(endbit - 1)?; + if !r.b()? { + return Ok(None); + } + let mut p = endbit.checked_sub(17).ok_or_else(|| Error::format("string stream flag without size"))?; + r.set_position(p)?; + let mut size = r.rs()? as usize; + if size & 0x8000 != 0 { + p = p.checked_sub(16).ok_or_else(|| Error::format("string stream size underflow"))?; + r.set_position(p)?; + let hi = r.rs()? as usize; + size = (size & 0x7FFF) | (hi << 15); + } + let start = p.checked_sub(size).ok_or_else(|| Error::format(format!("string stream of {size} bits does not fit")))?; + Ok(Some((BitReader::with_bounds(data, start, p), start))) +} diff --git a/crates/dwg/src/read/styles.rs b/crates/dwg/src/read/styles.rs new file mode 100644 index 00000000..54883665 --- /dev/null +++ b/crates/dwg/src/read/styles.rs @@ -0,0 +1,1243 @@ +//! The style objects the model keeps as their DXF groups +//! ([`Groups`]): visual styles, materials, table styles, multileader, +//! section and detail view styles, and dimension associations, to and from +//! their DWG records (R2013 and later). +//! +//! The spec documents MLEADERSTYLE and TABLESTYLE; for the others the +//! layouts come from AutoCAD's own files, each record of the MI-201 corpus +//! read field by field against the DXF AutoCAD wrote of the same drawing +//! (black-box, as `PROVENANCE.md` records). Most follow their DXF groups in +//! order; where AutoCAD stores a field elsewhere in the record, or keeps a +//! DXF group out of the DWG (the property counts and group numbers DXF +//! adds), the layout says so. A record that does not fit its layout is +//! reported, and the object stays as its original bytes or is left out. + +use super::streams::Streams; +use super::version::DwgVersion as V; +use crate::bits::BitReader; +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)] +enum D { + B, + Bs, + Bl, + Bd, + Rc, + Tv, + /// A handle with the given reference code. + H(u8), + /// CmColor: DXF 62 (the colour index), 420 (true colour) when set. + Cmc, + /// CmColor whose DXF group holds the method word itself. + Word, + /// 2RD: a 2D point, one DXF point group. + Rd2, +} + +/// One DXF group of a record, in DXF order. +#[derive(Clone, Debug)] +enum G { + /// Subclass marker (DXF only). + M(&'static str), + /// A value stored in both forms. + V(u16, D), + /// A group only DXF has, with the value AutoCAD writes there. + X(u16, i64), + /// A handle DXF leaves out when it is null. + OptH(u16), + /// A whole number or flag at the end of a record that DXF in the + /// reference's older layout leaves out, and the value it has then. + Tail(u16, D, i64), + /// A count and that many values: DXF count group, item group. + Rep(u16, D, u16, D), +} + +/// A step of the DWG record, in DWG order. +#[derive(Clone, Copy, Debug)] +enum W { + /// The value of DXF group number `n` of the layout. + I(usize), + /// A value only DWG has. + K(D, i64), +} + +struct Layout { + dxf: Vec, + dwg: Vec, +} + +/// The layout of a type, or `None` for types handled by code below. +fn layout(kind: &str) -> Option { + use D::*; + use G::*; + Some(match kind { + // The objects raster images use (§20.4.81, §20.4.82, §20.4.91, + // checked against the specification text). They keep the DXF + // groups' order, except that IMAGEDEF's record puts the path after + // the image size and the pixel size last. + "IMAGEDEF" => Layout { + dxf: vec![M("AcDbRasterImageDef"), V(90, Bl), V(1, Tv), V(10, Rd2), V(11, Rd2), V(280, B), V(281, Rc)], + dwg: vec![W::I(1), W::I(3), W::I(2), W::I(5), W::I(6), W::I(4)], + }, + "IMAGEDEF_REACTOR" => Layout { dxf: vec![M("AcDbRasterImageDefReactor"), V(90, Bl)], dwg: vec![W::I(1)] }, + "RASTERVARIABLES" => { + Layout { dxf: vec![M("AcDbRasterVariables"), V(90, Bl), V(70, Bs), V(71, Bs), V(72, Bs)], dwg: vec![W::I(1), W::I(2), W::I(3), W::I(4)] } + } + "VISUALSTYLE" => { + let mut dxf = vec![M("AcDbVisualStyle"), V(2, Tv), V(70, Bs), X(177, 3), V(291, B), X(70, 58)]; + for code in VISUALSTYLE_PROPERTIES { + let d = match code { + 90 => Bl, + 40 => Bd, + 62 => Cmc, + 290 => B, + _ => Tv, + }; + dxf.push(V(code, d)); + dxf.push(V(176, Bs)); + } + // DXF 177 is 3 where the DWG record holds 2. + let mut dwg = vec![W::I(1), W::I(2), W::K(Bs, 2), W::I(4)]; + dwg.extend((6..dxf.len()).map(W::I)); + Layout { dxf, dwg } + } + "MLEADERSTYLE" => { + let dxf = vec![ + M("AcDbMLeaderStyle"), + V(179, Bs), + V(170, Bs), + V(171, Bs), + V(172, Bs), + V(90, Bl), + V(40, Bd), + V(41, Bd), + V(173, Bs), + V(91, Word), + OptH(340), + V(92, Bl), + V(290, B), + V(42, Bd), + V(291, B), + V(43, Bd), + V(3, Tv), + OptH(341), + V(44, Bd), + V(300, Tv), + OptH(342), + V(174, Bs), + V(178, Bs), + V(175, Bs), + V(176, Bs), + V(93, Word), + V(45, Bd), + V(292, B), + V(297, B), + V(46, Bd), + OptH(343), + V(94, Word), + V(47, Bd), + V(49, Bd), + V(140, Bd), + V(293, B), + V(141, Bd), + V(294, B), + V(177, Bs), + V(142, Bd), + V(295, B), + V(296, B), + V(143, Bd), + V(271, Bs), + V(272, Bs), + V(273, Bs), + Tail(298, B, 0), + ]; + // The spec's order: 273 before 272. + let mut dwg: Vec = (1..dxf.len()).map(W::I).collect(); + let (a, b) = (dwg.len() - 3, dwg.len() - 2); + dwg.swap(a, b); + Layout { dxf, dwg } + } + "ACDBSECTIONVIEWSTYLE" => { + let mut dxf = model_doc_view(); + let base = dxf.len(); + dxf.extend([ + M("AcDbSectionViewStyle"), + V(70, Bs), // 1 + X(71, 0), // 2 + V(90, Bl), // 3 + X(71, 1), // 4 + V(340, H(5)), // 5 + V(62, Cmc), // 6 + V(40, Bd), // 7 + V(340, H(5)), // 8 + V(340, H(5)), // 9 + V(62, Cmc), // 10 + V(40, Bd), // 11 + V(300, Tv), // 12 + V(40, Bd), // 13 + V(90, Bl), // 14 + V(40, Bd), // 15 + V(90, Bl), // 16 + X(71, 2), // 17 + V(340, H(5)), // 18 + V(90, Bl), // 19 + V(62, Cmc), // 20 + V(340, H(5)), // 21 + V(90, Bl), // 22 + V(62, Cmc), // 23 + V(40, Bd), // 24 + V(40, Bd), // 25 + V(40, Bd), // 26 + X(71, 3), // 27 + V(340, H(5)), // 28 + V(62, Cmc), // 29 + V(40, Bd), // 30 + V(90, Bl), // 31 + V(40, Bd), // 32 + V(90, Bl), // 33 + V(300, Tv), // 34 + X(71, 4), // 35 + V(62, Cmc), // 36 + V(62, Cmc), // 37 + V(300, Tv), // 38 + V(40, Bd), // 39 + V(90, Bl), // 40 + V(290, B), // 41 + V(290, B), // 42 + Rep(90, Bl, 40, Bd), // 43 + ]); + // AutoCAD stores the fields DXF lists at 14–16 and 25 near the + // end, before the angle list. + let order = [ + 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19, 20, 21, 22, 23, 24, 26, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 14, 15, + 16, 25, 43, + ]; + let mut dwg: Vec = (1..base).map(W::I).collect(); + dwg.extend(order.iter().map(|i| W::I(base + i))); + Layout { dxf, dwg } + } + "ACDBDETAILVIEWSTYLE" => { + let mut dxf = model_doc_view(); + let base = dxf.len(); + dxf.extend([ + M("AcDbDetailViewStyle"), + V(70, Bs), // 1 + X(71, 0), // 2 + V(90, Bl), // 3 + X(71, 1), // 4 + V(340, H(5)), // 5 + V(62, Cmc), // 6 + V(40, Bd), // 7 + V(340, H(5)), // 8 + V(62, Cmc), // 9 + V(40, Bd), // 10 + V(300, Tv), // 11 + V(40, Bd), // 12 + V(280, Rc), // 13 + X(71, 2), // 14 + V(340, H(5)), // 15 + V(90, Bl), // 16 + V(62, Cmc), // 17 + X(71, 3), // 18 + V(340, H(5)), // 19 + V(62, Cmc), // 20 + V(40, Bd), // 21 + V(90, Bl), // 22 + V(40, Bd), // 23 + V(90, Bl), // 24 + V(300, Tv), // 25 + X(71, 4), // 26 + V(340, H(5)), // 27 + V(90, Bl), // 28 + V(62, Cmc), // 29 + V(340, H(5)), // 30 + V(90, Bl), // 31 + V(62, Cmc), // 32 + V(280, Rc), // 33 + ]); + let order = [1, 3, 5, 6, 7, 8, 12, 13, 9, 10, 11, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33]; + let mut dwg: Vec = (1..base).map(W::I).collect(); + dwg.extend(order.iter().map(|i| W::I(base + i))); + Layout { dxf, dwg } + } + _ => return None, + }) +} + +/// The part section and detail view styles share. +fn model_doc_view() -> Vec { + use D::*; + use G::*; + vec![M("AcDbModelDocViewStyle"), V(70, Bs), V(3, Tv), V(290, B), V(300, Tv), V(90, Bl)] +} + +/// The value kind of each of a visual style's 58 properties, by DXF code +/// (the same in all 24 of AutoCAD's default styles); each is followed by +/// its flag (176). +const VISUALSTYLE_PROPERTIES: [u16; 58] = [ + 90, 90, 90, 90, 40, 40, 62, 90, 90, 62, 62, 90, 90, 40, 90, 62, 40, 90, 90, 90, 62, 90, 90, 90, 290, 90, 40, 90, 290, 290, 290, 290, 290, 290, + 290, 290, 290, 90, 40, 40, 90, 62, 90, 90, 62, 290, 90, 90, 90, 290, 90, 62, 40, 90, 1, 290, 40, 40, +]; + +// --------------------------------------------------------------------------- +// Values +// --------------------------------------------------------------------------- + +/// A value read from or for one field. +#[derive(Clone, Debug, PartialEq)] +enum Val { + Int(i64), + Real(f64), + Str(String), + Handle(Handle), + Point(Vec3), + /// A CmColor method word (and, for `D::Cmc`, the colour index DXF + /// gives with it). + Color(u32), + List(Vec), + Null, +} + +fn xr(code: u16, v: &Val) -> XrValue { + use super::nongraphic::{XrType, xr_type}; + let i = match v { + Val::Int(i) => *i, + Val::Real(f) => *f as i64, + _ => 0, + }; + let f = match v { + Val::Real(f) => *f, + Val::Int(i) => *i as f64, + _ => 0.0, + }; + match xr_type(code) { + Some(XrType::Str) => XrValue::Str(match v { + Val::Str(s) => s.clone(), + _ => String::new(), + }), + Some(XrType::Point) => XrValue::Point(match v { + Val::Point(p) => *p, + _ => Vec3::ZERO, + }), + Some(XrType::Real) => XrValue::Real(f), + Some(XrType::Int8) => XrValue::Int8(i as i8), + Some(XrType::Int16) => XrValue::Int16(i as i16), + Some(XrType::Int32) => XrValue::Int32(i as i32), + Some(XrType::Int64) => XrValue::Int64(i), + Some(XrType::Bool) => XrValue::Bool(i != 0), + Some(XrType::Handle) => XrValue::Handle(match v { + Val::Handle(h) => *h, + _ => Handle::NULL, + }), + Some(XrType::Bytes) | None => XrValue::Int32(i as i32), + } +} + +fn from_xr(v: &XrValue) -> Val { + match v { + XrValue::Str(s) => Val::Str(s.clone()), + XrValue::Point(p) => Val::Point(*p), + XrValue::Real(f) => Val::Real(*f), + XrValue::Int8(i) => Val::Int(*i as i64), + XrValue::Int16(i) => Val::Int(*i as i64), + XrValue::Int32(i) => Val::Int(*i as i64), + XrValue::Int64(i) => Val::Int(*i), + XrValue::Bool(b) => Val::Int(*b as i64), + XrValue::Handle(h) => Val::Handle(*h), + XrValue::Bytes(_) => Val::Null, + } +} + +/// DXF 62 (and 420) for a method word, as AutoCAD writes them: the nearest +/// index beside a true colour. +fn color_groups(code: u16, word: u32, out: &mut Vec<(u16, XrValue)>) { + let index: i16 = match word >> 24 { + 0xC0 => 256, + 0xC1 => 0, + 0xC2 => crate::read::model::color::nearest_aci((word >> 16) as u8, (word >> 8) as u8, word as u8) as i16, + 0xC3 => (word & 0xFF) as i16, + 0xC8 => 257, + _ => 7, + }; + out.push((code, XrValue::Int16(index))); + if word >> 24 == 0xC2 { + out.push((420, XrValue::Int32((word & 0xFF_FFFF) as i32))); + } +} + +fn word_of(index: i64, rgb: Option) -> u32 { + match rgb { + Some(rgb) => 0xC200_0000 | (rgb as u32 & 0xFF_FFFF), + None => match index { + 256 => 0xC000_0000, + 0 => 0xC100_0000, + 257 => 0xC800_0000, + i => 0xC300_0000 | (i as u32 & 0xFF), + }, + } +} + +// --------------------------------------------------------------------------- +// Reading DWG +// --------------------------------------------------------------------------- + +fn read(s: &mut Streams, own: u64, d: D) -> Result { + Ok(match d { + D::B => Val::Int(s.dat.b()? as i64), + D::Bs => Val::Int(s.dat.bs()? as i16 as i64), + D::Bl => Val::Int(s.dat.bl()? as i32 as i64), + D::Bd => Val::Real(s.dat.bd()?), + D::Rc => Val::Int(s.dat.rc()? as i64), + D::Tv => Val::Str(s.tv()?), + D::Rd2 => { + let [x, y] = s.dat.rd2()?; + Val::Point(Vec3::new(x, y, 0.0)) + } + D::H(_) => Val::Handle(Handle(s.h_abs(own)?)), + D::Cmc | D::Word => { + let _index = s.dat.bs()?; + let word = s.dat.bl()?; + let names = s.dat.rc()?; + if names != 0 { + return Err(Error::format("named colour in a style object")); + } + Val::Color(word) + } + }) +} + +fn decode_layout(s: &mut Streams, own: u64, l: &Layout) -> Result> { + let mut vals: Vec = vec![Val::Null; l.dxf.len()]; + for w in &l.dwg { + match *w { + W::K(d, want) => { + let got = read(s, own, d)?; + if got != Val::Int(want) { + return Err(Error::format(format!("expected {want}, found {got:?}"))); + } + } + W::I(i) => { + vals[i] = match &l.dxf[i] { + G::V(_, d) | G::Tail(_, d, _) => read(s, own, *d)?, + G::OptH(_) => read(s, own, D::H(5))?, + G::Rep(_, cd, _, id) => { + let n = match read(s, own, *cd)? { + Val::Int(n) if (0..=10_000).contains(&n) => n as usize, + other => return Err(Error::format(format!("count {other:?}"))), + }; + let mut list = Vec::with_capacity(n); + for _ in 0..n { + list.push(read(s, own, *id)?); + } + Val::List(list) + } + _ => Val::Null, + }; + } + } + } + let mut out = Vec::new(); + for (g, v) in l.dxf.iter().zip(&vals) { + match g { + G::M(name) => out.push((100, XrValue::Str(name.to_string()))), + G::X(code, value) => out.push((*code, xr(*code, &Val::Int(*value)))), + G::V(code, D::Cmc) => match v { + Val::Color(w) => color_groups(*code, *w, &mut out), + _ => return Err(Error::format("colour expected")), + }, + G::V(code, D::Word) => match v { + Val::Color(w) => out.push((*code, XrValue::Int32(*w as i32))), + _ => return Err(Error::format("colour expected")), + }, + G::V(code, _) | G::Tail(code, _, _) => out.push((*code, xr(*code, v))), + G::OptH(code) => { + if let Val::Handle(h) = v + && !h.is_null() + { + out.push((*code, XrValue::Handle(*h))); + } + } + G::Rep(cc, _, ic, _) => { + let list = match v { + Val::List(l) => l.as_slice(), + _ => &[], + }; + out.push((*cc, xr(*cc, &Val::Int(list.len() as i64)))); + for x in list { + out.push((*ic, xr(*ic, x))); + } + } + } + } + Ok(out) +} + +/// The groups of a style object from its DWG record, the common part and +/// common handles already read. `None` for types this module does not +/// know; an error for a record that does not fit its layout. +pub(crate) fn decode(kind: &str, s: &mut Streams, own: u64, d: &Lookup) -> Option> { + if !Groups::KINDS.contains(&kind) || s.ver < since(kind) { + return None; + } + let items = match kind { + "DIMASSOC" => decode_dimassoc(s, own), + "MATERIAL" => decode_material(s), + "TABLESTYLE" => decode_tablestyle(s, own, d), + "CELLSTYLEMAP" => return None, + k => decode_layout(s, own, &layout(k)?), + }; + Some(items.map(|items| Groups { kind: kind.to_string(), items })) +} + +// --------------------------------------------------------------------------- +// Writing DWG +// --------------------------------------------------------------------------- + +/// The groups of a record, walked in DXF order. +struct Cur<'a> { + items: &'a [(u16, XrValue)], + at: usize, + kind: &'a str, +} + +impl<'a> Cur<'a> { + fn new(g: &'a Groups) -> Self { + Cur { items: &g.items, at: 0, kind: &g.kind } + } + fn peek(&self) -> Option { + self.items.get(self.at).map(|x| x.0) + } + /// Groups not read yet. + fn left(&self) -> usize { + self.items.len().saturating_sub(self.at) + } + fn take(&mut self, code: u16) -> Result<&'a XrValue> { + match self.items.get(self.at) { + Some((c, v)) if *c == code => { + self.at += 1; + Ok(v) + } + other => Err(Error::format(format!("{}: group {code} expected at item {}, found {:?}", self.kind, self.at, other.map(|x| x.0)))), + } + } + fn int(&mut self, code: u16) -> Result { + match from_xr(self.take(code)?) { + Val::Int(i) => Ok(i), + Val::Real(f) => Ok(f as i64), + v => Err(Error::format(format!("{}: group {code}: number expected, {v:?}", self.kind))), + } + } + fn point(&mut self, code: u16) -> Result { + match self.take(code)? { + XrValue::Point(p) => Ok(*p), + other => Err(Error::format(format!("{}: group {code} is {other:?}, a point expected", self.kind))), + } + } + + fn real(&mut self, code: u16) -> Result { + match from_xr(self.take(code)?) { + Val::Real(f) => Ok(f), + Val::Int(i) => Ok(i as f64), + v => Err(Error::format(format!("{}: group {code}: number expected, {v:?}", self.kind))), + } + } + fn str(&mut self, code: u16) -> Result { + match self.take(code)? { + XrValue::Str(s) => Ok(s.clone()), + v => Err(Error::format(format!("{}: group {code}: text expected, {v:?}", self.kind))), + } + } + fn handle(&mut self, code: u16) -> Result { + match self.take(code)? { + XrValue::Handle(h) => Ok(*h), + v => Err(Error::format(format!("{}: group {code}: handle expected, {v:?}", self.kind))), + } + } + fn color(&mut self, code: u16) -> Result { + let index = self.int(code)?; + let rgb = if self.peek() == Some(420) { Some(self.int(420)?) } else { None }; + if self.peek() == Some(430) { + return Err(Error::format(format!("{}: named colour", self.kind))); + } + Ok(word_of(index, rgb)) + } + fn done(&self) -> Result<()> { + match self.items.get(self.at) { + None => Ok(()), + Some((c, _)) => Err(Error::format(format!("{}: unexpected group {c} at item {}", self.kind, self.at))), + } + } +} + +fn write(w: &mut ObjW, d: D, v: &Val) -> Result<()> { + let int = || match v { + Val::Int(i) => Ok(*i), + _ => Err(Error::format(format!("number expected, {v:?}"))), + }; + match d { + D::B => w.dat.b(int()? != 0), + D::Bs => w.dat.bs(int()? as i16 as u16), + D::Bl => w.dat.bl(int()? as i32 as u32), + D::Bd => w.dat.bd(match v { + Val::Real(f) => *f, + Val::Int(i) => *i as f64, + _ => return Err(Error::format("number expected")), + }), + D::Rc => w.dat.rc(int()? as u8), + D::Rd2 => match v { + Val::Point(p) => w.dat.rd2([p.x, p.y]), + _ => return Err(Error::format("point expected")), + }, + D::Tv => w.tv(match v { + Val::Str(s) => s, + _ => "", + }), + D::H(code) => { + let h = match v { + Val::Handle(h) => *h, + _ => Handle::NULL, + }; + w.hdl.handle(code, h.0); + } + D::Cmc | D::Word => { + let word = match v { + Val::Color(c) => *c, + Val::Int(i) => *i as u32, + _ => return Err(Error::format("colour expected")), + }; + w.dat.bs(0); + w.dat.bl(word); + w.dat.rc(0); + } + } + Ok(()) +} + +fn encode_layout(w: &mut ObjW, g: &Groups, l: &Layout) -> Result<()> { + let mut c = Cur::new(g); + let mut vals: Vec = vec![Val::Null; l.dxf.len()]; + for (i, f) in l.dxf.iter().enumerate() { + vals[i] = match f { + G::M(name) => { + if c.str(100)? != *name { + return Err(Error::format(format!("{}: subclass {name} expected", g.kind))); + } + Val::Null + } + G::X(code, _) => { + c.take(*code)?; + Val::Null + } + G::V(code, D::Cmc) => Val::Color(c.color(*code)?), + G::V(code, D::Word) => Val::Color(c.int(*code)? as u32), + G::V(code, D::Tv) => Val::Str(c.str(*code)?), + G::V(code, D::H(_)) => Val::Handle(c.handle(*code)?), + G::V(code, D::Bd) => Val::Real(c.real(*code)?), + G::V(code, D::Rd2) => Val::Point(c.point(*code)?), + G::V(code, _) => Val::Int(c.int(*code)?), + G::Tail(code, _, missing) => Val::Int(if c.peek() == Some(*code) { c.int(*code)? } else { *missing }), + G::OptH(code) => { + if c.peek() == Some(*code) { + Val::Handle(c.handle(*code)?) + } else { + Val::Handle(Handle::NULL) + } + } + G::Rep(cc, _, ic, id) => { + // Each item is one group: a count past the groups left is + // damage, and must not size the allocation. + let n = (c.int(*cc)?.max(0) as usize).min(c.left()); + let mut list = Vec::with_capacity(n); + for _ in 0..n { + list.push(match id { + D::Bd => Val::Real(c.real(*ic)?), + D::Tv => Val::Str(c.str(*ic)?), + _ => Val::Int(c.int(*ic)?), + }); + } + Val::List(list) + } + }; + } + c.done()?; + for step in &l.dwg { + match *step { + W::K(d, v) => write(w, d, &Val::Int(v))?, + W::I(i) => match (&l.dxf[i], &vals[i]) { + (G::V(_, d) | G::Tail(_, d, _), v) => write(w, *d, v)?, + (G::OptH(_), v) => write(w, D::H(5), v)?, + (G::Rep(_, cd, _, id), Val::List(list)) => { + write(w, *cd, &Val::Int(list.len() as i64))?; + for x in list { + write(w, *id, x)?; + } + } + _ => {} + }, + } + } + Ok(()) +} + +/// 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<()> { + if w.ver < since(&g.kind) { + return Err(Error::unsupported(format!("{} before {:?}", g.kind, since(&g.kind)))); + } + match g.kind.as_str() { + "DIMASSOC" => encode_dimassoc(w, g), + "MATERIAL" => encode_material(w, g), + "TABLESTYLE" => encode_tablestyle(w, g, &Lookup::new(d)), + k => match layout(k) { + Some(l) => encode_layout(w, g, &l), + None => Err(Error::unsupported(format!("{k} is kept for DXF only"))), + }, + } +} + +/// The first version whose records of `kind` this module reads and writes: +/// the raster objects' layouts are the specification's, for every +/// version; the others come from AutoCAD 2027's R2013 and later files. +fn since(kind: &str) -> V { + match kind { + "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES" => V::R13, + _ => V::R2013, + } +} + +/// Names and handles the codecs look up in the drawing: text styles by +/// name for the table style (DXF names its text style, DWG points at it). +pub(crate) struct Lookup { + text_styles: Vec<(String, Handle)>, +} + +impl Lookup { + #[cfg(test)] + pub(crate) fn empty() -> Lookup { + Lookup { text_styles: Vec::new() } + } + + pub fn new(d: &Drawing) -> Lookup { + let text_styles = d + .objects + .values() + .filter_map(|o| match &o.kind { + ObjectKind::TextStyle(t) => Some((t.name.clone(), o.handle)), + ObjectKind::NamedRecord(r) if o.type_code == 0x35 => Some((r.name.clone(), o.handle)), + _ => None, + }) + .collect(); + Lookup { text_styles } + } + fn style_handle(&self, name: &str) -> Handle { + self.text_styles.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, h)| *h).unwrap_or(Handle::NULL) + } + fn style_name(&self, h: Handle) -> String { + self.text_styles.iter().find(|(_, x)| *x == h).map(|(n, _)| n.clone()).unwrap_or_default() + } +} + +// --------------------------------------------------------------------------- +// DIMASSOC +// --------------------------------------------------------------------------- + +/// DIMASSOC: the dimension (330), the association flags (90: one bit per +/// point reference present, up to four), the transformation-space flag +/// (70) and rotated-dimension type (71), then each point reference: its +/// class (1), osnap type (72), main objects (331), subentity type (73), +/// graphics marker (91), geometry parameter (40), point (10) and whether +/// a last point reference follows (75). References with intersection +/// objects or xref paths are not handled. +fn decode_dimassoc(s: &mut Streams, own: u64) -> Result> { + let mut out = vec![(100, XrValue::Str("AcDbDimAssoc".into()))]; + let flags = s.dat.bl()?; + let trans = s.dat.b()?; + let rotated = s.dat.rc()?; + let dim = s.h_abs(own)?; + out.push((330, XrValue::Handle(Handle(dim)))); + out.push((90, XrValue::Int32(flags as i32))); + out.push((70, XrValue::Int16(trans as i16))); + out.push((71, XrValue::Int16(rotated as i16))); + for bit in 0..4 { + if flags & (1 << bit) == 0 { + continue; + } + let class = s.tv()?; + let osnap = s.dat.rc()?; + let n = s.dat.bl()? as usize; + if n > 64 { + return Err(Error::format("DIMASSOC: object count")); + } + let mut mains = Vec::with_capacity(n); + for _ in 0..n { + mains.push(s.h_abs(own)?); + } + let subent = s.dat.bs()?; + let marker = s.dat.bl()?; + let extra = s.dat.bl()?; + if extra != 0 { + return Err(Error::format("DIMASSOC: intersection or xref data")); + } + let param = s.dat.bd()?; + let p = s.dat.bd3()?; + let last = s.dat.b()?; + out.push((1, XrValue::Str(class))); + out.push((72, XrValue::Int16(osnap as i16))); + for m in mains { + out.push((331, XrValue::Handle(Handle(m)))); + } + out.push((73, XrValue::Int16(subent as i16))); + out.push((91, XrValue::Int32(marker as i32))); + out.push((40, XrValue::Real(param))); + out.push((10, XrValue::Point(Vec3::new(p[0], p[1], p[2])))); + out.push((75, XrValue::Int16(last as i16))); + } + Ok(out) +} + +fn encode_dimassoc(w: &mut ObjW, g: &Groups) -> Result<()> { + let mut c = Cur::new(g); + if c.str(100)? != "AcDbDimAssoc" { + return Err(Error::format("DIMASSOC: subclass")); + } + let dim = c.handle(330)?; + let flags = c.int(90)?; + w.dat.bl(flags as u32); + w.dat.b(c.int(70)? != 0); + w.dat.rc(c.int(71)? as u8); + w.h(Ref::SoftPtr, dim); + for bit in 0..4 { + if flags & (1 << bit) == 0 { + continue; + } + w.tv(&c.str(1)?); + w.dat.rc(c.int(72)? as u8); + let mut mains = Vec::new(); + while c.peek() == Some(331) { + mains.push(c.handle(331)?); + } + w.dat.bl(mains.len() as u32); + for m in mains { + w.h(Ref::SoftPtr, m); + } + w.dat.bs(c.int(73)? as u16); + w.dat.bl(c.int(91)? as u32); + // Writers that follow the DXF reference give a 301 here, empty when + // the reference has no intersection or xref data (AutoCAD leaves it + // out then). + if c.peek() == Some(301) && !c.str(301)?.is_empty() { + return Err(Error::unsupported("DIMASSOC: intersection or xref data")); + } + w.dat.bl(0); + w.dat.bd(c.real(40)?); + let p = match from_xr(c.take(10)?) { + Val::Point(p) => p, + _ => return Err(Error::format("DIMASSOC: point expected")), + }; + w.dat.bd3([p.x, p.y, p.z]); + w.dat.b(c.int(75)? != 0); + } + c.done() +} + +// --------------------------------------------------------------------------- +// MATERIAL +// --------------------------------------------------------------------------- + +/// A material's record between its name and its six map transforms, and +/// after the last, as AutoCAD writes its default materials (ByLayer, +/// ByBlock, Global). The DXF of those materials gives only the name, the +/// map sources (all 0) and the six matrices; the rest of each record is +/// AutoCAD's default values, which these runs hold. A material with any +/// other property set is not handled. +const MATERIAL_RUNS: [&str; 7] = [ + "0000000001000000000101000000100000000100000001", + "00000000000000000101000000100000000100000001", + "0000000000000000000000000000000000000000000000000000000000111000000011111101000000100000000100000001", + "000000000101000000100000000100000001", + "0000000001000000100000000100000001", + "000000000101000000100000000100000001", + "0000000010101010010111111110", +]; +/// The matrix codes, and the DXF-only source group (0) before each but the +/// last. +const MATERIAL_MAPS: [(u16, Option); 6] = [(43, Some(72)), (47, Some(77)), (49, Some(171)), (142, Some(175)), (144, Some(179)), (147, None)]; + +fn read_run(r: &mut BitReader, run: &str) -> Result<()> { + for ch in run.bytes() { + if r.b()? != (ch == b'1') { + return Err(Error::format("MATERIAL: not one of AutoCAD's default materials")); + } + } + Ok(()) +} + +fn decode_material(s: &mut Streams) -> Result> { + let name = s.tv()?; + let description = s.tv()?; + let mut out = vec![(100, XrValue::Str("AcDbMaterial".into())), (1, XrValue::Str(name))]; + // DXF gives the description only when there is one. + if !description.is_empty() { + out.push((2, XrValue::Str(description))); + } + for (i, (code, source)) in MATERIAL_MAPS.iter().enumerate() { + read_run(&mut s.dat, MATERIAL_RUNS[i])?; + if let Some(src) = source { + out.push((*src, XrValue::Int16(0))); + } + for _ in 0..16 { + out.push((*code, XrValue::Real(s.dat.bd()?))); + } + } + read_run(&mut s.dat, MATERIAL_RUNS[6])?; + Ok(out) +} + +fn encode_material(w: &mut ObjW, g: &Groups) -> Result<()> { + let mut c = Cur::new(g); + if c.str(100)? != "AcDbMaterial" { + return Err(Error::format("MATERIAL: subclass")); + } + w.tv(&c.str(1)?); + w.tv(&if c.peek() == Some(2) { c.str(2)? } else { String::new() }); + for (i, (code, source)) in MATERIAL_MAPS.iter().enumerate() { + for ch in MATERIAL_RUNS[i].bytes() { + w.dat.b(ch == b'1'); + } + if let Some(src) = source + && c.int(*src)? != 0 + { + return Err(Error::format("MATERIAL: map source other than the default")); + } + for _ in 0..16 { + w.dat.bd(c.real(*code)?); + } + } + for ch in MATERIAL_RUNS[6].bytes() { + w.dat.b(ch == b'1'); + } + c.done() +} + +// --------------------------------------------------------------------------- +// TABLESTYLE +// --------------------------------------------------------------------------- + +/// One row style of a table style as DXF gives it (the pre-2008 layout +/// AutoCAD still writes to DXF): text style, height, alignment, text and +/// fill colours, data type and unit, format. +#[derive(Debug, Clone, PartialEq)] +struct RowStyle { + text_style: Handle, + height: f64, + alignment: i64, + text_color: i64, + fill_color: i64, + fill_on: bool, + data_type: i64, + unit_type: i64, + format: String, +} + +/// The borders DXF gives each row (lineweight, visibility, colour, six +/// times), as every row of AutoCAD's default table style has them; the +/// DWG record then stores no border. +const DEFAULT_BORDER: (i64, i64, i64) = (-2, 1, 0); + +/// The table style in DWG (spec §20.4.101.2, R24): a header, the "Table" +/// cell style, then the title, header and data cell styles, each a cell +/// style (§20.4.101.4) with no margin overrides and no borders. AutoCAD's +/// DXF gives the pre-2008 layout (rows in the order data, title, header); +/// both carry the same values for a style with default borders and +/// margins, which is what this handles. +fn decode_tablestyle(s: &mut Streams, own: u64, d: &Lookup) -> Result> { + let version = s.dat.rc()?; + let description = s.tv()?; + let flow = s.dat.bl()?; + let next_id = s.dat.bl()?; + if next_id != 101 { + return Err(Error::format("TABLESTYLE: custom cell styles")); + } + let _owner = s.h_abs(own)?; + let table = read_cell_style(s, own)?; + let (id, class, name) = (s.dat.bl()?, s.dat.bl()?, s.tv()?); + if (id, class, name.as_str()) != (4, 2, "Table") || table.1 != 0 { + return Err(Error::format("TABLESTYLE: unexpected table cell style")); + } + let n = s.dat.bl()?; + if n != 3 { + return Err(Error::format("TABLESTYLE: cell style count")); + } + let mut rows = Vec::new(); + for want in 1..=3u32 { + let pre = s.dat.bl()?; + let (row, merge) = read_cell_style(s, own)?; + let (id, _class, _name) = (s.dat.bl()?, s.dat.bl()?, s.tv()?); + if pre != want || id != want || merge != if want == 1 { 0x8000 } else { 0 } { + return Err(Error::format("TABLESTYLE: unexpected cell style")); + } + rows.push(row); + } + let mut out = vec![ + (100, XrValue::Str("AcDbTableStyle".into())), + (280, XrValue::Int8(version as i8)), + (3, XrValue::Str(description)), + (70, XrValue::Int16(flow as i16)), + (71, XrValue::Int16(0)), + (40, XrValue::Real(0.06)), + (41, XrValue::Real(0.06)), + (280, XrValue::Int8(0)), + (281, XrValue::Int8(0)), + ]; + // DXF order: data, title, header. + for row in [&rows[2], &rows[0], &rows[1]] { + out.push((7, XrValue::Str(d.style_name(row.text_style)))); + out.push((140, XrValue::Real(row.height))); + out.push((170, XrValue::Int16(row.alignment as i16))); + out.push((62, XrValue::Int16(row.text_color as i16))); + out.push((63, XrValue::Int16(row.fill_color as i16))); + out.push((283, XrValue::Int8(row.fill_on as i8))); + out.push((90, XrValue::Int32(row.data_type as i32))); + out.push((91, XrValue::Int32(row.unit_type as i32))); + out.push((1, XrValue::Str(row.format.clone()))); + for k in 0..6u16 { + out.push((274 + k, XrValue::Int16(DEFAULT_BORDER.0 as i16))); + out.push((284 + k, XrValue::Int8(DEFAULT_BORDER.1 as i8))); + out.push((64 + k, XrValue::Int16(DEFAULT_BORDER.2 as i16))); + } + } + Ok(out) +} + +/// A cell style with data, no margin overrides and no borders; returns the +/// row values and the merge flags. +fn read_cell_style(s: &mut Streams, own: u64) -> Result<(RowStyle, u32)> { + let kind = s.dat.bl()?; + let has_data = s.dat.bs()?; + if kind != 5 || has_data != 1 { + return Err(Error::format("TABLESTYLE: cell style without data")); + } + let overrides = s.dat.bl()?; + let merge = s.dat.bl()?; + let background = read(s, own, D::Cmc)?; + let layout = s.dat.bl()?; + let (cf90, cf91) = (s.dat.bl()?, s.dat.bl()?); + let data_type = s.dat.bl()? as i64; + let unit_type = s.dat.bl()? as i64; + let format = s.tv()?; + let rotation = s.dat.bd()?; + let block_scale = s.dat.bd()?; + let alignment = s.dat.bl()? as i64; + let color = read(s, own, D::Cmc)?; + let text_style = Handle(s.h_abs(own)?); + let height = s.dat.bd()?; + let margins = s.dat.bs()?; + let borders = s.dat.bl()?; + if overrides != 0 || layout != 1 || cf90 != 0 || cf91 != 0 || rotation != 0.0 || block_scale != 1.0 || margins != 0 || borders != 0 { + return Err(Error::format("TABLESTYLE: cell style with overrides, margins or borders")); + } + let (fill_on, fill_color) = match background { + Val::Color(0xC800_0000) => (false, 7), + Val::Color(w) => (true, aci_of(w)), + _ => (false, 7), + }; + let text_color = match color { + Val::Color(w) => aci_of(w), + _ => 0, + }; + Ok((RowStyle { text_style, height, alignment, text_color, fill_color, fill_on, data_type, unit_type, format }, merge)) +} + +fn aci_of(word: u32) -> i64 { + let mut v = Vec::new(); + color_groups(62, word, &mut v); + match v[0].1 { + XrValue::Int16(i) => i as i64, + _ => 7, + } +} + +fn write_cell_style(w: &mut ObjW, row: &RowStyle, merge: u32, text_style: Handle) { + w.dat.bl(5); + w.dat.bs(1); + w.dat.bl(0); + w.dat.bl(merge); + let bg = if row.fill_on { word_of(row.fill_color, None) } else { 0xC800_0000 }; + write(w, D::Cmc, &Val::Color(bg)).ok(); + w.dat.bl(1); + w.dat.bl(0); + w.dat.bl(0); + w.dat.bl(row.data_type as u32); + w.dat.bl(row.unit_type as u32); + w.tv(&row.format); + w.dat.bd(0.0); + w.dat.bd(1.0); + w.dat.bl(row.alignment as u32); + write(w, D::Cmc, &Val::Color(word_of(row.text_color, None))).ok(); + w.h(Ref::HardPtr, text_style); + w.dat.bd(row.height); + w.dat.bs(0); + w.dat.bl(0); +} + +/// Groups a table style's row may hold after its text style (7). +fn is_row_group(code: u16) -> bool { + matches!(code, 140 | 170 | 62 | 63 | 283 | 90 | 91 | 1 | 274..=279 | 284..=289 | 64..=69) +} + +/// One row style of a table style: its text style (7), then its groups up +/// to the next row's text style or the end, in whatever order the file has +/// them. AutoCAD interleaves each border's lineweight, visibility and +/// colour (274, 284, 64, 275, …); the DXF reference lists them by kind +/// (274–279, 284–289, 64–69), which other writers follow, and its older +/// layout has no cell data type, unit type or format (90, 91, 1), which +/// then take the values AutoCAD writes (512, 0, none). +fn row_style(c: &mut Cur<'_>, d: &Lookup) -> Result { + let style = c.str(7)?; + let start = c.at; + while c.peek().is_some_and(|code| code != 7) { + c.at += 1; + } + let groups = c.items.get(start..c.at).unwrap_or_default(); + let kind = c.kind; + if let Some((code, _)) = groups.iter().find(|(code, _)| !is_row_group(*code)) { + return Err(Error::format(format!("{kind}: unexpected group {code} in a row style"))); + } + let value = |code: u16| groups.iter().find(|(c, _)| *c == code).map(|(_, v)| v); + let number = |code: u16, missing: Option| -> Result { + match value(code).map(from_xr) { + Some(Val::Int(i)) => Ok(i as f64), + Some(Val::Real(f)) => Ok(f), + Some(v) => Err(Error::format(format!("{kind}: group {code}: number expected, {v:?}"))), + None => missing.ok_or_else(|| Error::format(format!("{kind}: a row style without group {code}"))), + } + }; + let int = |code: u16, missing: Option| number(code, missing.map(|m| m as f64)).map(|f| f as i64); + let format = match value(1) { + Some(XrValue::Str(s)) => s.clone(), + Some(v) => return Err(Error::format(format!("{kind}: group 1: text expected, {v:?}"))), + None => String::new(), + }; + for k in 0..6u16 { + let border = (int(274 + k, Some(DEFAULT_BORDER.0))?, int(284 + k, Some(DEFAULT_BORDER.1))?, int(64 + k, Some(DEFAULT_BORDER.2))?); + if border != DEFAULT_BORDER { + return Err(Error::unsupported("TABLESTYLE: borders other than the default")); + } + } + Ok(RowStyle { + text_style: d.style_handle(&style), + height: number(140, None)?, + alignment: int(170, None)?, + text_color: int(62, None)?, + fill_color: int(63, None)?, + fill_on: int(283, None)? != 0, + data_type: int(90, Some(512))?, + unit_type: int(91, Some(0))?, + format, + }) +} + +fn encode_tablestyle(w: &mut ObjW, g: &Groups, d: &Lookup) -> Result<()> { + let mut c = Cur::new(g); + if c.str(100)? != "AcDbTableStyle" { + return Err(Error::format("TABLESTYLE: subclass")); + } + // The DXF of AutoCAD 2007 and later starts with the version; the + // reference's older layout, which other writers follow, has none. + let version = if c.peek() == Some(280) { c.int(280)? } else { 0 }; + let description = c.str(3)?; + let flow = c.int(70)?; + let flags = c.int(71)?; + let _h_margin = c.real(40)?; + let _v_margin = c.real(41)?; + let suppress_title = c.int(280)?; + let suppress_header = c.int(281)?; + if flags != 0 || suppress_title != 0 || suppress_header != 0 { + return Err(Error::unsupported("TABLESTYLE: flags or suppressed rows")); + } + let mut rows = Vec::new(); + for _ in 0..3 { + rows.push(row_style(&mut c, d)?); + } + c.done()?; + let (data, title, header) = (&rows[0], &rows[1], &rows[2]); + w.dat.rc(version as u8); + w.tv(&description); + w.dat.bl(flow as u32); + w.dat.bl(101); + w.h(Ref::HardOwner, Handle::NULL); + // The "Table" cell style: AutoCAD's defaults, at the data rows' height. + let table = RowStyle { + text_style: Handle::NULL, + alignment: 1, + text_color: 0, + fill_on: false, + fill_color: 7, + format: String::new(), + data_type: 512, + unit_type: 0, + height: data.height, + }; + write_cell_style(w, &table, 0, Handle::NULL); + w.dat.bl(4); + w.dat.bl(2); + w.tv("Table"); + w.dat.bl(3); + for (id, class, name, row, merge) in [(1u32, 1u32, "_TITLE", title, 0x8000u32), (2, 1, "_HEADER", header, 0), (3, 2, "_DATA", data, 0)] { + w.dat.bl(id); + write_cell_style(w, row, merge, row.text_style); + w.dat.bl(id); + w.dat.bl(class); + w.tv(name); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A style object's groups as DXF gives them, every value plain, and + /// the repeated list claiming `claimed` items while holding two. + fn groups(kind: &str, claimed: i32) -> Groups { + let l = layout(kind).expect("a laid-out kind"); + let mut items = Vec::new(); + for f in &l.dxf { + match f { + G::M(name) => items.push((100, XrValue::Str(name.to_string()))), + G::V(code, D::Tv) => items.push((*code, XrValue::Str(String::new()))), + G::V(code, D::Bd) => items.push((*code, XrValue::Real(1.0))), + G::V(code, D::H(_)) => items.push((*code, XrValue::Handle(Handle::NULL))), + G::V(code, D::Cmc) => items.push((*code, XrValue::Int16(256))), + G::V(code, _) => items.push((*code, XrValue::Int32(0))), + G::X(code, v) => items.push((*code, XrValue::Int16(*v as i16))), + G::OptH(_) => {} + G::Tail(code, _, v) => items.push((*code, XrValue::Int16(*v as i16))), + G::Rep(count, _, item, _) => { + items.push((*count, XrValue::Int32(claimed))); + items.push((*item, XrValue::Real(0.5))); + items.push((*item, XrValue::Real(0.25))); + } + } + } + Groups { kind: kind.into(), items } + } + + #[test] + fn a_claimed_count_does_not_size_the_list() { + let l = layout("ACDBSECTIONVIEWSTYLE").expect("laid out"); + // Sound: two items, both written. + let mut w = ObjW::new(V::R2018, Handle(0x100)); + 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)); + encode_layout(&mut w, &groups("ACDBSECTIONVIEWSTYLE", i32::MAX), &l).unwrap(); + } +} diff --git a/crates/dwg/src/read/tables.rs b/crates/dwg/src/read/tables.rs new file mode 100644 index 00000000..0e9031f1 --- /dev/null +++ b/crates/dwg/src/read/tables.rs @@ -0,0 +1,483 @@ +//! Symbol-table objects: control objects, BLOCK_HEADER, LAYER and the +//! common fields of other table records. +//! +//! Written from knowledge of the spec, chapter 20. VERIFY against the spec +//! PDF and real files. + +use super::streams::Streams; +use super::version::DwgVersion as V; +use crate::read::error::{Error, Result}; +use crate::read::geom::{Vec2, Vec3}; +use crate::read::model::{BlockHeader, Control, Handle, Layer, Linetype, LinetypeElement, NamedRecord, ObjectKind, TextStyle}; + +/// Fields every table record starts with: name, the "64" flag, the xref +/// index and the xref-dependent flag. +fn record_common(s: &mut Streams) -> Result { + Ok(record_common_flags(s)?.0) +} + +/// The common fields with the two flags as DXF 70 bits: 64 (referenced) +/// and 16 (dependent on an xref). +/// +/// From R2007 the record stores only the xref index: an AC1032 file saved +/// by AutoCAD LT 2026 has no 64-flag and no xref-dependent bit (every +/// LAYER, APPID and BLOCK_HEADER record then ends exactly where its +/// string stream begins; with the two bits none does). The specification +/// (§20.4.52 and the other table records) still lists both bits. Whether +/// the change came with R2007, R2010 or R2013 is not yet confirmed by +/// files of those versions; `object.rs` reports a record whose data does +/// not end at its strings, which is how a wrong guess would show. +fn record_common_flags(s: &mut Streams) -> Result<(String, u16)> { + let name = s.tv()?; + if s.ver.has_string_stream() { + let _xref_index_plus1 = s.dat.bs()?; + return Ok((name, 0)); + } + let flag64 = s.dat.b()?; + let _xref_index_plus1 = s.dat.bs()?; + let xref_dependent = s.dat.b()?; + Ok((name, ((flag64 as u16) << 6) | ((xref_dependent as u16) << 4))) +} + +/// Returns the control object and its entry count. +pub(crate) fn control(s: &mut Streams) -> Result<(Control, u32)> { + let n = s.dat.bl()?; + Ok((Control::default(), n)) +} + +pub(crate) struct BlockHeaderCounts { + pub owned: u32, + pub inserts: u32, + pub lists_entities: bool, +} + +pub(crate) fn block_header(s: &mut Streams) -> Result<(BlockHeader, BlockHeaderCounts)> { + let mut b = BlockHeader { name: record_common(s)?, ..Default::default() }; + b.anonymous = s.dat.b()?; + b.has_attribs = s.dat.b()?; + b.is_xref = s.dat.b()?; + b.is_overlaid = s.dat.b()?; + if s.ver >= V::R2000 { + let _loaded = s.dat.b()?; + } + let lists_entities = !b.is_xref && !b.is_overlaid; + let owned = if s.ver >= V::R2004 && lists_entities { s.dat.bl()? } else { 0 }; + b.base_point = Vec3::from_array(s.dat.bd3()?); + b.xref_path = s.tv()?; + let mut inserts = 0u32; + if s.ver >= V::R2000 { + // A run of non-zero bytes, one per insert handle, ended by a zero. + loop { + let c = s.dat.rc()?; + if c == 0 { + break; + } + inserts += 1; + if inserts > 1_000_000 { + return Err(Error::format("BLOCK_HEADER insert count runaway")); + } + } + b.description = s.tv()?; + let preview = s.dat.bl()? as usize; + s.dat.skip_bits(preview.saturating_mul(8))?; + } + if s.ver >= V::R2007 { + b.insert_units = s.dat.bs()?; + b.not_explodable = !s.dat.b()?; + let _scaling = s.dat.rc()?; + } + Ok((b, BlockHeaderCounts { owned, inserts, lists_entities })) +} + +pub(crate) fn layer(s: &mut Streams) -> Result { + let mut l = Layer { name: record_common(s)?, plot: true, ..Default::default() }; + if s.ver <= V::R14 { + let frozen = s.dat.b()?; + let on = s.dat.b()?; + let frozen_new = s.dat.b()?; + let locked = s.dat.b()?; + l.frozen = frozen; + l.locked = locked; + l.flags = (frozen as u16) | ((!on as u16) << 1) | ((frozen_new as u16) << 2) | ((locked as u16) << 3); + } else { + let flags = s.dat.bs()?; + l.flags = flags; + l.frozen = flags & 0x01 != 0; + l.locked = flags & 0x08 != 0; + l.plot = flags & 0x10 != 0; + l.lineweight = ((flags & 0x03E0) >> 5) as u8; + } + let (color, index) = s.cmc()?; + // Up to R14 a negative colour index marks a layer that is switched + // off. From R2000 the flag word's 0x02 bit says it: the spec (§20.4.54) + // calls the bit "on", but AutoCAD 2027's files leave it clear on every + // layer their DXF shows on (corpus MI-201, 2000 to 2018), so a set bit + // is a layer that is off. From R2004 the colour's index field is always + // 0 (the colour is in the method word), so its sign says nothing. + l.off = if s.ver >= V::R2000 { l.flags & 0x02 != 0 } else { index < 0 }; + l.color = color; + Ok(l) +} + +/// VIEW, UCS, VPORT, DIMSTYLE, VX records: only the name is decoded for +/// now. +pub(crate) fn named_record(s: &mut Streams) -> Result { + Ok(NamedRecord { name: record_common(s)? }) +} + +/// APPID (§20.4.66): the name, then an undocumented RC (DXF 71), which an +/// AC1032 file confirms is there. +pub(crate) fn appid(s: &mut Streams) -> Result { + let name = record_common(s)?; + let _unknown71 = s.dat.rc()?; + Ok(NamedRecord { name }) +} + +/// Most elements AutoCAD allows in one linetype pattern. +const MAX_DASHES: usize = 12; + +/// LTYPE (ODA spec §20.4.58, read from the specification text): name, +/// description and pattern. Not yet checked against real files, so the +/// record must pass checks the specification makes possible (alignment +/// 'A', at most 12 elements, element lengths adding up to the pattern +/// length); one that does not is kept by name only, as before. +pub(crate) fn linetype(s: &mut Streams) -> Result { + let (name, flags) = record_common_flags(s)?; + Ok(match linetype_body(s, &name, flags) { + Ok(lt) => ObjectKind::Linetype(lt), + Err(_) => ObjectKind::NamedRecord(NamedRecord { name }), + }) +} + +fn linetype_body(s: &mut Streams, name: &str, flags: u16) -> Result { + let description = s.tv()?; + let pattern_length = s.dat.bd()?; + let alignment = s.dat.rc()?; + let n = s.dat.rc()? as usize; + if alignment != b'A' || n > MAX_DASHES || !pattern_length.is_finite() || pattern_length < 0.0 { + return Err(Error::format("LTYPE: unexpected pattern header")); + } + let mut elements = Vec::with_capacity(n); + for _ in 0..n { + let length = s.dat.bd()?; + let shape = s.dat.bs()?; + let x = s.dat.rd()?; + let y = s.dat.rd()?; + let scale = s.dat.bd()?; + let rotation = s.dat.bd()?; + let complex = s.dat.bs()?; + elements.push(LinetypeElement { length, complex, shape, style: Handle::NULL, scale, rotation, offset: Vec2::new(x, y), text: String::new() }); + } + let sane = elements + .iter() + .all(|e| e.length.is_finite() && e.length.abs() < 1e9 && e.offset.is_finite() && e.scale.is_finite() && e.rotation.is_finite()); + let sum: f64 = elements.iter().map(|e| e.length.abs()).sum(); + if !sane || (sum - pattern_length).abs() > 1e-6 * (1.0 + pattern_length) { + return Err(Error::format("LTYPE: elements do not add up to the pattern")); + } + // Text elements (DXF 74 bit 2) find their string in a text area by + // their 75 value: 0-terminated strings, 256 bytes up to R2004, and 512 + // bytes of UTF-16 from R2007, present only when some element is text. + // Shape elements (bit 4) keep their shape number in 75. The spec's note + // on the shape flag gives these two bits the other way round, against + // its own R2007 rule and the DXF reference for group 74; the DXF + // meaning is used. VERIFY with real files. A missing area only loses + // the text (the handles are in their own stream). + let is_text = |e: &LinetypeElement| e.complex & 2 != 0; + if s.ver <= V::R2004 { + if let Ok(area) = s.dat.raw_bytes(256) { + for e in elements.iter_mut().filter(|e| is_text(e)) { + let start = (e.shape as usize).min(area.len()); + let end = area[start..].iter().position(|&b| b == 0).map_or(area.len(), |p| start + p); + e.text = crate::read::text::decode_ansi(&area[start..end], s.codepage); + e.shape = 0; + } + } + } else if elements.iter().any(is_text) { + // R2007+: 512 bytes "if the 0x02 bit is set on any shape flag" + // (the spec's words), read as UTF-16. VERIFY with real files. + if let Ok(area) = s.dat.raw_bytes(512) { + for e in elements.iter_mut().filter(|e| is_text(e)) { + let units: Vec = area + .get(e.shape as usize..) + .unwrap_or(&[]) + .as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .take_while(|&u| u != 0) + .collect(); + e.text = String::from_utf16_lossy(&units); + e.shape = 0; + } + } + } + Ok(Linetype { name: name.to_string(), description, flags, pattern_length, elements }) +} + +/// STYLE (ODA spec §20.4.56, read from the specification text, and checked +/// against its example): name, flags, sizes and font files. A record whose +/// values are out of range is kept by name only. +pub(crate) fn text_style(s: &mut Streams) -> Result { + let (name, flags) = record_common_flags(s)?; + Ok(match text_style_body(s, &name, flags) { + Ok(t) => ObjectKind::TextStyle(t), + Err(_) => ObjectKind::NamedRecord(NamedRecord { name }), + }) +} + +fn text_style_body(s: &mut Streams, name: &str, flags: u16) -> Result { + let vertical = s.dat.b()?; + let shape_file = s.dat.b()?; + let height = s.dat.bd()?; + let width_factor = s.dat.bd()?; + let oblique = s.dat.bd()?; + let generation = s.dat.rc()?; + let last_height = s.dat.bd()?; + let font_file = s.tv()?; + let bigfont_file = s.tv()?; + let ok = height.is_finite() + && height >= 0.0 + && width_factor.is_finite() + && width_factor > 0.0 + && width_factor <= 100.0 + && oblique.is_finite() + && oblique.abs() < std::f64::consts::FRAC_PI_2 + && last_height.is_finite() + && last_height >= 0.0; + if !ok { + return Err(Error::format("STYLE: values out of range")); + } + Ok(TextStyle { + name: name.to_string(), + flags: flags | (shape_file as u16) | ((vertical as u16) << 2), + height, + width_factor, + oblique, + generation: generation as u16, + last_height, + font_file, + bigfont_file, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bits::BitReader; + + /// Writes DWG bit codes, first bit most significant, for building + /// records in tests. + #[derive(Default)] + struct Bits { + out: Vec, + n: usize, + } + + impl Bits { + fn bit(&mut self, v: bool) { + if self.n.is_multiple_of(8) { + self.out.push(0); + } + if v { + let last = self.out.len() - 1; + self.out[last] |= 0x80 >> (self.n % 8); + } + self.n += 1; + } + fn bits(&mut self, v: u64, count: u32) { + for i in (0..count).rev() { + self.bit((v >> i) & 1 == 1); + } + } + fn rc(&mut self, v: u8) { + self.bits(v as u64, 8); + } + fn rd(&mut self, v: f64) { + for b in v.to_le_bytes() { + self.rc(b); + } + } + fn bs(&mut self, v: u16) { + match v { + 0 => self.bits(2, 2), + 1..=255 => { + self.bits(1, 2); + self.rc(v as u8); + } + _ => { + self.bits(0, 2); + self.rc(v as u8); + self.rc((v >> 8) as u8); + } + } + } + fn bd(&mut self, v: f64) { + if v == 1.0 { + self.bits(1, 2); + } else if v == 0.0 { + self.bits(2, 2); + } else { + self.bits(0, 2); + self.rd(v); + } + } + fn tv(&mut self, s: &str) { + self.bs(s.len() as u16); + for b in s.bytes() { + self.rc(b); + } + } + /// Name, 64-flag, xref index + 1, xref-dependent. + fn record(&mut self, name: &str) { + self.tv(name); + self.bit(false); + self.bs(0); + self.bit(false); + } + } + + fn ltype_bytes(alignment: u8, dashes: &[f64], text: Option<&str>) -> Vec { + let mut w = Bits::default(); + w.record("GAS"); + w.tv("Gas line"); + w.bd(dashes.iter().map(|d| d.abs()).sum()); + w.rc(alignment); + w.rc(dashes.len() as u8); + for (i, &d) in dashes.iter().enumerate() { + w.bd(d); + let is_text = text.is_some() && i == 1; + w.bs(if is_text { 1 } else { 0 }); // shape code: offset 1 in the area + w.rd(if is_text { -0.1 } else { 0.0 }); + w.rd(0.0); + w.bd(1.0); + w.bd(0.0); + w.bs(if is_text { 2 } else { 0 }); + } + let mut area = [0u8; 256]; + if let Some(t) = text { + area[1..1 + t.len()].copy_from_slice(t.as_bytes()); + } + for b in area { + w.rc(b); + } + w.out + } + + fn read(bytes: &[u8]) -> ObjectKind { + let mut s = Streams { ver: V::R2000, codepage: 30, dat: BitReader::new(bytes), strs: None, hdl: None }; + linetype(&mut s).unwrap() + } + + #[test] + fn linetype_patterns_and_text_elements_are_read() { + match read(<ype_bytes(b'A', &[12.0, -1.5, 3.0, -1.5], None)) { + ObjectKind::Linetype(l) => { + assert_eq!(l.name, "GAS"); + assert_eq!(l.description, "Gas line"); + assert_eq!(l.dashes(), vec![12.0, -1.5, 3.0, -1.5]); + assert_eq!(l.pattern_length, 18.0); + } + other => panic!("{other:?}"), + } + match read(<ype_bytes(b'A', &[12.7, -5.08, 0.0], Some("GAS"))) { + ObjectKind::Linetype(l) => { + assert_eq!(l.elements[1].text, "GAS"); + assert_eq!(l.elements[1].complex, 2); + assert_eq!(l.elements[1].shape, 0); + assert_eq!(l.elements[1].offset, Vec2::new(-0.1, 0.0)); + } + other => panic!("{other:?}"), + } + } + + /// An LTYPE record of `ver` named GAS, its elements given as (length, + /// DXF 74 flags, 75 code), followed by `area`. + fn ltype_in(ver: V, elements: &[(f64, u16, u16)], area: &[u8], referenced: bool) -> ObjectKind { + let mut w = Bits::default(); + let strings_apart = ver.has_string_stream(); + if !strings_apart { + w.tv("GAS"); + } + if strings_apart { + // R2007+: the xref index only (see `record_common_flags`). + w.bs(0); + } else { + w.bit(referenced); + w.bs(0); + w.bit(referenced); + } + if !strings_apart { + w.tv(""); + } + w.bd(elements.iter().map(|e| e.0.abs()).sum()); + w.rc(b'A'); + w.rc(elements.len() as u8); + for &(length, flags, code) in elements { + w.bd(length); + w.bs(code); + w.rd(0.0); + w.rd(0.0); + w.bd(1.0); + w.bd(0.0); + w.bs(flags); + } + for &b in area { + w.rc(b); + } + let mut s = Streams { ver, codepage: 30, dat: BitReader::new(&w.out), strs: None, hdl: None }; + linetype(&mut s).unwrap() + } + + #[test] + fn text_and_shape_elements_by_their_flag_bits() { + let lt = |k: ObjectKind| match k { + ObjectKind::Linetype(l) => l, + other => panic!("{other:?}"), + }; + // R2000: the 256-byte area is always there. + let mut area = vec![0u8; 256]; + area[1..4].copy_from_slice(b"GAS"); + let text = lt(ltype_in(V::R2000, &[(12.7, 0, 0), (-5.08, 2, 1)], &area, false)); + assert_eq!((text.elements[1].text.as_str(), text.elements[1].shape), ("GAS", 0)); + let shape = lt(ltype_in(V::R2000, &[(12.7, 0, 0), (-5.08, 4, 130)], &area, false)); + let e = &shape.elements[1]; + assert_eq!((e.text.as_str(), e.shape, e.complex), ("", 130, 4)); + // R2010: 512 bytes of UTF-16, there only when an element is text. + let mut area = vec![0u8; 512]; + for (i, u) in "GAS".encode_utf16().enumerate() { + area[2 + 2 * i..4 + 2 * i].copy_from_slice(&u.to_le_bytes()); + } + let text = lt(ltype_in(V::R2010, &[(12.7, 0, 0), (-5.08, 2, 2)], &area, false)); + assert_eq!(text.elements[1].text, "GAS"); + let shape = lt(ltype_in(V::R2010, &[(12.7, 0, 0), (-5.08, 4, 130)], &[], false)); + assert_eq!(shape.elements[1].shape, 130); + // The referenced and xref-dependent bits come through as DXF 70. + let xref = lt(ltype_in(V::R2000, &[(1.0, 0, 0), (-1.0, 0, 0)], &[0; 256], true)); + assert_eq!(xref.flags, 64 | 16); + } + + #[test] + fn linetypes_that_fail_the_checks_keep_their_name() { + // Alignment not 'A': a layout this reader does not trust. + assert_eq!(read(<ype_bytes(b'X', &[1.0, -1.0], None)), ObjectKind::NamedRecord(NamedRecord { name: "GAS".into() })); + // Lengths that do not add up to the pattern length. + let mut w = Bits::default(); + w.record("ODD"); + w.tv(""); + w.bd(99.0); + w.rc(b'A'); + w.rc(1); + w.bd(2.0); + w.bs(0); + w.rd(0.0); + w.rd(0.0); + w.bd(1.0); + w.bd(0.0); + w.bs(0); + assert_eq!(read(&w.out), ObjectKind::NamedRecord(NamedRecord { name: "ODD".into() })); + // Cut short after the name: still the name. + let full = ltype_bytes(b'A', &[1.0, -1.0], None); + assert!(matches!(read(&full[..6]), ObjectKind::NamedRecord(_))); + } +} diff --git a/crates/dwg/src/records/error.rs b/crates/dwg/src/records/error.rs new file mode 100644 index 00000000..3d7cf3b3 --- /dev/null +++ b/crates/dwg/src/records/error.rs @@ -0,0 +1,83 @@ +//! Error type shared by the whole core. + +use std::fmt; + +/// Broad category of a failure. Callers mostly display the message, but the +/// kind lets a UI decide whether to offer "open anyway" or report a bug. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorKind { + /// Reading the file from disk failed. + Io, + /// The file is not a DWG file, or the version code is unknown. + NotDwg, + /// A DWG version we recognise but do not read yet (for example R2007). + UnsupportedVersion, + /// A feature inside a supported file that is not implemented yet + /// (for example password-encrypted sections). + Unsupported, + /// Ran past the end of a buffer or bit stream. + Truncated, + /// Data does not match the structure the specification describes. + Format, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error { + pub kind: ErrorKind, + pub message: String, +} + +pub type Result = std::result::Result; + +impl Error { + pub fn new(kind: ErrorKind, message: impl Into) -> Self { + Error { kind, message: message.into() } + } + pub fn format(message: impl Into) -> Self { + Error::new(ErrorKind::Format, message) + } + pub fn truncated(message: impl Into) -> Self { + Error::new(ErrorKind::Truncated, message) + } + pub fn unsupported(message: impl Into) -> Self { + Error::new(ErrorKind::Unsupported, message) + } + /// Prefix the message with context, keeping the kind. + pub fn context(mut self, ctx: impl fmt::Display) -> Self { + self.message = format!("{ctx}: {}", self.message); + self + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + ErrorKind::Io => "I/O error", + ErrorKind::NotDwg => "not a DWG file", + ErrorKind::UnsupportedVersion => "unsupported DWG version", + ErrorKind::Unsupported => "unsupported feature", + ErrorKind::Truncated => "truncated data", + ErrorKind::Format => "format error", + }; + write!(f, "{kind}: {}", self.message) + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::new(ErrorKind::Io, e.to_string()) + } +} + +/// Attach context to any `Result<_, Error>`. +pub trait ResultExt { + fn ctx(self, ctx: impl fmt::Display) -> Result; +} + +impl ResultExt for Result { + fn ctx(self, ctx: impl fmt::Display) -> Result { + self.map_err(|e| e.context(ctx)) + } +} diff --git a/crates/dwg/src/records/geom/curve.rs b/crates/dwg/src/records/geom/curve.rs new file mode 100644 index 00000000..1d877588 --- /dev/null +++ b/crates/dwg/src/records/geom/curve.rs @@ -0,0 +1,243 @@ +//! Curve helpers: polyline bulges, arc and ellipse tessellation, and NURBS +//! evaluation. + +use super::{EPS, Vec2, Vec3}; +use std::f64::consts::{PI, TAU}; + +/// A circular arc described by centre, radius and start/end angles +/// (radians). The arc runs counter-clockwise from `start` to `end`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ArcSeg { + pub center: Vec2, + pub radius: f64, + pub start: f64, + pub end: f64, +} + +impl ArcSeg { + /// Counter-clockwise sweep in (0, 2π]. + pub fn sweep(&self) -> f64 { + normalize_sweep(self.end - self.start) + } + pub fn point_at(&self, angle: f64) -> Vec2 { + self.center + Vec2::from_angle(angle) * self.radius + } +} + +/// Map an angle difference into (0, 2π]; a zero difference means a full turn. +pub fn normalize_sweep(mut d: f64) -> f64 { + if !d.is_finite() { + return TAU; + } + d %= TAU; + if d <= 1e-12 { + d += TAU; + } + d +} + +pub fn normalize_angle(a: f64) -> f64 { + let mut a = a % TAU; + if a < 0.0 { + a += TAU; + } + a +} + +/// Convert a polyline segment with a bulge into an arc. A bulge is the +/// tangent of a quarter of the included angle; positive bulges turn +/// counter-clockwise. Returns the arc plus whether it runs clockwise from +/// `p1` to `p2` (in which case start/end are swapped so the arc itself is +/// still expressed counter-clockwise). `None` for straight segments. +pub fn bulge_to_arc(p1: Vec2, p2: Vec2, bulge: f64) -> Option<(ArcSeg, bool)> { + if bulge.abs() < 1e-12 || !bulge.is_finite() { + return None; + } + let chord = p2 - p1; + let d = chord.length(); + if d < EPS { + return None; + } + let u = chord / d; + let h = (d / 2.0) * (1.0 - bulge * bulge) / (2.0 * bulge); + let center = (p1 + p2) * 0.5 + u.perp() * h; + let radius = d * (1.0 + bulge * bulge) / (4.0 * bulge.abs()); + let a1 = (p1 - center).angle(); + let a2 = (p2 - center).angle(); + if bulge > 0.0 { + Some((ArcSeg { center, radius, start: a1, end: a2 }, false)) + } else { + Some((ArcSeg { center, radius, start: a2, end: a1 }, true)) + } +} + +/// Number of segments for a sweep so each covers at most `max_step` +/// radians. +pub fn segment_count(sweep: f64, max_step: f64) -> usize { + let n = (sweep.abs() / max_step).ceil(); + if n.is_finite() { (n as usize).clamp(1, 4096) } else { 1 } +} + +/// Default angular step for tessellation: 2° per segment. +pub const DEFAULT_STEP: f64 = PI / 90.0; + +/// Points along an arc, including both ends, counter-clockwise. +pub fn tessellate_arc(arc: &ArcSeg, max_step: f64) -> Vec { + let sweep = arc.sweep(); + let n = segment_count(sweep, max_step); + (0..=n).map(|i| arc.point_at(arc.start + sweep * (i as f64) / (n as f64))).collect() +} + +/// Points along a polyline with bulges. Vertices are `(point, bulge)` +/// where the bulge applies to the segment leaving that vertex. +pub fn tessellate_bulge_polyline(verts: &[(Vec2, f64)], closed: bool, max_step: f64) -> Vec { + let mut out = Vec::new(); + if verts.is_empty() { + return out; + } + let n = verts.len(); + let segs = if closed { n } else { n - 1 }; + out.push(verts[0].0); + for i in 0..segs { + let (p1, b) = verts[i]; + let p2 = verts[(i + 1) % n].0; + match bulge_to_arc(p1, p2, b) { + None => out.push(p2), + Some((arc, reversed)) => { + let mut pts = tessellate_arc(&arc, max_step); + if reversed { + pts.reverse(); + } + out.extend_from_slice(&pts[1..]); + } + } + } + out +} + +/// Points of an ellipse in 3D: centre, major-axis vector (full length to +/// the ellipse), minor-axis vector, parameter range. `end <= start` wraps. +pub fn tessellate_ellipse(center: Vec3, major: Vec3, minor: Vec3, start: f64, end: f64, max_step: f64) -> Vec { + let sweep = normalize_sweep(end - start); + let n = segment_count(sweep, max_step); + (0..=n) + .map(|i| { + let t = start + sweep * (i as f64) / (n as f64); + center + major * t.cos() + minor * t.sin() + }) + .collect() +} + +/// Evaluate a (possibly rational) B-spline at parameter `u` with de Boor's +/// algorithm. `weights` may be empty for a non-rational curve. +pub fn nurbs_point(degree: usize, knots: &[f64], ctrl: &[Vec3], weights: &[f64], u: f64) -> Option { + let n = ctrl.len(); + if n == 0 || degree == 0 || knots.len() < n + degree + 1 { + return None; + } + let p = degree; + // Find the knot span k with knots[k] <= u < knots[k+1], clamped to the + // valid range [p, n-1]. + let mut k = p; + while k < n - 1 && u >= knots[k + 1] { + k += 1; + } + let rational = weights.len() == n; + // Homogeneous control points. + let mut d: Vec<[f64; 4]> = (0..=p) + .map(|j| { + let i = k + j - p; + let w = if rational { weights[i] } else { 1.0 }; + let c = ctrl[i]; + [c.x * w, c.y * w, c.z * w, w] + }) + .collect(); + for r in 1..=p { + for j in (r..=p).rev() { + let i = k + j - p; + let denom = knots[i + p + 1 - r] - knots[i]; + let alpha = if denom.abs() < EPS { 0.0 } else { (u - knots[i]) / denom }; + let prev = d[j - 1]; + for (c, v) in d[j].iter_mut().enumerate() { + *v = (1.0 - alpha) * prev[c] + alpha * *v; + } + } + } + let h = d[p]; + if h[3].abs() < EPS { + return None; + } + Some(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])) +} + +/// Sample a B-spline over its valid parameter range. +pub fn tessellate_nurbs(degree: usize, knots: &[f64], ctrl: &[Vec3], weights: &[f64]) -> Vec { + let n = ctrl.len(); + if n < 2 || degree == 0 || knots.len() < n + degree + 1 { + return ctrl.to_vec(); + } + let u0 = knots[degree]; + let u1 = knots[n]; + // Also rejects NaN knots. + if u1.partial_cmp(&u0) != Some(std::cmp::Ordering::Greater) { + return ctrl.to_vec(); + } + let samples = (n * 16).clamp(32, 2048); + let mut out = Vec::with_capacity(samples + 1); + for i in 0..=samples { + let mut u = u0 + (u1 - u0) * (i as f64) / (samples as f64); + if i == samples { + u = u1 - (u1 - u0) * 1e-12; + } + if let Some(p) = nurbs_point(degree, knots, ctrl, weights, u) { + out.push(p); + } + } + if let Some(last) = ctrl.last() { + // Clamped splines end exactly on the last control point. + if knots[n..].iter().all(|&k| (k - u1).abs() < 1e-12) + && let Some(tail) = out.last_mut() + { + *tail = *last; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 + } + + #[test] + fn semicircle_bulge() { + // Bulge 1 = 180° counter-clockwise from (0,0) to (2,0): centre (1,0), + // radius 1, passing through (1,-1). + let (arc, rev) = bulge_to_arc(Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), 1.0).unwrap(); + assert!(!rev); + assert!(close(arc.center.x, 1.0) && close(arc.center.y, 0.0)); + assert!(close(arc.radius, 1.0)); + let mid = arc.point_at(arc.start + arc.sweep() / 2.0); + assert!(close(mid.y, -1.0)); + } + + #[test] + fn negative_bulge_goes_clockwise() { + let (arc, rev) = bulge_to_arc(Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), -1.0).unwrap(); + assert!(rev); + let mid = arc.point_at(arc.start + arc.sweep() / 2.0); + assert!(close(mid.y, 1.0)); + } + + #[test] + fn nurbs_line() { + // Degree 1 clamped spline is the control polygon. + let knots = [0.0, 0.0, 1.0, 1.0]; + let ctrl = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(4.0, 2.0, 0.0)]; + let p = nurbs_point(1, &knots, &ctrl, &[], 0.5).unwrap(); + assert!(close(p.x, 2.0) && close(p.y, 1.0)); + } +} diff --git a/crates/dwg/src/records/geom/mod.rs b/crates/dwg/src/records/geom/mod.rs new file mode 100644 index 00000000..6c2a5938 --- /dev/null +++ b/crates/dwg/src/records/geom/mod.rs @@ -0,0 +1,318 @@ +//! Geometry primitives: vectors, affine transforms, the object coordinate +//! system (OCS), bounding boxes and curve helpers. + +pub mod curve; + +use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub}; + +pub const EPS: f64 = 1e-12; + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Vec2 { + pub x: f64, + pub y: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Vec3 { + pub x: f64, + pub y: f64, + pub z: f64, +} + +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; + pub const fn new(x: f64, y: f64) -> Self { + Vec2 { x, y } + } + pub fn from_array(a: [f64; 2]) -> Self { + Vec2 { x: a[0], y: a[1] } + } + pub fn dot(self, o: Vec2) -> f64 { + self.x * o.x + self.y * o.y + } + /// z component of the 3D cross product. + pub fn cross(self, o: Vec2) -> f64 { + self.x * o.y - self.y * o.x + } + pub fn length(self) -> f64 { + self.x.hypot(self.y) + } + pub fn normalized(self) -> Vec2 { + let l = self.length(); + if l < EPS { Vec2::ZERO } else { self / l } + } + /// Rotated 90° counter-clockwise. + pub fn perp(self) -> Vec2 { + Vec2 { x: -self.y, y: self.x } + } + pub fn angle(self) -> f64 { + self.y.atan2(self.x) + } + pub fn from_angle(a: f64) -> Vec2 { + Vec2 { x: a.cos(), y: a.sin() } + } + pub fn distance(self, o: Vec2) -> f64 { + (self - o).length() + } + pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { + self + (o - self) * t + } + pub fn extend(self, z: f64) -> Vec3 { + Vec3 { x: self.x, y: self.y, z } + } + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } +} + +impl Vec3 { + pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + pub const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 }; + pub const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 }; + pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; + + pub const fn new(x: f64, y: f64, z: f64) -> Self { + Vec3 { x, y, z } + } + pub fn from_array(a: [f64; 3]) -> Self { + Vec3 { x: a[0], y: a[1], z: a[2] } + } + pub fn to_array(self) -> [f64; 3] { + [self.x, self.y, self.z] + } + pub fn dot(self, o: Vec3) -> f64 { + self.x * o.x + self.y * o.y + self.z * o.z + } + pub fn cross(self, o: Vec3) -> Vec3 { + Vec3 { x: self.y * o.z - self.z * o.y, y: self.z * o.x - self.x * o.z, z: self.x * o.y - self.y * o.x } + } + pub fn length(self) -> f64 { + self.dot(self).sqrt() + } + pub fn normalized(self) -> Vec3 { + let l = self.length(); + if l < EPS { Vec3::ZERO } else { self / l } + } + pub fn xy(self) -> Vec2 { + Vec2 { x: self.x, y: self.y } + } + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() + } +} + +macro_rules! impl_vec_ops { + ($t:ident, $($f:ident),+) => { + impl Add for $t { type Output = $t; fn add(self, o: $t) -> $t { $t { $($f: self.$f + o.$f),+ } } } + impl Sub for $t { type Output = $t; fn sub(self, o: $t) -> $t { $t { $($f: self.$f - o.$f),+ } } } + impl Mul for $t { type Output = $t; fn mul(self, s: f64) -> $t { $t { $($f: self.$f * s),+ } } } + impl Div for $t { type Output = $t; fn div(self, s: f64) -> $t { $t { $($f: self.$f / s),+ } } } + impl Neg for $t { type Output = $t; fn neg(self) -> $t { $t { $($f: -self.$f),+ } } } + impl AddAssign for $t { fn add_assign(&mut self, o: $t) { $(self.$f += o.$f;)+ } } + }; +} +impl_vec_ops!(Vec2, x, y); +impl_vec_ops!(Vec3, x, y, z); + +/// Affine transform in 3D: `p' = M * [x y z 1]ᵀ` with a 3×4 matrix. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Transform { + pub m: [[f64; 4]; 3], +} + +impl Default for Transform { + fn default() -> Self { + Transform::IDENTITY + } +} + +impl Transform { + pub const IDENTITY: Transform = Transform { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] }; + + pub fn translation(v: Vec3) -> Transform { + let mut t = Transform::IDENTITY; + t.m[0][3] = v.x; + t.m[1][3] = v.y; + t.m[2][3] = v.z; + t + } + + pub fn scale(s: Vec3) -> Transform { + Transform { m: [[s.x, 0.0, 0.0, 0.0], [0.0, s.y, 0.0, 0.0], [0.0, 0.0, s.z, 0.0]] } + } + + pub fn rotation_z(angle: f64) -> Transform { + let (s, c) = angle.sin_cos(); + Transform { m: [[c, -s, 0.0, 0.0], [s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] } + } + + /// Columns are the images of the x, y and z axes; `origin` is the + /// translation. + pub fn from_axes(x: Vec3, y: Vec3, z: Vec3, origin: Vec3) -> Transform { + Transform { m: [[x.x, y.x, z.x, origin.x], [x.y, y.y, z.y, origin.y], [x.z, y.z, z.z, origin.z]] } + } + + /// OCS → WCS for an extrusion (normal) vector, via the arbitrary axis + /// algorithm. + pub fn ocs_to_wcs(normal: Vec3) -> Transform { + let (ax, ay, az) = arbitrary_axes(normal); + Transform::from_axes(ax, ay, az, Vec3::ZERO) + } + + /// `self` applied after `first`: (self ∘ first)(p) = self(first(p)). + pub fn after(&self, first: &Transform) -> Transform { + let a = &self.m; + let b = &first.m; + let mut r = [[0.0; 4]; 3]; + for (i, row) in r.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + let mut v = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]; + if j == 3 { + v += a[i][3]; + } + *cell = v; + } + } + Transform { m: r } + } + + pub fn apply(&self, p: Vec3) -> Vec3 { + let m = &self.m; + Vec3 { + x: m[0][0] * p.x + m[0][1] * p.y + m[0][2] * p.z + m[0][3], + y: m[1][0] * p.x + m[1][1] * p.y + m[1][2] * p.z + m[1][3], + z: m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3], + } + } + + pub fn apply_vector(&self, v: Vec3) -> Vec3 { + let m = &self.m; + Vec3 { + x: m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, + y: m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, + z: m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z, + } + } + + /// Apply to a 2D point lying at elevation `z` and project to plan (XY). + pub fn apply_xy(&self, p: Vec2, z: f64) -> Vec2 { + self.apply(p.extend(z)).xy() + } + + /// If the plan projection of a plane spanned by `u`,`v` (unit, + /// orthogonal, in the source space) is a similarity, return + /// (uniform scale, mirrored). Circles map to circles exactly then. + pub fn plane_similarity(&self, u: Vec3, v: Vec3) -> Option<(f64, bool)> { + let a = self.apply_vector(u).xy(); + let b = self.apply_vector(v).xy(); + let la = a.length(); + let lb = b.length(); + if la < EPS || lb < EPS { + return None; + } + let rel = 1e-6; + if (la - lb).abs() > rel * la.max(lb) || a.dot(b).abs() > rel * la * lb { + return None; + } + Some((la, a.cross(b) < 0.0)) + } +} + +/// The arbitrary axis algorithm used by AutoCAD for object coordinate +/// systems: returns the OCS x, y and z axes in WCS for a normal vector. +pub fn arbitrary_axes(normal: Vec3) -> (Vec3, Vec3, Vec3) { + let n = { + let l = normal.length(); + if l < EPS || !l.is_finite() { Vec3::Z } else { normal / l } + }; + let limit = 1.0 / 64.0; + let ax = if n.x.abs() < limit && n.y.abs() < limit { Vec3::Y.cross(n) } else { Vec3::Z.cross(n) }.normalized(); + let ay = n.cross(ax).normalized(); + (ax, ay, n) +} + +/// True when the normal is the default +Z (within tolerance). +pub fn is_default_normal(n: Vec3) -> bool { + (n.x.abs() < 1e-12) && (n.y.abs() < 1e-12) && (n.z - 1.0).abs() < 1e-12 +} + +/// Axis-aligned bounding box in plan. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BBox { + pub min: Vec2, + pub max: Vec2, +} + +impl Default for BBox { + fn default() -> Self { + BBox::EMPTY + } +} + +impl BBox { + pub const EMPTY: BBox = BBox { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } }; + + pub fn is_empty(&self) -> bool { + self.min.x > self.max.x || self.min.y > self.max.y + } + pub fn add(&mut self, p: Vec2) { + if !p.is_finite() { + return; + } + self.min.x = self.min.x.min(p.x); + self.min.y = self.min.y.min(p.y); + self.max.x = self.max.x.max(p.x); + self.max.y = self.max.y.max(p.y); + } + pub fn union(&mut self, o: &BBox) { + if !o.is_empty() { + self.add(o.min); + self.add(o.max); + } + } + pub fn width(&self) -> f64 { + if self.is_empty() { 0.0 } else { self.max.x - self.min.x } + } + pub fn height(&self) -> f64 { + if self.is_empty() { 0.0 } else { self.max.y - self.min.y } + } + pub fn center(&self) -> Vec2 { + (self.min + self.max) * 0.5 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 + } + + #[test] + fn arbitrary_axis_default_and_flipped() { + let (ax, ay, az) = arbitrary_axes(Vec3::Z); + assert!(close(ax.x, 1.0) && close(ay.y, 1.0) && close(az.z, 1.0)); + // Normal (0,0,-1): mirrored plan, x axis becomes -X. + let (ax, ay, _) = arbitrary_axes(Vec3::new(0.0, 0.0, -1.0)); + assert!(close(ax.x, -1.0) && close(ay.y, 1.0)); + } + + #[test] + fn compose() { + let t = Transform::translation(Vec3::new(10.0, 0.0, 0.0)).after(&Transform::rotation_z(std::f64::consts::FRAC_PI_2)); + let p = t.apply(Vec3::new(1.0, 0.0, 0.0)); + assert!(close(p.x, 10.0) && close(p.y, 1.0)); + } + + #[test] + fn similarity_detection() { + let t = Transform::scale(Vec3::new(2.0, 2.0, 1.0)); + assert_eq!(t.plane_similarity(Vec3::X, Vec3::Y), Some((2.0, false))); + let t = Transform::scale(Vec3::new(-2.0, 2.0, 1.0)); + assert_eq!(t.plane_similarity(Vec3::X, Vec3::Y), Some((2.0, true))); + let t = Transform::scale(Vec3::new(2.0, 1.0, 1.0)); + assert_eq!(t.plane_similarity(Vec3::X, Vec3::Y), None); + } +} diff --git a/crates/dwg/src/records/mod.rs b/crates/dwg/src/records/mod.rs new file mode 100644 index 00000000..388e60aa --- /dev/null +++ b/crates/dwg/src/records/mod.rs @@ -0,0 +1,25 @@ +//! BlackCAD's drawing database, shared by its DWG and DXF codecs +//! (`cad-dwg`, `cad-dxf`) and by the CAD core (`cad-core`). +//! +//! - [`model`]: the drawing database, keyed by DWG-style handles, and +//! editing (layers, records, new entities), with undoable changes +//! - [`geom`]: vectors, transforms, OCS, curves +//! - [`text`]: code pages, escape sequences and MTEXT formatting codes +//! - [`version`]: the DWG versions, which the database records for objects +//! it keeps as their original DWG records +//! - [`error`]: the error type of every crate built on this one +//! +//! It uses the Rust standard library only and no `unsafe` code. + +// A file is only a claim: no input reaches a panic. Tests may unwrap. +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +pub mod error; +pub mod geom; +pub mod model; +pub mod text; +pub mod version; + +pub use error::{Error, ErrorKind, Result}; +pub use model::Drawing; +pub use version::DwgVersion; diff --git a/crates/dwg/src/records/model/color.rs b/crates/dwg/src/records/model/color.rs new file mode 100644 index 00000000..5e0f161a --- /dev/null +++ b/crates/dwg/src/records/model/color.rs @@ -0,0 +1,178 @@ +//! Colors: AutoCAD Color Index (ACI) values, true colors and by-layer / +//! by-block references. + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Color { + #[default] + ByLayer, + ByBlock, + /// ACI 1–255. + Index(u8), + /// True color. + Rgb(u8, u8, u8), + /// Explicitly no color (rare; some table defaults). + None, +} + +impl Color { + /// Interpret an ACI number: 0 = BYBLOCK, 256 = BYLAYER, 1–255 = index. + /// Negative values (a switched-off layer's color) use the magnitude. + pub fn from_aci(value: i16) -> Color { + match value { + 0 => Color::ByBlock, + 256 | 257 => Color::ByLayer, + v if v < 0 => Color::from_aci(v.checked_neg().unwrap_or(7)), + v if (1..=255).contains(&v) => Color::Index(v as u8), + _ => Color::ByLayer, + } + } + + /// Decode the 32-bit "color method + RGB" word used by R2004+ CmColor: + /// the high byte selects the method (0xC0 by layer, 0xC1 by block, + /// 0xC2 true color, 0xC3 ACI in the low byte, 0xC8 none). + pub fn from_method_word(word: u32, fallback_index: i16) -> Color { + let method = (word >> 24) as u8; + match method { + 0xC0 => Color::ByLayer, + 0xC1 => Color::ByBlock, + 0xC2 => Color::Rgb((word >> 16) as u8, (word >> 8) as u8, word as u8), + 0xC3 => Color::from_aci((word & 0xFF) as i16), + 0xC8 => Color::None, + _ => Color::from_aci(fallback_index), + } + } + + /// The "color method + RGB" word ([`Color::from_method_word`] reads it + /// back): 0xC0 by layer, 0xC1 by block, 0xC2 true color, 0xC3 index, + /// 0xC8 none. Index 0 is ACI's "by block" and is written as such. + pub fn to_method_word(self) -> u32 { + match self { + Color::ByLayer => 0xC000_0000, + Color::ByBlock | Color::Index(0) => 0xC100_0000, + Color::Rgb(r, g, b) => 0xC200_0000 | (r as u32) << 16 | (g as u32) << 8 | b as u32, + Color::Index(i) => 0xC300_0000 | i as u32, + Color::None => 0xC800_0000, + } + } + + /// Resolve to RGB for display, given the color the ByLayer/ByBlock + /// reference points at. + pub fn resolve(self, by_layer: Color, by_block: Color) -> (u8, u8, u8) { + match self { + Color::ByLayer => match by_layer { + Color::ByLayer | Color::ByBlock | Color::None => aci_rgb(7), + c => c.resolve(Color::Index(7), Color::Index(7)), + }, + Color::ByBlock => match by_block { + Color::ByLayer | Color::ByBlock | Color::None => aci_rgb(7), + c => c.resolve(Color::Index(7), Color::Index(7)), + }, + Color::Index(i) => aci_rgb(i), + Color::Rgb(r, g, b) => (r, g, b), + Color::None => aci_rgb(7), + } + } + + /// Nearest ACI index, for formats without true color. + pub fn to_aci(self) -> i16 { + match self { + Color::ByLayer => 256, + Color::ByBlock => 0, + Color::Index(i) => i as i16, + Color::Rgb(r, g, b) => nearest_aci(r, g, b) as i16, + Color::None => 7, + } + } +} + +fn hsv_to_rgb(h_deg: f64, s: f64, v: f64) -> (u8, u8, u8) { + let v255 = v * 255.0; + let c = v255 * s; + let hp = (h_deg / 60.0) % 6.0; + let x = c * (1.0 - ((hp % 2.0) - 1.0).abs()); + let (r1, g1, b1) = match hp as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = v255 - c; + let f = |t: f64| (t + m).floor().clamp(0.0, 255.0) as u8; + (f(r1), f(g1), f(b1)) +} + +/// RGB for an ACI index. Indices 10–249 are generated from the standard +/// layout: 24 hues 15° apart, five brightness levels, each followed by a +/// half-saturated tint. +pub fn aci_rgb(index: u8) -> (u8, u8, u8) { + match index { + 0 => (0, 0, 0), + 1 => (255, 0, 0), + 2 => (255, 255, 0), + 3 => (0, 255, 0), + 4 => (0, 255, 255), + 5 => (0, 0, 255), + 6 => (255, 0, 255), + 7 => (255, 255, 255), + 8 => (128, 128, 128), + 9 => (192, 192, 192), + 10..=249 => { + let i = index as u32 - 10; + let hue = (i / 10) as f64 * 15.0; + let k = i % 10; + let level = [1.0, 0.8, 0.6, 0.5, 0.3][(k / 2) as usize]; + let sat = if k & 1 == 0 { 1.0 } else { 0.5 }; + hsv_to_rgb(hue, sat, level) + } + 250 => (51, 51, 51), + 251 => (91, 91, 91), + 252 => (132, 132, 132), + 253 => (173, 173, 173), + 254 => (214, 214, 214), + 255 => (255, 255, 255), + } +} + +pub fn nearest_aci(r: u8, g: u8, b: u8) -> u8 { + let mut best = 7u8; + let mut best_d = u32::MAX; + for i in 1..=255u8 { + let (ar, ag, ab) = aci_rgb(i); + let d = (ar as i32 - r as i32).pow(2) as u32 + (ag as i32 - g as i32).pow(2) as u32 + (ab as i32 - b as i32).pow(2) as u32; + if d < best_d { + best_d = d; + best = i; + } + } + best +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn palette_spot_checks() { + assert_eq!(aci_rgb(10), (255, 0, 0)); + assert_eq!(aci_rgb(11), (255, 127, 127)); + assert_eq!(aci_rgb(12), (204, 0, 0)); + assert_eq!(aci_rgb(15), (153, 76, 76)); + assert_eq!(aci_rgb(18), (76, 0, 0)); + assert_eq!(nearest_aci(250, 5, 5), 1); + } + + #[test] + fn method_word() { + assert_eq!(Color::from_method_word(0xC2FF8000, 0), Color::Rgb(255, 128, 0)); + assert_eq!(Color::from_method_word(0xC3000005, 0), Color::Index(5)); + assert_eq!(Color::from_method_word(0xC0000000, 3), Color::ByLayer); + assert_eq!(Color::from_aci(-3), Color::Index(3)); + for c in [Color::ByLayer, Color::ByBlock, Color::Rgb(1, 2, 3), Color::Index(250), Color::None] { + assert_eq!(Color::from_method_word(c.to_method_word(), 7), c); + } + // Index 0 is ACI's "by block", as group 62 writes it. + assert_eq!(Color::Index(0).to_method_word(), 0xC100_0000); + } +} diff --git a/crates/dwg/src/records/model/lineweight.rs b/crates/dwg/src/records/model/lineweight.rs new file mode 100644 index 00000000..c8daebba --- /dev/null +++ b/crates/dwg/src/records/model/lineweight.rs @@ -0,0 +1,199 @@ +//! Lineweights. +//! +//! From R2000, DWG stores a lineweight as an index into a fixed table of +//! standard weights, plus three special values (by layer, by block, the +//! drawing's default). DXF writes the weight itself, in hundredths of a +//! millimetre (group 370), with -1, -2 and -3 for the special values. +//! +//! The model keeps the DWG index (the *code*), exactly as read, in +//! [`EntityCommon::lineweight`](super::EntityCommon::lineweight), +//! [`Layer::lineweight`](super::Layer::lineweight) and the dimension style. +//! [`Lineweight`] interprets it. +//! +//! The standard weights are the ones the DXF reference lists for group 370. +//! That DWG stores an index follows from the specification: a layer keeps +//! its lineweight in five bits of its flag word (ODA spec §20.4.54, mask +//! 0x03E0), too few for the weights themselves. The order of the index +//! table and the codes of the special values are from knowledge, not from +//! the specification text, which does not list them. VERIFY against real +//! files. + +use std::fmt; + +/// The standard weights in hundredths of a millimetre, in index order. +pub const STANDARD: [u16; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211]; + +/// A lineweight as the drawing means it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Lineweight { + ByLayer, + ByBlock, + /// The drawing's default weight (`$LWDEFAULT`, 0.25 mm unless set). + Default, + /// One of the [`STANDARD`] weights, in hundredths of a millimetre. + Hundredths(u16), +} + +impl Lineweight { + /// DWG code for "by layer". + pub const CODE_BY_LAYER: u8 = 29; + /// DWG code for "by block". + pub const CODE_BY_BLOCK: u8 = 30; + /// DWG code for "the drawing's default". + pub const CODE_DEFAULT: u8 = 31; + /// The weight `Default` stands for: AutoCAD's own default for + /// `$LWDEFAULT`, 0.25 mm. + pub const DEFAULT_HUNDREDTHS: u16 = 25; + + /// Interpret a DWG code. Codes outside the table (24–28, 32 and up) + /// are read as the default weight; the code itself stays in the model + /// unchanged. + pub fn from_code(code: u8) -> Lineweight { + match code { + 0..=23 => Lineweight::Hundredths(STANDARD[code as usize]), + Self::CODE_BY_LAYER => Lineweight::ByLayer, + Self::CODE_BY_BLOCK => Lineweight::ByBlock, + _ => Lineweight::Default, + } + } + + /// The DWG code. A weight that is not one of the standard ones takes + /// the code of the nearest standard weight. + pub fn code(self) -> u8 { + match self { + Lineweight::ByLayer => Self::CODE_BY_LAYER, + Lineweight::ByBlock => Self::CODE_BY_BLOCK, + Lineweight::Default => Self::CODE_DEFAULT, + Lineweight::Hundredths(h) => nearest_index(h as f64) as u8, + } + } + + /// Interpret a DXF group 370 value: -1 by layer, -2 by block, -3 + /// default, otherwise hundredths of a millimetre (rounded to the + /// nearest standard weight). + pub fn from_dxf(v: i16) -> Lineweight { + match v { + -1 => Lineweight::ByLayer, + -2 => Lineweight::ByBlock, + v if v >= 0 => Lineweight::Hundredths(STANDARD[nearest_index(v as f64)]), + _ => Lineweight::Default, + } + } + + /// The DXF group 370 value. + pub fn dxf(self) -> i16 { + match self { + Lineweight::ByLayer => -1, + Lineweight::ByBlock => -2, + Lineweight::Default => -3, + Lineweight::Hundredths(h) => STANDARD[nearest_index(h as f64)] as i16, + } + } + + /// The standard weight nearest to `mm` millimetres. + pub fn from_mm(mm: f64) -> Lineweight { + let h = if mm.is_finite() { mm * 100.0 } else { 0.0 }; + Lineweight::Hundredths(STANDARD[nearest_index(h)]) + } + + /// The weight in millimetres, if it is a weight (not by layer, by + /// block or default). + pub fn mm(self) -> Option { + match self { + Lineweight::Hundredths(h) => Some(h as f64 / 100.0), + _ => None, + } + } + + /// Millimetres to draw with: `Default` (and an unresolved by-layer or + /// by-block weight) counts as 0.25 mm. + pub fn effective_mm(self) -> f64 { + self.mm().unwrap_or(Self::DEFAULT_HUNDREDTHS as f64 / 100.0) + } + + /// Replace "by layer" and "by block" with what they refer to. + pub fn resolve(self, layer: Lineweight, block: Lineweight) -> Lineweight { + let pick = |w: Lineweight| match w { + Lineweight::ByLayer | Lineweight::ByBlock => Lineweight::Default, + w => w, + }; + match self { + Lineweight::ByLayer => pick(layer), + Lineweight::ByBlock => pick(block), + w => w, + } + } +} + +/// Index of the standard weight nearest to `hundredths` (ties go to the +/// heavier weight). +fn nearest_index(hundredths: f64) -> usize { + let mut best = 0; + let mut best_d = f64::INFINITY; + for (i, &w) in STANDARD.iter().enumerate() { + let d = (w as f64 - hundredths).abs(); + if d <= best_d { + best_d = d; + best = i; + } + } + best +} + +impl fmt::Display for Lineweight { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Lineweight::ByLayer => f.write_str("ByLayer"), + Lineweight::ByBlock => f.write_str("ByBlock"), + Lineweight::Default => f.write_str("Default"), + Lineweight::Hundredths(h) => write!(f, "{}.{:02} mm", h / 100, h % 100), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_round_trip() { + for code in 0u8..=23 { + assert_eq!(Lineweight::from_code(code).code(), code); + } + for code in [29u8, 30, 31] { + assert_eq!(Lineweight::from_code(code).code(), code); + } + assert_eq!(Lineweight::from_code(11), Lineweight::Hundredths(50)); + assert_eq!(Lineweight::from_code(7), Lineweight::Hundredths(25)); + assert_eq!(Lineweight::from_code(26), Lineweight::Default); + assert_eq!(Lineweight::from_code(255), Lineweight::Default); + } + + #[test] + fn dxf_values_and_millimetres() { + assert_eq!(Lineweight::from_dxf(-1), Lineweight::ByLayer); + assert_eq!(Lineweight::from_dxf(-2), Lineweight::ByBlock); + assert_eq!(Lineweight::from_dxf(-3), Lineweight::Default); + assert_eq!(Lineweight::from_dxf(50).dxf(), 50); + // Not a standard weight: the nearest one. + assert_eq!(Lineweight::from_dxf(48), Lineweight::Hundredths(50)); + assert_eq!(Lineweight::from_mm(0.5), Lineweight::Hundredths(50)); + assert_eq!(Lineweight::from_mm(0.6), Lineweight::Hundredths(60)); + assert_eq!(Lineweight::from_mm(0.3), Lineweight::Hundredths(30)); + assert_eq!(Lineweight::from_mm(9.0), Lineweight::Hundredths(211)); + assert_eq!(Lineweight::from_mm(f64::NAN), Lineweight::Hundredths(0)); + assert_eq!(Lineweight::Hundredths(50).to_string(), "0.50 mm"); + assert_eq!(Lineweight::Hundredths(211).to_string(), "2.11 mm"); + assert_eq!(Lineweight::Default.effective_mm(), 0.25); + } + + #[test] + fn resolving() { + let l = Lineweight::Hundredths(50); + let b = Lineweight::Hundredths(35); + assert_eq!(Lineweight::ByLayer.resolve(l, b), l); + assert_eq!(Lineweight::ByBlock.resolve(l, b), b); + assert_eq!(Lineweight::Hundredths(18).resolve(l, b), Lineweight::Hundredths(18)); + assert_eq!(Lineweight::ByLayer.resolve(Lineweight::ByBlock, b), Lineweight::Default); + } +} diff --git a/crates/dwg/src/records/model/mod.rs b/crates/dwg/src/records/model/mod.rs new file mode 100644 index 00000000..0e3bb482 --- /dev/null +++ b/crates/dwg/src/records/model/mod.rs @@ -0,0 +1,2083 @@ +//! The drawing database: every object in a DWG file keyed by its handle, +//! with typed data for the objects the core understands. +//! +//! The model mirrors DWG's own object graph (handles, owners, reactors, +//! extension dictionaries, extended data) rather than a simplified geometry +//! list, so that +//! DWG maps onto it, and onto the native `.cad` format, without losing +//! structure. + +pub mod color; + +pub mod lineweight; +mod objects; +mod store; + +pub use color::Color; + +pub use lineweight::Lineweight; +pub use objects::*; +pub use store::{Journal, ListOp, ObjectMap, Touch}; + +use crate::records::geom::{Vec2, Vec3}; +use crate::records::version::DwgVersion; +use std::collections::BTreeMap; +use std::fmt; + +/// An object's database handle. 0 means "no object". +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Handle(pub u64); + +impl Handle { + pub const NULL: Handle = Handle(0); + pub fn is_null(self) -> bool { + self.0 == 0 + } +} + +impl fmt::Display for Handle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:X}", self.0) + } +} + +/// Where an entity lives, from the entity-mode bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Space { + /// Owned by a block, polyline, insert… (see `Object::owner`). + #[default] + Owned, + /// The active paper-space layout. + Paper, + /// Model space. + Model, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum LinetypeRef { + #[default] + ByLayer, + ByBlock, + Continuous, + Handle(Handle), +} + +/// Properties shared by every entity. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityCommon { + pub space: Space, + pub layer: Handle, + pub linetype: LinetypeRef, + pub color: Color, + /// Raw transparency word when present (R2004+). + pub transparency: Option, + pub linetype_scale: f64, + /// Lineweight code as DWG stores it (see [`Lineweight`]); files older + /// than R2000 have none, and their entities read as by layer. + pub lineweight: u8, + pub invisible: bool, + pub plotstyle: Handle, + pub material: Handle, +} + +impl Default for EntityCommon { + /// An entity that takes everything from its layer: colour, linetype + /// and lineweight by layer, linetype scale 1. + fn default() -> Self { + EntityCommon { + space: Space::Owned, + layer: Handle::NULL, + linetype: LinetypeRef::ByLayer, + color: Color::ByLayer, + transparency: None, + linetype_scale: 1.0, + lineweight: Lineweight::CODE_BY_LAYER, + invisible: false, + plotstyle: Handle::NULL, + material: Handle::NULL, + } + } +} + +impl EntityCommon { + /// A model-space entity on `layer`, everything else by layer. + pub fn in_model_space(layer: Handle) -> Self { + EntityCommon { space: Space::Model, layer, ..Default::default() } + } + + /// The lineweight code, interpreted. + pub fn weight(&self) -> Lineweight { + Lineweight::from_code(self.lineweight) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Line { + pub start: Vec3, + pub end: Vec3, + pub thickness: f64, + pub extrusion: Vec3, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Circle { + /// Centre in the entity's OCS. + pub center: Vec3, + pub radius: f64, + pub thickness: f64, + pub extrusion: Vec3, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Arc { + /// Centre in the entity's OCS. + pub center: Vec3, + pub radius: f64, + pub thickness: f64, + pub extrusion: Vec3, + /// Radians, counter-clockwise in the OCS. + pub start_angle: f64, + pub end_angle: f64, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Point { + pub position: Vec3, + pub thickness: f64, + pub extrusion: Vec3, + pub x_axis_angle: f64, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Ellipse { + /// WCS centre. + pub center: Vec3, + /// WCS vector from the centre to the end of the major axis. + pub major_axis: Vec3, + pub extrusion: Vec3, + pub axis_ratio: f64, + pub start_param: f64, + pub end_param: f64, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct LwPolyline { + pub flags: u16, + pub const_width: f64, + pub elevation: f64, + pub thickness: f64, + pub extrusion: Vec3, + /// OCS vertices. + pub points: Vec, + /// One bulge per vertex, or empty when none are stored. + pub bulges: Vec, + pub widths: Vec<(f64, f64)>, + pub vertex_ids: Vec, +} + +impl LwPolyline { + pub const FLAG_CLOSED: u16 = 0x200; + pub fn is_closed(&self) -> bool { + self.flags & Self::FLAG_CLOSED != 0 + } + pub fn bulge(&self, i: usize) -> f64 { + self.bulges.get(i).copied().unwrap_or(0.0) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PolylineKind { + #[default] + Polyline2d, + Polyline3d, + PolyfaceMesh, + PolygonMesh, +} + +/// Old-style POLYLINE header. Its vertices are separate VERTEX objects. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Polyline { + pub kind: PolylineKind, + pub flags: u16, + pub curve_type: u16, + pub start_width: f64, + pub end_width: f64, + pub thickness: f64, + pub elevation: f64, + pub extrusion: Vec3, + /// Vertex handles in order when the file lists them (R2004+), or the + /// first/last vertex (R13–R2000). + pub vertices: Vec, + pub first_vertex: Handle, + pub last_vertex: Handle, + pub seqend: Handle, +} + +impl Polyline { + pub fn is_closed(&self) -> bool { + self.flags & 1 != 0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum VertexKind { + #[default] + Vertex2d, + Vertex3d, + Mesh, + PfaceVertex, + PfaceFace, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Vertex { + pub kind: VertexKind, + pub flags: u8, + pub point: Vec3, + pub start_width: f64, + pub end_width: f64, + pub bulge: f64, + pub tangent_dir: f64, + pub id: u32, + /// Polyface face vertex indices (1-based, negative = invisible edge). + pub face: [i16; 4], +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Text { + /// OCS insertion point (x, y); z is `elevation`. + pub insertion: Vec2, + pub alignment: Vec2, + pub elevation: f64, + pub extrusion: Vec3, + pub thickness: f64, + pub oblique: f64, + pub rotation: f64, + pub height: f64, + pub width_factor: f64, + pub value: String, + pub generation: u16, + pub h_align: u16, + pub v_align: u16, + pub style: Handle, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Attribute { + pub text: Text, + pub tag: String, + pub prompt: String, + pub flags: u8, + pub field_length: u16, + pub is_definition: bool, + /// Lock position (AutoCAD 2007 and later): the attribute stays where + /// it is in its block reference, with no grip of its own. A reference's + /// attributes take it from their definitions. + pub lock_position: bool, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct MText { + pub insertion: Vec3, + pub extrusion: Vec3, + pub x_axis: Vec3, + pub rect_width: f64, + pub rect_height: f64, + pub text_height: f64, + pub attachment: u16, + pub drawing_dir: u16, + /// Raw contents with inline formatting codes. + pub contents: String, + pub linespacing_factor: f64, + /// Line spacing "exactly" (DXF 73 = 2) rather than "at least" (1, the + /// default), where lines grow for taller characters. + pub linespacing_exact: bool, + pub style: Handle, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Insert { + pub insertion: Vec3, + pub scale: Vec3, + pub rotation: f64, + pub extrusion: Vec3, + pub has_attribs: bool, + pub block_header: Handle, + pub attribs: Vec, + pub first_attrib: Handle, + pub last_attrib: Handle, + pub seqend: Handle, + /// MINSERT array: columns, rows, column spacing, row spacing. + pub array: Option<(u16, u16, f64, f64)>, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Solid { + pub thickness: f64, + pub elevation: f64, + pub corners: [Vec2; 4], + pub extrusion: Vec3, + pub is_trace: bool, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Face3d { + pub corners: [Vec3; 4], + pub invisible_edges: u16, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Spline { + pub degree: u32, + pub rational: bool, + pub closed: bool, + pub periodic: bool, + pub knots: Vec, + pub control_points: Vec, + pub weights: Vec, + pub fit_points: Vec, + pub fit_tolerance: f64, + pub start_tangent: Vec3, + pub end_tangent: Vec3, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DimensionKind { + #[default] + Linear, + Aligned, + Ordinate, + Angular3Pt, + Angular2Line, + Radius, + Diameter, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Dimension { + pub kind: DimensionKind, + pub extrusion: Vec3, + pub text_midpoint: Vec2, + pub elevation: f64, + pub flags: u8, + pub user_text: String, + pub text_rotation: f64, + pub horizontal_direction: f64, + pub insert_scale: Vec3, + pub insert_rotation: f64, + pub attachment: u16, + pub measurement: f64, + pub clone_insertion: Vec2, + /// Definition points by DXF group number (10, 13, 14, 15, 16). + pub pt10: Vec3, + pub pt13: Vec3, + pub pt14: Vec3, + pub pt15: Vec3, + pub pt16: Vec2, + pub ext_line_rotation: f64, + pub dim_rotation: f64, + pub leader_length: f64, + pub dimstyle: Handle, + /// The anonymous "*D" block holding the dimension's graphics. + pub block: Handle, +} + +impl Dimension { + fn base(kind: DimensionKind) -> Dimension { + Dimension { kind, extrusion: Vec3::Z, insert_scale: Vec3::new(1.0, 1.0, 1.0), attachment: 5, ..Default::default() } + } + + /// A linear dimension between `p1` and `p2`, measured along the + /// direction `rotation` (radians: 0 horizontal, π/2 vertical), with its + /// dimension line through `line_at`. The text sits in the middle of + /// the dimension line. + pub fn linear(p1: Vec2, p2: Vec2, line_at: Vec2, rotation: f64) -> Dimension { + let u = Vec2::from_angle(rotation); + let a = line_at + u * (p1 - line_at).dot(u); + let b = line_at + u * (p2 - line_at).dot(u); + Dimension { + pt10: b.extend(0.0), + pt13: p1.extend(0.0), + pt14: p2.extend(0.0), + dim_rotation: rotation, + text_midpoint: (a + b) * 0.5, + measurement: (p2 - p1).dot(u).abs(), + ..Dimension::base(DimensionKind::Linear) + } + } + + /// An aligned dimension between `p1` and `p2`, measured along the line + /// between them, its dimension line `offset` to the left of it + /// (looking from `p1` to `p2`; negative for the right). + pub fn aligned(p1: Vec2, p2: Vec2, offset: f64) -> Dimension { + let n = (p2 - p1).normalized().perp(); + let (a, b) = (p1 + n * offset, p2 + n * offset); + Dimension { + pt10: b.extend(0.0), + pt13: p1.extend(0.0), + pt14: p2.extend(0.0), + text_midpoint: (a + b) * 0.5, + measurement: p1.distance(p2), + ..Dimension::base(DimensionKind::Aligned) + } + } + + /// A diameter dimension across a circle, its line at `angle` + /// (radians) through the centre. + pub fn diameter(center: Vec2, radius: f64, angle: f64) -> Dimension { + let d = Vec2::from_angle(angle) * radius; + Dimension { + pt15: (center + d).extend(0.0), + pt10: (center - d).extend(0.0), + text_midpoint: center, + measurement: 2.0 * radius, + ..Dimension::base(DimensionKind::Diameter) + } + } + + /// A radius dimension pointing at the arc at `angle` (radians). The + /// text goes outside, along that direction (its position is left to + /// the renderer: a zero `text_midpoint` means "default"). + pub fn radius(center: Vec2, radius: f64, angle: f64) -> Dimension { + Dimension { + pt10: center.extend(0.0), + pt15: (center + Vec2::from_angle(angle) * radius).extend(0.0), + measurement: radius, + ..Dimension::base(DimensionKind::Radius) + } + } + + /// An angular dimension of the angle at `vertex` between the rays + /// through `p1` and `p2` (three-point DIMANGULAR), its arc through + /// `arc_at`. The angle measured is the one on `arc_at`'s side: placed + /// outside the angle between the rays, the dimension measures the + /// rest of the turn. + pub fn angular(vertex: Vec2, p1: Vec2, p2: Vec2, arc_at: Vec2) -> Dimension { + let mut d = Dimension { + pt10: arc_at.extend(0.0), + pt13: p1.extend(0.0), + pt14: p2.extend(0.0), + pt15: vertex.extend(0.0), + ..Dimension::base(DimensionKind::Angular3Pt) + }; + d.measurement = d.angular_arc().map(|a| a.sweep).unwrap_or(0.0); + d + } + + /// An angular dimension between two lines, `a1`–`a2` and `b1`–`b2` + /// (DIMANGULAR on two lines), its arc through `arc_at`: of the four + /// angles the lines make where they meet, the one `arc_at` is in. + /// `None` when the lines are parallel. + pub fn angular_lines(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2, arc_at: Vec2) -> Option { + let mut d = Dimension { + pt13: a1.extend(0.0), + pt14: a2.extend(0.0), + pt15: b1.extend(0.0), + pt10: b2.extend(0.0), + pt16: arc_at, + ..Dimension::base(DimensionKind::Angular2Line) + }; + d.measurement = d.angular_arc()?.sweep; + Some(d) + } + + /// The arc of an angular dimension: where it is and which angle it + /// spans. `None` for other kinds, and for degenerate definitions + /// (parallel lines, points on the vertex). + pub fn angular_arc(&self) -> Option { + use std::f64::consts::{PI, TAU}; + let norm = |a: f64| { + let a = a % TAU; + if a < 0.0 { a + TAU } else { a } + }; + match self.kind { + DimensionKind::Angular3Pt => { + let c = self.pt15.xy(); + let (p1, p2, at) = (self.pt13.xy(), self.pt14.xy(), self.pt10.xy()); + let (d1, d2) = (p1.distance(c), p2.distance(c)); + if d1 < 1e-12 || d2 < 1e-12 { + return None; + } + let (a1, a2) = ((p1 - c).angle(), (p2 - c).angle()); + let s12 = norm(a2 - a1); + if s12 < 1e-12 { + return None; + } + let r = at.distance(c); + let r = if r > 1e-12 { r } else { d1.min(d2) }; + let inside = at.distance(c) < 1e-12 || norm((at - c).angle() - a1) <= s12; + Some(if inside { + AngularArc { center: c, start: a1, sweep: s12, radius: r, legs: [(0.0, d1), (0.0, d2)] } + } else { + AngularArc { center: c, start: a2, sweep: TAU - s12, radius: r, legs: [(0.0, d2), (0.0, d1)] } + }) + } + DimensionKind::Angular2Line => { + let (p, q) = (self.pt13.xy(), self.pt14.xy()); + let (s, e) = (self.pt15.xy(), self.pt10.xy()); + let (u, w) = (q - p, e - s); + let den = u.cross(w); + if u.length() < 1e-12 || w.length() < 1e-12 || den.abs() < 1e-12 * u.length() * w.length() { + return None; + } + let c = p + u * ((s - p).cross(w) / den); + let at = self.pt16; + let r = at.distance(c); + if r < 1e-12 { + return None; + } + // The four rays from the vertex, by line. + let (b1, b2) = (u.angle(), w.angle()); + let rays = [(b1, 0usize), (b1 + PI, 0), (b2, 1), (b2 + PI, 1)]; + let la = (at - c).angle(); + // The ray at or before the location going clockwise opens + // the sector; the next one counter-clockwise closes it. + let start = rays.iter().min_by(|x, y| norm(la - x.0).total_cmp(&norm(la - y.0))).copied()?; + let end = rays.iter().filter(|x| x.1 != start.1).min_by(|x, y| norm(x.0 - start.0).total_cmp(&norm(y.0 - start.0))).copied()?; + let sweep = norm(end.0 - start.0); + let extent = |line: usize, ang: f64| { + let dir = Vec2::from_angle(ang); + let (x, y) = if line == 0 { (p, q) } else { (s, e) }; + let (tx, ty) = ((x - c).dot(dir), (y - c).dot(dir)); + (tx.min(ty), tx.max(ty)) + }; + Some(AngularArc { center: c, start: norm(start.0), sweep, radius: r, legs: [extent(start.1, start.0), extent(end.1, end.0)] }) + } + _ => None, + } + } +} + +/// Where an angular dimension's arc runs ([`Dimension::angular_arc`]): +/// counter-clockwise from `start` through `sweep` (radians) at `radius` +/// about `center`. `legs` gives, for the ray at each end of the arc, how +/// far along it the measured feature runs (nearest and farthest distance +/// from the centre): extension lines bridge the gap from there to the +/// arc. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AngularArc { + pub center: Vec2, + pub start: f64, + pub sweep: f64, + pub radius: f64, + pub legs: [(f64, f64); 2], +} + +impl Line { + /// A line in the XY plane. + pub fn new(a: Vec2, b: Vec2) -> Line { + Line { start: a.extend(0.0), end: b.extend(0.0), thickness: 0.0, extrusion: Vec3::Z } + } +} + +impl Circle { + /// A circle in the XY plane. + pub fn new(center: Vec2, radius: f64) -> Circle { + Circle { center: center.extend(0.0), radius, thickness: 0.0, extrusion: Vec3::Z } + } +} + +impl Arc { + /// An arc in the XY plane, counter-clockwise from `start` to `end` + /// (radians). + pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Arc { + Arc { center: center.extend(0.0), radius, thickness: 0.0, extrusion: Vec3::Z, start_angle: start, end_angle: end } + } +} + +impl LwPolyline { + /// A polyline of straight segments in the XY plane. + pub fn new(points: Vec, closed: bool) -> LwPolyline { + LwPolyline { flags: if closed { Self::FLAG_CLOSED } else { 0 }, extrusion: Vec3::Z, points, ..Default::default() } + } +} + +impl Text { + /// Single-line text with its left end on the baseline at `position`. + pub fn new(position: Vec2, height: f64, value: &str) -> Text { + Text { insertion: position, alignment: position, extrusion: Vec3::Z, height, width_factor: 1.0, value: value.into(), ..Default::default() } + } + + /// Single-line text aligned at `position`: `h_align` 0 left, 1 centre, + /// 2 right, 4 middle; `v_align` 0 baseline, 1 bottom, 2 middle, 3 top + /// (DXF groups 72 and 73). + pub fn aligned(position: Vec2, height: f64, value: &str, h_align: u16, v_align: u16) -> Text { + Text { h_align, v_align, ..Text::new(position, height, value) } + } +} + +impl MText { + /// Multi-line text: `width` 0 for no wrapping; `attachment` 1–9 (top, + /// middle, bottom rows; left, centre, right columns). Lines break at + /// `\P`. + pub fn new(insertion: Vec2, height: f64, width: f64, contents: &str, attachment: u16) -> MText { + MText { + insertion: insertion.extend(0.0), + extrusion: Vec3::Z, + x_axis: Vec3::X, + rect_width: width, + text_height: height, + attachment, + drawing_dir: 1, + contents: contents.into(), + linespacing_factor: 1.0, + ..Default::default() + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HatchEdge { + Line { a: Vec2, b: Vec2 }, + Arc { center: Vec2, radius: f64, start: f64, end: f64, ccw: bool }, + Ellipse { center: Vec2, major: Vec2, ratio: f64, start: f64, end: f64, ccw: bool }, + Spline { degree: u32, knots: Vec, control_points: Vec, weights: Vec }, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HatchPath { + Edges { flags: u32, edges: Vec }, + Polyline { flags: u32, closed: bool, vertices: Vec<(Vec2, f64)> }, +} + +/// One family of parallel lines of a hatch pattern, in the hatch's own +/// coordinates with its angle and scale already applied (DXF groups 53, +/// 43–46, 79, 49): lines at `angle` through `base`, each the last moved by +/// `offset`, dashed by `dashes` (positive dash, negative gap, zero dot; +/// empty for solid lines). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct HatchPatternLine { + pub angle: f64, + pub base: Vec2, + pub offset: Vec2, + pub dashes: Vec, +} + +/// A program's hatch pattern library as the DWG and DXF writers ask it: +/// given the drawing and a pattern hatch that holds no line families, the +/// line families to store, so that other programs draw the pattern. +pub type HatchLibrary<'a> = dyn Fn(&Drawing, &Hatch) -> Vec + 'a; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Hatch { + pub elevation: f64, + pub extrusion: Vec3, + pub pattern_name: String, + pub solid_fill: bool, + pub associative: bool, + pub is_gradient: bool, + pub paths: Vec, + pub style: u16, + pub pattern_type: u16, + pub pattern_angle: f64, + pub pattern_scale: f64, + /// A user-defined pattern drawn twice, the second set at 90°. + pub pattern_double: bool, + /// The pattern's line families as the file stores them. Empty for a + /// solid fill, and in drawings saved before format 2.4, where the + /// renderer takes the pattern from the library by name. + pub pattern_lines: Vec, + /// Points picked inside the boundary when the hatch was made. + pub seed_points: Vec, + /// The objects each path was made from, in path order: the boundary of + /// an associative hatch, which carries the hatch as a persistent + /// reactor (DWG's boundary object handles, DXF 97 and 330). A path past + /// the end of the list has none. + pub sources: Vec>, +} + +/// XLINE and RAY: a construction line through `base` along `direction` +/// (WCS, a unit vector), infinite both ways (XLINE) or from `base` on +/// (RAY). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ConstructionLine { + pub base: Vec3, + pub direction: Vec3, +} + +impl ConstructionLine { + /// A construction line in the XY plane. + pub fn new(base: Vec2, direction: Vec2) -> ConstructionLine { + let d = direction.normalized(); + ConstructionLine { base: base.extend(0.0), direction: Vec3::new(d.x, d.y, 0.0) } + } +} + +/// LEADER (ODA spec §20.4.47, DXF LEADER): an arrow and a line through +/// `vertices` to an annotation, usually an MTEXT. +#[derive(Debug, Clone, PartialEq)] +pub struct Leader { + /// WCS vertices, the arrow at the first. + pub vertices: Vec, + /// DXF 71. + pub arrowhead: bool, + /// DXF 72: false straight segments, true a spline through the vertices. + pub spline: bool, + /// DXF 73: 0 MTEXT, 1 tolerance, 2 block reference, 3 none. + pub annotation_type: u16, + /// DXF 74: the hook line runs along the horizontal direction. + pub hookline_on_x: bool, + /// DXF 75. + pub hookline: bool, + /// DXF 40, 41: the annotation's extents. + pub text_height: f64, + pub text_width: f64, + /// The leader plane's origin (DWG only; the first vertex by default). + pub origin: Vec3, + pub extrusion: Vec3, + /// DXF 211: the "horizontal" direction. + pub x_direction: Vec3, + /// DXF 212: offset of the last vertex from a block annotation's + /// insertion point. + pub block_offset: Vec3, + /// DXF 213: offset of the last vertex from the annotation. + pub annotation_offset: Vec3, + /// DXF 340: the annotation. + pub annotation: Handle, + pub dimstyle: Handle, + /// Fields DWG stores whose meaning is not documented, kept as read: + /// the leading bit, then (R2000+) a short and two bits. + pub unknown: (bool, u16, bool, bool), +} + +impl Default for Leader { + fn default() -> Self { + Leader { + vertices: Vec::new(), + arrowhead: true, + spline: false, + annotation_type: 3, + hookline_on_x: true, + hookline: false, + text_height: 0.0, + text_width: 0.0, + origin: Vec3::ZERO, + extrusion: Vec3::Z, + x_direction: Vec3::X, + block_offset: Vec3::ZERO, + annotation_offset: Vec3::ZERO, + annotation: Handle::NULL, + dimstyle: Handle::NULL, + unknown: (false, 0, false, false), + } + } +} + +/// TOLERANCE (ODA spec §20.4.49, DXF TOLERANCE): a geometric tolerance +/// feature control frame. Its text holds the frame's contents in the GD&T +/// codes the DXF reference describes (`%%v` separates boxes, `^J` starts a +/// new line, `{\Fgdt;…}` symbols); its size, gap and colours come from the +/// dimension style. +#[derive(Debug, Clone, PartialEq)] +pub struct Tolerance { + /// DXF 10: the middle of the left edge of the first frame line (WCS). + pub insertion: Vec3, + /// DXF 11: the frame's X direction (WCS). + pub x_direction: Vec3, + /// DXF 210. + pub extrusion: Vec3, + /// DXF 1: the frame contents. + pub text: String, + /// DXF 3 (by name) / DWG hard pointer: the dimension style. + pub dimstyle: Handle, + /// R13 and R14 only: an undocumented short, the text height and the + /// gap (DIMGAP × DIMSCALE when it was made). Later versions take both + /// from the dimension style and don't store them; kept as read. + pub r14: Option<(u16, f64, f64)>, +} + +impl Default for Tolerance { + fn default() -> Self { + Tolerance { insertion: Vec3::ZERO, x_direction: Vec3::X, extrusion: Vec3::Z, text: String::new(), dimstyle: Handle::NULL, r14: None } + } +} + +/// One vertex of a multiline (ODA spec §20.4.50, DXF MLINE 11, 12, 13, +/// 74, 41, 75, 42). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct MLineVertex { + /// DXF 11 (WCS). + pub point: Vec3, + /// DXF 12: the direction of the segment that starts here. + pub direction: Vec3, + /// DXF 13: the miter direction at this vertex. + pub miter: Vec3, + /// Per element of the style, in style order: the segment parameters + /// (DXF 41: where the element's line starts along the miter, then + /// where its breaks start and end along the segment) and the area fill + /// parameters (DXF 42). + pub params: Vec<(Vec, Vec)>, +} + +/// MLINE (ODA spec §20.4.50, DXF MLINE): a multiline, parallel lines drawn +/// with the elements of its MLINESTYLE. +#[derive(Debug, Clone, PartialEq)] +pub struct MLine { + /// DXF 340 (and 2, by name): the MLINESTYLE. + pub style: Handle, + /// DXF 40: element offsets are multiplied by this. + pub scale: f64, + /// DXF 70: 0 top, 1 zero, 2 bottom. + pub justification: u8, + /// DXF 10: the start point (WCS). + pub base: Vec3, + /// DXF 210. + pub extrusion: Vec3, + /// DXF 71: 1 has vertices, 2 closed, 4 start caps suppressed, 8 end + /// caps suppressed. DWG stores the same word ("open 1, closed 3"). + pub flags: u16, + /// DXF 73: the number of elements of the style when it was drawn. + pub lines_in_style: u8, + pub vertices: Vec, +} + +impl Default for MLine { + fn default() -> Self { + MLine { + style: Handle::NULL, + scale: 1.0, + justification: 0, + base: Vec3::ZERO, + extrusion: Vec3::Z, + flags: 1, + lines_in_style: 0, + vertices: Vec::new(), + } + } +} + +/// IMAGE and WIPEOUT (AcDbRasterImage; ODA spec §20.4.80, DXF IMAGE and +/// WIPEOUT): a raster image placed by its pixel vectors, or a wipeout, an +/// image-less raster entity whose clip polygon masks what lies under it. +/// An image's file is its IMAGEDEF object's ([`Self::definition`]). +#[derive(Debug, Clone, PartialEq)] +pub struct RasterImage { + /// DXF 90. + pub class_version: u32, + /// DXF 10: the lower-left corner of the image (WCS). + pub insertion: Vec3, + /// DXF 11, 12: one pixel's width (U) and height (V) vectors. + pub u: Vec3, + pub v: Vec3, + /// DXF 13: the image size in pixels. + pub size: Vec2, + /// DXF 70: 1 show the image, 2 show it when not aligned with the + /// screen, 4 use the clip boundary, 8 transparency on. + pub display: u16, + /// DXF 280. + pub clipping: bool, + /// DXF 281, 282, 283: brightness, contrast and fade, 0 to 100. + pub brightness: u8, + pub contrast: u8, + pub fade: u8, + /// DXF 290 (R2010+): the inside of the clip boundary is clipped away. + pub clip_inside: bool, + /// DXF 71: 1 rectangle (two opposite corners), 2 polygon. + pub clip_type: u16, + /// DXF 14: the clip boundary in pixel coordinates. + pub clip: Vec, + /// DXF 340: the IMAGEDEF (null for a wipeout). + pub definition: Handle, + /// DXF 360: the IMAGEDEF_REACTOR the image owns (null for a wipeout). + pub reactor: Handle, +} + +impl Default for RasterImage { + fn default() -> Self { + RasterImage { + class_version: 0, + insertion: Vec3::ZERO, + u: Vec3::X, + v: Vec3::Y, + size: Vec2::new(1.0, 1.0), + display: 7, + clipping: false, + brightness: 50, + contrast: 50, + fade: 0, + clip_inside: false, + clip_type: 1, + clip: Vec::new(), + definition: Handle::NULL, + reactor: Handle::NULL, + } + } +} + +/// A VIEWPORT entity: a window on a layout that shows model space at a +/// scale (ODA spec §20.4.38, DXF VIEWPORT). The first viewport of each +/// layout (id 1) is the layout's own view of the paper, not a window. +#[derive(Debug, Clone, PartialEq)] +pub struct PaperViewport { + /// Centre on the paper, and size, in paper units. + pub center: Vec3, + pub width: f64, + pub height: f64, + /// DXF 69: 1 for the layout's own view; windows count from 2. DWG does + /// not store it: the reader numbers viewports in block order. + pub id: i16, + pub view_target: Vec3, + pub view_direction: Vec3, + pub twist: f64, + /// Height of the model shown, in model units: the scale is + /// `height / view_height`. + pub view_height: f64, + pub lens: f64, + pub front_clip: f64, + pub back_clip: f64, + pub snap_angle: f64, + /// Model point at the viewport's centre (display coordinates). + pub view_center: Vec2, + pub snap_base: Vec2, + pub snap_spacing: Vec2, + pub grid_spacing: Vec2, + pub circle_zoom: u16, + pub grid_major: u16, + pub frozen_layers: Vec, + /// DXF 90 status bits (0x20000: switched off). + pub status: u32, + pub style_sheet: String, + pub render_mode: u8, + pub ucs_at_origin: bool, + pub ucs_per_viewport: bool, + pub ucs_origin: Vec3, + pub ucs_x: Vec3, + pub ucs_y: Vec3, + pub ucs_elevation: f64, + pub ucs_ortho_type: u16, + pub shade_plot_mode: u16, + pub default_lights: bool, + pub lighting_type: u8, + pub brightness: f64, + pub contrast: f64, + pub ambient: Color, + pub clip_boundary: Handle, + pub named_ucs: Handle, + pub base_ucs: Handle, + pub background: Handle, + pub visual_style: Handle, + pub shade_plot: Handle, + pub sun: Handle, +} + +impl PaperViewport { + /// Status bits a new viewport starts with: on, UCS icon shown, fast + /// zoom, adaptive grid. + pub const DEFAULT_STATUS: u32 = 0x8000 | 0x20 | 0x40 | 0x80 | 0x40000 | 0x80000; + pub const STATUS_OFF: u32 = 0x20000; + + /// A viewport `width` × `height` centred at `center` on the paper, + /// showing model space around `view_center` at `scale` (paper units + /// per model unit). + pub fn new(center: Vec2, width: f64, height: f64, view_center: Vec2, scale: f64, id: i16) -> PaperViewport { + let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + PaperViewport { + center: center.extend(0.0), + width, + height, + id, + view_target: Vec3::ZERO, + view_direction: Vec3::Z, + twist: 0.0, + view_height: height / scale, + lens: 50.0, + front_clip: 0.0, + back_clip: 0.0, + snap_angle: 0.0, + view_center, + snap_base: Vec2::ZERO, + snap_spacing: Vec2::new(10.0, 10.0), + grid_spacing: Vec2::new(10.0, 10.0), + circle_zoom: 1000, + grid_major: 5, + frozen_layers: Vec::new(), + status: Self::DEFAULT_STATUS, + style_sheet: String::new(), + render_mode: 0, + ucs_at_origin: true, + ucs_per_viewport: true, + ucs_origin: Vec3::ZERO, + ucs_x: Vec3::X, + ucs_y: Vec3::Y, + ucs_elevation: 0.0, + ucs_ortho_type: 0, + shade_plot_mode: 0, + default_lights: true, + lighting_type: 1, + brightness: 0.0, + contrast: 0.0, + ambient: Color::Index(250), + clip_boundary: Handle::NULL, + named_ucs: Handle::NULL, + base_ucs: Handle::NULL, + background: Handle::NULL, + visual_style: Handle::NULL, + shade_plot: Handle::NULL, + sun: Handle::NULL, + } + } + + /// Paper units per model unit. + pub fn scale(&self) -> f64 { + if self.view_height > 0.0 && self.view_height.is_finite() { self.height / self.view_height } else { 1.0 } + } + + pub fn is_on(&self) -> bool { + self.status & Self::STATUS_OFF == 0 + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct BlockHeader { + pub name: String, + pub anonymous: bool, + pub has_attribs: bool, + pub is_xref: bool, + pub is_overlaid: bool, + pub base_point: Vec3, + pub xref_path: String, + pub description: String, + pub insert_units: u16, + /// Whether EXPLODE may break its references apart (DXF 280, DWG from + /// R2007). AutoCAD's blocks are explodable unless set otherwise, so the + /// model stores the exception. + pub not_explodable: bool, + pub block_entity: Handle, + /// Owned entities in order (R2004+). Empty for R13–R2000, where the + /// first/last pair and entity owners are used instead. + pub entities: Vec, + pub first_entity: Handle, + pub last_entity: Handle, + pub endblk: Handle, + pub layout: Handle, + /// What the block is as a manufactured part, when it is one (the + /// model space record holds it for a drawing of a single part). + pub part: Part, +} + +/// A block as a manufactured part: the bill-of-materials data a drawing +/// carries (Proposed, see FORMAT.md). Empty strings and zeros are unset. +/// Material, grade and thickness describe what the part is made of; how a +/// machine cuts it is not part of the drawing (DESIGN §1). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Part { + /// For example "Steel", "Stainless steel", "Aluminium". + pub material: String, + /// For example "S355JR", "304", "5083-H111". + pub grade: String, + /// Sheet or plate thickness in drawing units; 0 unset. + pub thickness: f64, + /// How many to make; 0 unset. + pub quantity: u32, +} + +impl Part { + pub fn is_empty(&self) -> bool { + *self == Part::default() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Layer { + pub name: String, + /// Raw flag word (R2000+) or reconstructed from the R13–R14 bits. + pub flags: u16, + pub frozen: bool, + pub off: bool, + pub locked: bool, + pub plot: bool, + pub color: Color, + pub linetype: Handle, + /// Lineweight code as DWG stores it (see [`Lineweight`]). + pub lineweight: u8, +} + +impl Default for Layer { + /// An unnamed layer that is on, thawed, unlocked and plots: white, + /// no linetype record, the default lineweight. + fn default() -> Self { + Layer { + name: String::new(), + flags: 0, + frozen: false, + off: false, + locked: false, + plot: true, + color: Color::Index(7), + linetype: Handle::NULL, + lineweight: Lineweight::CODE_DEFAULT, + } + } +} + +impl Layer { + /// The lineweight code, interpreted. + pub fn weight(&self) -> Lineweight { + Lineweight::from_code(self.lineweight) + } + + /// The flag word as R2000+ DWG lays it out (ODA spec §20.4.54), from + /// the fields: 0x01 frozen, 0x02 off (the bit the spec calls "on"; see + /// `dwg::tables::layer`), 0x08 locked, 0x10 plots, bits 5–9 + /// the lineweight code. Other bits of the stored word (0x04, frozen in + /// new viewports) are kept. + pub fn dwg_flags(&self) -> u16 { + let kept = self.flags & !(0x01 | 0x02 | 0x08 | 0x10 | 0x03E0); + kept | (self.frozen as u16) + | ((self.off as u16) << 1) + | ((self.locked as u16) << 3) + | ((self.plot as u16) << 4) + | (((self.lineweight as u16) & 0x1F) << 5) + } +} + +/// One element of a linetype pattern (DXF groups 49 and 74–75, 340, 46, +/// 50, 44–45, 9). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct LinetypeElement { + /// Positive: a dash of that length. Negative: a gap. Zero: a dot. + pub length: f64, + /// Complex element flags (DXF 74): 0 for a plain dash; 1 absolute + /// rotation, 2 text, 4 shape. + pub complex: u16, + /// Shape number (DXF 75), for shape elements. + pub shape: u16, + /// Text style or shape file (DXF 340), for complex elements. + pub style: Handle, + /// Scale of the text or shape (DXF 46). + pub scale: f64, + /// Rotation of the text or shape, radians (DXF 50). + pub rotation: f64, + /// Offset of the text or shape (DXF 44, 45). + pub offset: Vec2, + /// The text of a text element (DXF 9). + pub text: String, +} + +impl LinetypeElement { + /// A plain dash (positive), gap (negative) or dot (zero). + pub fn plain(length: f64) -> Self { + LinetypeElement { length, scale: 1.0, ..Default::default() } + } +} + +/// A linetype table record (LTYPE) with its pattern. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Linetype { + pub name: String, + pub description: String, + /// DXF 70 flags. + pub flags: u16, + /// Total pattern length as stored (DXF 40): the sum of the element + /// lengths' magnitudes. + pub pattern_length: f64, + /// Elements in order. Empty for a continuous line. + pub elements: Vec, +} + +impl Linetype { + /// A plain dash-and-gap linetype. + pub fn simple(name: &str, description: &str, lengths: &[f64]) -> Self { + Linetype { + name: name.into(), + description: description.into(), + flags: 0, + pattern_length: lengths.iter().map(|l| l.abs()).sum(), + elements: lengths.iter().map(|&l| LinetypeElement::plain(l)).collect(), + } + } + + /// The dash lengths (positive dash, negative gap, zero dot). + pub fn dashes(&self) -> Vec { + self.elements.iter().map(|e| e.length).collect() + } +} + +/// A text style table record (STYLE). +#[derive(Debug, Clone, PartialEq)] +pub struct TextStyle { + pub name: String, + /// DXF 70 flags: 1 shape file, 4 vertical text. + pub flags: u16, + /// Fixed text height, or 0 when the height is given per text. + pub height: f64, + pub width_factor: f64, + /// Oblique angle, radians. + pub oblique: f64, + /// DXF 71 generation flags: 2 backwards, 4 upside down. + pub generation: u16, + /// The last height used (DXF 42). + pub last_height: f64, + /// Font file name, e.g. `simplex.shx` or `arial.ttf`. + pub font_file: String, + /// Big-font file name, for Asian scripts. + pub bigfont_file: String, +} + +impl Default for TextStyle { + fn default() -> Self { + TextStyle { + name: String::new(), + flags: 0, + height: 0.0, + width_factor: 1.0, + oblique: 0.0, + generation: 0, + last_height: 0.0, + font_file: String::new(), + bigfont_file: String::new(), + } + } +} + +/// A dimension style table record (DIMSTYLE): the dimension variables +/// the core uses. Each field names its DXF group and variable. +#[derive(Debug, Clone, PartialEq)] +pub struct DimStyle { + pub name: String, + /// 70: flags. + pub flags: u16, + /// 3 DIMPOST: text around the measurement, `<>` standing for it. + pub post_text: String, + /// 40 DIMSCALE: overall scale of sizes (text, arrows, gaps). + pub scale: f64, + /// 41 DIMASZ: arrowhead length. + pub arrow_size: f64, + /// 42 DIMEXO: gap between the object and an extension line. + pub ext_offset: f64, + /// 43 DIMDLI: spacing of stacked (baseline) dimensions. + pub baseline_spacing: f64, + /// 44 DIMEXE: how far extension lines run past the dimension line. + pub ext_extension: f64, + /// 45 DIMRND: rounding of measurements (0 none). + pub rounding: f64, + /// 46 DIMDLE: dimension line past the extension lines (with ticks). + pub dim_line_extension: f64, + /// 140 DIMTXT: text height. + pub text_height: f64, + /// 141 DIMCEN: centre mark size (0 none, negative with centre lines). + pub center_mark: f64, + /// 142 DIMTSZ: oblique tick size instead of arrowheads (0 arrows). + pub tick_size: f64, + /// 143 DIMALTF: alternate-unit factor. + pub alt_factor: f64, + /// 144 DIMLFAC: measurement scale factor. + pub linear_factor: f64, + /// 147 DIMGAP: gap around the text where it breaks the line. + pub text_gap: f64, + /// 73 DIMTIH: text inside the extension lines reads horizontally. + pub text_inside_horizontal: bool, + /// 74 DIMTOH: text outside the extension lines reads horizontally. + pub text_outside_horizontal: bool, + /// 77 DIMTAD: 0 text centred in a break of the dimension line, + /// 1 above it. + pub text_above: u16, + /// 78 DIMZIN: zero suppression flags. + pub zero_suppression: u16, + /// 170 DIMALT: show alternate units. + pub alt_units: bool, + /// 171 DIMALTD: decimal places of alternate units. + pub alt_decimals: u16, + /// DIMCLRD: dimension line and arrow colour. + pub line_color: Color, + /// DIMCLRE: extension line colour. + pub ext_color: Color, + /// DIMCLRT: text colour. + pub text_color: Color, + /// 271 DIMDEC: decimal places. + pub decimals: u16, + /// 276 DIMFRAC: fraction format (0 horizontal, 1 diagonal, 2 inline). + pub fraction_format: u16, + /// 277 DIMLUNIT: unit format (1 scientific, 2 decimal, 3 engineering, + /// 4 architectural, 5 fractional). + pub unit_format: u16, + /// 278 DIMDSEP: decimal separator character. + pub decimal_separator: char, + /// 280 DIMJUST: horizontal text position. + pub text_justify: u16, + /// 340 DIMTXSTY: text style. + pub text_style: Handle, + /// 371 DIMLWD: dimension line weight, as a DWG code. + pub line_weight: u8, + /// 372 DIMLWE: extension line weight, as a DWG code. + pub ext_weight: u8, +} + +impl Default for DimStyle { + /// Neutral values: sizes 0 (the renderer then uses the standard style + /// for the drawing's units), colours and weights by block. + fn default() -> Self { + DimStyle { + name: String::new(), + flags: 0, + post_text: String::new(), + scale: 1.0, + arrow_size: 0.0, + ext_offset: 0.0, + baseline_spacing: 0.0, + ext_extension: 0.0, + rounding: 0.0, + dim_line_extension: 0.0, + text_height: 0.0, + center_mark: 0.0, + tick_size: 0.0, + alt_factor: 25.4, + linear_factor: 1.0, + text_gap: 0.0, + text_inside_horizontal: true, + text_outside_horizontal: true, + text_above: 0, + zero_suppression: 0, + alt_units: false, + alt_decimals: 2, + line_color: Color::ByBlock, + ext_color: Color::ByBlock, + text_color: Color::ByBlock, + decimals: 2, + fraction_format: 0, + unit_format: 2, + decimal_separator: '.', + text_justify: 0, + text_style: Handle::NULL, + line_weight: Lineweight::CODE_BY_BLOCK, + ext_weight: Lineweight::CODE_BY_BLOCK, + } + } +} + +/// A symbol-table control object (BLOCK_CONTROL, LAYER_CONTROL, …). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Control { + pub entries: Vec, + /// BLOCK_CONTROL only. + pub model_space: Handle, + pub paper_space: Handle, +} + +/// A table record the core keeps only the name of: VIEW, UCS, VPORT, +/// APPID, … and, from DWG files, DIMSTYLE (not decoded yet) and any LTYPE +/// or STYLE record the reader could not decode. New drawings store those +/// as [`Linetype`], [`TextStyle`] and [`DimStyle`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct NamedRecord { + pub name: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ObjectKind { + Line(Line), + Circle(Circle), + Arc(Arc), + Point(Point), + Ellipse(Ellipse), + LwPolyline(LwPolyline), + Polyline(Polyline), + Vertex(Vertex), + SeqEnd, + Text(Text), + Attribute(Attribute), + MText(MText), + Insert(Insert), + Solid(Solid), + Face3d(Face3d), + Spline(Spline), + Dimension(Dimension), + Hatch(Hatch), + /// XLINE: a construction line, infinite both ways. + Xline(ConstructionLine), + /// RAY: a construction line from its base point on. + Ray(ConstructionLine), + Leader(Leader), + Tolerance(Tolerance), + MLine(MLine), + /// IMAGE. + Image(Box), + /// WIPEOUT. + Wipeout(Box), + /// A VIEWPORT entity on a layout. + PaperViewport(Box), + /// BLOCK entity that opens a block definition. + BlockBegin { + name: String, + }, + BlockEnd, + BlockHeader(BlockHeader), + Layer(Layer), + Control(Control), + NamedRecord(NamedRecord), + Linetype(Linetype), + TextStyle(TextStyle), + DimStyle(DimStyle), + /// A VPORT table record whole. + Viewport(Box), + /// A DIMSTYLE table record with every variable (as DWG and DXF files + /// store them); [`DimStyle`] is the style a new drawing starts with. + DimStyleRecord(Box), + /// A non-graphical object: dictionary, extension record, layout, … + NonGraphic(NonGraphic), + /// Recognised type the core does not decode yet. + Unsupported, + /// Decoding failed; the message says where. + Failed(String), + /// A kind of native record from a newer revision of the `.cad` format. + /// The number is its kind code; its fields are kept, undecoded, in + /// [`Object::unknown_tags`] so a save writes them back unchanged. Only + /// readers create this, and never with a code this version knows. + NewerKind(i16), + /// A native record whose kind fields could not be decoded (damage, or + /// a writer that broke the format); the message says why. Everything + /// from where the kind tag should be is kept in + /// [`Object::unknown_tags`], and a save writes it back as it was, so + /// the next reader sees and reports the same problem. Only readers + /// create this. + Damaged(String), +} + +impl ObjectKind { + pub fn is_decoded(&self) -> bool { + !matches!(self, ObjectKind::Unsupported | ObjectKind::Failed(_) | ObjectKind::NewerKind(_) | ObjectKind::Damaged(_)) + } +} + +/// Extended data (DXF "XDATA", DWG "EED"): values an application attaches +/// to an object, under the application's registered name. An object can +/// carry one block per application. +/// +/// The value kinds are DXF's group codes 1000–1071, with their meaning +/// from the DXF reference. The model sets no size limits; AutoCAD allows +/// 16 KB of extended data per object, 255-byte strings and 127-byte binary +/// chunks, and a DXF or DWG writer has to respect those. +#[derive(Debug, Clone, PartialEq)] +pub struct XData { + /// The registered application (group 1001). + pub app: XDataApp, + pub items: Vec, +} + +impl XData { + /// The application's registered name, when known. + pub fn app_name(&self) -> Option<&str> { + match &self.app { + XDataApp::Name(n) => Some(n), + XDataApp::Handle(_) => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum XDataApp { + /// The registered application name, as in its APPID table record. + Name(String), + /// The APPID table record by handle, kept this way only when its name + /// is not known (the source file refers to a record that is missing or + /// could not be read). DWG stores every application this way; readers + /// turn handles into names when the record exists. + Handle(Handle), +} + +/// One extended-data value. Each variant names its DXF group code. +#[derive(Debug, Clone, PartialEq)] +pub enum XValue { + /// 1000: a string. + Str(String), + /// 1002 `{`: opens a nested list. + Open, + /// 1002 `}`: closes a nested list. + Close, + /// 1003: a layer, by handle (as DWG stores it; DXF writes the layer's + /// name). It follows renames. + Layer(Handle), + /// 1004: binary data. + Bytes(Vec), + /// 1005: a handle of another object. Translated when objects are + /// copied into another drawing. + Handle(Handle), + /// 1010: three reals. Editing never changes them. + Point(Vec3), + /// 1011: a world position. Moved, scaled, rotated, mirrored and + /// stretched along with the object. + Position(Vec3), + /// 1012: a world displacement. Scaled, rotated and mirrored along with + /// the object, but not moved or stretched. + Displacement(Vec3), + /// 1013: a world direction. Rotated and mirrored along with the object, + /// but not moved, scaled or stretched. + Direction(Vec3), + /// 1040: a real. + Real(f64), + /// 1041: a distance. Scaled along with the object. + Distance(f64), + /// 1042: a scale factor. Scaled along with the object. + ScaleFactor(f64), + /// 1070: a 16-bit integer. + Int16(i16), + /// 1071: a 32-bit integer. + Int32(i32), + /// DWG extended data that could not be decoded: the bytes from the item + /// that failed to the end of the application's data, exactly as stored, + /// with the version of the file they came from (string items are + /// encoded differently before and after R2007). + Undecoded { version: DwgVersion, data: Vec }, +} + +/// One object from the file. +#[derive(Debug, Clone, PartialEq)] +pub struct Object { + pub handle: Handle, + pub type_code: u16, + /// "LINE", "LAYER", or a class DXF name for custom types. + pub type_name: String, + pub owner: Handle, + pub reactors: Vec, + pub xdictionary: Handle, + /// Present for entities. + pub entity: Option, + pub kind: ObjectKind, + /// Where the object starts (file offset for R13–R15, offset in the + /// AcDb:AcDbObjects section for R2004+). + pub offset: usize, + /// Size of the object data in bytes. + pub size: usize, + /// Non-fatal decode problem (for example an unreadable handle stream). + pub note: Option, + /// The object's original DWG bytes, kept when the core could not decode + /// it (`Unsupported` or `Failed`), or kept only its name (a + /// `NamedRecord`), so a save does not lose it. Those + /// bytes include the object's extended data, which `xdata` holds + /// decoded; a DWG writer that writes `raw` must rebuild that part if + /// `xdata` was changed. + pub raw: Option, + /// Extended data (XDATA), one block per application, in stored order. + pub xdata: Vec, + /// Fields written by a newer revision of the native format, which this + /// version does not read: encoded `.cad` tags, kept exactly as found so + /// that saving the object writes them back after the kind's fields. + /// Empty for objects that did not come from a newer writer. + /// + /// For a `Damaged` object they hold everything from where the kind tag + /// should be. Code that replaces an object's kind should clear them. + /// The writer does not check them: they must be whole tags with no + /// extended-data codes (1000–1071). + pub unknown_tags: Vec, +} + +impl Object { + /// Bytes the object holds, roughly: for budgeting the undo history, + /// not for exact accounting. Counts the parts that grow (lists of + /// points, text, kept file bytes). + pub fn approx_bytes(&self) -> usize { + use std::mem::size_of; + let kind = match &self.kind { + ObjectKind::LwPolyline(p) => p.points.len() * size_of::() + p.bulges.len() * 8 + p.widths.len() * 16 + p.vertex_ids.len() * 4, + ObjectKind::Text(t) => t.value.len(), + ObjectKind::MText(t) => t.contents.len(), + ObjectKind::Spline(sp) => sp.knots.len() * 8 + sp.weights.len() * 8 + (sp.control_points.len() + sp.fit_points.len()) * size_of::(), + ObjectKind::Hatch(h) => h.paths.len() * 256 + h.pattern_lines.len() * 64, + ObjectKind::Leader(l) => l.vertices.len() * size_of::(), + ObjectKind::Tolerance(t) => t.text.len(), + ObjectKind::MLine(m) => { + m.vertices.iter().map(|v| size_of::() + v.params.iter().map(|(a, b)| 48 + (a.len() + b.len()) * 8).sum::()).sum() + } + ObjectKind::Image(r) | ObjectKind::Wipeout(r) => size_of::() + r.clip.len() * size_of::(), + ObjectKind::PaperViewport(v) => size_of::() + v.frozen_layers.len() * 8, + ObjectKind::BlockHeader(b) => b.entities.len() * size_of::(), + ObjectKind::Failed(m) | ObjectKind::Damaged(m) => m.len(), + _ => 0, + }; + size_of::() + + kind + + self.type_name.len() + + self.reactors.len() * size_of::() + + self.note.as_ref().map_or(0, String::len) + + self.raw.as_ref().map_or(0, |r| r.data.len()) + + self.xdata.iter().map(|x| 32 + x.items.len() * 48).sum::() + + self.unknown_tags.len() + } +} + +/// An object's undecoded DWG record, exactly as stored in the source file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawDwgObject { + /// Version of the file the bytes came from; they are only meaningful + /// to a reader or writer of that version. + pub version: DwgVersion, + /// Size of the handle stream in bits (R2010+), else 0. + pub handle_stream_bits: u64, + /// The object data that follows the size prefix (without the CRC). + pub data: Vec, +} + +impl Object { + pub fn is_entity(&self) -> bool { + self.entity.is_some() + } + + /// The extended data an application attached to this object. Names + /// compare without regard to ASCII case, as AutoCAD compares them. + pub fn xdata_for(&self, app: &str) -> Option<&XData> { + self.xdata.iter().find(|x| x.app_name().is_some_and(|n| n.eq_ignore_ascii_case(app))) + } +} + +/// A custom class declared in the file (object types 500 and up). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ClassDef { + pub number: u16, + pub proxy_flags: u16, + pub app_name: String, + pub cpp_name: String, + pub dxf_name: String, + pub was_zombie: bool, + /// 0x1F2 for entity classes, 0x1F3 for object classes. + pub item_class_id: u16, + /// Objects of the class the drawing has made (DXF 91); 0 unknown. + pub instance_count: u32, + /// The DWG version and maintenance release the class came with, as + /// R2004+ files record them; 0 unknown. + pub dwg_version: u32, + pub maintenance_version: u32, +} + +impl ClassDef { + pub fn is_entity(&self) -> bool { + self.item_class_id == 0x1F2 + } +} + +/// The header variables the core uses, plus whether the header parse was +/// cross-checked against the object map. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct HeaderVars { + /// True when the parse was validated (control-object handles resolved + /// to objects of the right type). Unverified values should not be + /// trusted. + pub verified: bool, + pub insunits: Option, + pub measurement: Option, + pub extmin: Option, + pub extmax: Option, + pub limmin: Option, + pub limmax: Option, + pub insbase: Option, + pub ltscale: Option, + pub textsize: Option, + /// Linear display format (`$LUNITS`): 1 scientific, 2 decimal, + /// 3 engineering, 4 architectural, 5 fractional. + pub lunits: Option, + /// Linear display precision (`$LUPREC`): decimal places, or for + /// fractions the power of two of the smallest denominator. + pub luprec: Option, + /// Angle display format (`$AUNITS`): 0 decimal degrees, 1 degrees, + /// minutes and seconds, 2 grads, 3 radians, 4 surveyor's units. + pub aunits: Option, + /// Angle display precision (`$AUPREC`). + pub auprec: Option, + /// Direction of angle 0, radians (`$ANGBASE`). + pub angbase: Option, + /// 1 when angles run clockwise (`$ANGDIR`). + pub angdir: Option, + /// Linetype scale given to new entities (`$CELTSCALE`). + pub celtscale: Option, + pub handseed: Option, + pub clayer: Handle, + /// Current text style (`$TEXTSTYLE`). + pub textstyle: Handle, + /// Linetype given to new entities (`$CELTYPE`): an LTYPE record, + /// normally the one named ByLayer. + pub celtype: Handle, + /// Current dimension style (`$DIMSTYLE`). + pub dimstyle: Handle, + pub block_control: Handle, + pub layer_control: Handle, + pub style_control: Handle, + pub linetype_control: Handle, + pub dimstyle_control: Handle, + pub model_space: Handle, + pub paper_space: Handle, + pub named_objects_dict: Handle, + /// Every variable the parser read, in file order, as display text. + pub raw: Vec<(String, String)>, + /// Why the parse was not verified, if it was not. + pub note: String, + /// Drawing properties: title, author and the like. + pub properties: Properties, + /// Variables written by a newer revision of the native format, which + /// this version does not read: encoded `.cad` tags, kept exactly as + /// found so that saving writes them back. + pub unknown_tags: Vec, +} + +/// Drawing properties, the fields of the "drawing properties" dialog of +/// CAD programs (DWG keeps them in its summary information). Empty +/// strings and zero times are unset. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Properties { + pub title: String, + pub subject: String, + pub author: String, + pub keywords: String, + pub comments: String, + pub last_saved_by: String, + pub revision: String, + /// Base for relative hyperlinks in the drawing. + pub hyperlink_base: String, + /// Unix seconds. + pub created: i64, + pub modified: i64, + /// Name and value pairs, in order; names are unique. + pub custom: Vec<(String, String)>, +} + +impl Properties { + pub fn is_empty(&self) -> bool { + *self == Properties::default() + } + + /// The named fields as (label, value), for display and the CLI. + pub fn fields(&self) -> [(&'static str, &str); 8] { + [ + ("title", &self.title), + ("subject", &self.subject), + ("author", &self.author), + ("keywords", &self.keywords), + ("comments", &self.comments), + ("last-saved-by", &self.last_saved_by), + ("revision", &self.revision), + ("hyperlink-base", &self.hyperlink_base), + ] + } + + /// Set a named field (one of [`Properties::fields`]) or, for any other + /// name, a custom property; an empty value removes a custom property. + pub fn set(&mut self, name: &str, value: &str) { + let v = value.to_string(); + match name { + "title" => self.title = v, + "subject" => self.subject = v, + "author" => self.author = v, + "keywords" => self.keywords = v, + "comments" => self.comments = v, + "last-saved-by" => self.last_saved_by = v, + "revision" => self.revision = v, + "hyperlink-base" => self.hyperlink_base = v, + _ => { + let at = self.custom.iter().position(|(k, _)| k == name); + match (at, value.is_empty()) { + (Some(i), true) => { + self.custom.remove(i); + } + (Some(i), false) => self.custom[i].1 = v, + (None, false) => self.custom.push((name.to_string(), v)), + (None, true) => {} + } + } + } + } +} + +/// Name of an `INSUNITS` value (drawing units), per the DXF reference. +pub fn units_name(insunits: u16) -> &'static str { + match insunits { + 0 => "unitless", + 1 => "inches", + 2 => "feet", + 3 => "miles", + 4 => "millimeters", + 5 => "centimeters", + 6 => "meters", + 7 => "kilometers", + 8 => "microinches", + 9 => "mils", + 10 => "yards", + 11 => "angstroms", + 12 => "nanometers", + 13 => "microns", + 14 => "decimeters", + 15 => "decameters", + 16 => "hectometers", + 17 => "gigameters", + 18 => "astronomical units", + 19 => "light years", + 20 => "parsecs", + 21 => "US survey feet", + _ => "unknown", + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Severity { + Info, + Warning, + Error, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Diagnostic { + pub severity: Severity, + pub message: String, +} + +/// Summary of one stored section (R2004+) or section locator (R13–R15). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SectionInfo { + pub name: String, + pub size: u64, + pub pages: u32, + pub compressed: bool, + pub encrypted: bool, +} + +/// Lookup tables built once after loading (see [`Drawing::rebuild_index`]). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct DrawingIndex { + pub model_space: Handle, + pub paper_space: Handle, + /// Object handles grouped by owner, in handle order. Model- and + /// paper-space entities (which files store without an owner handle) are + /// grouped under the space's block record. + pub owned: BTreeMap>, +} + +/// A loaded drawing. +#[derive(Debug, Clone, PartialEq)] +pub struct Drawing { + pub version: DwgVersion, + pub maintenance_version: u8, + pub codepage: u16, + pub header: HeaderVars, + pub classes: Vec, + pub objects: ObjectMap, + pub sections: Vec, + pub diagnostics: Vec, + pub index: DrawingIndex, +} + +impl Drawing { + /// Record a save the way AutoCAD does when it writes a file: who saved + /// it (the drawing properties' "last saved by") and when (TDUPDATE and + /// TDUUPDATE, and TDCREATE and TDUCREATE if the drawing has no creation + /// time yet). `unix_seconds` is UTC; with no time zone at hand the + /// local times are given in UTC too. + pub fn stamp_save(&mut self, saved_by: &str, unix_seconds: i64) { + let julian = 2_440_588.0 + unix_seconds as f64 / 86_400.0; + let text = format!("{julian}"); + let set = |raw: &mut Vec<(String, String)>, name: &str, value: &str| match raw.iter_mut().find(|(k, _)| k == name) { + Some(e) => e.1 = value.to_string(), + None => raw.push((name.to_string(), value.to_string())), + }; + let created = self.header.raw.iter().find(|(k, _)| k == "TDCREATE").and_then(|(_, v)| v.parse::().ok()).is_some_and(|v| v > 0.0); + if !created { + set(&mut self.header.raw, "TDCREATE", &text); + set(&mut self.header.raw, "TDUCREATE", &text); + self.header.properties.created = unix_seconds; + } + set(&mut self.header.raw, "TDUPDATE", &text); + set(&mut self.header.raw, "TDUUPDATE", &text); + self.header.properties.last_saved_by = saved_by.to_string(); + self.header.properties.modified = unix_seconds; + } + + pub fn get(&self, h: Handle) -> Option<&Object> { + self.objects.get(&h) + } + + pub fn layer(&self, h: Handle) -> Option<&Layer> { + match &self.get(h)?.kind { + ObjectKind::Layer(l) => Some(l), + _ => None, + } + } + + /// A linetype record with its pattern. A DWG linetype the reader could + /// not decode keeps only its name (see [`NamedRecord`]); use + /// [`Drawing::record_name`] for any. + pub fn linetype(&self, h: Handle) -> Option<&Linetype> { + match &self.get(h)?.kind { + ObjectKind::Linetype(l) => Some(l), + _ => None, + } + } + + pub fn text_style(&self, h: Handle) -> Option<&TextStyle> { + match &self.get(h)?.kind { + ObjectKind::TextStyle(s) => Some(s), + _ => None, + } + } + + pub fn dim_style(&self, h: Handle) -> Option<&DimStyle> { + match &self.get(h)?.kind { + ObjectKind::DimStyle(s) => Some(s), + _ => None, + } + } + + /// The name of a table record of any kind (layer, linetype, style, + /// block, …). + pub fn record_name(&self, h: Handle) -> Option<&str> { + Some(match &self.get(h)?.kind { + ObjectKind::Layer(l) => &l.name, + ObjectKind::Linetype(l) => &l.name, + ObjectKind::TextStyle(s) => &s.name, + ObjectKind::DimStyle(s) => &s.name, + ObjectKind::BlockHeader(b) => &b.name, + ObjectKind::NamedRecord(r) => &r.name, + ObjectKind::Viewport(v) => &v.name, + ObjectKind::DimStyleRecord(r) => &r.name, + _ => return None, + }) + } + + pub fn block_header(&self, h: Handle) -> Option<&BlockHeader> { + match &self.get(h)?.kind { + ObjectKind::BlockHeader(b) => Some(b), + _ => None, + } + } + + pub fn block_by_name(&self, name: &str) -> Option<(Handle, &BlockHeader)> { + self.objects.values().find_map(|o| match &o.kind { + ObjectKind::BlockHeader(b) if b.name.eq_ignore_ascii_case(name) => Some((o.handle, b)), + _ => None, + }) + } + + /// Find a space's block record: verified header first, then the + /// BLOCK_CONTROL object, then by name. + fn find_space(&self, from_header: Handle, paper: bool) -> Handle { + if self.header.verified && self.block_header(from_header).is_some() { + return from_header; + } + for o in self.objects.values() { + if let ObjectKind::Control(c) = &o.kind { + let h = if paper { c.paper_space } else { c.model_space }; + if !h.is_null() && self.block_header(h).is_some() { + return h; + } + } + } + let name = if paper { "*Paper_Space" } else { "*Model_Space" }; + self.block_by_name(name).map(|(h, _)| h).unwrap_or(Handle::NULL) + } + + /// Recompute the lookup tables. Call after changing `objects`. + pub fn rebuild_index(&mut self) { + let model_space = self.find_space(self.header.model_space, false); + let paper_space = self.find_space(self.header.paper_space, true); + let mut owned: BTreeMap> = BTreeMap::new(); + for o in self.objects.values() { + let key = match o.entity.as_ref().map(|e| e.space) { + Some(Space::Model) => model_space, + Some(Space::Paper) => paper_space, + _ => o.owner, + }; + if !key.is_null() { + owned.entry(key).or_default().push(o.handle); + } + } + self.index = DrawingIndex { model_space, paper_space, owned }; + } + + /// Handle of the *Model_Space block record. + pub fn model_space(&self) -> Handle { + self.index.model_space + } + + /// Handle of the active *Paper_Space block record. + pub fn paper_space(&self) -> Handle { + self.index.paper_space + } + + /// Objects owned by `owner` (in handle order). + pub fn owned_by(&self, owner: Handle) -> impl Iterator { + self.index.owned.get(&owner).into_iter().flatten().filter_map(move |h| self.get(*h)) + } + + /// Entities belonging to a block record, in drawing order where the file + /// records it (R2004+), otherwise in handle order. + pub fn block_entities(&self, block: Handle) -> Vec<&Object> { + let Some(bh) = self.block_header(block) else { + return Vec::new(); + }; + if !bh.entities.is_empty() { + let listed: Vec<&Object> = bh.entities.iter().filter_map(|h| self.get(*h)).filter(|o| o.is_entity()).collect(); + if !listed.is_empty() { + return listed; + } + } + self.owned_by(block).filter(|o| o.is_entity()).filter(|o| !matches!(o.kind, ObjectKind::BlockBegin { .. } | ObjectKind::BlockEnd)).collect() + } + + pub fn model_space_entities(&self) -> Vec<&Object> { + let ms = self.model_space(); + if !ms.is_null() { + return self.block_entities(ms); + } + // No block record found: fall back to entity modes alone. + self.objects.values().filter(|o| o.entity.as_ref().map(|e| e.space == Space::Model).unwrap_or(false)).collect() + } + + /// Vertices of an old-style POLYLINE, in order. + pub fn polyline_vertices(&self, polyline: &Object) -> Vec<&Vertex> { + let ObjectKind::Polyline(pl) = &polyline.kind else { + return Vec::new(); + }; + fn vertex(o: &Object) -> Option<&Vertex> { + match &o.kind { + ObjectKind::Vertex(v) => Some(v), + _ => None, + } + } + let from_list: Vec<&Vertex> = pl.vertices.iter().filter_map(|h| self.get(*h)).filter_map(vertex).collect(); + if !from_list.is_empty() { + return from_list; + } + // R13–R2000: vertices are owned by the polyline; handles ascend in + // creation order. + self.owned_by(polyline.handle).filter_map(vertex).collect() + } + + /// Attributes attached to an INSERT. + pub fn insert_attributes(&self, insert: &Object) -> Vec<&Object> { + let ObjectKind::Insert(ins) = &insert.kind else { + return Vec::new(); + }; + let listed: Vec<&Object> = ins.attribs.iter().filter_map(|h| self.get(*h)).collect(); + if !listed.is_empty() { + return listed; + } + self.owned_by(insert.handle).filter(|o| matches!(o.kind, ObjectKind::Attribute(_))).collect() + } + + /// Number each layout's viewports in drawing order, the layout's own + /// view first (DWG stores no numbers; DXF does). Viewports that + /// already have numbers keep them. + pub fn number_viewports(&mut self) { + let blocks: Vec = self.objects.values().filter(|o| matches!(o.kind, ObjectKind::BlockHeader(_))).map(|o| o.handle).collect(); + for b in blocks { + let vps: Vec = + self.block_entities(b).iter().filter(|o| matches!(o.kind, ObjectKind::PaperViewport(_))).map(|o| o.handle).collect(); + for (i, h) in vps.iter().enumerate() { + if let Some(ObjectKind::PaperViewport(v)) = self.objects.get_mut(h).map(|o| &mut o.kind) + && v.id == 0 + { + v.id = (i + 1).min(i16::MAX as usize) as i16; + } + } + } + } + + /// Counts of objects by type name: (decoded, unsupported, failed). + pub fn type_counts(&self) -> BTreeMap { + let mut m: BTreeMap = BTreeMap::new(); + for o in self.objects.values() { + let e = m.entry(o.type_name.clone()).or_default(); + match o.kind { + ObjectKind::Unsupported | ObjectKind::NewerKind(_) => e.1 += 1, + ObjectKind::Failed(_) | ObjectKind::Damaged(_) => e.2 += 1, + _ => e.0 += 1, + } + } + m + } +} diff --git a/crates/dwg/src/records/model/objects.rs b/crates/dwg/src/records/model/objects.rs new file mode 100644 index 00000000..f4e6a5fb --- /dev/null +++ b/crates/dwg/src/records/model/objects.rs @@ -0,0 +1,421 @@ +//! Non-graphical objects and the table records the drawing keeps whole: +//! dictionaries, extension records, layouts, scales, multiline styles, +//! plot-style placeholders and dictionary variables (DXF OBJECTS +//! section), the VPORT record and a DIMSTYLE record's every variable. +//! +//! Their fields are those of the DXF reference and of the ODA +//! specification's chapter 20 (DICTIONARY §20.4.44, DICTIONARYWDFLT +//! §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. + +use super::{Color, DimStyle, Handle, Lineweight}; +use crate::records::geom::{Vec2, Vec3}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Dictionary { + /// DXF 281. + pub cloning: u16, + /// DXF 280. + pub hard_owner: u8, + pub entries: Vec<(String, Handle)>, + /// ACDBDICTIONARYWDFLT only: the default entry (DXF 340). + pub default: Option, +} + +/// One value of an extension record, by DXF group code. +#[derive(Debug, Clone, PartialEq)] +pub enum XrValue { + Str(String), + Point(Vec3), + Real(f64), + Int8(i8), + Int16(i16), + Int32(i32), + Int64(i64), + Bool(bool), + Bytes(Vec), + Handle(Handle), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct XRecord { + /// DXF 280. + pub cloning: u16, + pub items: Vec<(u16, XrValue)>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MLineElement { + pub offset: f64, + pub color: Color, + /// R2018: the linetype record. Before R2018 the file stores an index. + pub linetype: Handle, + pub linetype_index: i16, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MLineStyle { + pub name: String, + pub description: String, + /// The DXF 70 flags (the DWG bit order converted). + pub flags: u16, + pub fill_color: Color, + pub start_angle: f64, + pub end_angle: f64, + pub elements: Vec, +} + +/// The plot settings part of a layout (DXF groups of AcDbPlotSettings). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PlotSettings { + pub page_setup_name: String, + pub printer: String, + pub flags: u16, + /// Left, bottom, right, top, millimetres. + pub margins: [f64; 4], + pub paper_width: f64, + pub paper_height: f64, + pub paper_size: String, + pub origin: Vec2, + pub paper_units: u16, + pub rotation: u16, + pub plot_type: u16, + pub window_min: Vec2, + pub window_max: Vec2, + pub real_world_units: f64, + pub drawing_units: f64, + pub style_sheet: String, + pub scale_type: u16, + pub scale_factor: f64, + pub image_origin: Vec2, + pub shade_plot_mode: u16, + pub shade_plot_res_level: u16, + pub shade_plot_custom_dpi: u16, + /// DXF 6, R2004+ by handle. + pub plot_view: Handle, + /// R2007+. + pub visual_style: Handle, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Layout { + pub plot: PlotSettings, + pub name: String, + pub tab_order: u32, + pub flags: u16, + pub ucs_origin: Vec3, + pub limmin: Vec2, + pub limmax: Vec2, + pub insbase: Vec3, + pub ucs_x: Vec3, + pub ucs_y: Vec3, + pub elevation: f64, + pub ortho_type: u16, + pub extmin: Vec3, + pub extmax: Vec3, + /// The paper-space block record (DXF 330 of AcDbLayout). + pub block: Handle, + pub last_viewport: Handle, + pub base_ucs: Handle, + pub named_ucs: Handle, + pub viewports: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Scale { + pub flag: u16, + pub name: String, + pub paper_units: f64, + pub drawing_units: f64, + pub unit_scale: bool, +} + +/// An object kept as its DXF groups, for the style objects whose fields +/// the program carries without interpreting them: visual styles, +/// materials, table styles and their cell style maps, multileader, section +/// and detail view styles, dimension associations, and the objects raster +/// images use (image definitions, their reactors, raster variables). `items` are the +/// groups after the common part (from the first subclass marker, 100, +/// which is kept), in DXF order, points as one item. The DWG reader and +/// writer convert them with a codec per type (`dwg::styles`). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Groups { + /// The DXF object type, as written after group 0. + pub kind: String, + pub items: Vec<(u16, XrValue)>, +} + +impl Groups { + /// The object types kept this way. + pub const KINDS: [&'static str; 11] = [ + "VISUALSTYLE", + "MATERIAL", + "TABLESTYLE", + "CELLSTYLEMAP", + "MLEADERSTYLE", + "ACDBSECTIONVIEWSTYLE", + "ACDBDETAILVIEWSTYLE", + "DIMASSOC", + // 0.14.0: the objects raster images use. + "IMAGEDEF", + "IMAGEDEF_REACTOR", + "RASTERVARIABLES", + ]; +} + +#[derive(Debug, Clone, PartialEq)] +pub enum NonGraphic { + Dictionary(Dictionary), + XRecord(XRecord), + Placeholder, + DictionaryVar { schema: u8, value: String }, + Scale(Scale), + Layout(Box), + MLineStyle(MLineStyle), + Groups(Groups), +} + +/// Every dimension variable a DIMSTYLE record stores (spec §20.4.68, +/// R2000+ layout), by its variable name. Colours are CmColors; angles in +/// radians; the handles are the text style, arrow blocks and linetypes. +#[derive(Debug, Clone, PartialEq)] +pub struct DimVars { + pub post: String, + pub apost: String, + pub scale: f64, + pub asz: f64, + pub exo: f64, + pub dli: f64, + pub exe: f64, + pub rnd: f64, + pub dle: f64, + pub tp: f64, + pub tm: f64, + pub fxl: f64, + pub jogang: f64, + pub tfill: u16, + pub tfillclr: Color, + pub tol: bool, + pub lim: bool, + pub tih: bool, + pub toh: bool, + pub se1: bool, + pub se2: bool, + pub tad: u16, + pub zin: u16, + pub azin: u16, + pub arcsym: u16, + pub txt: f64, + pub cen: f64, + pub tsz: f64, + pub altf: f64, + pub lfac: f64, + pub tvp: f64, + pub tfac: f64, + pub gap: f64, + pub altrnd: f64, + pub alt: bool, + pub altd: u16, + pub tofl: bool, + pub sah: bool, + pub tix: bool, + pub soxd: bool, + pub clrd: Color, + pub clre: Color, + pub clrt: Color, + pub adec: u16, + pub dec: u16, + pub tdec: u16, + pub altu: u16, + pub alttd: u16, + pub aunit: u16, + pub frac: u16, + pub lunit: u16, + pub dsep: u16, + pub tmove: u16, + pub just: u16, + pub sd1: bool, + pub sd2: bool, + pub tolj: u16, + pub tzin: u16, + pub altz: u16, + pub alttz: u16, + pub upt: bool, + pub fit: u16, + pub fxlon: bool, + pub txtdirection: bool, + pub altmzf: f64, + pub altmzs: String, + pub mzf: f64, + pub mzs: String, + /// DXF lineweight values (-1 by layer, -2 by block, -3 default). + pub lwd: i16, + pub lwe: i16, + /// The trailing bit the spec calls "unknown" (sets bit 1 of DXF 70). + pub flag_bit: bool, + pub txsty: Handle, + pub ldrblk: Handle, + pub blk: Handle, + pub blk1: Handle, + pub blk2: Handle, + pub ltype: Handle, + pub ltex1: Handle, + pub ltex2: Handle, +} + +/// A DIMSTYLE table record whole: its name and every variable. +#[derive(Debug, Clone, PartialEq)] +pub struct DimStyleRecord { + pub name: String, + pub vars: DimVars, +} + +/// The viewport table record (VPORT, spec §20.4.64), R2000+ fields. +#[derive(Debug, Clone, PartialEq)] +pub struct Vport { + pub name: String, + pub view_height: f64, + /// Width over height (the file stores width; this is divided back). + pub aspect: f64, + pub center: Vec2, + pub target: Vec3, + pub direction: Vec3, + pub twist: f64, + pub lens: f64, + pub front_clip: f64, + pub back_clip: f64, + /// DXF 71 view mode bits. + pub view_mode: u16, + pub render_mode: u8, + pub default_lights: bool, + pub lighting_type: u8, + pub brightness: f64, + pub contrast: f64, + pub ambient: Color, + pub lower_left: Vec2, + pub upper_right: Vec2, + pub circle_zoom: u16, + pub fast_zoom: bool, + pub ucsicon: u8, + pub grid_on: bool, + pub grid_spacing: Vec2, + pub snap_on: bool, + pub snap_style: bool, + pub snap_isopair: u16, + pub snap_rotation: f64, + pub snap_base: Vec2, + pub snap_spacing: Vec2, + pub unknown_bit: bool, + pub ucs_per_viewport: bool, + pub ucs_origin: Vec3, + pub ucs_x: Vec3, + pub ucs_y: Vec3, + pub ucs_elevation: f64, + pub ucs_ortho_type: u16, + pub grid_flags: u16, + pub grid_major: u16, + pub background: Handle, + pub visual_style: Handle, + pub sun: Handle, + pub named_ucs: Handle, + pub base_ucs: Handle, +} + +impl Vport { + /// The *Active viewport AutoCAD's templates start with, looking at + /// `min`–`max` with a margin. + pub fn looking_at(min: Vec2, max: Vec2) -> Vport { + let (w, h) = (max.x - min.x, max.y - min.y); + let ok = w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0; + let (center, height, aspect) = if ok { + (Vec2::new((min.x + max.x) / 2.0, (min.y + max.y) / 2.0), h * 1.1, (w / h).max(1.0)) + } else { + (Vec2::new(6.0, 4.5), 9.0, 12.0 / 9.0) + }; + Vport { + name: "*Active".into(), + view_height: height, + aspect, + center, + target: Vec3::ZERO, + direction: Vec3::Z, + twist: 0.0, + lens: 50.0, + front_clip: 0.0, + back_clip: 0.0, + view_mode: 0, + render_mode: 0, + default_lights: true, + lighting_type: 1, + brightness: 0.0, + contrast: 0.0, + ambient: Color::Index(250), + lower_left: Vec2::ZERO, + upper_right: Vec2::new(1.0, 1.0), + circle_zoom: 100, + fast_zoom: true, + ucsicon: 3, + grid_on: false, + grid_spacing: Vec2::new(0.5, 0.5), + snap_on: false, + snap_style: false, + snap_isopair: 0, + snap_rotation: 0.0, + snap_base: Vec2::ZERO, + snap_spacing: Vec2::new(0.5, 0.5), + unknown_bit: false, + ucs_per_viewport: true, + ucs_origin: Vec3::ZERO, + ucs_x: Vec3::X, + ucs_y: Vec3::new(0.0, 1.0, 0.0), + ucs_elevation: 0.0, + ucs_ortho_type: 0, + grid_flags: 3, + grid_major: 5, + background: Handle::NULL, + visual_style: Handle::NULL, + sun: Handle::NULL, + named_ucs: Handle::NULL, + base_ucs: Handle::NULL, + } + } +} + +impl DimVars { + /// Fill in what a drawing-model dimension style holds. + pub fn apply_model(&mut self, s: &DimStyle) { + self.post = s.post_text.clone(); + self.scale = s.scale; + self.asz = s.arrow_size; + self.exo = s.ext_offset; + self.dli = s.baseline_spacing; + self.exe = s.ext_extension; + self.rnd = s.rounding; + self.dle = s.dim_line_extension; + self.txt = s.text_height; + self.cen = s.center_mark; + self.tsz = s.tick_size; + self.altf = s.alt_factor; + self.lfac = s.linear_factor; + self.gap = s.text_gap; + self.tih = s.text_inside_horizontal; + self.toh = s.text_outside_horizontal; + self.tad = s.text_above; + self.zin = s.zero_suppression; + self.alt = s.alt_units; + self.altd = s.alt_decimals; + self.clrd = s.line_color; + self.clre = s.ext_color; + self.clrt = s.text_color; + self.dec = s.decimals; + self.frac = s.fraction_format; + self.lunit = s.unit_format; + self.dsep = s.decimal_separator as u16; + self.just = s.text_justify; + self.txsty = s.text_style; + self.lwd = Lineweight::from_code(s.line_weight).dxf(); + self.lwe = Lineweight::from_code(s.ext_weight).dxf(); + } +} diff --git a/crates/dwg/src/records/model/store.rs b/crates/dwg/src/records/model/store.rs new file mode 100644 index 00000000..2228b508 --- /dev/null +++ b/crates/dwg/src/records/model/store.rs @@ -0,0 +1,342 @@ +//! The drawing's objects by handle, able to record what an edit changes. +//! +//! Reading goes through `Deref` to the map. Every way of changing it is a +//! method here, so while a journal is open ([`ObjectMap::start_journal`]) +//! the first time an edit touches an object, the object as it was is kept. +//! That record is the edit's undo: [`Drawing::revert`](super::Drawing::revert) +//! puts those objects back and returns the record that puts them forward +//! again. An edit costs memory in proportion to what it touches, not to +//! the size of the drawing. +//! +//! A block record's entity list (R2004+ files list every entity of model +//! space in it) is the exception to keeping whole objects: adding or +//! erasing one entity would copy the whole list. The list is changed +//! through [`ObjectMap::list_insert`] and [`ObjectMap::list_remove`] +//! instead, which record the one position changed. + +use super::{Handle, Object, ObjectKind}; +use std::collections::BTreeMap; +use std::ops::Deref; + +/// One change to a block record's entity list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ListOp { + Insert(usize, Handle), + Remove(usize, Handle), +} + +impl ListOp { + fn inverse(self) -> ListOp { + match self { + ListOp::Insert(at, h) => ListOp::Remove(at, h), + ListOp::Remove(at, h) => ListOp::Insert(at, h), + } + } +} + +/// What an edit did to one object. +/// +/// To take the edit back: put `prior` back (when there is one), then undo +/// `list_ops` from the last. List changes are recorded only until the +/// object is kept whole, so `prior` is the object with those changes made. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Touch { + /// The object before the edit (`Some(None)`: it did not exist). + pub prior: Option>, + pub list_ops: Vec, +} + +/// The objects an edit touched, as they were. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Journal { + pub touched: BTreeMap, +} + +impl Journal { + pub fn is_empty(&self) -> bool { + self.touched.is_empty() + } + + /// Add the record of a later edit, so the two undo as one. + pub fn merge(&mut self, later: Journal) { + for (h, t) in later.touched { + match self.touched.get_mut(&h) { + None => { + self.touched.insert(h, t); + } + // A whole object kept by the earlier edit already undoes + // everything after it. + Some(e) if e.prior.is_some() => {} + Some(e) => { + e.list_ops.extend(t.list_ops); + e.prior = t.prior; + } + } + } + } + + /// Bytes the record holds, roughly. + pub fn approx_bytes(&self) -> usize { + self.touched + .values() + .map(|t| { + 64 + t.list_ops.len() * std::mem::size_of::() + + match &t.prior { + Some(Some(o)) => o.approx_bytes(), + _ => 0, + } + }) + .sum() + } +} + +/// The drawing's objects (see the module documentation). +#[derive(Default)] +pub struct ObjectMap { + map: BTreeMap, + journal: Option, +} + +impl ObjectMap { + pub fn new() -> ObjectMap { + ObjectMap::default() + } + + /// Start recording what changes. + pub fn start_journal(&mut self) { + self.journal = Some(Journal::default()); + } + + /// Stop recording; what changed since [`ObjectMap::start_journal`]. + pub fn take_journal(&mut self) -> Journal { + self.journal.take().unwrap_or_default() + } + + pub fn journaling(&self) -> bool { + self.journal.is_some() + } + + /// Keep the object as it is now, if this is the first time it is + /// changed since the journal started. + fn keep(&mut self, h: Handle) { + if let Some(j) = &mut self.journal { + let t = j.touched.entry(h).or_default(); + if t.prior.is_none() { + t.prior = Some(self.map.get(&h).cloned()); + } + } + } + + pub fn get_mut(&mut self, h: &Handle) -> Option<&mut Object> { + if self.map.contains_key(h) { + self.keep(*h); + } + self.map.get_mut(h) + } + + pub fn insert(&mut self, h: Handle, o: Object) -> Option { + self.keep(h); + self.map.insert(h, o) + } + + pub fn remove(&mut self, h: &Handle) -> Option { + if self.map.contains_key(h) { + self.keep(*h); + } + self.map.remove(h) + } + + /// Every object, to change: while journaling, each is kept first. + pub fn values_mut(&mut self) -> impl Iterator { + if self.journal.is_some() { + let all: Vec = self.map.keys().copied().collect(); + for h in all { + self.keep(h); + } + } + self.map.values_mut() + } + + /// Every object with its handle, to change: as for `values_mut`. + pub fn iter_mut(&mut self) -> impl Iterator { + if self.journal.is_some() { + let all: Vec = self.map.keys().copied().collect(); + for h in all { + self.keep(h); + } + } + self.map.iter_mut() + } + + pub fn retain(&mut self, mut f: impl FnMut(&Handle, &mut Object) -> bool) { + let gone: Vec = self.map.iter_mut().filter_map(|(h, o)| (!f(h, o)).then_some(*h)).collect(); + for h in gone { + self.remove(&h); + } + } + + pub fn clear(&mut self) { + let all: Vec = self.map.keys().copied().collect(); + for h in all { + self.remove(&h); + } + } + + pub fn into_map(self) -> BTreeMap { + self.map + } + + /// The entity list of block record `block`, if it is one. + fn list(&mut self, block: Handle) -> Option<&mut Vec> { + match self.map.get_mut(&block).map(|o| &mut o.kind) { + Some(ObjectKind::BlockHeader(b)) => Some(&mut b.entities), + _ => None, + } + } + + fn record(&mut self, block: Handle, op: ListOp) { + if let Some(j) = &mut self.journal { + let t = j.touched.entry(block).or_default(); + // Once the record is kept whole, it undoes this too. + if t.prior.is_none() { + t.list_ops.push(op); + } + } + } + + /// Put `h` in block record `block`'s entity list at `at` (the end when + /// `None`). Nothing when `block` is not a block record. + pub fn list_insert(&mut self, block: Handle, at: Option, h: Handle) { + let Some(list) = self.list(block) else { + return; + }; + let at = at.unwrap_or(list.len()).min(list.len()); + list.insert(at, h); + self.record(block, ListOp::Insert(at, h)); + } + + /// Take `h` out of block record `block`'s entity list, wherever it is. + pub fn list_remove(&mut self, block: Handle, h: Handle) { + let Some(list) = self.list(block) else { + return; + }; + let Some(at) = list.iter().position(|x| *x == h) else { + return; + }; + list.remove(at); + self.record(block, ListOp::Remove(at, h)); + // Listed twice (a damaged file): take the rest out too. + while let Some(list) = self.list(block) { + let Some(at) = list.iter().position(|x| *x == h) else { + break; + }; + list.remove(at); + self.record(block, ListOp::Remove(at, h)); + } + } + + fn undo_op(&mut self, block: Handle, op: ListOp) { + let Some(list) = self.list(block) else { + return; + }; + match op { + ListOp::Insert(at, h) => { + if list.get(at) == Some(&h) { + list.remove(at); + } else if let Some(i) = list.iter().position(|x| *x == h) { + list.remove(i); + } + } + ListOp::Remove(at, h) => list.insert(at.min(list.len()), h), + } + } + + /// Take back what `j` records (see [`Touch`]); the record that makes + /// the same change again. Nothing is copied: objects move between the + /// map and the records. + pub fn revert(&mut self, j: Journal) -> Journal { + debug_assert!(self.journal.is_none(), "revert while journaling"); + let mut back = Journal::default(); + for (h, t) in j.touched { + let mut inv = Touch::default(); + if let Some(prior) = t.prior { + inv.prior = Some(self.map.remove(&h)); + if let Some(o) = prior { + self.map.insert(h, o); + } + } + for op in t.list_ops.iter().rev() { + self.undo_op(h, *op); + // With the object put back whole, it needs no list changes. + if inv.prior.is_none() { + inv.list_ops.push(op.inverse()); + } + } + back.touched.insert(h, inv); + } + back + } +} + +impl Deref for ObjectMap { + type Target = BTreeMap; + fn deref(&self) -> &Self::Target { + &self.map + } +} + +/// A copy has no journal: it is a new drawing. +impl Clone for ObjectMap { + fn clone(&self) -> ObjectMap { + ObjectMap { map: self.map.clone(), journal: None } + } +} + +/// The objects only; an open journal is not part of the drawing. +impl PartialEq for ObjectMap { + fn eq(&self, other: &ObjectMap) -> bool { + self.map == other.map + } +} + +impl std::fmt::Debug for ObjectMap { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.map.fmt(f) + } +} + +impl From> for ObjectMap { + fn from(map: BTreeMap) -> ObjectMap { + ObjectMap { map, journal: None } + } +} + +impl FromIterator<(Handle, Object)> for ObjectMap { + fn from_iter>(it: I) -> ObjectMap { + ObjectMap::from(it.into_iter().collect::>()) + } +} + +impl Extend<(Handle, Object)> for ObjectMap { + fn extend>(&mut self, it: I) { + for (h, o) in it { + self.insert(h, o); + } + } +} + +impl IntoIterator for ObjectMap { + type Item = (Handle, Object); + type IntoIter = std::collections::btree_map::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.map.into_iter() + } +} + +impl<'a> IntoIterator for &'a ObjectMap { + type Item = (&'a Handle, &'a Object); + type IntoIter = std::collections::btree_map::Iter<'a, Handle, Object>; + fn into_iter(self) -> Self::IntoIter { + self.map.iter() + } +} diff --git a/crates/dwg/src/records/text.rs b/crates/dwg/src/records/text.rs new file mode 100644 index 00000000..3d10102e --- /dev/null +++ b/crates/dwg/src/records/text.rs @@ -0,0 +1,238 @@ +//! Text helpers: 8-bit code page decoding, AutoCAD escape sequences and +//! MTEXT inline-format stripping. + +/// Windows-1252 characters for bytes 0x80–0x9F (the rest of the upper half +/// matches Latin-1). Unassigned positions map to the C1 control of the same +/// value. +const CP1252_HIGH: [u32; 32] = [ + 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, +]; + +/// Name for the DWGCODEPAGE value stored in the file header, where known. +/// Only the common Western value is mapped so far. +pub fn codepage_name(cp: u16) -> &'static str { + match cp { + 30 => "ANSI_1252", + _ => "unmapped (decoded as ANSI_1252)", + } +} + +/// Decode an 8-bit DWG string (R13–R2004). Every code page is decoded as +/// Windows-1252 for now; `\U+XXXX` escapes, which AutoCAD uses for +/// characters outside the code page, are expanded. +pub fn decode_ansi(bytes: &[u8], _codepage: u16) -> String { + let mut s = String::with_capacity(bytes.len()); + for &b in bytes { + if b == 0 { + break; + } + let c = match b { + 0x80..=0x9F => CP1252_HIGH[(b - 0x80) as usize], + _ => b as u32, + }; + s.push(char::from_u32(c).unwrap_or('\u{FFFD}')); + } + expand_unicode_escapes(&s) +} + +/// Decode Windows-1252 bytes one character per byte, keeping NULs and +/// leaving `\U+XXXX` escapes as they are. Every byte maps to a distinct +/// character, so the bytes can be recovered exactly. +pub fn decode_cp1252_exact(bytes: &[u8]) -> String { + bytes + .iter() + .map(|&b| { + let c = match b { + 0x80..=0x9F => CP1252_HIGH[(b - 0x80) as usize], + _ => b as u32, + }; + char::from_u32(c).unwrap_or('\u{FFFD}') + }) + .collect() +} + +/// Replace `\U+XXXX` (four hex digits) with the character it names. +pub fn expand_unicode_escapes(s: &str) -> String { + if !s.contains("\\U+") && !s.contains("\\u+") { + return s.to_string(); + } + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while i < chars.len() { + if chars[i] == '\\' && i + 7 <= chars.len() && (chars[i + 1] == 'U' || chars[i + 1] == 'u') && chars[i + 2] == '+' { + let hex: String = chars[i + 3..i + 7].iter().collect(); + if let Ok(v) = u32::from_str_radix(&hex, 16) + && let Some(c) = char::from_u32(v) + { + out.push(c); + i += 7; + continue; + } + } + out.push(chars[i]); + i += 1; + } + out +} + +/// Expand the `%%` control codes used in single-line TEXT: %%c (diameter), +/// %%d (degree), %%p (plus/minus), %%% (percent), %%nnn (character code). +/// Underline/overline toggles (%%u, %%o) are dropped. +pub fn expand_percent_codes(s: &str) -> String { + if !s.contains("%%") { + return s.to_string(); + } + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while i < chars.len() { + if chars[i] == '%' + && chars.get(i + 1) == Some(&'%') + && let Some(&c) = chars.get(i + 2) + { + match c.to_ascii_lowercase() { + 'c' => { + out.push('\u{2300}'); + i += 3; + continue; + } + 'd' => { + out.push('\u{00B0}'); + i += 3; + continue; + } + 'p' => { + out.push('\u{00B1}'); + i += 3; + continue; + } + '%' => { + out.push('%'); + i += 3; + continue; + } + 'u' | 'o' | 'k' => { + i += 3; + continue; + } + d if d.is_ascii_digit() => { + let mut j = i + 2; + let mut v: u32 = 0; + while j < chars.len() && j < i + 5 && chars[j].is_ascii_digit() { + v = v * 10 + chars[j].to_digit(10).unwrap_or(0); + j += 1; + } + if let Some(ch) = char::from_u32(v) { + out.push(ch); + } + i = j; + continue; + } + _ => {} + } + } + out.push(chars[i]); + i += 1; + } + out +} + +/// Reduce MTEXT contents to plain text: paragraphs become newlines and +/// formatting codes are removed. Stacked fractions render as "a/b". +pub fn strip_mtext(s: &str) -> String { + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + match c { + '{' | '}' => { + i += 1; + } + '\\' if i + 1 < chars.len() => { + let code = chars[i + 1]; + match code { + 'P' | 'X' => { + out.push('\n'); + i += 2; + } + 'N' => { + out.push('\n'); + i += 2; + } + '~' => { + out.push('\u{00A0}'); + i += 2; + } + '\\' | '{' | '}' => { + out.push(code); + i += 2; + } + 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => { + i += 2; + } + 'U' | 'u' if chars.get(i + 2) == Some(&'+') => { + // Leave for the unicode pass. + out.push('\\'); + i += 1; + } + 'S' => { + // \Snum^den; or \Snum/den; or \Snum#den; + let mut j = i + 2; + let mut frac = String::new(); + while j < chars.len() && chars[j] != ';' { + let ch = chars[j]; + frac.push(if ch == '^' || ch == '#' { '/' } else { ch }); + j += 1; + } + out.push_str(frac.trim()); + i = (j + 1).min(chars.len()); + } + 'A' | 'C' | 'c' | 'F' | 'f' | 'H' | 'Q' | 'T' | 'W' | 'p' => { + // Parameterised code terminated by ';'. + let mut j = i + 2; + while j < chars.len() && chars[j] != ';' { + j += 1; + } + i = (j + 1).min(chars.len()); + } + _ => { + i += 2; + } + } + } + _ => { + out.push(c); + i += 1; + } + } + } + expand_percent_codes(&expand_unicode_escapes(&out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ansi_and_escapes() { + assert_eq!(decode_ansi(b"R\x80 5\xB0", 30), "R€ 5°"); + assert_eq!(decode_ansi(b"A\\U+00D8B", 30), "AØB"); + assert_eq!(decode_ansi(b"abc\0junk", 30), "abc"); + } + + #[test] + fn percent_codes() { + assert_eq!(expand_percent_codes("%%c25 %%p0.1 45%%d 100%%%"), "⌀25 ±0.1 45° 100%"); + assert_eq!(expand_percent_codes("%%uUNDER%%u"), "UNDER"); + } + + #[test] + fn mtext() { + assert_eq!(strip_mtext("{\\fArial|b1|i0;Plate}\\PQTY 2"), "Plate\nQTY 2"); + assert_eq!(strip_mtext("\\H2.5x;\\S1/2;\" hole"), "1/2\" hole"); + assert_eq!(strip_mtext("a\\\\b\\{c\\}"), "a\\b{c}"); + } +} diff --git a/crates/dwg/src/records/version.rs b/crates/dwg/src/records/version.rs new file mode 100644 index 00000000..e9c8a8ab --- /dev/null +++ b/crates/dwg/src/records/version.rs @@ -0,0 +1,130 @@ +//! DWG version codes. +//! +//! Spec: ODA Open Design Specification for .dwg files v5.4.1, §3.2.1 +//! "VERSION ID" (verified against the spec text). + +use std::fmt; + +/// The DWG format generations. Ordering follows release order, so +/// `v >= DwgVersion::R2000` reads as "R2000 or later". +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DwgVersion { + /// AC1012 — AutoCAD Release 13 + R13, + /// AC1014 — AutoCAD Release 14 + R14, + /// AC1015 — AutoCAD 2000/2000i/2002 (the spec also calls this R15) + R2000, + /// AC1018 — AutoCAD 2004/2005/2006 + R2004, + /// AC1021 — AutoCAD 2007/2008/2009 + R2007, + /// AC1024 — AutoCAD 2010/2011/2012 + R2010, + /// AC1027 — AutoCAD 2013 through 2017 + R2013, + /// AC1032 — AutoCAD 2018 and later (still current in 2027) + R2018, +} + +impl DwgVersion { + /// Parse the six-byte ASCII version tag at the start of the file. + pub fn from_magic(magic: &[u8]) -> Option { + let tag = magic.get(..6)?; + Some(match tag { + b"AC1012" => DwgVersion::R13, + b"AC1014" => DwgVersion::R14, + b"AC1015" => DwgVersion::R2000, + b"AC1018" => DwgVersion::R2004, + b"AC1021" => DwgVersion::R2007, + b"AC1024" => DwgVersion::R2010, + b"AC1027" => DwgVersion::R2013, + b"AC1032" => DwgVersion::R2018, + _ => return None, + }) + } + + /// Parse a version tag stored on its own (as the native format stores + /// it): exactly the six characters, nothing after them. + pub fn from_tag(tag: &str) -> Option { + if tag.len() == 6 { DwgVersion::from_magic(tag.as_bytes()) } else { None } + } + + pub fn magic(self) -> &'static str { + match self { + DwgVersion::R13 => "AC1012", + DwgVersion::R14 => "AC1014", + DwgVersion::R2000 => "AC1015", + DwgVersion::R2004 => "AC1018", + DwgVersion::R2007 => "AC1021", + DwgVersion::R2010 => "AC1024", + DwgVersion::R2013 => "AC1027", + DwgVersion::R2018 => "AC1032", + } + } + + /// Human-readable release range. + pub fn releases(self) -> &'static str { + match self { + DwgVersion::R13 => "AutoCAD R13", + DwgVersion::R14 => "AutoCAD R14", + DwgVersion::R2000 => "AutoCAD 2000–2002", + DwgVersion::R2004 => "AutoCAD 2004–2006", + DwgVersion::R2007 => "AutoCAD 2007–2009", + DwgVersion::R2010 => "AutoCAD 2010–2012", + DwgVersion::R2013 => "AutoCAD 2013–2017", + DwgVersion::R2018 => "AutoCAD 2018 and later", + } + } + + /// R13–R15 use the flat "section locator" container; R2004 and later + /// use the paged, compressed container (R2007 has its own variant). + pub fn uses_paged_container(self) -> bool { + self >= DwgVersion::R2004 + } + + /// From R2007 on, object strings live in a separate string stream and + /// are UTF-16. + pub fn has_string_stream(self) -> bool { + self >= DwgVersion::R2007 + } +} + +impl fmt::Display for DwgVersion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} ({})", self.magic(), self.releases()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn magic_round_trip() { + for v in [ + DwgVersion::R13, + DwgVersion::R14, + DwgVersion::R2000, + DwgVersion::R2004, + DwgVersion::R2007, + DwgVersion::R2010, + DwgVersion::R2013, + DwgVersion::R2018, + ] { + assert_eq!(DwgVersion::from_magic(v.magic().as_bytes()), Some(v)); + } + assert_eq!(DwgVersion::from_magic(b"AC1009"), None); + assert_eq!(DwgVersion::from_magic(b"AC10"), None); + assert_eq!(DwgVersion::from_tag("AC1018"), Some(DwgVersion::R2004)); + assert_eq!(DwgVersion::from_tag("AC1018-not-a-version"), None); + } + + #[test] + fn ordering() { + assert!(DwgVersion::R2018 > DwgVersion::R2004); + assert!(DwgVersion::R2000 < DwgVersion::R2004); + assert!(DwgVersion::R2004.uses_paged_container()); + assert!(!DwgVersion::R2000.uses_paged_container()); + } +} diff --git a/crates/dwg/src/write/check.rs b/crates/dwg/src/write/check.rs new file mode 100644 index 00000000..000e6f3d --- /dev/null +++ b/crates/dwg/src/write/check.rs @@ -0,0 +1,125 @@ +//! 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/container.rs b/crates/dwg/src/write/container.rs new file mode 100644 index 00000000..5c74edb5 --- /dev/null +++ b/crates/dwg/src/write/container.rs @@ -0,0 +1,264 @@ +//! The R2004-family paged container (spec chapter 4), as AutoCAD 2027 +//! lays out an AC1032 file: the file header with its encrypted block, the +//! data pages of each section in stream order, the section map, the page +//! map, and the encrypted block again at the end. +//! +//! The choices the spec leaves open follow AutoCAD's own files of the +//! MI-201 corpus (2004, 2010, 2013 and 2018 alike): data pages are +//! numbered from 1 in stream order and the section map and page map take +//! the numbers 3 and 4 past the last data page; each system page is +//! followed by a copy of its header with the sizes and checksum zeroed; +//! the gaps that keep pages on 0x20 boundaries are filled from the magic +//! number sequence; the second copy of the encrypted header follows the +//! page map directly. + +use crate::crc::{crc32, page_checksum}; +use crate::lz77; +use crate::read::error::{Error, Result}; +use crate::read::r2004::magic_sequence; + +const FILE_ID: &[u8; 12] = b"AcFssFcAJMB\0"; +const PAGE_MAP_TYPE: u32 = 0x4163_0E3B; +const SECTION_MAP_TYPE: u32 = 0x4163_003B; +const DATA_PAGE_TYPE: u32 = 0x4163_043B; +const PAGE_MASK: u32 = 0x4164_536B; +/// The page size of compressed sections. +pub(crate) const MAX_PAGE: usize = 0x7400; + +/// One section to store. +pub(crate) struct Section { + pub name: &'static str, + pub data: Vec, + pub compressed: bool, + /// Bytes per page before compression; pages are padded to it. + pub page_size: usize, +} + +/// What the file header records beside the maps. +pub(crate) struct FileInfo { + pub version: [u8; 6], + /// Byte 0x0B. + pub maintenance: u8, + /// Bytes 0x11 and 0x12: the application version and its maintenance + /// release. + pub app_version: u8, + pub app_maintenance: u8, + pub codepage: u16, + /// Bytes 0x3C and 0x40 (R2018). + pub acad_maintenance: u32, +} + +fn round_up(n: usize, to: usize) -> usize { + n.div_ceil(to) * to +} + +fn put_u32(v: &mut [u8], at: usize, x: u32) { + v[at..at + 4].copy_from_slice(&x.to_le_bytes()); +} +fn put_u64(v: &mut [u8], at: usize, x: u64) { + v[at..at + 8].copy_from_slice(&x.to_le_bytes()); +} + +/// Fill to `to` bytes with the magic number sequence (§4.3). +fn pad_to(out: &mut Vec, to: usize) { + let n = to.saturating_sub(out.len()); + out.extend_from_slice(&magic_sequence(n)); +} + +/// A system page: header, compressed data, the header again with sizes +/// and checksum zeroed (§4.3). +fn system_page(kind: u32, data: &[u8], compress: Compress) -> Vec { + let comp = compress(data).unwrap_or_else(|| data.to_vec()); + let mut hdr = [0u8; 20]; + put_u32(&mut hdr, 0, kind); + put_u32(&mut hdr, 4, data.len() as u32); + put_u32(&mut hdr, 8, comp.len() as u32); + put_u32(&mut hdr, 12, 2); + let sum = page_checksum(page_checksum(0, &hdr), &comp); + put_u32(&mut hdr, 16, sum); + let mut out = hdr.to_vec(); + out.extend_from_slice(&comp); + let mut tail = [0u8; 20]; + put_u32(&mut tail, 0, kind); + put_u32(&mut tail, 12, 2); + out.extend_from_slice(&tail); + out +} + +/// The size AutoCAD records for the page map's page: room beyond what it +/// holds, by the number of pages (fitted to AutoCAD's files with 15, 17 +/// and 18 pages: 0x5C0, 0x5E0, 0x600). The page map is the last page, so +/// the size places nothing. +fn page_map_extent(pages: usize) -> usize { + round_up(0x4D0 + 16 * pages, 0x20) +} + +struct PageRec { + number: u32, + address: usize, + extent: usize, +} + +/// Pack the sections, given in stream order. The section map lists them +/// with descending ids in the order given by `map_order` (names), which +/// must name every section once. +pub(crate) fn pack(info: &FileInfo, sections: &[Section], map_order: &[&str]) -> Result> { + pack_with(info, sections, map_order, lz77::compress) +} + +/// The page compressor (§4.7). +pub(crate) type Compress = fn(&[u8]) -> Option>; + +/// [`pack`] with a chosen compressor. +pub(crate) fn pack_with(info: &FileInfo, sections: &[Section], map_order: &[&str], compress: Compress) -> Result> { + let mut out = vec![0u8; 0x100]; + let mut pages: Vec = Vec::new(); + // Section id by name: the empty section is 0, then descending in map + // order. + let n = map_order.len() as u32; + let id_of = |name: &str| -> Result { + let i = map_order.iter().position(|m| *m == name).ok_or_else(|| Error::format(format!("section {name} is not in the section map")))?; + Ok(n - i as u32) + }; + // (name, page number, data size, start) for the section map. + let mut page_refs: Vec<(&str, u32, u32, u64)> = Vec::new(); + let mut first_page_address: Vec<(&str, usize)> = Vec::new(); + for s in sections { + let id = id_of(s.name)?; + let chunks: Vec<&[u8]> = if s.data.is_empty() { Vec::new() } else { s.data.chunks(s.page_size).collect() }; + for (i, chunk) in chunks.iter().enumerate() { + let mut page = chunk.to_vec(); + page.resize(s.page_size, 0); + let stored = if s.compressed { compress(&page).unwrap_or(page) } else { page }; + let address = out.len(); + if i == 0 { + first_page_address.push((s.name, address)); + } + let extent = round_up(32 + stored.len(), 0x20); + let number = pages.len() as u32 + 1; + let start = (i * s.page_size) as u64; + let data_sum = page_checksum(0, &stored); + let mut hdr = [0u8; 32]; + put_u32(&mut hdr, 0, DATA_PAGE_TYPE); + put_u32(&mut hdr, 4, id); + put_u32(&mut hdr, 8, stored.len() as u32); + put_u32(&mut hdr, 12, extent as u32); + put_u64(&mut hdr, 16, start); + put_u32(&mut hdr, 28, data_sum); + let header_sum = page_checksum(data_sum, &hdr); + put_u32(&mut hdr, 24, header_sum); + let m = PAGE_MASK ^ address as u32; + for w in hdr.as_chunks_mut::<4>().0 { + *w = (u32::from_le_bytes(*w) ^ m).to_le_bytes(); + } + out.extend_from_slice(&hdr); + out.extend_from_slice(&stored); + pad_to(&mut out, address + extent); + pages.push(PageRec { number, address, extent }); + page_refs.push((s.name, number, stored.len() as u32, start)); + } + } + let last_data = pages.len() as u32; + + // Section map (§4.5). + let mut sm = Vec::new(); + for v in [n + 1, 2, MAX_PAGE as u32, 0, n + 1] { + sm.extend_from_slice(&v.to_le_bytes()); + } + let mut describe = |name: &str, size: u64, page_size: u32, compressed: bool, id: u32| { + let refs: Vec<_> = page_refs.iter().filter(|r| r.0 == name && !name.is_empty()).collect(); + sm.extend_from_slice(&size.to_le_bytes()); + sm.extend_from_slice(&(refs.len() as u32).to_le_bytes()); + sm.extend_from_slice(&page_size.to_le_bytes()); + sm.extend_from_slice(&1u32.to_le_bytes()); + sm.extend_from_slice(&(if compressed { 2u32 } else { 1 }).to_le_bytes()); + sm.extend_from_slice(&id.to_le_bytes()); + sm.extend_from_slice(&0u32.to_le_bytes()); + let mut nm = [0u8; 64]; + nm[..name.len()].copy_from_slice(name.as_bytes()); + sm.extend_from_slice(&nm); + for r in refs { + sm.extend_from_slice(&r.1.to_le_bytes()); + sm.extend_from_slice(&r.2.to_le_bytes()); + sm.extend_from_slice(&r.3.to_le_bytes()); + } + }; + describe("", 0, MAX_PAGE as u32, true, 0); + for name in map_order { + let s = sections.iter().find(|s| s.name == *name).ok_or_else(|| Error::format(format!("section map names {name}, which is not written")))?; + let id = id_of(s.name)?; + describe(s.name, s.data.len() as u64, s.page_size as u32, s.compressed, id); + } + let section_map_id = last_data + 3; + let sm_address = out.len(); + let sm_page = system_page(SECTION_MAP_TYPE, &sm, compress); + let sm_extent = round_up(sm_page.len(), 0x20); + out.extend_from_slice(&sm_page); + pad_to(&mut out, sm_address + sm_extent); + pages.push(PageRec { number: section_map_id, address: sm_address, extent: sm_extent }); + + // Page map (§4.4), itself the last page. + let page_map_id = last_data + 4; + let pm_address = out.len(); + let pm_extent = page_map_extent(pages.len() + 1); + pages.push(PageRec { number: page_map_id, address: pm_address, extent: pm_extent }); + let mut pm = Vec::new(); + for p in &pages { + pm.extend_from_slice(&p.number.to_le_bytes()); + pm.extend_from_slice(&(p.extent as u32).to_le_bytes()); + } + debug_assert!(pages.windows(2).all(|w| w[0].address + w[0].extent == w[1].address)); + out.extend_from_slice(&system_page(PAGE_MAP_TYPE, &pm, compress)); + let second_header = out.len(); + + // The encrypted header block (§4.1). + let mut e = [0u8; 0x6C]; + e[..12].copy_from_slice(FILE_ID); + put_u32(&mut e, 0x10, 0x6C); + put_u32(&mut e, 0x14, 4); + put_u32(&mut e, 0x24, 1); + put_u32(&mut e, 0x28, page_map_id); + put_u64(&mut e, 0x2C, (pm_address + pm_extent - 0x100) as u64); + put_u64(&mut e, 0x34, second_header as u64); + put_u32(&mut e, 0x40, pages.len() as u32); + put_u32(&mut e, 0x44, 0x20); + put_u32(&mut e, 0x48, 0x80); + put_u32(&mut e, 0x4C, 0x40); + put_u32(&mut e, 0x50, page_map_id); + put_u64(&mut e, 0x54, (pm_address - 0x100) as u64); + put_u32(&mut e, 0x5C, section_map_id); + put_u32(&mut e, 0x60, page_map_id); + let crc = crc32(0, &e); + put_u32(&mut e, 0x68, crc); + let mask = magic_sequence(0x100); + let encrypted: Vec = e.iter().zip(&mask).map(|(a, b)| a ^ b).collect(); + out.extend_from_slice(&encrypted); + + // The plain file header. + let at = |name: &str| -> u32 { first_page_address.iter().find(|(n, _)| *n == name).map(|(_, a)| *a as u32 + 0x20).unwrap_or(0) }; + let h = &mut out[..0x100]; + h[..6].copy_from_slice(&info.version); + h[0x0B] = info.maintenance; + h[0x0C] = 3; + put_u32(h, 0x0D, at("AcDb:Preview")); + h[0x11] = info.app_version; + h[0x12] = info.app_maintenance; + h[0x13..0x15].copy_from_slice(&info.codepage.to_le_bytes()); + put_u32(h, 0x20, at("AcDb:SummaryInfo")); + put_u32(h, 0x28, 0x80); + put_u32(h, 0x2C, at("AcDb:AppInfo")); + put_u32(h, 0x30, at("AcDb:AppInfoHistory")); + put_u32(h, 0x34, 0x202); + put_u32(h, 0x38, 0x1DD); + put_u32(h, 0x3C, info.acad_maintenance); + put_u32(h, 0x40, info.acad_maintenance); + h[0x80..0xEC].copy_from_slice(&encrypted); + h[0xEC..0x100].copy_from_slice(&mask[0xEC..0x100]); + Ok(out) +} + +/// Where the first page of each section will start, for sections whose +/// content records file addresses (the preview). Mirrors `pack`. +pub(crate) fn uncompressed_page_extent(page_size: usize) -> usize { + round_up(32 + page_size, 0x20) +} diff --git a/crates/dwg/src/write/mod.rs b/crates/dwg/src/write/mod.rs new file mode 100644 index 00000000..9a15f5a2 --- /dev/null +++ b/crates/dwg/src/write/mod.rs @@ -0,0 +1,385 @@ +//! 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 new file mode 100644 index 00000000..6f37f28a --- /dev/null +++ b/crates/dwg/src/write/objects.rs @@ -0,0 +1,1838 @@ +//! 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() } + } + + /// 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 { + let bytes: Vec = s.chars().map(|c| c as u32 as u8).collect(); + b.push(bytes.len().min(255) as u8); + b.push(30); + b.extend_from_slice(&bytes[..bytes.len().min(255)]); + } + } + 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 new file mode 100644 index 00000000..b602a207 --- /dev/null +++ b/crates/dwg/src/write/sections.rs @@ -0,0 +1,608 @@ +//! 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). +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`. +fn iso_datetime(v: f64) -> String { + let (day, ms) = julian(v); + // Days since 0000-03-01, then the civil calendar. + let z = day as i64 - 1_721_120; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + let s = ms / 1000; + format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60) +} + +fn xml_text(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">") +} + +/// 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/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index dcf0fef7..592d610a 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -255,7 +255,7 @@ fn mif_escape_at(chars: &[char], i: usize) -> Option { /// page (four hex digits, one UTF-16 code unit; characters above U+FFFF are a surrogate pair of /// escapes), and the `\M+nXXXX` sequences for double-byte East Asian characters. Malformed /// escapes, unpaired surrogates and unknown `\M+` code pages are kept as literal text. -fn unescape_unicode(s: &str) -> String { +pub fn unescape_unicode(s: &str) -> String { if !s.contains("\\U+") && !s.contains("\\M+") { return s.to_string(); } diff --git a/crates/io/examples/dwg_bench.rs b/crates/io/examples/dwg_bench.rs new file mode 100644 index 00000000..1dba2ec9 --- /dev/null +++ b/crates/io/examples/dwg_bench.rs @@ -0,0 +1,79 @@ +//! Open-speed benchmark for the two DWG readers (`docs/dwg.md`). +//! +//! Builds a drawing of lines, arcs, circles and text (200,000 entities by default), saves it as +//! a 2018 DWG, then opens it with acadrust and with DraftCraft's own reader and says how long +//! each took and whether every entity the native reader maps came out the same. +//! +//! ```text +//! cargo run --release -p draftcraft-io --example dwg_bench -- [entities] [--keep out.dwg] +//! ``` + +use std::collections::HashMap; +use std::time::Instant; + +use draftcraft_doc::{Arc, Circle, Common, Drawing, EntityKind, HAlign, Line, Space, Text, VAlign}; +use draftcraft_geom::Vec3; +use draftcraft_io::{DwgReader, read_dwg_with}; + +fn drawing(n: usize) -> Drawing { + let mut d = Drawing::new_imperial(); + d.header.set_str("ACADVER", "AC1032"); + let side = ((n / 4) as f64).sqrt().ceil().max(1.0) as usize; + for i in 0..n { + let cell = i / 4; + let (x, y) = ((cell % side) as f64 * 40.0, (cell / side) as f64 * 40.0); + let kind = match i % 4 { + 0 => EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 30.0, y + 10.0, 0.0) }), + 1 => EntityKind::Arc(Arc { center: Vec3::new(x + 10.0, y + 20.0, 0.0), radius: 6.0, start: 0.3, end: 2.8 }), + 2 => EntityKind::Circle(Circle { center: Vec3::new(x + 25.0, y + 25.0, 0.0), radius: 4.0 }), + _ => EntityKind::Text(Text { + insert: Vec3::new(x, y + 32.0, 0.0), + align_pt: None, + height: 2.5, + value: format!("PART {cell}"), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + }), + }; + let _ = d.add(&Space::Model, Common::default(), kind); + } + d +} + +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1e3 +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().skip(1).collect(); + let n = args.first().and_then(|a| a.parse().ok()).unwrap_or(200_000); + let keep = args.iter().position(|a| a == "--keep").and_then(|i| args.get(i + 1)); + + let t = Instant::now(); + let d = drawing(n); + eprintln!("built {} entities in {:.0} ms", d.entity_count(), ms(t)); + let t = Instant::now(); + let dwg = draftcraft_io::write(&d, "bench.dwg")?; + eprintln!("saved a {:.1} MB DWG 2018 in {:.0} ms", dwg.len() as f64 / 1048576.0, ms(t)); + if let Some(path) = keep { + std::fs::write(path, &dwg)?; + } + + let t = Instant::now(); + let a = read_dwg_with(&dwg, DwgReader::Acadrust)?; + let ta = ms(t); + let t = Instant::now(); + let n2 = read_dwg_with(&dwg, DwgReader::Native)?; + let tn = ms(t); + + let native: HashMap = n2.model.iter().map(|e| (e.handle.0, e.clone())).collect(); + let same = a.model.iter().filter(|e| native.get(&e.handle.0).is_some_and(|x| x.kind == e.kind && x.common == e.common)).count(); + println!("open, acadrust: {ta:>7.0} ms"); + println!("open, native: {tn:>7.0} ms ({:.1}x)", ta / tn.max(1e-9)); + println!("identical entities: {same} of {}", a.model.len()); + Ok(()) +} diff --git a/crates/io/src/dwg_read.rs b/crates/io/src/dwg_read.rs new file mode 100644 index 00000000..c1256b7f --- /dev/null +++ b/crates/io/src/dwg_read.rs @@ -0,0 +1,619 @@ +//! DWG → Drawing, straight from the records `draftcraft-dwg`'s reader decodes: no DXF in between. +//! +//! The reader maps what it covers and counts the rest in [`Coverage`]: the entity types, entity +//! properties and objects it doesn't carry into the drawing yet. [`crate::read`] uses it only when +//! nothing was left out (or when asked to, for tests and measurements); otherwise the file goes +//! through acadrust as before, so opening a file never loses what that path keeps. +//! +//! Where a value means the same in DWG and DXF (an OCS point, a transparency word), the conversion +//! is the DXF reader's own (`dxf_read`), so each rule exists once. + +use std::collections::{BTreeMap, HashMap}; + +use draftcraft_color::{Color, Rgb}; +use draftcraft_doc::{ + Arc, Block, Circle, Common, DashElement, Drawing, Ellipse, Entity, EntityKind, Face3d, HAlign, Handle, Insert, Layer, Layout, Line, Linetype, + Lineweight, LwPolyline, MText, Point, RayLine, Solid, Text, TextStyle, VAlign, +}; +use draftcraft_dwg::records::geom; +use draftcraft_dwg::records::model::{self as rec, NonGraphic, Object, ObjectKind}; +use draftcraft_geom::{PolyVertex, Vec2, Vec3}; + +use crate::dxf_read::{ocs_n, style_font_of, transparency_440}; +use crate::{IoError, Result}; + +/// What the DWG reader left out of the drawing: one count per entity type, property or object +/// type (`"HATCH"`, `"INSERT with attributes"`, `"object VISUALSTYLE"`). Empty when the drawing +/// carries everything the file holds that DraftCraft keeps. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Coverage { + pub left_out: BTreeMap, +} + +impl Coverage { + /// True when nothing was left out. + pub fn is_whole(&self) -> bool { + self.left_out.is_empty() + } + fn miss(&mut self, what: impl Into) { + *self.left_out.entry(what.into()).or_default() += 1; + } + /// One line for messages: `HATCH × 3, INSERT with attributes × 1`. + pub fn summary(&self) -> String { + self.left_out.iter().map(|(k, n)| format!("{k} × {n}")).collect::>().join(", ") + } +} + +/// Objects that carry no drawing content of their own, or whose content DraftCraft writes again +/// from its own model on save, so leaving them out loses nothing: table controls, the records +/// read through their tables, block begin/end markers and the dictionaries that index them. +fn structural(o: &Object) -> bool { + matches!( + o.kind, + ObjectKind::Control(_) + | ObjectKind::BlockBegin { .. } + | ObjectKind::BlockEnd + | ObjectKind::SeqEnd + | ObjectKind::BlockHeader(_) + | ObjectKind::Layer(_) + | ObjectKind::Linetype(_) + | ObjectKind::TextStyle(_) + | ObjectKind::NonGraphic(NonGraphic::Layout(_)) + ) +} + +/// Names by handle, for resolving the references entities make. +#[derive(Default)] +struct Names { + layers: HashMap, + linetypes: HashMap, + styles: HashMap, + blocks: HashMap, +} + +/// Read a DWG file into a drawing, with what the reader left out. +pub fn read(bytes: &[u8]) -> Result<(Drawing, Coverage)> { + let dwg = draftcraft_dwg::read_bytes(bytes).map_err(|e| IoError::Format(format!("DWG: {e}")))?; + let mut cov = Coverage::default(); + let mut d = Drawing::new_imperial(); + d.layouts.clear(); + d.header.set_i64("INSUNITS", 0); + d.header.set_str("ACADVER", dwg.version.magic()); + header(&dwg.header, &mut d); + let names = tables(&dwg, &mut d); + let layouts = layouts(&dwg, &mut d); + for o in dwg.objects.values() { + if o.entity.is_none() && !structural(o) { + cov.miss(format!("object {}", o.type_name)); + } + if matches!(o.kind, ObjectKind::Failed(_) | ObjectKind::Unsupported) && o.entity.is_some() { + cov.miss(format!("undecoded {}", o.type_name)); + } + } + let first_layout = d.layouts.iter().min_by_key(|l| l.tab_order).map(|l| l.name.clone()); + for o in block_records(&dwg) { + let ObjectKind::BlockHeader(bh) = &o.kind else { continue }; + let name = names.blocks.get(&o.handle.0).cloned().unwrap_or_else(|| bh.name.clone()); + let owned = dwg.block_entities(o.handle); + let ents: Vec = owned.into_iter().filter(|e| !marker(e)).filter_map(|e| entity(e, &names, &mut cov)).collect(); + let up = name.to_ascii_uppercase(); + if up == "*MODEL_SPACE" { + for e in ents { + d.ensure_layer(&e.common.layer); + d.model.push(e); + } + } else if up.starts_with("*PAPER_SPACE") { + let lname = layouts.get(&o.handle.0).cloned().or_else(|| first_layout.clone()); + if let Some(l) = lname.and_then(|n| d.layouts.iter_mut().find(|l| l.name == n)) { + for e in ents { + l.entities.push(e); + } + } + } else { + if bh.is_xref { + cov.miss("external reference"); + continue; + } + let mut b = Block::new(&name); + b.base = v3(bh.base_point); + b.description.clone_from(&bh.description); + b.anonymous = bh.anonymous; + b.explodable = !bh.not_explodable; + b.units = u8::try_from(bh.insert_units).unwrap_or(0); + for e in ents { + b.entities.push(e); + } + d.blocks.insert(name, std::sync::Arc::new(b)); + } + } + if d.layouts.is_empty() { + d.layouts.push(Layout::new("Layout1", 1)); + } + if d.layer("0").is_none() { + d.layers.insert(0, Layer::default()); + } + if let Some(seed) = dwg.objects.keys().map(|h| h.0).max() { + d.bump_handseed(Handle(seed)); + } + Ok((d, cov)) +} + +/// BLOCK and ENDBLK, which open and close a block's entities: the block itself carries them. +fn marker(o: &Object) -> bool { + matches!(o.kind, ObjectKind::BlockBegin { .. } | ObjectKind::BlockEnd | ObjectKind::SeqEnd) +} + +/// The block records in table order: model space, paper space, then the block table's entries, +/// then any the table doesn't list (in handle order). +fn block_records(dwg: &rec::Drawing) -> Vec<&Object> { + let control = dwg.objects.values().find_map(|o| match &o.kind { + ObjectKind::Control(c) if o.type_code == 0x30 => Some(c), + _ => None, + }); + let mut order: Vec = vec![dwg.model_space(), dwg.paper_space()]; + order.extend(control.map(|c| c.entries.clone()).unwrap_or_default()); + let mut seen = std::collections::HashSet::new(); + let mut out: Vec<&Object> = order + .into_iter() + .filter(|h| seen.insert(*h)) + .filter_map(|h| dwg.objects.get(&h)) + .filter(|o| matches!(o.kind, ObjectKind::BlockHeader(_))) + .collect(); + out.extend(dwg.objects.values().filter(|o| matches!(o.kind, ObjectKind::BlockHeader(_)) && !seen.contains(&o.handle))); + out +} + +/// Block names by record handle. DWG stores anonymous blocks unnumbered (`*D`, `*U`); each gets +/// a number per prefix in table order, as AutoCAD numbers them when it writes a DXF (`*D0`, `*D1`), +/// skipping names the drawing already uses. +fn block_names(dwg: &rec::Drawing) -> HashMap { + let records = block_records(dwg); + let mut taken: std::collections::HashSet = + records.iter().filter_map(|o| if let ObjectKind::BlockHeader(b) = &o.kind { Some(b.name.to_ascii_uppercase()) } else { None }).collect(); + let mut next: HashMap = HashMap::new(); + let mut names = HashMap::new(); + for o in records { + let ObjectKind::BlockHeader(b) = &o.kind else { continue }; + let bare = b.name.len() >= 2 + && b.name.starts_with('*') + && b.name.chars().skip(1).all(|c| c.is_ascii_alphabetic()) + && !b.name.eq_ignore_ascii_case("*Model_Space") + && !b.name.eq_ignore_ascii_case("*Paper_Space"); + let name = if bare { + let n = next.entry(b.name.to_ascii_uppercase()).or_insert(0); + loop { + let cand = format!("{}{}", b.name, n); + *n += 1; + if taken.insert(cand.to_ascii_uppercase()) { + break cand; + } + } + } else { + b.name.clone() + }; + names.insert(o.handle.0, name); + } + names +} + +fn v3(p: geom::Vec3) -> Vec3 { + Vec3::new(p.x, p.y, p.z) +} + +/// The header variables the reader decodes, under their DXF names. +fn header(h: &rec::HeaderVars, d: &mut Drawing) { + let ints = [ + ("INSUNITS", h.insunits), + ("MEASUREMENT", h.measurement), + ("LUNITS", h.lunits), + ("LUPREC", h.luprec), + ("AUNITS", h.aunits), + ("AUPREC", h.auprec), + ("ANGDIR", h.angdir), + ]; + for (name, v) in ints { + if let Some(v) = v { + d.header.set_i64(name, i64::from(v)); + } + } + let reals = [("LTSCALE", h.ltscale), ("TEXTSIZE", h.textsize), ("CELTSCALE", h.celtscale), ("ANGBASE", h.angbase)]; + for (name, v) in reals { + if let Some(v) = v.filter(|v| v.is_finite()) { + d.header.set_f64(name, v); + } + } + for (name, p) in [("EXTMIN", h.extmin), ("EXTMAX", h.extmax), ("INSBASE", h.insbase)] { + if let Some(p) = p { + d.header.set(name, draftcraft_doc::HVal::Point(v3(p))); + } + } + for (name, p) in [("LIMMIN", h.limmin), ("LIMMAX", h.limmax)] { + if let Some(p) = p { + d.header.set(name, draftcraft_doc::HVal::Point(Vec3::new(p.x, p.y, 0.0))); + } + } +} + +fn color(c: rec::Color) -> Color { + match c { + rec::Color::ByLayer | rec::Color::None => Color::ByLayer, + rec::Color::ByBlock => Color::ByBlock, + rec::Color::Index(i) => Color::from_aci(i16::from(i)), + rec::Color::Rgb(r, g, b) => Color::True(Rgb::from_u32(u32::from(r) << 16 | u32::from(g) << 8 | u32::from(b))), + } +} + +fn lineweight(code: u8) -> Lineweight { + Lineweight::from_dxf(rec::Lineweight::from_code(code).dxf()) +} + +/// Layers, linetypes and text styles, replacing the new drawing's defaults of the same name. +fn tables(dwg: &rec::Drawing, d: &mut Drawing) -> Names { + let mut n = Names { blocks: block_names(dwg), ..Names::default() }; + for o in dwg.objects.values() { + match &o.kind { + ObjectKind::Linetype(lt) => { + n.linetypes.insert(o.handle.0, lt.name.clone()); + let pattern = lt.elements.iter().map(|e| DashElement::dash(e.length)); + // As the DXF reader does: a name the drawing already has (ByLayer, ByBlock, + // Continuous) keeps DraftCraft's own record. + if !d.linetypes.iter().any(|x| x.name.eq_ignore_ascii_case(<.name)) { + d.linetypes.push(Linetype { name: lt.name.clone(), description: lt.description.clone(), pattern: pattern.collect() }); + } + } + ObjectKind::TextStyle(s) if !s.name.is_empty() => { + n.styles.insert(o.handle.0, s.name.clone()); + let st = TextStyle { + name: s.name.clone(), + font: style_font_of(s.font_file.clone(), first_str(&o.xdata, "ACAD"), own_font(&o.xdata)), + big_font: s.bigfont_file.clone(), + height: s.height, + width_factor: s.width_factor, + oblique: s.oblique, + backwards: s.generation & 2 != 0, + upside_down: s.generation & 4 != 0, + vertical: s.flags & 4 != 0, + annotative: annotative(&o.xdata), + }; + replace(&mut d.text_styles, st, |x| &x.name); + } + _ => {} + } + } + for o in dwg.objects.values() { + if let ObjectKind::Layer(l) = &o.kind { + n.layers.insert(o.handle.0, l.name.clone()); + let layer = Layer { + name: l.name.clone(), + color: color(l.color), + linetype: n.linetypes.get(&l.linetype.0).cloned().unwrap_or_else(|| "Continuous".into()), + lineweight: lineweight(l.lineweight), + on: !l.off, + frozen: l.frozen, + locked: l.locked, + plot: l.plot, + ..Layer::new(&l.name) + }; + replace(&mut d.layers, layer, |x| &x.name); + } + } + n +} + +/// The first string of application `app`'s extended data. +fn first_str(x: &[rec::XData], app: &str) -> Option { + let a = x.iter().find(|a| a.app_name().is_some_and(|n| n.eq_ignore_ascii_case(app)))?; + a.items.iter().find_map(|v| if let rec::XValue::Str(s) = v { Some(s.trim().to_string()) } else { None }) +} + +/// The font name in DraftCraft's own extended data (`FONT`, name). +fn own_font(x: &[rec::XData]) -> Option { + let a = x.iter().find(|a| a.app_name().is_some_and(|n| n.eq_ignore_ascii_case(crate::dxf_ext::APP)))?; + a.items.windows(2).find_map(|w| match w { + [rec::XValue::Str(m), rec::XValue::Str(n)] if m == "FONT" => Some(n.clone()), + _ => None, + }) +} + +/// A style's annotative flag, from `AcadAnnotative` extended data as the DXF reader reads it: the +/// second integer of its `AnnotativeData` list. +fn annotative(x: &[rec::XData]) -> bool { + let Some(a) = x.iter().find(|a| a.app_name().is_some_and(|n| n.eq_ignore_ascii_case("AcadAnnotative"))) else { return false }; + let start = a.items.iter().position(|v| matches!(v, rec::XValue::Str(s) if s == "AnnotativeData")); + let ints = a.items.iter().skip(start.map_or(a.items.len(), |i| i + 1)).filter_map(|v| match v { + rec::XValue::Int16(i) => Some(i64::from(*i)), + _ => None, + }); + ints.into_iter().nth(1).is_some_and(|i| i != 0) +} + +/// Put `item` in place of the entry with the same name (case-insensitive), or at the end. +fn replace(list: &mut Vec, item: T, name: impl Fn(&T) -> &String) { + let key = name(&item).to_ascii_uppercase(); + match list.iter_mut().find(|x| name(x).to_ascii_uppercase() == key) { + Some(slot) => *slot = item, + None => list.push(item), + } +} + +/// The drawing's paper-space layouts, in tab order: paper-space block record → layout name. +fn layouts(dwg: &rec::Drawing, d: &mut Drawing) -> HashMap { + let mut found: Vec<&rec::Layout> = dwg + .objects + .values() + .filter_map(|o| if let ObjectKind::NonGraphic(NonGraphic::Layout(l)) = &o.kind { Some(l.as_ref()) } else { None }) + .filter(|l| !l.name.eq_ignore_ascii_case("Model")) + .collect(); + found.sort_by_key(|l| l.tab_order); + let mut by_block = HashMap::new(); + for l in found { + d.layouts.push(Layout::new(&l.name, l.tab_order)); + by_block.insert(l.block.0, l.name.clone()); + } + by_block +} + +/// The properties every entity has. +fn common(c: &rec::EntityCommon, extrusion: Option, thickness: f64, names: &Names, cov: &mut Coverage) -> Common { + let linetype = match c.linetype { + rec::LinetypeRef::ByLayer => "ByLayer".to_string(), + rec::LinetypeRef::ByBlock => "ByBlock".to_string(), + rec::LinetypeRef::Continuous => "Continuous".to_string(), + rec::LinetypeRef::Handle(h) => names.linetypes.get(&h.0).cloned().unwrap_or_else(|| "ByLayer".into()), + }; + if !c.plotstyle.is_null() { + cov.miss("entity plot style"); + } + if !c.material.is_null() { + cov.miss("entity material"); + } + Common { + layer: names.layers.get(&c.layer.0).cloned().unwrap_or_else(|| "0".into()), + color: color(c.color), + linetype, + lineweight: lineweight(c.lineweight), + ltscale: if c.linetype_scale > 0.0 { c.linetype_scale } else { 1.0 }, + transparency: c.transparency.map(|v| transparency_440(i64::from(v))).unwrap_or_default(), + visible: !c.invisible, + thickness, + extrusion: extrusion.map(v3).unwrap_or(Vec3::new(0.0, 0.0, 1.0)), + ..Common::default() + } +} + +/// One entity, or `None` (counted in `cov`) when the reader doesn't map it yet. +fn entity(o: &Object, names: &Names, cov: &mut Coverage) -> Option { + let ec = o.entity.as_ref()?; + if !o.xdictionary.is_null() { + cov.miss("entity extension dictionary"); + } + let (ext, thick) = extrusion_of(&o.kind); + let c = common(ec, ext, thick, names, cov); + let kind = match kind(o, &c, names) { + Some(k) => k, + None => { + cov.miss(o.type_name.clone()); + return None; + } + }; + let mut e = Entity::new(Handle(o.handle.0), kind); + e.common = c; + e.common.xdata = xdata(&o.xdata, names, cov); + Some(e) +} + +fn extrusion_of(k: &ObjectKind) -> (Option, f64) { + match k { + ObjectKind::Line(l) => (Some(l.extrusion), l.thickness), + ObjectKind::Circle(c) => (Some(c.extrusion), c.thickness), + ObjectKind::Arc(a) => (Some(a.extrusion), a.thickness), + ObjectKind::Point(p) => (Some(p.extrusion), p.thickness), + ObjectKind::Ellipse(e) => (Some(e.extrusion), 0.0), + ObjectKind::Text(t) => (Some(t.extrusion), t.thickness), + ObjectKind::MText(t) => (Some(t.extrusion), 0.0), + ObjectKind::Insert(i) => (Some(i.extrusion), 0.0), + ObjectKind::LwPolyline(p) => (Some(p.extrusion), p.thickness), + ObjectKind::Solid(s) => (Some(s.extrusion), s.thickness), + _ => (None, 0.0), + } +} + +/// Other applications' extended data as the DXF groups the drawing keeps (`Common::xdata`), with +/// the DXF reader's rules (`dxf_raw`): DraftCraft's own applications and the ones its reader turns +/// into properties are left to that (and counted here, as this reader doesn't yet), and an +/// application whose list braces don't balance is dropped. +fn xdata(x: &[rec::XData], names: &Names, cov: &mut Coverage) -> Vec { + use draftcraft_doc::RawTag; + use rec::XValue; + let real = |code: i32, v: f64| RawTag { code, value: draftcraft_dxf::Value::Real(v).as_str() }; + let mut out = Vec::new(); + for app in x { + let Some(name) = app.app_name() else { + cov.miss("extended data of an unknown application"); + continue; + }; + let up = name.to_ascii_uppercase(); + if crate::dxf_raw::OWN_APPS.contains(&up.as_str()) { + cov.miss(format!("{up} extended data")); + continue; + } + let mut groups = vec![RawTag { code: 1001, value: name.to_string() }]; + let mut depth = 0i32; + let mut ok = true; + for v in &app.items { + let pt = |base: i32, p: &geom::Vec3| [real(base, p.x), real(base + 10, p.y), real(base + 20, p.z)]; + match v { + XValue::Str(t) => groups.push(RawTag { code: 1000, value: t.clone() }), + XValue::Open => { + depth += 1; + groups.push(RawTag { code: 1002, value: "{".into() }); + } + XValue::Close => { + depth -= 1; + ok &= depth >= 0; + groups.push(RawTag { code: 1002, value: "}".into() }); + } + XValue::Layer(h) => groups.push(RawTag { code: 1003, value: names.layers.get(&h.0).cloned().unwrap_or_else(|| "0".into()) }), + XValue::Bytes(b) => groups.push(RawTag { code: 1004, value: b.iter().map(|x| format!("{x:02X}")).collect() }), + XValue::Handle(h) => groups.push(RawTag { code: 1005, value: format!("{:X}", h.0) }), + XValue::Point(p) => groups.extend(pt(1010, p)), + XValue::Position(p) => groups.extend(pt(1011, p)), + XValue::Displacement(p) => groups.extend(pt(1012, p)), + XValue::Direction(p) => groups.extend(pt(1013, p)), + XValue::Real(r) => groups.push(real(1040, *r)), + XValue::Distance(r) => groups.push(real(1041, *r)), + XValue::ScaleFactor(r) => groups.push(real(1042, *r)), + XValue::Int16(i) => groups.push(RawTag { code: 1070, value: i.to_string() }), + XValue::Int32(i) => groups.push(RawTag { code: 1071, value: i.to_string() }), + XValue::Undecoded { .. } => { + cov.miss("undecoded extended data"); + ok = false; + } + } + } + if ok && depth == 0 && out.len() + groups.len() <= crate::dxf_raw::MAX_XDATA_GROUPS { + out.extend(groups); + } + } + out +} + +/// The DraftCraft entity for a DWG entity, with the DXF reader's conventions: angles in radians, +/// 2D entities' points from their OCS, and a mirrored OCS (extrusion z < 0) turned into the WCS +/// geometry it draws. +fn kind(o: &Object, c: &Common, names: &Names) -> Option { + let n = c.extrusion; + let mirrored = n.z < 0.0; + Some(match &o.kind { + ObjectKind::Line(l) => EntityKind::Line(Line { a: v3(l.start), b: v3(l.end) }), + ObjectKind::Point(p) => EntityKind::Point(Point { p: v3(p.position), angle: p.x_axis_angle }), + ObjectKind::Circle(ci) => EntityKind::Circle(Circle { center: ocs_n(n, v3(ci.center)), radius: ci.radius.abs() }), + ObjectKind::Arc(a) => { + let mut arc = Arc { center: ocs_n(n, v3(a.center)), radius: a.radius.abs(), start: a.start_angle, end: a.end_angle }; + if mirrored { + let (s, e) = (std::f64::consts::PI - arc.end, std::f64::consts::PI - arc.start); + arc.start = draftcraft_geom::norm_angle(s); + arc.end = draftcraft_geom::norm_angle(e); + } + EntityKind::Arc(arc) + } + ObjectKind::Ellipse(el) => { + let mut e = Ellipse { + center: v3(el.center), + major: v3(el.major_axis), + ratio: el.axis_ratio.clamp(1e-9, 1.0), + start: el.start_param, + end: el.end_param, + }; + if mirrored && (draftcraft_geom::ccw_sweep(e.start, e.end) - std::f64::consts::TAU).abs() > 1e-9 { + let (s, e2) = (-e.end, -e.start); + e.start = draftcraft_geom::norm_angle(s); + e.end = draftcraft_geom::norm_angle(e2); + } + EntityKind::Ellipse(e) + } + ObjectKind::LwPolyline(p) => { + let mut vertices: Vec = p + .points + .iter() + .enumerate() + .map(|(i, q)| { + let (sw, ew) = p.widths.get(i).copied().unwrap_or((0.0, 0.0)); + PolyVertex { p: Vec2::new(q.x, q.y), start_width: sw, end_width: ew, bulge: p.bulges.get(i).copied().unwrap_or(0.0) } + }) + .collect(); + if mirrored { + for v in &mut vertices { + v.p.x = -v.p.x; + v.bulge = -v.bulge; + } + } + EntityKind::LwPolyline(LwPolyline { + vertices, + closed: p.flags & 512 != 0, + const_width: p.const_width, + elevation: p.elevation, + plinegen: p.flags & 256 != 0, + }) + } + ObjectKind::Text(t) if !mirrored => { + let halign = match t.h_align { + 1 => HAlign::Center, + 2 => HAlign::Right, + 3 => HAlign::Aligned, + 4 => HAlign::Middle, + 5 => HAlign::Fit, + _ => HAlign::Left, + }; + let valign = match t.v_align { + 1 => VAlign::Bottom, + 2 => VAlign::Middle, + 3 => VAlign::Top, + _ => VAlign::Baseline, + }; + let at = |p: geom::Vec2| Vec3::new(p.x, p.y, t.elevation); + let plain = halign == HAlign::Left && valign == VAlign::Baseline; + EntityKind::Text(Text { + insert: at(t.insertion), + align_pt: (!plain).then(|| at(t.alignment)), + height: t.height.max(1e-9), + value: draftcraft_dxf::unescape_unicode(&t.value), + rotation: t.rotation, + width_factor: t.width_factor, + oblique: t.oblique, + style: names.styles.get(&t.style.0).cloned().unwrap_or_else(|| "Standard".into()), + halign, + valign, + }) + } + ObjectKind::MText(t) if !mirrored => EntityKind::MText(MText { + insert: v3(t.insertion), + height: t.text_height, + width: t.rect_width, + attach: u8::try_from(t.attachment.clamp(1, 9)).unwrap_or(1), + rotation: Vec2::new(t.x_axis.x, t.x_axis.y).angle(), + style: names.styles.get(&t.style.0).cloned().unwrap_or_else(|| "Standard".into()), + contents: draftcraft_dxf::unescape_unicode(&t.contents), + line_spacing: t.linespacing_factor, + line_spacing_exact: t.linespacing_exact, + columns: None, + }), + ObjectKind::Insert(i) if !i.has_attribs => { + let block = names.blocks.get(&i.block_header.0).cloned()?; + let flat = n.x.hypot(n.y) <= 1e-3 * n.z.abs(); + let mut p = v3(i.insertion); + let mut scale = v3(i.scale); + let mut rotation = i.rotation; + let (cols, rows, mut col_spacing, row_spacing) = i.array.map_or((1, 1, 0.0, 0.0), |(c, r, cs, rs)| (u32::from(c), u32::from(r), cs, rs)); + if mirrored && flat { + p = ocs_n(n, p); + scale.x = -scale.x; + rotation = -rotation; + col_spacing = -col_spacing; + } + EntityKind::Insert(Insert { + block, + insert: p, + scale, + rotation, + attribs: Vec::new(), + cols: cols.clamp(1, 10_000), + rows: rows.clamp(1, 10_000), + col_spacing, + row_spacing, + clip: None, + }) + } + ObjectKind::Solid(s) => { + let at = |q: geom::Vec2| ocs_n(n, Vec3::new(q.x, q.y, s.elevation)); + let corners = s.corners.map(at); + if s.is_trace { EntityKind::Trace(Solid { corners }) } else { EntityKind::Solid(Solid { corners }) } + } + ObjectKind::Face3d(f) => { + EntityKind::Face3d(Face3d { corners: f.corners.map(v3), hidden_edges: u8::try_from(f.invisible_edges & 0x0f).unwrap_or(0) }) + } + ObjectKind::Xline(x) => EntityKind::XLine(RayLine { base: v3(x.base), dir: v3(x.direction) }), + ObjectKind::Ray(x) => EntityKind::Ray(RayLine { base: v3(x.base), dir: v3(x.direction) }), + _ => return None, + }) +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index bffa0cdd..867ac311 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -43,12 +43,12 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCO /// Applications whose xdata DraftCraft reads and writes itself. `ACAD` holds dimension overrides /// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. -const OWN_APPS: &[&str] = &["DRAFTCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; +pub(crate) const OWN_APPS: &[&str] = &["DRAFTCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; /// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object). -const MAX_XDATA_GROUPS: usize = 16_384; +pub(crate) const MAX_XDATA_GROUPS: usize = 16_384; /// Longest ownership chain followed. const MAX_DEPTH: usize = 64; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index aaa695e3..ef52df90 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -15,6 +15,8 @@ use draftcraft_geom::{PolyVertex, Spline, Vec2, Vec3}; use crate::{IoError, Result}; mod common; +pub(crate) use common::{ocs_n, transparency_440}; +pub(crate) use tables::style_font_of; mod dimassoc; mod document; mod entities; diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 9a1ec452..baa87306 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -38,7 +38,7 @@ impl T<'_> { /// An entity's group 440: `0x01` in the top byte is ByBlock, `0x02` a fixed alpha (mapped to a /// percentage as for layers), anything else ByLayer. -fn transparency_440(v: i64) -> Transparency { +pub(crate) fn transparency_440(v: i64) -> Transparency { match (v >> 24) & 0xff { 1 => Transparency::ByBlock, 2 => { @@ -109,6 +109,6 @@ pub(super) fn ocs(c: &Common, p: Vec3) -> Vec3 { ocs_n(c.extrusion, p) } -pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { +pub(crate) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { if (n.z - 1.0).abs() < 1e-12 && n.x.abs() < 1e-12 && n.y.abs() < 1e-12 { p } else { draftcraft_geom::Mat4::ocs(n).apply(p) } } diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index f872d28e..bb9afa15 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -71,17 +71,23 @@ fn annotative(tags: &[Tag]) -> bool { /// family of the style's `ACAD` xdata (`1000` typeface) when it has no font file (how AutoCAD /// stores TrueType styles); otherwise the file. fn style_font(tags: &[Tag], file: String) -> String { - if file.trim().is_empty() - && let Some(face) = - crate::dxf_ext::xdata(tags, "ACAD").iter().find(|t| t.code == 1000).map(|t| t.str().trim().to_string()).filter(|f| !f.is_empty()) - { - return face; - } + let face = crate::dxf_ext::xdata(tags, "ACAD").iter().find(|t| t.code == 1000).map(|t| t.str().trim().to_string()); let x = crate::dxf_ext::xdata(tags, crate::dxf_ext::APP); let own = x.windows(2).find_map(|w| match w { [m, n] if m.code == 1000 && m.str() == "FONT" && n.code == 1000 => Some(n.str()), _ => None, }); + style_font_of(file, face, own) +} + +/// [`style_font`] from its parts: the font file, the first string of the style's `ACAD` xdata +/// (the TrueType typeface) and the font name of its `DRAFTCRAFT` xdata. The DWG reader uses it too. +pub(crate) fn style_font_of(file: String, acad_face: Option, own: Option) -> String { + if file.trim().is_empty() + && let Some(face) = acad_face.filter(|f| !f.is_empty()) + { + return face; + } let stem = file.trim().to_ascii_lowercase(); let base = stem.rsplit(['/', '\\']).next().unwrap_or_default(); match own { diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b928c810..4808a364 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -5,6 +5,7 @@ /// What a DXF file holds that DraftCraft doesn't model, kept and written back (#528). mod dxf_raw; +pub mod dwg_read; /// XCLIP boundaries as SPATIAL_FILTER objects. mod dxf_clip; mod dxf_ext; @@ -62,11 +63,11 @@ pub enum IoError { pub type Result = std::result::Result; -/// How a program runs the DWG reader and writer in a child process (`draftcraft_dwg::worker`). +/// How a program runs the DWG reader and writer in a child process (`draftcraft_dwg::acadrust::worker`). pub mod dwg_worker { - pub use draftcraft_dwg::{WORKER_ARG, serve_if_asked, use_own_worker}; + pub use draftcraft_dwg::acadrust::{WORKER_ARG, serve_if_asked, use_own_worker}; #[cfg(all(not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] - pub use draftcraft_dwg::{crash_worker_for_test, use_worker}; + pub use draftcraft_dwg::acadrust::{crash_worker_for_test, use_worker}; } fn ext(name: impl AsRef) -> String { @@ -80,13 +81,61 @@ pub fn read(bytes: &[u8], name: impl AsRef) -> Result { } /// [`read`], also returning the DXF rendition a DWG was read through (`None` for other files), +/// Which reader opens DWG files. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DwgReader { + /// acadrust, through DXF (`draftcraft_dwg::acadrust`): the default while DraftCraft's own + /// reader doesn't cover everything a file can hold. + Acadrust, + /// DraftCraft's own reader ([`dwg_read`]), straight into the drawing. What it leaves out is + /// listed in the drawing's read notes. + Native, + /// DraftCraft's own reader when it carries the whole file over, acadrust otherwise. + Auto, +} + +impl DwgReader { + /// `DRAFTCRAFT_DWG_READER=native`, `auto` or `acadrust` (the default). + pub fn from_env() -> DwgReader { + match std::env::var("DRAFTCRAFT_DWG_READER").unwrap_or_default().to_ascii_lowercase().as_str() { + "native" => DwgReader::Native, + "auto" => DwgReader::Auto, + _ => DwgReader::Acadrust, + } + } +} + +/// Read a DWG file with the reader named. +pub fn read_dwg_with(bytes: &[u8], reader: DwgReader) -> Result { + read_dwg_source(bytes, reader).map(|(d, _)| d) +} + +/// A DWG file, and the DXF acadrust converted it to when it was that reader (which the +/// round-trip harness counts against). +fn read_dwg_source(bytes: &[u8], reader: DwgReader) -> Result<(Drawing, Option>)> { + let limits = draftcraft_dwg::Limits::DEFAULT; + if reader != DwgReader::Acadrust { + if bytes.len() > limits.max_dwg_bytes { + return Err(IoError::Format(format!("DWG: the file is larger than the {} MB DraftCraft opens", limits.max_dwg_bytes >> 20))); + } + let (mut d, cov) = dwg_read::read(bytes)?; + if reader == DwgReader::Native || cov.is_whole() { + if !cov.is_whole() { + d.read_notes.push(format!("DWG: left out of the drawing: {}", cov.summary())); + } + return Ok((d, None)); + } + } + let (dxf, notes) = draftcraft_dwg::acadrust::decode(bytes, limits).map_err(IoError::Format)?; + let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?; + d.read_notes = notes; + Ok((d, Some(dxf))) +} + /// which the round-trip harness counts. pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option>)> { if draftcraft_dwg::is_dwg(bytes) { - let (dxf, notes) = draftcraft_dwg::decode(bytes, draftcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?; - let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?; - d.read_notes = notes; - return Ok((d, Some(dxf))); + return read_dwg_source(bytes, DwgReader::from_env()); } let d = match (Format::from_path(name), ext(name).as_str()) { (Some(Format::Svg | Format::Svgz), _) => svg_read::read(bytes), @@ -133,18 +182,18 @@ pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Re /// [`write_with`], also returning what the file leaves out of the drawing: for a DWG, how many /// records of each DXF type the DWG writer can't write (other programs' custom entities and /// objects); for other formats, nothing. -pub fn write_noted(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Result<(Vec, draftcraft_dwg::Unwritten)> { +pub fn write_noted(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Result<(Vec, draftcraft_dwg::acadrust::Unwritten)> { let name = name.as_ref(); if matches!(Format::from_path(name), Some(Format::Dwg)) && !opts.binary { return write_dwg(d, opts.version.unwrap_or_else(|| save_version(d).max(Version::R2004))); } - write_with(d, name, opts).map(|b| (b, draftcraft_dwg::Unwritten::new())) + write_with(d, name, opts).map(|b| (b, draftcraft_dwg::acadrust::Unwritten::new())) } /// The DWG bridge reads our R2000 DXF and writes the DWG at `version`, in the DWG worker when /// there is one. -fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec, draftcraft_dwg::Unwritten)> { - draftcraft_dwg::encode_noted(dxf_write::dwg_bridge(d, version).as_bytes(), version.code()).map_err(IoError::Format) +fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec, draftcraft_dwg::acadrust::Unwritten)> { + draftcraft_dwg::acadrust::encode_noted(dxf_write::dwg_bridge(d, version).as_bytes(), version.code()).map_err(IoError::Format) } /// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 3c05d259..6acc2f62 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -813,7 +813,7 @@ fn viewport_frozen_layers_survive_dwg() { let back = read(&dwg, "t.dwg").unwrap(); assert_eq!(viewport_frozen(&back, 2), vec!["Walls".to_string(), "A B".to_string()]); // The DWG holds them in group 331, what AutoCAD reads. - let p = pairs(&String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + let p = pairs(&String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap()); assert_eq!(frozen_331(&p), [layer_handle(&p, "Walls"), layer_handle(&p, "A B")]); } @@ -955,8 +955,8 @@ fn generated_arrowhead_blocks_are_not_kept_as_user_blocks() { for (_, name) in crate::dxf_ext::ARROWS.iter().filter(|(k, _)| *k != draftcraft_render::Arrowhead::ClosedFilled) { assert!(dxf.contains(&format!("\r\n{name}\r\n")), "{name} is written"); } - let dwg = draftcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); - let from_dwg = read_dxf(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let from_dwg = read_dxf(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); for (back, what) in [(read_dxf(dxf.as_bytes()).unwrap(), "DXF"), (from_dwg, "DWG")] { assert!(back.blocks.keys().all(|k| !k.starts_with('_')), "{what}: {:?}", back.blocks.keys().collect::>()); assert!(roundtrip(&back).blocks.keys().all(|k| !k.starts_with('_')), "{what}: second save"); @@ -987,8 +987,8 @@ fn file_arrowhead_blocks_with_standard_names_are_kept() { d.dim_styles.push(DimStyle { name: "Dots".into(), arrow_block1: "_Dot".into(), arrow_block2: "_DotSmall".into(), ..DimStyle::default() }); let kinds = |d: &Drawing, name: &str| d.block(name).map(|b| b.entities.iter().map(|e| e.kind.clone()).collect::>()).unwrap_or_default(); let dxf = write_dxf(&d); - let dwg = draftcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); - let from_dwg = read_dxf(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let from_dwg = read_dxf(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); for (back, what) in [(read_dxf(dxf.as_bytes()).unwrap(), "DXF"), (from_dwg, "DWG")] { for name in ["_Dot", "_DotSmall"] { assert_eq!(kinds(&back, name), kinds(&d, name), "{what}: {name}"); @@ -1058,7 +1058,7 @@ fn many_entities(n: usize) -> Drawing { #[cfg(not(target_arch = "wasm32"))] fn ac1024_dwg(n: usize) -> Vec { let dxf = write_dxf(&many_entities(n)).replacen("AC1015", "AC1024", 1); - let dwg = draftcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(dxf.as_bytes()).unwrap(); assert_eq!(draftcraft_dwg::version(&dwg).as_deref(), Some("AC1024")); dwg } @@ -1071,7 +1071,7 @@ fn ac1024_dwg(n: usize) -> Vec { fn ac1024_dwg_with_many_entities_opens() { let n = 30_000; let dwg = ac1024_dwg(n); - let dxf = draftcraft_dwg::dwg_to_dxf(&dwg).unwrap(); + let dxf = draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap(); let tags = draftcraft_dxf::parse(&dxf).unwrap().len(); assert!(dxf.len() < dwg.len() * 20, "DXF {} bytes from {} DWG bytes", dxf.len(), dwg.len()); assert!(tags < dwg.len(), "{tags} group codes from {} DWG bytes", dwg.len()); @@ -1088,15 +1088,15 @@ fn ac1024_dwg_with_many_entities_opens() { #[test] fn oversized_dwg_and_dxf_are_rejected_early() { let dwg = ac1024_dwg(3000); - let full = draftcraft_dwg::dwg_to_dxf(&dwg).unwrap().len(); + let full = draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap().len(); assert!(full > 400_000, "{full}"); let limits = draftcraft_dwg::Limits { max_dxf_bytes: 300_000, ..draftcraft_dwg::Limits::DEFAULT }; - let e = draftcraft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err(); + let e = draftcraft_dwg::acadrust::dwg_to_dxf_with(&dwg, limits).unwrap_err(); assert!(e.starts_with("DWG: converting this 0."), "{e}"); assert!(e.contains("MB file produced more than 0.3 MB of drawing data (the limit)"), "{e}"); let limits = draftcraft_dwg::Limits { max_dwg_bytes: 100_000, ..draftcraft_dwg::Limits::DEFAULT }; - let e = draftcraft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err(); + let e = draftcraft_dwg::acadrust::dwg_to_dxf_with(&dwg, limits).unwrap_err(); assert!(e.starts_with("DWG: the file is 0.") && e.ends_with("MB, larger than the 0.1 MB DraftCraft opens"), "{e}"); // Lines that aren't even group codes: the size is reported before anything is parsed. @@ -1929,8 +1929,8 @@ fn arc_length_dimension_keeps_its_kind_and_centre_on_roundtrip() { _ => panic!("not a dimension"), } // And through DWG. - let dwg = draftcraft_dwg::dxf_to_dwg(text.as_bytes()).unwrap(); - let back = read_dxf(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(text.as_bytes()).unwrap(); + let back = read_dxf(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); let dims: Vec<_> = back.model.iter().filter_map(|e| if let EntityKind::Dimension(x) = &e.kind { Some(x.clone()) } else { None }).collect(); assert_eq!(dims.len(), 1); assert!(matches!(dims[0].kind, DimKind::ArcLength), "{:?}", dims[0].kind); diff --git a/crates/io/tests/dimassoc_angular_radial.rs b/crates/io/tests/dimassoc_angular_radial.rs index 9e1f6544..9f785e22 100644 --- a/crates/io/tests/dimassoc_angular_radial.rs +++ b/crates/io/tests/dimassoc_angular_radial.rs @@ -285,7 +285,7 @@ fn standard_dimassoc_associates_in_dxf_and_dwg() { let back = read_dxf(plain.as_bytes()).unwrap(); assert_standard_assoc(&c, &back, "DXF"); - let dwg = draftcraft_dwg::dxf_to_dwg_as(plain.as_bytes(), Version::R2018.code()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg_as(plain.as_bytes(), Version::R2018.code()).unwrap(); let back = read(&dwg, "case.dwg").unwrap(); assert_standard_assoc(&c, &back, "DWG"); } diff --git a/crates/io/tests/dwg_required_dictionaries.rs b/crates/io/tests/dwg_required_dictionaries.rs index 0133c5c4..e4d61eb7 100644 --- a/crates/io/tests/dwg_required_dictionaries.rs +++ b/crates/io/tests/dwg_required_dictionaries.rs @@ -92,7 +92,7 @@ fn an_ac1018_dwg_gets_the_variable_dictionary_autocad_always_writes() { #[test] fn the_dictionary_keeps_the_drawings_dimassoc_and_hidetext() { let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DIMASSOC\n70\n1\n9\n$HIDETEXT\n70\n0\n0\nENDSEC\n0\nEOF\n"; - let dwg = draftcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG"); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG"); let doc = read_dwg(&dwg); let vars = variable_dictionary(&doc).expect("AC1018 DWG: the named object dictionary has an AcDbVariableDictionary"); assert_eq!(value(&vars, "DIMASSOC"), Some("1"), "DIMASSOC in {vars:?}"); @@ -107,7 +107,7 @@ fn the_dictionary_keeps_the_drawings_dimassoc_and_hidetext() { #[test] fn impossible_header_values_fall_back_to_the_defaults() { let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DIMASSOC\n70\n9\n9\n$HIDETEXT\n70\n7\n0\nENDSEC\n0\nEOF\n"; - let dwg = draftcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG"); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG"); let doc = read_dwg(&dwg); let vars = variable_dictionary(&doc).expect("AC1018 DWG: the named object dictionary has an AcDbVariableDictionary"); assert_eq!(value(&vars, "DIMASSOC"), Some("2"), "DIMASSOC in {vars:?}"); @@ -139,7 +139,7 @@ fn a_variable_dictionary_the_drawing_has_is_left_alone() { assert!(source.set_drawing_variable("CMLEADERSTYLE", "Notes")); let dxf = acadrust::DxfWriter::new(&source).write_to_vec().expect("write a DXF with the dictionary"); - let dwg = draftcraft_dwg::dxf_to_dwg_as(&dxf, "AC1018").expect("write the DWG"); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg_as(&dxf, "AC1018").expect("write the DWG"); let doc = read_dwg(&dwg); let vars = variable_dictionary(&doc).expect("the drawing's dictionary is kept"); assert_eq!(vars.len(), 1, "{vars:?}"); diff --git a/crates/io/tests/it/acad_interop.rs b/crates/io/tests/it/acad_interop.rs index 15c31d74..2e8c6764 100644 --- a/crates/io/tests/it/acad_interop.rs +++ b/crates/io/tests/it/acad_interop.rs @@ -155,7 +155,7 @@ fn a_rotated_linear_dimension_stores_its_projected_length() { Vec3::new(-40.0, 105.0, 0.0), ); let dwg = write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); - let dxf = String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dxf = String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); let t = tags(&dxf); let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap(); let m: f64 = t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap(); @@ -242,7 +242,7 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification() /// Group 42 of a dimension in the DXF AutoCAD reads from `d`'s DWG. fn stored_measurement(d: &Drawing) -> f64 { let dwg = write_with(d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); - let dxf = String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dxf = String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); let t = tags(&dxf); let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap(); t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap() diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index eebc9519..8374d028 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -93,7 +93,7 @@ fn dwg_keeps_the_solids_geometry() { let d = draftcraft_io::read_dxf(dxf().as_bytes()).unwrap(); let dwg = draftcraft_io::write(&d, "x.dwg").unwrap(); // The DWG read back (as the bridge's DXF) binds the same bytes to both solids. - let back = String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let back = String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); let mut got = asm_data(&back); got.sort(); assert_eq!(got, vec![("2A".to_string(), SAB_HEX.to_string()), ("2B".to_string(), SAB_HEX.to_string())]); diff --git a/crates/io/tests/it/codepages.rs b/crates/io/tests/it/codepages.rs index cfaf4b86..2b980d91 100644 --- a/crates/io/tests/it/codepages.rs +++ b/crates/io/tests/it/codepages.rs @@ -248,7 +248,7 @@ fn hostile_multibyte_never_panics() { #[test] fn pre_2007_dwg_text_decodes_through_the_bridge() { let dxf = ascii_dxf("AC1015", "ANSI_1251", b"\xD1\xEB\xEE\xE9", b"\xC1\xEB\xEE\xEA", b"\xCF\xF0\xE8\xE2\xE5\xF2"); - let dwg = draftcraft_dwg::dxf_to_dwg(&dxf).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(&dxf).unwrap(); let d = draftcraft_io::read(&dwg, "x.dwg").unwrap(); assert_eq!(names(&d), ("Слой".into(), "Блок".into(), "Привет".into())); } diff --git a/crates/io/tests/it/dwg_native_read.rs b/crates/io/tests/it/dwg_native_read.rs new file mode 100644 index 00000000..a4970fa0 --- /dev/null +++ b/crates/io/tests/it/dwg_native_read.rs @@ -0,0 +1,260 @@ +//! DraftCraft's own DWG reader (`dwg_read`) against the acadrust path: on every entity type it +//! maps, every entity it maps is the one acadrust's DXF gives the DXF reader, in the same space, +//! with the same properties; and the layers, linetypes, text styles, blocks and layouts agree. + +use std::sync::Arc as Shared; + +use draftcraft_color::{Color, Rgb}; +use draftcraft_doc::*; +use draftcraft_geom::{PolyVertex, Vec2, Vec3}; +use draftcraft_io::{DwgReader, read_dwg_with}; + +/// Every entity with where it lives: `model`, `layout NAME` or `block NAME`. +fn placed(d: &Drawing) -> Vec<(String, Shared)> { + let mut v: Vec<_> = d.model.iter().map(|e| ("model".to_string(), e.clone())).collect(); + for l in &d.layouts { + v.extend(l.entities.iter().map(|e| (format!("layout {}", l.name), e.clone()))); + } + for (n, b) in &d.blocks { + v.extend(b.entities.iter().map(|e| (format!("block {n}"), e.clone()))); + } + v +} + +/// The entity types `dwg_read` maps. +fn mapped(k: &EntityKind) -> bool { + matches!( + k, + EntityKind::Line(_) + | EntityKind::Point(_) + | EntityKind::Circle(_) + | EntityKind::Arc(_) + | EntityKind::Ellipse(_) + | EntityKind::LwPolyline(_) + | EntityKind::Text(_) + | EntityKind::MText(_) + | EntityKind::Insert(_) + | EntityKind::Solid(_) + | EntityKind::Trace(_) + | EntityKind::Face3d(_) + | EntityKind::XLine(_) + | EntityKind::Ray(_) + ) +} + +/// The native reading agrees with the acadrust reading on everything the native reader maps. +/// `same_lineweight`: R14 files store no lineweights; acadrust reports 0.00 mm for them, the +/// native reader ByLayer (what an R14 entity has), so R14 entities are compared without them. +fn assert_agree(dwg: &[u8], what: &str, same_lineweight: bool) -> usize { + let a = read_dwg_with(dwg, DwgReader::Acadrust).unwrap(); + let n = read_dwg_with(dwg, DwgReader::Native).unwrap(); + let native: std::collections::HashMap)> = placed(&n).into_iter().map(|(s, e)| (e.handle.0, (s, e))).collect(); + let mut checked = 0; + for (space, e) in placed(&a).into_iter().filter(|(_, e)| mapped(&e.kind)) { + let Some((nspace, ne)) = native.get(&e.handle.0) else { panic!("{what}: {:X} ({:?}) missing from the native reading", e.handle.0, e.kind) }; + assert_eq!(&space, nspace, "{what}: {:X}", e.handle.0); + assert_eq!(e.kind, ne.kind, "{what}: {:X}", e.handle.0); + let mut c = ne.common.clone(); + if !same_lineweight { + c.lineweight = e.common.lineweight; + } + assert_eq!(e.common, c, "{what}: {:X} {:?}", e.handle.0, e.kind); + checked += 1; + } + let mut layers = n.layers.clone(); + if !same_lineweight { + for (l, al) in layers.iter_mut().zip(&a.layers) { + l.lineweight = al.lineweight; + } + } + assert_eq!(a.layers, layers, "{what}: layers"); + assert_eq!(a.linetypes, n.linetypes, "{what}: linetypes"); + assert_eq!(a.text_styles, n.text_styles, "{what}: text styles"); + assert_eq!(a.blocks.keys().collect::>(), n.blocks.keys().collect::>(), "{what}: block names"); + let layouts = |d: &Drawing| d.layouts.iter().map(|l| (l.name.clone(), l.tab_order)).collect::>(); + assert_eq!(layouts(&a), layouts(&n), "{what}: layouts"); + checked +} + +fn common(layer: &str) -> Common { + Common { layer: layer.into(), ..Common::default() } +} + +/// One of every entity type the native reader maps, with the properties and conventions it +/// converts: an OCS-mirrored arc, circle and polyline, aligned text, a block reference, widths +/// and bulges, colours, a linetype, a lineweight, transparency and another application's xdata. +fn every_mapped_type() -> Drawing { + let mut d = Drawing::new_imperial(); + d.linetypes.push(Linetype { + name: "DASHED".into(), + description: "Dashed".into(), + pattern: vec![DashElement::dash(0.5), DashElement::dash(-0.25)], + }); + let mut walls = Layer::new("WALLS"); + walls.color = Color::from_aci(1); + walls.linetype = "DASHED".into(); + walls.lineweight = Lineweight::from_dxf(35); + d.layers.push(walls); + let mut block = Block::new("BOLT"); + block.entities.push(Entity::new(Handle(0x900), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 }))); + d.blocks.insert("BOLT".into(), Shared::new(block)); + let mirrored = Common { extrusion: Vec3::new(0.0, 0.0, -1.0), ..common("WALLS") }; + let styled = Common { + color: Color::True(Rgb::from_u32(0x00_80_40_20)), + transparency: Transparency::Percent(40), + ltscale: 2.0, + lineweight: Lineweight::from_dxf(50), + xdata: vec![ + RawTag { code: 1001, value: "MYAPP".into() }, + RawTag { code: 1000, value: "note".into() }, + RawTag { code: 1070, value: "7".into() }, + ], + ..common("0") + }; + let m = Space::Model; + let kinds = vec![ + (styled.clone(), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 5.0, 1.0) })), + (common("WALLS"), EntityKind::Point(Point { p: Vec3::new(1.0, 2.0, 0.0), angle: 0.0 })), + (common("WALLS"), EntityKind::Circle(Circle { center: Vec3::new(3.0, 4.0, 0.0), radius: 2.0 })), + (mirrored.clone(), EntityKind::Circle(Circle { center: Vec3::new(-3.0, 4.0, 0.0), radius: 1.0 })), + (common("0"), EntityKind::Arc(Arc { center: Vec3::new(5.0, 5.0, 0.0), radius: 3.0, start: 0.25, end: 2.5 })), + (mirrored.clone(), EntityKind::Arc(Arc { center: Vec3::new(5.0, -5.0, 0.0), radius: 3.0, start: 0.25, end: 2.5 })), + ( + common("0"), + EntityKind::Ellipse(Ellipse { center: Vec3::new(20.0, 0.0, 0.0), major: Vec3::new(4.0, 1.0, 0.0), ratio: 0.5, start: 0.0, end: 3.0 }), + ), + ( + mirrored, + EntityKind::LwPolyline(LwPolyline { + vertices: vec![ + PolyVertex { p: Vec2::new(0.0, 0.0), bulge: 0.5, start_width: 0.1, end_width: 0.2 }, + PolyVertex { p: Vec2::new(4.0, 0.0), ..Default::default() }, + PolyVertex { p: Vec2::new(4.0, 3.0), ..Default::default() }, + ], + closed: true, + const_width: 0.0, + elevation: 0.0, + plinegen: false, + }), + ), + ( + common("0"), + EntityKind::Text(Text { + insert: Vec3::new(0.0, 10.0, 0.0), + align_pt: Some(Vec3::new(5.0, 10.0, 0.0)), + height: 0.5, + value: "Größe 90°".into(), + rotation: 0.3, + width_factor: 0.8, + oblique: 0.1, + style: "Standard".into(), + halign: HAlign::Center, + valign: VAlign::Middle, + }), + ), + ( + common("0"), + EntityKind::MText(MText { + insert: Vec3::new(0.0, 20.0, 0.0), + height: 0.25, + width: 6.0, + attach: 5, + rotation: 0.5, + style: "Standard".into(), + contents: "First\\Psecond {\\fArial|b1;bold}".into(), + line_spacing: 1.5, + line_spacing_exact: false, + columns: None, + }), + ), + ( + common("WALLS"), + EntityKind::Insert(Insert { + block: "BOLT".into(), + insert: Vec3::new(30.0, 0.0, 0.0), + scale: Vec3::new(2.0, 2.0, 1.0), + rotation: 0.7, + attribs: vec![], + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }), + ), + ( + common("0"), + EntityKind::Solid(Solid { + corners: [Vec3::new(0.0, 30.0, 0.0), Vec3::new(2.0, 30.0, 0.0), Vec3::new(0.0, 32.0, 0.0), Vec3::new(2.0, 32.0, 0.0)], + }), + ), + ( + common("0"), + EntityKind::Face3d(Face3d { + corners: [Vec3::new(0.0, 40.0, 0.0), Vec3::new(2.0, 40.0, 1.0), Vec3::new(2.0, 42.0, 2.0), Vec3::new(0.0, 42.0, 1.0)], + hidden_edges: 5, + }), + ), + (common("0"), EntityKind::XLine(RayLine { base: Vec3::new(0.0, 50.0, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) })), + (common("0"), EntityKind::Ray(RayLine { base: Vec3::new(0.0, 55.0, 0.0), dir: Vec3::new(0.0, 1.0, 0.0) })), + ]; + for (c, k) in kinds { + d.add(&m, c, k).unwrap(); + } + d +} + +#[test] +fn every_mapped_type_reads_as_through_acadrust_in_every_version() { + let d = every_mapped_type(); + for ver in ["AC1015", "AC1018", "AC1024", "AC1027", "AC1032"] { + let mut d = d.clone(); + d.header.set_str("ACADVER", ver); + let dwg = draftcraft_io::write(&d, "x.dwg").unwrap(); + let checked = assert_agree(&dwg, ver, true); + assert!(checked >= 16, "{ver}: only {checked} entities compared"); + // Every entity type in the file is one the reader maps: only objects are left out. + let (_, cov) = draftcraft_io::dwg_read::read(&dwg).unwrap(); + let entities_left_out: Vec<_> = cov.left_out.keys().filter(|k| !k.starts_with("object ")).collect(); + assert!(entities_left_out.is_empty(), "{ver}: {entities_left_out:?}"); + } +} + +/// AutoCAD's own files of the MI-201 drawing (R14 to 2018) when `MI201_CORPUS` names them; the +/// 2007 file's container isn't read yet. +#[test] +fn corpus_reads_as_through_acadrust() { + let Some(dir) = std::env::var_os("MI201_CORPUS") else { return }; + let dir = std::path::PathBuf::from(dir); + for (name, same_lw) in [ + ("mi201-r14.dwg", false), + ("mi201-r2000.dwg", true), + ("mi201-r2004.dwg", true), + ("mi201-r2010.dwg", true), + ("mi201-r2013.dwg", true), + ("mi201-r2018.dwg", true), + ] { + let Ok(dwg) = std::fs::read(dir.join(name)) else { continue }; + let checked = assert_agree(&dwg, name, same_lw); + assert!(checked >= 50, "{name}: only {checked} entities compared"); + } +} + +/// A damaged file is an error or a drawing, never a crash: every prefix of a saved DWG, and the +/// file with its bytes flipped in turn. +#[test] +fn damaged_dwg_does_not_panic() { + let mut d = every_mapped_type(); + d.header.set_str("ACADVER", "AC1032"); + let dwg = draftcraft_io::write(&d, "x.dwg").unwrap(); + for cut in (0..dwg.len()).step_by(97) { + let _ = draftcraft_io::dwg_read::read(dwg.get(..cut).unwrap_or_default()); + } + for at in (0..dwg.len()).step_by(61) { + let mut b = dwg.clone(); + if let Some(x) = b.get_mut(at) { + *x ^= 0xA5; + } + let _ = draftcraft_io::dwg_read::read(&b); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 2e6c894a..a2aa8dd3 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -20,6 +20,7 @@ mod drafting_spacing; #[cfg(not(target_arch = "wasm32"))] mod dwg_header_vars; mod dwg_layout_owner; +mod dwg_native_read; #[cfg(not(target_arch = "wasm32"))] mod dwg_roundtrip_losses; mod dwt_template; diff --git a/crates/io/tests/it/model_layout_plot_type.rs b/crates/io/tests/it/model_layout_plot_type.rs index 127ebef6..c430e998 100644 --- a/crates/io/tests/it/model_layout_plot_type.rs +++ b/crates/io/tests/it/model_layout_plot_type.rs @@ -59,7 +59,7 @@ fn model_layout_plots_extents_fitted_and_layouts_their_sheet() { fn model_layout_plot_type_survives_the_dwg_bridge() { let dwg = draftcraft_io::write(&drawing(), "x.dwg").unwrap(); // What the DWG holds, as the bridge's own DXF. - let dxf = String::from_utf8_lossy(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).to_string(); + let dxf = String::from_utf8_lossy(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).to_string(); let p = plots(&dxf); let model = p.iter().find(|(n, _, _)| n.eq_ignore_ascii_case("Model")).unwrap(); assert_eq!(model.1, Some(1), "{p:?}"); diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index e64cc18b..b5e5c84c 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -93,7 +93,7 @@ fn dwg_mtext_caret_spaces_round_trip() -> TestResult { }); assert_eq!(text, Some(contents), "native DWG {version:?}, pass={pass}, {handle:?}"); } - let dxf = draftcraft_dwg::dwg_to_dxf(&bytes)?; + let dxf = draftcraft_dwg::acadrust::dwg_to_dxf(&bytes)?; let converted = read(&dxf, "bridge.dxf")?; assert_contents(&converted, &expected, &format!("DWG bridge DXF {version:?}, pass={pass}"))?; d = read(&bytes, "carets.dwg")?; @@ -112,7 +112,7 @@ fn bridge_caret_space_is_escaped_once_in_each_direction() -> TestResult { let native = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.into_bytes()))?.read()?; assert!(native.entities().any(|e| matches!(e, acadrust::EntityType::MText(t) if t.value == "^ C"))); let dwg = write_with(&d, "carets.dwg", &SaveOptions { version: Some(Version::R2018), binary: false })?; - let returned = String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg)?)?; + let returned = String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg)?)?; assert!(returned.contains(" 1\r\n^ C\r\n"), "the return bridge must encode the separator independently of authored whitespace"); Ok(()) } diff --git a/crates/io/tests/it/ole2frame_roundtrip.rs b/crates/io/tests/it/ole2frame_roundtrip.rs index 80ba62ee..ceafbb9d 100644 --- a/crates/io/tests/it/ole2frame_roundtrip.rs +++ b/crates/io/tests/it/ole2frame_roundtrip.rs @@ -90,7 +90,7 @@ fn dwg_keeps_ole_objects() { assert_eq!(ole(&d), 1); let dwg = draftcraft_io::write(&d, "x.dwg").unwrap(); - let back = String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let back = String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); let got = frames(&back); assert_eq!(got.len(), 1, "{got:?}"); assert_kept(&got[0]); @@ -99,14 +99,14 @@ fn dwg_keeps_ole_objects() { let again = draftcraft_io::read(&dwg, "x.dwg").unwrap(); assert_eq!(ole(&again), 1); let dwg = draftcraft_io::write(&again, "x.dwg").unwrap(); - let got = frames(&String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + let got = frames(&String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap()); assert_eq!(got.len(), 1, "{got:?}"); assert_kept(&got[0]); // Older DWG versions keep it the same way. for version in [draftcraft_io::Version::R2000, draftcraft_io::Version::R2010] { let dwg = draftcraft_io::write_with(&d, "x.dwg", &draftcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); - let got = frames(&String::from_utf8(draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + let got = frames(&String::from_utf8(draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap()); assert_eq!(got.len(), 1, "{version:?}: {got:?}"); assert_kept(&got[0]); } diff --git a/crates/io/tests/it/sortents.rs b/crates/io/tests/it/sortents.rs index 50dab03d..ac5eb6be 100644 --- a/crates/io/tests/it/sortents.rs +++ b/crates/io/tests/it/sortents.rs @@ -107,8 +107,8 @@ fn the_block_draw_order_survives_dxf_and_dwg() { /// The table itself (not DraftCraft's reordered records) goes through the DWG bridge (#2410). #[test] fn a_partial_block_table_survives_the_dwg_bridge() { - let dwg = draftcraft_dwg::dxf_to_dwg(block_dxf().as_bytes()).unwrap(); - let dxf = draftcraft_dwg::dwg_to_dxf(&dwg).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(block_dxf().as_bytes()).unwrap(); + let dxf = draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap(); let d = draftcraft_io::read_dxf(&dxf).unwrap(); assert_eq!(block_kinds(&d), ["wipeout", "circle", "hline", "vline"]); } @@ -120,8 +120,8 @@ fn a_zero_sort_handle_draws_last() { let dxf = block_dxf_with("331\n25B\n5\n0\n331\n25D\n5\n25E\n331\n25E\n5\n25B\n"); let want = ["wipeout", "circle", "vline", "hline"]; assert_eq!(block_kinds(&draftcraft_io::read_dxf(dxf.as_bytes()).unwrap()), want, "DXF"); - let dwg = draftcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); - let back = draftcraft_io::read_dxf(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let back = draftcraft_io::read_dxf(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); assert_eq!(block_kinds(&back), want, "DWG"); } @@ -135,7 +135,7 @@ fn two_unlisted_block_entities_each_sort_by_their_own_handle() { let dxf = block_dxf_with("331\n25B\n5\n25B\n331\n25D\n5\n25D\n"); let want = ["hline", "circle", "vline", "wipeout"]; assert_eq!(block_kinds(&draftcraft_io::read_dxf(dxf.as_bytes()).unwrap()), want, "DXF"); - let dwg = draftcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); - let back = draftcraft_io::read_dxf(&draftcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let dwg = draftcraft_dwg::acadrust::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let back = draftcraft_io::read_dxf(&draftcraft_dwg::acadrust::dwg_to_dxf(&dwg).unwrap()).unwrap(); assert_eq!(block_kinds(&back), want, "DWG"); } diff --git a/docs/dwg.md b/docs/dwg.md new file mode 100644 index 00000000..46b7d658 --- /dev/null +++ b/docs/dwg.md @@ -0,0 +1,117 @@ +# DWG in DraftCraft + +DraftCraft reads DWG files with its own reader, which builds the drawing straight from the file +with no DXF in between, or with acadrust (through DXF), the fallback for what its own reader +doesn't cover yet. Saving DWG still goes through acadrust. + +## Layout + +``` +crates/dwg (draftcraft-dwg: layer 0, depends on no other workspace crate) + read/ DWG R13 to 2018 and later (except 2007) → one record per object + write/ AutoCAD 2018 (AC1032) DWG from records (not used for saving yet) + records/ the records: one plain struct per DWG object type, decoded and then dropped + bits.rs, crc.rs, lz77.rs the format's primitives, shared by reading and writing + acadrust/ DWG ⇄ DXF bytes through the acadrust crate (MPL-2.0, used unmodified), + in a child process on desktop builds +crates/io + dxf_read, dxf_write DXF ⇄ drawing + dwg_read DWG records → drawing +``` + +The reader, writer and records come from BlackCAD (, +MIT OR Apache-2.0), written from the Open Design Alliance's public DWG specification. + +Rules this layout keeps: + +- **One model.** `draftcraft-doc`'s `Drawing` is the only drawing. The records are decoded, + mapped by `dwg_read` and dropped; nothing keeps or edits them. +- **No file decoded twice** on a normal open, and **no DXF text** between a DWG file and the + drawing on the native path. +- **Each conversion rule once.** Where a value means the same in DWG and DXF, `dwg_read` calls the + DXF reader's helper rather than repeating it: `ocs_n` (OCS → WCS), `transparency_440`, + `style_font_of` (a text style's font), `draftcraft_dxf::unescape_unicode` (`\U+XXXX` escapes) + and `dxf_raw`'s rules for other applications' extended data. +- **`io` reads and writes both formats.** The format crates below it (`draftcraft-dxf`, + `draftcraft-dwg`) know their bytes, never the drawing. + +## Choosing the reader + +`DRAFTCRAFT_DWG_READER` picks the reader for every DWG opened (`draftcraft_io::read`), and +`draftcraft_io::read_dwg_with(bytes, DwgReader)` picks it for one call: + +| Value | Reader | +|---|---| +| `acadrust` (default) | acadrust through DXF, as before | +| `native` | DraftCraft's own reader; what it left out is listed in the drawing's read notes | +| `auto` | the native reading when it left nothing out, acadrust otherwise | + +The default stays `acadrust` until the native reader carries everything a real file holds (below), +so opening a file never loses what it keeps today. + +## What the native reader maps + +- **Entities:** LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE, TEXT, MTEXT, INSERT (without + attributes), SOLID, TRACE, 3DFACE, XLINE, RAY, with layer, colour (ACI and true colour), linetype, + lineweight, linetype scale, transparency, visibility, thickness, extrusion (a mirrored OCS as the + DXF reader turns it into WCS geometry) and other applications' extended data. +- **Tables:** layers, linetypes, text styles (font, flags, annotative). +- **Blocks:** block definitions with their entities; anonymous blocks, which DWG stores unnumbered + (`*D`), are numbered per prefix in table order as AutoCAD numbers them in DXF (`*D0`, `*D1`). +- **Layouts:** paper-space layouts in tab order, with their entities. +- **Header:** INSUNITS, MEASUREMENT, LUNITS, LUPREC, AUNITS, AUPREC, ANGBASE, ANGDIR, LTSCALE, + TEXTSIZE, CELTSCALE, EXTMIN, EXTMAX, LIMMIN, LIMMAX, INSBASE, ACADVER. + +## Not covered yet + +`dwg_read::Coverage` counts everything below. Under `auto` such a file goes through acadrust. + +- DIMENSION, HATCH, SPLINE, LEADER, MLEADER, POLYLINE (2D, 3D, mesh), attributes (ATTRIB, ATTDEF), + VIEWPORT, IMAGE, WIPEOUT, TABLE, MLINE, TOLERANCE. +- Mirrored TEXT and MTEXT, entity plot styles and materials, extension dictionaries, external + references. +- Non-graphic objects that DraftCraft keeps as foreign data: dictionaries, XRECORD, VISUALSTYLE, + SCALE, MATERIAL, MLEADERSTYLE, TABLESTYLE, DICTIONARYVAR and the rest. AutoCAD writes these + into every file, so `auto` falls back on AutoCAD's files until they are mapped. + +Order of work: non-graphic objects into `Drawing::foreign` (then `auto` can be the default); the +missing entity types; saving DWG 2018 with the writer in `draftcraft-dwg` and a read-back check; +acadrust behind a feature, for 2007 files and older save-as versions. + +## Tests + +- `cargo test -p draftcraft-dwg`: the reader's and the format primitives' own tests. +- `cargo test -p draftcraft-io --test it dwg_native_read`: the native reader against the acadrust + path. A drawing with every mapped entity type and property is saved as DWG 2000, 2004, 2010, + 2013 and 2018 and opened both ways; every entity must come out the same (handle, space, kind, + properties), and so must the layers, linetypes, text styles, block names and layouts. Damaged + files (prefixes, flipped bytes) must return an error or a drawing, never a panic. + +`MI201_CORPUS` names a folder of real AutoCAD files (BlackCAD's `corpus/mosaiciron-mi201`: +MI-201 saved by AutoCAD from R14 to 2018). With it set, the tests above also run on those files. +Without it they skip. R14 files store no lineweights: acadrust reports 0.00 mm for them, the +native reader ByLayer (layers: Default), so R14 is compared without lineweights. + +``` +MI201_CORPUS=/path/to/blackcad/corpus/mosaiciron-mi201 cargo test -p draftcraft-dwg -p draftcraft-io +``` + +## Speed + +``` +cargo run --release -p draftcraft-io --example dwg_bench -- [entities] [--keep out.dwg] +``` + +`dwg_bench` builds a drawing of lines, arcs, circles and text (200,000 entities by default), saves +it as DWG 2018, opens it with both readers, and checks that every entity came out the same. + +Measured 2026-11-09 on a 2-core cloud machine (release build, single runs): + +| Drawing | acadrust | native | +|---|---|---| +| `dwg_bench`, 200,000 entities | 2,233–2,310 ms | **676–765 ms** (3.0–3.3×) | +| MI-201's entities copied 6,250 times (200,054), written by acadrust | 2,176 ms | **624 ms** | +| the same, written by BlackCAD's writer | 2,113 ms | **565 ms** | + +The native time is the decode (about 0.3 s for 200,000 entities) plus building the drawing. +acadrust decodes, writes about 30 MB of DXF text, and DraftCraft's DXF reader parses it again.