Skip to main content

dxf/
lib.rs

1// dxf -- DXF import (G6e2; docs/RENDER2D.md "DXF"): the ASCII format of AutoCAD R12 to 2018 read into a data model
2// that needs no GPU: the header's variables, the tables of layers, linetypes, text styles, block records and
3// dimension styles, blocks with their entities, and the entities of the drawing.  lib/render2d puts it into a scene
4// (render2d::dxf); a converter or a test reads the same without a device.
5//
6//   dxf::load(bytes, &Limits) -> Result<Document>        the whole file in memory, every entity kept
7//   dxf::read(&mut source, &Limits, &mut sink) -> Result<Stats>   streaming: the source hands out the file in pieces,
8//        the sink gets the header, the tables, each block when it is complete and each entity of ENTITIES as it is
9//        read (nothing of ENTITIES is kept: a file of a gigabyte loads in bounded memory)
10//   mtext::parse(text, height) -> Mtext                   MTEXT's inline format codes as paragraphs of runs
11//   specials(text) -> Vec<Special>                       TEXT's %% codes (degree, diameter, under- and overline)
12//   aci_rgb(index), font_substitute(name)                AutoCAD's colour index, which repository font stands in
13//
14// Binary DXF is refused (Error::Binary).  Files are untrusted input: every count, length and size is bounded
15// (Limits), a malformed value is skipped with a note, a group code that is no number ends the file with an error;
16// nothing nests deeper than POLYLINE / VERTEX and INSERT / ATTRIB, so there is no recursion.  Strings before AutoCAD
17// 2007 are in the header's code page ($DWGCODEPAGE, formats::encoding's character sets and multi-byte encodings), from
18// AC1021 on UTF-8; \U+XXXX and \M+NXXXX are decoded everywhere, %% codes and MTEXT's codes where the text is drawn
19// (specials, mtext).
20#![no_std]
21#![forbid(unsafe_code)]
22
23extern crate alloc;
24
25use alloc::collections::BTreeMap;
26use alloc::string::String;
27use alloc::vec::Vec;
28
29mod fonts;
30pub mod mtext;
31mod pairs;
32mod read;
33mod strings;
34
35pub use fonts::{font_substitute, Family, Substitute, SAMPLE};
36pub use strings::{decode_unicode_escapes, specials, Special};
37
38/// what went wrong; the text says where
39#[non_exhaustive]
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42    /// a binary DXF ("AutoCAD Binary DXF"): not read (decision 31: the ASCII format)
43    Binary,
44    /// not a DXF: a group code that is no number, a pair cut off (the line in the text)
45    Invalid(String),
46    /// a Limits value exceeded
47    Limit(String),
48}
49
50impl core::fmt::Display for Error {
51    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
52        match self {
53            Error::Binary => write!(f, "DXF: a binary DXF, only the ASCII format is read"),
54            Error::Invalid(s) => write!(f, "DXF: invalid: {s}"),
55            Error::Limit(s) => write!(f, "DXF: over a limit: {s}"),
56        }
57    }
58}
59
60pub type Result<T> = core::result::Result<T, Error>;
61
62/// the bounds a file must stay in (Limits::DEFAULT; raise them for large files you trust more)
63#[derive(Clone, Copy, Debug)]
64pub struct Limits {
65    /// bytes of one line (a group code or a value)
66    pub line_bytes: usize,
67    /// group pairs of one entity (with its vertices and attributes) and the bytes of their values
68    pub entity_pairs: usize,
69    pub entity_bytes: usize,
70    /// points of one entity: vertices, control points, knots, a hatch's edges and its pattern's dashes
71    pub entity_points: usize,
72    /// entities kept: all of a Document's, or the blocks' while streaming
73    pub kept_entities: u64,
74    /// points kept (as entity_points, summed over what is kept)
75    pub kept_points: u64,
76    /// blocks, distinct names (layers, linetypes, styles, blocks), entries of all tables
77    pub blocks: usize,
78    pub names: usize,
79    pub table_entries: usize,
80}
81
82impl Limits {
83    pub const DEFAULT: Limits = Limits {
84        line_bytes: 1 << 20,
85        entity_pairs: 1 << 24,
86        entity_bytes: 1 << 28,
87        entity_points: 1 << 24,
88        kept_entities: 1 << 26,
89        kept_points: 1 << 28,
90        blocks: 1 << 20,
91        names: 1 << 22,
92        table_entries: 1 << 20,
93    };
94}
95
96impl Default for Limits {
97    fn default() -> Limits {
98        Limits::DEFAULT
99    }
100}
101
102/// a point (x, y, z)
103pub type P3 = [f64; 3];
104
105/// a name of the file (a layer, linetype, text style, block, an entity's kind): an index into Names; names that differ
106/// only in the case of ASCII letters are one (AutoCAD's rule)
107#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
108pub struct Name(pub u32);
109
110/// the names of a file, in the order they were first seen (Name(0) is the layer "0")
111#[derive(Clone, Debug, Default)]
112pub struct Names {
113    list: Vec<String>,
114    map: BTreeMap<Vec<u8>, u32>,
115}
116
117impl Names {
118    /// the name's text as the file first spelled it
119    pub fn get(&self, n: Name) -> &str {
120        self.list.get(n.0 as usize).map_or("", |s| s.as_str())
121    }
122
123    /// a name that is already known
124    pub fn find(&self, s: &str) -> Option<Name> {
125        self.map.get(&key(s.as_bytes())[..]).map(|&i| Name(i))
126    }
127
128    pub fn len(&self) -> usize {
129        self.list.len()
130    }
131
132    pub fn is_empty(&self) -> bool {
133        self.list.is_empty()
134    }
135
136    pub(crate) fn intern(&mut self, s: &str, limit: usize) -> Result<Name> {
137        let k = key(s.as_bytes());
138        if let Some(&i) = self.map.get(&k) {
139            return Ok(Name(i));
140        }
141        if self.list.len() >= limit {
142            return Err(Error::Limit(alloc::format!("more than {limit} distinct names")));
143        }
144        let i = self.list.len() as u32;
145        self.list.push(String::from(s));
146        self.map.insert(k, i);
147        Ok(Name(i))
148    }
149}
150
151/// a name's key: ASCII letters in upper case
152fn key(s: &[u8]) -> Vec<u8> {
153    s.iter().map(|b| b.to_ascii_uppercase()).collect()
154}
155
156/// an entity's colour (62, 420): by layer, by block, an index of AutoCAD's palette (1 to 255; aci_rgb) or a true
157/// colour 0xRRGGBB (420 wins over 62)
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
159pub enum Color {
160    #[default]
161    ByLayer,
162    ByBlock,
163    Aci(u8),
164    Rgb(u32),
165}
166
167/// an entity's linetype (6): by layer (also when absent), by block, or a linetype of the table ("CONTINUOUS" is one)
168#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
169pub enum Linetype {
170    #[default]
171    ByLayer,
172    ByBlock,
173    Named(Name),
174}
175
176/// a lineweight (370): by layer, by block, the drawing's default ($LWDEFAULT), or hundredths of a millimetre
177#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
178pub enum Lineweight {
179    #[default]
180    ByLayer,
181    ByBlock,
182    Default,
183    Mm100(u16),
184}
185
186/// a transparency (440): by layer, by block, or an alpha (255: opaque, 0: invisible)
187#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
188pub enum Transparency {
189    #[default]
190    ByLayer,
191    ByBlock,
192    Alpha(u8),
193}
194
195/// what every entity has
196#[non_exhaustive]
197#[derive(Clone, Copy, Debug, PartialEq)]
198pub struct Common {
199    /// the entity's kind as the file names it (LINE, LWPOLYLINE, ...)
200    pub kind: Name,
201    /// 5 (0: none)
202    pub handle: u64,
203    /// 8 (the layer "0" when absent)
204    pub layer: Name,
205    pub linetype: Linetype,
206    pub color: Color,
207    pub lineweight: Lineweight,
208    /// 48 (1 when absent)
209    pub ltscale: f64,
210    pub transparency: Transparency,
211    /// 210 (0, 0, 1 when absent): the normal of the entity's object coordinate system (OCS)
212    pub extrusion: P3,
213    /// 39
214    pub thickness: f64,
215    /// 60 = 1
216    pub invisible: bool,
217    /// 67 = 1: in paper space
218    pub paper: bool,
219}
220
221impl Default for Common {
222    fn default() -> Common {
223        Common { kind: Name(0), handle: 0, layer: Name(0), linetype: Linetype::ByLayer, color: Color::ByLayer, lineweight: Lineweight::ByLayer, ltscale: 1.0,
224                 transparency: Transparency::ByLayer, extrusion: [0.0, 0.0, 1.0], thickness: 0.0, invisible: false, paper: false }
225    }
226}
227
228/// an entity: what all have, and its kind's geometry
229#[non_exhaustive]
230#[derive(Clone, Debug, PartialEq)]
231pub struct Entity {
232    pub common: Common,
233    pub kind: Kind,
234}
235
236/// a vertex of a polyline: its point (OCS for 2D polylines, WCS for 3D), the bulge of the segment that starts here (the
237/// tangent of a quarter of its arc's angle, positive: counter-clockwise), the widths at its start and end
238#[derive(Clone, Copy, Debug, PartialEq, Default)]
239pub struct Vertex {
240    pub at: P3,
241    pub bulge: f64,
242    pub start_width: f64,
243    pub end_width: f64,
244}
245
246/// LWPOLYLINE, and POLYLINE with its VERTEXes (2D and 3D; meshes are Kind::Mesh)
247#[non_exhaustive]
248#[derive(Clone, Debug, PartialEq, Default)]
249pub struct Polyline {
250    pub vertices: Vec<Vertex>,
251    /// 70 bit 1
252    pub closed: bool,
253    /// 70 bit 128: the linetype's pattern runs on across the vertices (else it starts anew at each)
254    pub plinegen: bool,
255    /// a 3D polyline (POLYLINE 70 bit 8): points in WCS, no bulges, no widths
256    pub three_d: bool,
257    /// 43 (LWPOLYLINE) or 40 / 41 of POLYLINE: the width where a vertex has none of its own
258    pub const_width: f64,
259    /// 38 (LWPOLYLINE) or 30 of POLYLINE's point: the OCS z
260    pub elevation: f64,
261}
262
263/// POLYLINE as a polyface mesh (70 bit 64: faces of up to four vertices, an edge invisible where its index is
264/// negative) or a polygon mesh (70 bit 16: m by n vertices, closed in m or n)
265#[non_exhaustive]
266#[derive(Clone, Debug, PartialEq, Default)]
267pub struct Mesh {
268    pub vertices: Vec<P3>,
269    /// polyface: per face its vertex indices from 1 (negative: the edge from it is invisible; 0: none)
270    pub faces: Vec<[i32; 4]>,
271    /// polygon mesh: its size and whether it closes
272    pub m: u32,
273    pub n: u32,
274    pub closed_m: bool,
275    pub closed_n: bool,
276}
277
278/// SPLINE (and the spline of a HELIX): degree, knots, control points with weights, fit points
279#[non_exhaustive]
280#[derive(Clone, Debug, PartialEq, Default)]
281pub struct Spline {
282    pub degree: u32,
283    /// 70: 1 closed, 2 periodic, 4 rational, 8 planar, 16 linear
284    pub flags: u32,
285    pub knots: Vec<f64>,
286    pub control: Vec<P3>,
287    /// one per control point, or empty (all 1)
288    pub weights: Vec<f64>,
289    pub fit: Vec<P3>,
290    pub start_tangent: Option<P3>,
291    pub end_tangent: Option<P3>,
292}
293
294/// TEXT, ATTRIB and ATTDEF
295#[non_exhaustive]
296#[derive(Clone, Debug, PartialEq, Default)]
297pub struct Text {
298    /// 1, decoded (\U+XXXX; the %% codes stay: specials())
299    pub text: String,
300    /// 7 (Standard when absent)
301    pub style: Option<Name>,
302    /// 10, 11 (OCS)
303    pub at: P3,
304    pub at2: Option<P3>,
305    /// 40
306    pub height: f64,
307    /// 50 (degrees)
308    pub rotation: f64,
309    /// 41, 51 (degrees): None when absent (the style's)
310    pub width: Option<f64>,
311    pub oblique: Option<f64>,
312    /// 71: 2 backward, 4 upside down (None: the style's)
313    pub generation: Option<u32>,
314    /// 72 (0 left, 1 center, 2 right, 3 aligned, 4 middle, 5 fit), 73 (0 baseline, 1 bottom, 2 middle, 3 top)
315    pub halign: u32,
316    pub valign: u32,
317    /// ATTRIB and ATTDEF: the tag (2) and the flags (70: 1 invisible, 2 constant, 4 verify, 8 preset)
318    pub tag: Option<String>,
319    pub attr_flags: u32,
320    /// ATTRIB / ATTDEF of several lines (R2018: an MTEXT inside them)
321    pub mtext: Option<alloc::boxed::Box<MText>>,
322}
323
324/// MTEXT
325#[non_exhaustive]
326#[derive(Clone, Debug, PartialEq, Default)]
327pub struct MText {
328    /// 3 ... and 1, joined, decoded (\U+XXXX); the format codes stay (mtext::parse)
329    pub text: String,
330    pub style: Option<Name>,
331    /// 10 (WCS)
332    pub at: P3,
333    /// 40, 41 (the reference rectangle's width: 0, no wrapping), 46 (its height, for columns)
334    pub height: f64,
335    pub width: f64,
336    pub rect_height: f64,
337    /// 71 (1 top left to 9 bottom right), 72 (1 left to right, 3 top to bottom, 5 by style)
338    pub attach: u32,
339    pub direction: u32,
340    /// 11 (WCS): the x axis' direction; else 50 (radians, in the OCS)
341    pub x_dir: Option<P3>,
342    pub rotation: f64,
343    /// 73 (1 at least, 2 exactly), 44 (the factor of the single spacing)
344    pub spacing_style: u32,
345    pub spacing: f64,
346    /// 90 (1 a background fill, 2 in the background colour, 16 a text frame), 63 / 421 its colour, 45 how far
347    /// beyond the text (a factor of the height)
348    pub bg_flags: u32,
349    pub bg_color: Color,
350    pub bg_scale: f64,
351    /// R2018's columns (75 type: 0 none, 1 static, 2 dynamic; 76 count; 48 width; 49 gutter; 50 heights)
352    pub column_type: u32,
353    pub column_count: u32,
354    pub column_width: f64,
355    pub column_gutter: f64,
356    pub column_heights: Vec<f64>,
357}
358
359/// INSERT (also MINSERT's array) with its ATTRIBs
360#[non_exhaustive]
361#[derive(Clone, Debug, PartialEq, Default)]
362pub struct Insert {
363    /// 2
364    pub block: Name,
365    /// 10 (OCS), 41 42 43, 50 (degrees)
366    pub at: P3,
367    pub scale: P3,
368    pub rotation: f64,
369    /// 70, 71 (0 read as 1), 44, 45
370    pub columns: u32,
371    pub rows: u32,
372    pub spacing: [f64; 2],
373    /// the ATTRIBs after it (each an Entity of Kind::Text)
374    pub attribs: Vec<Entity>,
375}
376
377/// an edge of a hatch's boundary path (angles in degrees, as the file has them)
378#[non_exhaustive]
379#[derive(Clone, Debug, PartialEq)]
380pub enum Edge {
381    Line { a: [f64; 2], b: [f64; 2] },
382    Arc { center: [f64; 2], radius: f64, start: f64, end: f64, ccw: bool },
383    /// major: the end of the major axis relative to the centre; ratio: minor over major
384    Ellipse { center: [f64; 2], major: [f64; 2], ratio: f64, start: f64, end: f64, ccw: bool },
385    Spline { degree: u32, rational: bool, periodic: bool, knots: Vec<f64>, control: Vec<[f64; 2]>, weights: Vec<f64>, fit: Vec<[f64; 2]> },
386    /// a polyline path: its vertices (x, y, bulge), closed
387    Poly { vertices: Vec<[f64; 3]>, closed: bool },
388}
389
390/// a hatch's boundary path: its flags (92: 1 external, 2 polyline, 4 derived, 8 textbox, 16 outermost) and edges
391#[non_exhaustive]
392#[derive(Clone, Debug, PartialEq, Default)]
393pub struct Path {
394    pub flags: u32,
395    pub edges: Vec<Edge>,
396}
397
398/// a line family of a hatch pattern as the file stores it, already scaled and turned: angle (53, degrees), a base
399/// point (43, 44), the offset to the next line (45, 46) and dashes (49: positive on, negative off, 0 a dot)
400#[non_exhaustive]
401#[derive(Clone, Debug, PartialEq, Default)]
402pub struct PatternLine {
403    pub angle: f64,
404    pub base: [f64; 2],
405    pub offset: [f64; 2],
406    pub dashes: Vec<f64>,
407}
408
409/// HATCH
410#[non_exhaustive]
411#[derive(Clone, Debug, PartialEq, Default)]
412pub struct Hatch {
413    /// 2, 70 (solid fill), 75 (0 normal, 1 outer, 2 ignore islands), 52, 41, 77
414    pub pattern: String,
415    pub solid: bool,
416    pub style: u32,
417    pub angle: f64,
418    pub scale: f64,
419    pub double: bool,
420    /// 30: the OCS z of the boundary
421    pub elevation: f64,
422    pub paths: Vec<Path>,
423    pub lines: Vec<PatternLine>,
424    /// 450 = 1: a gradient (its two colours, 63/421 after 453)
425    pub gradient: bool,
426    pub gradient_colors: Vec<Color>,
427}
428
429/// SOLID, TRACE (the outline 10, 11, 13, 12 in OCS) and 3DFACE (10, 11, 12, 13 in WCS; 70: invisible edges)
430#[non_exhaustive]
431#[derive(Clone, Copy, Debug, PartialEq, Default)]
432pub struct Quad {
433    pub points: [P3; 4],
434    pub face: bool,
435    pub invisible_edges: u32,
436}
437
438/// what draws through an anonymous block: DIMENSION (and its kinds ARC_DIMENSION, LARGE_RADIAL_DIMENSION) and
439/// ACAD_TABLE (2: the block; 10 its insertion point for a table)
440#[non_exhaustive]
441#[derive(Clone, Debug, PartialEq, Default)]
442pub struct BlockRef {
443    pub block: Option<Name>,
444    pub at: P3,
445    /// ACAD_TABLE's 11: its horizontal direction (WCS)
446    pub x_dir: Option<P3>,
447}
448
449/// LEADER: its vertices (WCS), an arrowhead (71), a spline path (72), the dimension style (3)
450#[non_exhaustive]
451#[derive(Clone, Debug, PartialEq, Default)]
452pub struct Leader {
453    pub vertices: Vec<P3>,
454    pub arrow: bool,
455    pub spline: bool,
456    pub dimstyle: Option<Name>,
457}
458
459/// WIPEOUT (and IMAGE's frame, read alike): insertion point, the u and v vectors of a pixel, the size in pixels, the
460/// clip boundary in pixel coordinates (71: 1 a rectangle of two corners, 2 a polygon)
461#[non_exhaustive]
462#[derive(Clone, Debug, PartialEq, Default)]
463pub struct Wipeout {
464    pub at: P3,
465    pub u: P3,
466    pub v: P3,
467    pub size: [f64; 2],
468    pub clip_type: u32,
469    pub clip: Vec<[f64; 2]>,
470}
471
472/// an entity's geometry
473#[non_exhaustive]
474#[derive(Clone, Debug, PartialEq)]
475pub enum Kind {
476    Line { a: P3, b: P3 },
477    /// POINT: WCS, 50 the angle of its symbol (degrees)
478    Point { at: P3, angle: f64 },
479    /// CIRCLE and ARC (OCS centre; angles in degrees, counter-clockwise from start to end)
480    Circle { center: P3, radius: f64 },
481    Arc { center: P3, radius: f64, start: f64, end: f64 },
482    /// ELLIPSE: WCS centre, the major axis' end relative to it, minor / major, the parameters (radians)
483    Ellipse { center: P3, major: P3, ratio: f64, start: f64, end: f64 },
484    Spline(Spline),
485    Polyline(Polyline),
486    Mesh(Mesh),
487    Text(Text),
488    MText(MText),
489    Insert(Insert),
490    Hatch(Hatch),
491    Quad(Quad),
492    BlockRef(BlockRef),
493    Leader(Leader),
494    Wipeout(Wipeout),
495    /// RAY (from `at`) and XLINE (both ways)
496    Ray { at: P3, dir: P3, both: bool },
497    /// what this reader does not read (its kind in Common::kind): counted, not drawn
498    Other,
499}
500
501/// a layer of the table
502#[non_exhaustive]
503#[derive(Clone, Copy, Debug, PartialEq)]
504pub struct Layer {
505    pub name: Name,
506    /// 62 (its magnitude) or 420
507    pub color: Color,
508    /// 62 negative: off; 70 bit 1: frozen, bit 4: locked; 290: plotted
509    pub on: bool,
510    pub frozen: bool,
511    pub locked: bool,
512    pub plot: bool,
513    /// 6 (None: CONTINUOUS)
514    pub linetype: Option<Name>,
515    /// 370 (Default when absent)
516    pub lineweight: Lineweight,
517    /// the XDATA AcCmTransparency (1071): an alpha
518    pub transparency: Option<u8>,
519}
520
521/// an element of a linetype: a dash (positive), a gap (negative) or a dot (0); a shape or text of a complex linetype
522/// is kept as a flag (74) and its text
523#[non_exhaustive]
524#[derive(Clone, Debug, PartialEq, Default)]
525pub struct Dash {
526    pub length: f64,
527    pub complex: u32,
528    pub text: Option<String>,
529}
530
531/// a linetype of the table
532#[non_exhaustive]
533#[derive(Clone, Debug, PartialEq, Default)]
534pub struct LinetypeDef {
535    pub name: Name,
536    pub description: String,
537    pub dashes: Vec<Dash>,
538    /// 40
539    pub total: f64,
540}
541
542/// a text style of the table
543#[non_exhaustive]
544#[derive(Clone, Debug, PartialEq, Default)]
545pub struct StyleDef {
546    pub name: Name,
547    /// 3: the font file (txt, simplex.shx, arial.ttf, ...), 4 the big font file
548    pub font: String,
549    pub bigfont: String,
550    /// the TrueType family the XDATA "ACAD" names (1000), if any
551    pub family: Option<String>,
552    /// 40 (0: none fixed), 41, 50 (degrees)
553    pub height: f64,
554    pub width: f64,
555    pub oblique: f64,
556    /// 70: 1 a shape file (not a text font), 4 vertical; 71: 2 backward, 4 upside down
557    pub flags: u32,
558    pub generation: u32,
559}
560
561/// a block record of the table
562#[non_exhaustive]
563#[derive(Clone, Debug, PartialEq, Default)]
564pub struct BlockRecord {
565    pub name: Name,
566    pub handle: u64,
567    /// 70: the insertion units
568    pub units: i32,
569}
570
571/// a dimension style (what a LEADER's arrow needs)
572#[non_exhaustive]
573#[derive(Clone, Debug, PartialEq, Default)]
574pub struct DimStyle {
575    pub name: Name,
576    /// 41 DIMASZ, 40 DIMSCALE
577    pub arrow_size: f64,
578    pub scale: f64,
579}
580
581/// the tables
582#[non_exhaustive]
583#[derive(Clone, Debug, Default)]
584pub struct Tables {
585    pub layers: Vec<Layer>,
586    pub linetypes: Vec<LinetypeDef>,
587    pub styles: Vec<StyleDef>,
588    pub block_records: Vec<BlockRecord>,
589    pub dimstyles: Vec<DimStyle>,
590}
591
592impl Tables {
593    pub fn layer(&self, n: Name) -> Option<&Layer> {
594        self.layers.iter().find(|l| l.name == n)
595    }
596
597    pub fn linetype(&self, n: Name) -> Option<&LinetypeDef> {
598        self.linetypes.iter().find(|l| l.name == n)
599    }
600
601    pub fn style(&self, n: Name) -> Option<&StyleDef> {
602        self.styles.iter().find(|l| l.name == n)
603    }
604
605    pub fn dimstyle(&self, n: Name) -> Option<&DimStyle> {
606        self.dimstyles.iter().find(|l| l.name == n)
607    }
608}
609
610/// the header's variables this reader uses
611#[non_exhaustive]
612#[derive(Clone, Debug, PartialEq)]
613pub struct Header {
614    /// $ACADVER (AC1009 R12 ... AC1032 2018; empty without a header), $DWGCODEPAGE
615    pub version: String,
616    pub codepage: String,
617    /// $INSUNITS (0 unitless, 1 inch, 4 mm, 6 m, ...)
618    pub insunits: i32,
619    /// $LTSCALE, $CELTSCALE
620    pub ltscale: f64,
621    /// $LWDISPLAY (None: not in the file), $LWDEFAULT (hundredths of a mm)
622    pub lwdisplay: Option<bool>,
623    pub lwdefault: u16,
624    /// $PDMODE, $PDSIZE
625    pub pdmode: i32,
626    pub pdsize: f64,
627    /// $EXTMIN, $EXTMAX
628    pub extmin: Option<P3>,
629    pub extmax: Option<P3>,
630    /// $DIMSCALE, $DIMASZ, $TEXTSIZE, $MIRRTEXT
631    pub dimscale: f64,
632    pub dimasz: f64,
633    pub textsize: f64,
634    pub mirrtext: bool,
635    /// whether the file had a HEADER section
636    pub present: bool,
637}
638
639impl Default for Header {
640    fn default() -> Header {
641        Header { version: String::new(), codepage: String::new(), insunits: 0, ltscale: 1.0, lwdisplay: None, lwdefault: 25, pdmode: 0, pdsize: 0.0, extmin: None, extmax: None,
642                 dimscale: 1.0, dimasz: 0.18, textsize: 0.2, mirrtext: false, present: false }
643    }
644}
645
646/// a block: its name, base point, flags (70: 1 anonymous, 2 attributes, 4 xref, 8 xref overlay, 16 external,
647/// 32 resolved, 64 referenced), entities
648#[non_exhaustive]
649#[derive(Clone, Debug, Default)]
650pub struct Block {
651    pub name: Name,
652    pub base: P3,
653    pub flags: u32,
654    /// 1: the file an xref names
655    pub xref: String,
656    pub entities: Vec<Entity>,
657    /// *Paper_Space...: a layout's
658    pub paper: bool,
659}
660
661/// where an entity marker was
662#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
663pub enum Where {
664    Entities,
665    Blocks,
666}
667
668/// what was read
669#[non_exhaustive]
670#[derive(Clone, Debug, Default)]
671pub struct Stats {
672    /// entity markers per section and kind as the reader took them (VERTEX, ATTRIB, SEQEND, BLOCK, ENDBLK count too)
673    pub kinds: BTreeMap<(Where, String), u64>,
674    /// entities of ENTITIES in paper space (67 = 1)
675    pub paper: u64,
676    /// bytes and lines read, group pairs
677    pub bytes: u64,
678    pub lines: u64,
679    pub pairs: u64,
680    /// sections seen
681    pub sections: Vec<String>,
682    /// what was skipped or guessed, each once (at most 64)
683    pub notes: Vec<String>,
684}
685
686impl Stats {
687    pub(crate) fn note(&mut self, s: String) {
688        if self.notes.len() < 64 && !self.notes.contains(&s) {
689            self.notes.push(s);
690        }
691    }
692
693    /// the count of a kind in a section
694    pub fn count(&self, w: Where, kind: &str) -> u64 {
695        self.kinds.get(&(w, String::from(kind))).copied().unwrap_or(0)
696    }
697}
698
699/// what a streaming read hands out, in the file's order: the header (also an empty one, before anything else), the
700/// tables (once, when the TABLES section ends, or empty before the first block or entity), each block when its ENDBLK
701/// is read, each entity of ENTITIES (paper space too: Common::paper)
702pub trait Sink {
703    fn header(&mut self, _h: &Header, _names: &Names) {}
704    fn tables(&mut self, _t: &Tables, _names: &Names) {}
705    fn block(&mut self, _b: Block, _names: &Names) {}
706    fn entity(&mut self, _e: Entity, _names: &Names) {}
707}
708
709/// a whole file
710#[non_exhaustive]
711#[derive(Clone, Debug, Default)]
712pub struct Document {
713    pub header: Header,
714    pub tables: Tables,
715    pub blocks: Vec<Block>,
716    pub entities: Vec<Entity>,
717    pub names: Names,
718    pub stats: Stats,
719}
720
721impl Document {
722    /// a name's text
723    pub fn name(&self, n: Name) -> &str {
724        self.names.get(n)
725    }
726
727    /// a block by its name
728    pub fn block(&self, n: Name) -> Option<&Block> {
729        self.blocks.iter().find(|b| b.name == n)
730    }
731}
732
733struct Collect {
734    doc: Document,
735}
736
737impl Sink for Collect {
738    fn header(&mut self, h: &Header, _: &Names) {
739        self.doc.header = h.clone();
740    }
741    fn tables(&mut self, t: &Tables, _: &Names) {
742        self.doc.tables = t.clone();
743    }
744    fn block(&mut self, b: Block, _: &Names) {
745        self.doc.blocks.push(b);
746    }
747    fn entity(&mut self, e: Entity, _: &Names) {
748        self.doc.entities.push(e);
749    }
750}
751
752/// a whole file in memory into a Document (every entity kept: Limits::kept_entities and kept_points bound them)
753pub fn load(bytes: &[u8], limits: &Limits) -> Result<Document> {
754    let mut at = 0usize;
755    let mut src = |buf: &mut [u8]| {
756        let n = buf.len().min(bytes.len() - at);
757        buf[..n].copy_from_slice(&bytes[at..at + n]);
758        at += n;
759        n
760    };
761    let mut c = Collect { doc: Document::default() };
762    let (stats, names) = read::run(&mut src, limits, &mut c, true)?;
763    c.doc.stats = stats;
764    c.doc.names = names;
765    Ok(c.doc)
766}
767
768/// a file read piece by piece: `source` fills a buffer and says how many bytes it put there (0: the end); the sink
769/// gets what was read in the file's order.  Only the tables and the blocks are kept (Limits bound them); the entities
770/// of ENTITIES go to the sink one by one
771pub fn read(source: &mut dyn FnMut(&mut [u8]) -> usize, limits: &Limits, sink: &mut dyn Sink) -> Result<(Stats, Names)> {
772    read::run(source, limits, sink, false)
773}
774
775/// whether bytes begin like a binary DXF
776pub fn is_binary(bytes: &[u8]) -> bool {
777    bytes.starts_with(b"AutoCAD Binary DXF")
778}
779
780/// AutoCAD's colour index (ACI) as 0xRRGGBB: 1 red, 2 yellow, 3 green, 4 cyan, 5 blue, 6 magenta, 7 white (black on a
781/// light background: the caller decides), 8 and 9 greys, 10 to 249 24 hues of 15 degrees, each in five brightnesses
782/// (255, 204, 153, 127, 76) and each of those mixed half with white of that brightness, 250 to 255 greys; 0 and 256
783/// (by block, by layer) are white
784pub fn aci_rgb(i: u8) -> u32 {
785    let rgb = |r: u32, g: u32, b: u32| (r << 16) | (g << 8) | b;
786    match i {
787        1 => rgb(255, 0, 0),
788        2 => rgb(255, 255, 0),
789        3 => rgb(0, 255, 0),
790        4 => rgb(0, 255, 255),
791        5 => rgb(0, 0, 255),
792        6 => rgb(255, 0, 255),
793        8 => rgb(128, 128, 128),
794        9 => rgb(192, 192, 192),
795        250 => rgb(51, 51, 51),
796        251 => rgb(80, 80, 80),
797        252 => rgb(105, 105, 105),
798        253 => rgb(130, 130, 130),
799        254 => rgb(190, 190, 190),
800        10..=249 => {
801            let k = (i - 10) as u32;
802            let (hue, level) = (k / 10, k % 10);
803            let v = [255.0, 204.0, 153.0, 127.0, 76.0][(level / 2) as usize];
804            // the hue at full saturation and brightness 1, in steps of 15 degrees
805            let h = hue as f64 * 15.0 / 60.0;
806            let sector = h as u32;
807            let f = h - sector as f64;
808            let (r, g, b) = match sector {
809                0 => (1.0, f, 0.0),
810                1 => (1.0 - f, 1.0, 0.0),
811                2 => (0.0, 1.0, f),
812                3 => (0.0, 1.0 - f, 1.0),
813                4 => (f, 0.0, 1.0),
814                _ => (1.0, 0.0, 1.0 - f),
815            };
816            let ch = |c: f64| {
817                let full = c * v;
818                let c = if level % 2 == 1 { full + 0.5 * (v - full) } else { full };
819                c as u32
820            };
821            rgb(ch(r), ch(g), ch(b))
822        }
823        _ => rgb(255, 255, 255),
824    }
825}