1#![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#[non_exhaustive]
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42 Binary,
44 Invalid(String),
46 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#[derive(Clone, Copy, Debug)]
64pub struct Limits {
65 pub line_bytes: usize,
67 pub entity_pairs: usize,
69 pub entity_bytes: usize,
70 pub entity_points: usize,
72 pub kept_entities: u64,
74 pub kept_points: u64,
76 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
102pub type P3 = [f64; 3];
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
108pub struct Name(pub u32);
109
110#[derive(Clone, Debug, Default)]
112pub struct Names {
113 list: Vec<String>,
114 map: BTreeMap<Vec<u8>, u32>,
115}
116
117impl Names {
118 pub fn get(&self, n: Name) -> &str {
120 self.list.get(n.0 as usize).map_or("", |s| s.as_str())
121 }
122
123 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
151fn key(s: &[u8]) -> Vec<u8> {
153 s.iter().map(|b| b.to_ascii_uppercase()).collect()
154}
155
156#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
169pub enum Linetype {
170 #[default]
171 ByLayer,
172 ByBlock,
173 Named(Name),
174}
175
176#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
178pub enum Lineweight {
179 #[default]
180 ByLayer,
181 ByBlock,
182 Default,
183 Mm100(u16),
184}
185
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
188pub enum Transparency {
189 #[default]
190 ByLayer,
191 ByBlock,
192 Alpha(u8),
193}
194
195#[non_exhaustive]
197#[derive(Clone, Copy, Debug, PartialEq)]
198pub struct Common {
199 pub kind: Name,
201 pub handle: u64,
203 pub layer: Name,
205 pub linetype: Linetype,
206 pub color: Color,
207 pub lineweight: Lineweight,
208 pub ltscale: f64,
210 pub transparency: Transparency,
211 pub extrusion: P3,
213 pub thickness: f64,
215 pub invisible: bool,
217 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#[non_exhaustive]
230#[derive(Clone, Debug, PartialEq)]
231pub struct Entity {
232 pub common: Common,
233 pub kind: Kind,
234}
235
236#[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#[non_exhaustive]
248#[derive(Clone, Debug, PartialEq, Default)]
249pub struct Polyline {
250 pub vertices: Vec<Vertex>,
251 pub closed: bool,
253 pub plinegen: bool,
255 pub three_d: bool,
257 pub const_width: f64,
259 pub elevation: f64,
261}
262
263#[non_exhaustive]
266#[derive(Clone, Debug, PartialEq, Default)]
267pub struct Mesh {
268 pub vertices: Vec<P3>,
269 pub faces: Vec<[i32; 4]>,
271 pub m: u32,
273 pub n: u32,
274 pub closed_m: bool,
275 pub closed_n: bool,
276}
277
278#[non_exhaustive]
280#[derive(Clone, Debug, PartialEq, Default)]
281pub struct Spline {
282 pub degree: u32,
283 pub flags: u32,
285 pub knots: Vec<f64>,
286 pub control: Vec<P3>,
287 pub weights: Vec<f64>,
289 pub fit: Vec<P3>,
290 pub start_tangent: Option<P3>,
291 pub end_tangent: Option<P3>,
292}
293
294#[non_exhaustive]
296#[derive(Clone, Debug, PartialEq, Default)]
297pub struct Text {
298 pub text: String,
300 pub style: Option<Name>,
302 pub at: P3,
304 pub at2: Option<P3>,
305 pub height: f64,
307 pub rotation: f64,
309 pub width: Option<f64>,
311 pub oblique: Option<f64>,
312 pub generation: Option<u32>,
314 pub halign: u32,
316 pub valign: u32,
317 pub tag: Option<String>,
319 pub attr_flags: u32,
320 pub mtext: Option<alloc::boxed::Box<MText>>,
322}
323
324#[non_exhaustive]
326#[derive(Clone, Debug, PartialEq, Default)]
327pub struct MText {
328 pub text: String,
330 pub style: Option<Name>,
331 pub at: P3,
333 pub height: f64,
335 pub width: f64,
336 pub rect_height: f64,
337 pub attach: u32,
339 pub direction: u32,
340 pub x_dir: Option<P3>,
342 pub rotation: f64,
343 pub spacing_style: u32,
345 pub spacing: f64,
346 pub bg_flags: u32,
349 pub bg_color: Color,
350 pub bg_scale: f64,
351 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#[non_exhaustive]
361#[derive(Clone, Debug, PartialEq, Default)]
362pub struct Insert {
363 pub block: Name,
365 pub at: P3,
367 pub scale: P3,
368 pub rotation: f64,
369 pub columns: u32,
371 pub rows: u32,
372 pub spacing: [f64; 2],
373 pub attribs: Vec<Entity>,
375}
376
377#[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 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 Poly { vertices: Vec<[f64; 3]>, closed: bool },
388}
389
390#[non_exhaustive]
392#[derive(Clone, Debug, PartialEq, Default)]
393pub struct Path {
394 pub flags: u32,
395 pub edges: Vec<Edge>,
396}
397
398#[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#[non_exhaustive]
411#[derive(Clone, Debug, PartialEq, Default)]
412pub struct Hatch {
413 pub pattern: String,
415 pub solid: bool,
416 pub style: u32,
417 pub angle: f64,
418 pub scale: f64,
419 pub double: bool,
420 pub elevation: f64,
422 pub paths: Vec<Path>,
423 pub lines: Vec<PatternLine>,
424 pub gradient: bool,
426 pub gradient_colors: Vec<Color>,
427}
428
429#[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#[non_exhaustive]
441#[derive(Clone, Debug, PartialEq, Default)]
442pub struct BlockRef {
443 pub block: Option<Name>,
444 pub at: P3,
445 pub x_dir: Option<P3>,
447}
448
449#[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#[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#[non_exhaustive]
474#[derive(Clone, Debug, PartialEq)]
475pub enum Kind {
476 Line { a: P3, b: P3 },
477 Point { at: P3, angle: f64 },
479 Circle { center: P3, radius: f64 },
481 Arc { center: P3, radius: f64, start: f64, end: f64 },
482 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 { at: P3, dir: P3, both: bool },
497 Other,
499}
500
501#[non_exhaustive]
503#[derive(Clone, Copy, Debug, PartialEq)]
504pub struct Layer {
505 pub name: Name,
506 pub color: Color,
508 pub on: bool,
510 pub frozen: bool,
511 pub locked: bool,
512 pub plot: bool,
513 pub linetype: Option<Name>,
515 pub lineweight: Lineweight,
517 pub transparency: Option<u8>,
519}
520
521#[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#[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 pub total: f64,
540}
541
542#[non_exhaustive]
544#[derive(Clone, Debug, PartialEq, Default)]
545pub struct StyleDef {
546 pub name: Name,
547 pub font: String,
549 pub bigfont: String,
550 pub family: Option<String>,
552 pub height: f64,
554 pub width: f64,
555 pub oblique: f64,
556 pub flags: u32,
558 pub generation: u32,
559}
560
561#[non_exhaustive]
563#[derive(Clone, Debug, PartialEq, Default)]
564pub struct BlockRecord {
565 pub name: Name,
566 pub handle: u64,
567 pub units: i32,
569}
570
571#[non_exhaustive]
573#[derive(Clone, Debug, PartialEq, Default)]
574pub struct DimStyle {
575 pub name: Name,
576 pub arrow_size: f64,
578 pub scale: f64,
579}
580
581#[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#[non_exhaustive]
612#[derive(Clone, Debug, PartialEq)]
613pub struct Header {
614 pub version: String,
616 pub codepage: String,
617 pub insunits: i32,
619 pub ltscale: f64,
621 pub lwdisplay: Option<bool>,
623 pub lwdefault: u16,
624 pub pdmode: i32,
626 pub pdsize: f64,
627 pub extmin: Option<P3>,
629 pub extmax: Option<P3>,
630 pub dimscale: f64,
632 pub dimasz: f64,
633 pub textsize: f64,
634 pub mirrtext: bool,
635 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#[non_exhaustive]
649#[derive(Clone, Debug, Default)]
650pub struct Block {
651 pub name: Name,
652 pub base: P3,
653 pub flags: u32,
654 pub xref: String,
656 pub entities: Vec<Entity>,
657 pub paper: bool,
659}
660
661#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
663pub enum Where {
664 Entities,
665 Blocks,
666}
667
668#[non_exhaustive]
670#[derive(Clone, Debug, Default)]
671pub struct Stats {
672 pub kinds: BTreeMap<(Where, String), u64>,
674 pub paper: u64,
676 pub bytes: u64,
678 pub lines: u64,
679 pub pairs: u64,
680 pub sections: Vec<String>,
682 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 pub fn count(&self, w: Where, kind: &str) -> u64 {
695 self.kinds.get(&(w, String::from(kind))).copied().unwrap_or(0)
696 }
697}
698
699pub 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#[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 pub fn name(&self, n: Name) -> &str {
724 self.names.get(n)
725 }
726
727 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
752pub 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
768pub 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
775pub fn is_binary(bytes: &[u8]) -> bool {
777 bytes.starts_with(b"AutoCAD Binary DXF")
778}
779
780pub 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 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}