Skip to main content

cadkit_core/
model.rs

1//! Format-neutral drawing model.
2//!
3//! Every reader (DWG, DGN, DXF) produces a [`Document`]. The model keeps the
4//! common CAD semantics typed and pushes format-specific details into
5//! [`Props`] under a format prefix (`dgn.`, `dwg.`, `dxf.`), so nothing a
6//! reader understood is thrown away.
7//!
8//! Conventions:
9//! - Coordinates are in drawing units (see [`Units`]); DGN UORs are already
10//!   converted to master units.
11//! - **Every point and vector is in world coordinates (WCS).** Readers convert
12//!   DWG/DXF object coordinates (OCS) to WCS; there is no OCS in this model.
13//! - Planar entities carry a `normal` that defines their plane. Angles
14//!   (arc start/end, text/insert rotation, hatch pattern angle) are radians,
15//!   counter-clockwise about that normal, measured from the plane's X axis as
16//!   given by the DXF arbitrary-axis algorithm (`geom_ops::arbitrary_axes`).
17//!   For `normal = +Z` this is the ordinary world X axis.
18//! - Ordered point lists (polyline vertices, face corners, hatch edges) are in
19//!   outline order. Readers fix format quirks such as DXF `SOLID` storing
20//!   corners 3 and 4 swapped.
21//! - Entities reference layers, blocks, linetypes and text styles by name.
22
23use std::collections::BTreeMap;
24
25use serde::{Deserialize, Serialize};
26
27use crate::geom::{Point3, Vec3};
28
29/// Format-specific extra data, keyed `"<format>.<name>"` (e.g. `"dgn.level_id"`).
30pub type Props = BTreeMap<String, Value>;
31
32/// A complete drawing.
33#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
34#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
35#[non_exhaustive]
36pub struct Document {
37    /// Version of this JSON layout; see [`SchemaVersion`].
38    #[serde(default)]
39    pub schema_version: SchemaVersion,
40    /// Where the data came from.
41    pub source: SourceInfo,
42    /// Unit of all coordinates in this document.
43    pub units: Units,
44    /// Layers (DWG/DXF layers, DGN levels).
45    pub layers: Vec<Layer>,
46    /// Linetype definitions.
47    pub linetypes: Vec<Linetype>,
48    /// Text style definitions.
49    pub text_styles: Vec<TextStyle>,
50    /// Block definitions (DWG/DXF blocks, DGN shared cell definitions).
51    pub blocks: Vec<Block>,
52    /// Model spaces, layouts and sheets that hold the drawn entities.
53    pub models: Vec<Model>,
54    /// Document-level extras (header variables, file properties).
55    pub props: Props,
56    /// Recoverable problems met while reading. A non-empty list does not mean failure.
57    pub warnings: Vec<Warning>,
58}
59
60impl Document {
61    /// Creates an empty drawing document.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Returns the primary design model (`ModelKind::Model`), falling back to the first model.
67    pub fn model_space(&self) -> Option<&Model> {
68        self.models
69            .iter()
70            .find(|m| m.kind == ModelKind::Model)
71            .or_else(|| self.models.first())
72    }
73
74    /// Returns a mutable reference to the primary design model, creating `"Model"` if `models` is empty.
75    pub fn model_space_mut(&mut self) -> &mut Model {
76        if self.models.is_empty() {
77            self.models.push(Model {
78                name: "Model".to_owned(),
79                kind: ModelKind::Model,
80                ..Model::default()
81            });
82        }
83        let idx = self
84            .models
85            .iter()
86            .position(|m| m.kind == ModelKind::Model)
87            .unwrap_or(0);
88        #[allow(clippy::expect_used)]
89        self.models
90            .get_mut(idx)
91            .expect("idx is in bounds of non-empty models")
92    }
93
94    /// Iterates over paper-space layout and sheet models (`kind != ModelKind::Model`).
95    pub fn layouts(&self) -> impl Iterator<Item = &Model> {
96        self.models.iter().filter(|m| m.kind != ModelKind::Model)
97    }
98
99    /// Iterates over top-level entities across all [`Document::models`].
100    pub fn all_entities(&self) -> impl Iterator<Item = &Entity> {
101        self.models.iter().flat_map(|m| m.entities.iter())
102    }
103
104    /// Iterates over top-level entities across all models whose effective layer matches `layer`
105    /// (treating `None` on an entity as layer `"0"`).
106    pub fn entities_on_layer<'a>(
107        &'a self,
108        layer: &'a str,
109    ) -> impl Iterator<Item = &'a Entity> + 'a {
110        self.all_entities()
111            .filter(move |e| e.layer.as_deref().unwrap_or("0") == layer)
112    }
113
114    /// Looks up a layer by exact name first, then ASCII case-insensitively.
115    pub fn layer(&self, name: &str) -> Option<&Layer> {
116        self.layers.iter().find(|l| l.name == name).or_else(|| {
117            self.layers
118                .iter()
119                .find(|l| l.name.eq_ignore_ascii_case(name))
120        })
121    }
122
123    /// Looks up a block definition by exact name first, then ASCII case-insensitively.
124    pub fn block(&self, name: &str) -> Option<&Block> {
125        self.blocks.iter().find(|b| b.name == name).or_else(|| {
126            self.blocks
127                .iter()
128                .find(|b| b.name.eq_ignore_ascii_case(name))
129        })
130    }
131
132    /// Total number of entities in [`Document::models`], counting nested [`EntityKind::Group`] children.
133    pub fn entity_count(&self) -> usize {
134        fn count_slice(slice: &[Entity]) -> usize {
135            let mut total = 0usize;
136            let mut stack: Vec<&[Entity]> = vec![slice];
137            while let Some(items) = stack.pop() {
138                total = total.saturating_add(items.len());
139                for e in items {
140                    if let EntityKind::Group { children, .. } = &e.kind
141                        && !children.is_empty()
142                    {
143                        stack.push(children);
144                    }
145                }
146            }
147            total
148        }
149        self.models.iter().fold(0usize, |acc, m| {
150            acc.saturating_add(count_slice(&m.entities))
151        })
152    }
153}
154
155/// Version of the [`Document`] JSON layout, serialized as the integer `schema_version`.
156///
157/// Every document this crate writes carries [`SchemaVersion::CURRENT`]. JSON without the
158/// field predates versioning and reads as version 1. [`crate::export::document_from_json`]
159/// rejects other versions with [`crate::Error::SchemaVersion`]. The version increases only
160/// when an existing field changes meaning or shape; new optional fields do not change it.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
162#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
163#[serde(transparent)]
164pub struct SchemaVersion(u32);
165
166impl SchemaVersion {
167    /// The version this crate reads and writes.
168    pub const CURRENT: Self = Self(1);
169
170    /// The version number.
171    pub const fn get(self) -> u32 {
172        self.0
173    }
174}
175
176impl Default for SchemaVersion {
177    fn default() -> Self {
178        Self::CURRENT
179    }
180}
181
182/// Origin of a [`Document`].
183#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
184#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
185#[non_exhaustive]
186pub struct SourceInfo {
187    /// File format family.
188    pub format: Format,
189    /// Format version as written in the file, e.g. `"AC1032"`, `"V8"`, `"V7"`.
190    pub version: String,
191    /// Producing application if recorded, e.g. `"MicroStation v8.11.9.578"`.
192    pub application: Option<String>,
193    /// Code page used for 8-bit strings, e.g. `"windows-1254"`.
194    pub codepage: Option<String>,
195}
196
197/// Lightweight header summary returned by header-only `inspect` routines without decoding entity streams.
198#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
200#[non_exhaustive]
201pub struct Summary {
202    /// File format family.
203    pub format: Format,
204    /// Format version as written in the file, e.g. `"AC1032"`, `"V8"`, `"V7"`, `"2.0"`.
205    pub version: String,
206    /// Whether the primary model is 3D, when recorded in the header.
207    pub is_3d: Option<bool>,
208    /// Drawing coordinate units, when recorded in the header.
209    pub units: Option<Units>,
210    /// Code page or encoding name recorded or implied by the header.
211    pub codepage: Option<String>,
212    /// Producing application if recorded in the header.
213    pub application: Option<String>,
214}
215
216impl Summary {
217    /// Creates a new header summary for `format` and `version`.
218    #[must_use]
219    pub fn new(format: Format, version: impl Into<String>) -> Self {
220        Self {
221            format,
222            version: version.into(),
223            is_3d: None,
224            units: None,
225            codepage: None,
226            application: None,
227        }
228    }
229
230    /// Sets [`Self::is_3d`].
231    #[must_use]
232    pub fn with_is_3d(mut self, is_3d: Option<bool>) -> Self {
233        self.is_3d = is_3d;
234        self
235    }
236
237    /// Sets [`Self::units`].
238    #[must_use]
239    pub fn with_units(mut self, units: Option<Units>) -> Self {
240        self.units = units;
241        self
242    }
243
244    /// Sets [`Self::codepage`].
245    #[must_use]
246    pub fn with_codepage(mut self, codepage: Option<String>) -> Self {
247        self.codepage = codepage;
248        self
249    }
250
251    /// Sets [`Self::application`].
252    #[must_use]
253    pub fn with_application(mut self, application: Option<String>) -> Self {
254        self.application = application;
255        self
256    }
257}
258
259/// File format family.
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
261#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
262#[serde(rename_all = "snake_case")]
263#[non_exhaustive]
264pub enum Format {
265    /// Not known (e.g. a document built in memory).
266    #[default]
267    Unknown,
268    /// AutoCAD DWG.
269    Dwg,
270    /// AutoCAD DXF (ASCII or binary).
271    Dxf,
272    /// MicroStation DGN V7 (ISFF).
273    DgnV7,
274    /// MicroStation DGN V8 (OLE compound file).
275    DgnV8,
276    /// CityGML 2.0 (XML application schema based on GML 3.1.1).
277    CityGml,
278}
279
280/// Drawing units.
281#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
282#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
283#[non_exhaustive]
284pub struct Units {
285    /// Named unit of the coordinates.
286    pub unit: LengthUnit,
287    /// Size of one drawing unit in meters, when known. Authoritative over `unit`
288    /// for non-standard DGN master units.
289    pub meters_per_unit: Option<f64>,
290}
291
292/// Length unit. Mirrors the DWG `$INSUNITS` set.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
294#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
295#[serde(rename_all = "snake_case")]
296#[allow(missing_docs)]
297pub enum LengthUnit {
298    #[default]
299    Unitless,
300    Inch,
301    Foot,
302    Mile,
303    Millimeter,
304    Centimeter,
305    Meter,
306    Kilometer,
307    Microinch,
308    Mil,
309    Yard,
310    Angstrom,
311    Nanometer,
312    Micrometer,
313    Decimeter,
314    Decameter,
315    Hectometer,
316    Gigameter,
317    AstronomicalUnit,
318    LightYear,
319    Parsec,
320    UsSurveyFoot,
321    /// A unit that is not in this list; see [`Units::meters_per_unit`].
322    Custom,
323}
324
325/// A layer (DGN: level).
326#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
327#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
328#[non_exhaustive]
329pub struct Layer {
330    /// Unique name.
331    pub name: String,
332    /// Native identifier (DWG handle, DGN level id).
333    pub id: Option<u64>,
334    /// Default color of entities on this layer.
335    pub color: Color,
336    /// Default linetype name.
337    pub linetype: Option<String>,
338    /// Default lineweight.
339    pub lineweight: Lineweight,
340    /// Layer is on / displayed.
341    pub visible: bool,
342    /// Layer is frozen.
343    pub frozen: bool,
344    /// Layer is locked.
345    pub locked: bool,
346    /// Layer is plotted.
347    pub plottable: bool,
348    /// Free-text description.
349    pub description: Option<String>,
350    /// Format-specific extras.
351    pub props: Props,
352}
353
354/// A linetype definition.
355#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
356#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
357#[non_exhaustive]
358pub struct Linetype {
359    /// Unique name.
360    pub name: String,
361    /// Description text.
362    pub description: Option<String>,
363    /// Dash pattern in drawing units: positive = dash, negative = gap, zero = dot.
364    pub pattern: Vec<f64>,
365    /// Format-specific extras.
366    pub props: Props,
367}
368
369/// A text style definition.
370#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
371#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
372#[non_exhaustive]
373pub struct TextStyle {
374    /// Unique name.
375    pub name: String,
376    /// Font file or font name.
377    pub font: Option<String>,
378    /// Fixed text height, 0 when variable.
379    pub height: f64,
380    /// Width factor (1.0 = normal).
381    pub width_factor: f64,
382    /// Oblique angle in radians.
383    pub oblique: f64,
384    /// Format-specific extras.
385    pub props: Props,
386}
387
388/// A block definition (DGN: shared cell definition).
389#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
390#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
391#[non_exhaustive]
392pub struct Block {
393    /// Unique name.
394    pub name: String,
395    /// Native identifier.
396    pub id: Option<u64>,
397    /// Insertion base point.
398    pub base_point: Point3,
399    /// Entities in block coordinates.
400    pub entities: Vec<Entity>,
401    /// Block is an external reference.
402    pub is_xref: bool,
403    /// Path of the external reference.
404    pub xref_path: Option<String>,
405    /// Description text.
406    pub description: Option<String>,
407    /// Format-specific extras.
408    pub props: Props,
409}
410
411/// A space that holds drawn entities: model space, a paper-space layout or a DGN model.
412#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
413#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414#[non_exhaustive]
415pub struct Model {
416    /// Display name.
417    pub name: String,
418    /// Native identifier.
419    pub id: Option<u64>,
420    /// Kind of space.
421    pub kind: ModelKind,
422    /// Model stores 3D geometry.
423    pub is_3d: bool,
424    /// Entities in drawing order.
425    pub entities: Vec<Entity>,
426    /// Format-specific extras.
427    pub props: Props,
428}
429
430/// Kind of [`Model`].
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
432#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
433#[serde(rename_all = "snake_case")]
434#[non_exhaustive]
435pub enum ModelKind {
436    /// Design / model space.
437    #[default]
438    Model,
439    /// Paper-space layout (DWG/DXF).
440    Layout,
441    /// Sheet model (DGN).
442    Sheet,
443}
444
445/// One drawn object.
446#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
447#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
448#[non_exhaustive]
449pub struct Entity {
450    /// Native identifier (DWG handle, DGN element id).
451    pub id: Option<u64>,
452    /// Layer name; `None` means the default layer.
453    pub layer: Option<String>,
454    /// Color.
455    pub color: Color,
456    /// Linetype name; `None` means by layer.
457    pub linetype: Option<String>,
458    /// Lineweight.
459    pub lineweight: Lineweight,
460    /// Entity is displayed.
461    pub visible: bool,
462    /// Geometry and type-specific data.
463    pub kind: EntityKind,
464    /// Attached non-graphic data: DWG attributes, DGN tags, item-type properties.
465    pub attributes: Vec<Attribute>,
466    /// Format-specific extras.
467    pub props: Props,
468    /// Original record bytes, kept only when [`crate::ReadOptions::keep_raw`] is set.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub raw: Option<Raw>,
471}
472
473impl Entity {
474    /// An entity with default symbology.
475    pub fn new(kind: EntityKind) -> Self {
476        Self {
477            id: None,
478            layer: None,
479            color: Color::ByLayer,
480            linetype: None,
481            lineweight: Lineweight::ByLayer,
482            visible: true,
483            kind,
484            attributes: Vec::new(),
485            props: Props::new(),
486            raw: None,
487        }
488    }
489
490    /// Constructs a [`EntityKind::Point`] entity.
491    pub fn point(position: Point3) -> Self {
492        Self::new(EntityKind::Point { position })
493    }
494
495    /// Constructs a [`EntityKind::Line`] entity.
496    pub fn line(start: Point3, end: Point3) -> Self {
497        Self::new(EntityKind::Line { start, end })
498    }
499
500    /// Constructs a straight-segment [`EntityKind::Polyline`] in the world XY plane (`normal = +Z`).
501    pub fn polyline(points: impl IntoIterator<Item = Point3>, closed: bool) -> Self {
502        Self::new(EntityKind::Polyline {
503            vertices: points.into_iter().map(Vertex::at).collect(),
504            closed,
505            normal: Vec3::Z,
506        })
507    }
508
509    /// Constructs a [`EntityKind::Circle`] in the world XY plane (`normal = +Z`).
510    pub fn circle(center: Point3, radius: f64) -> Self {
511        Self::new(EntityKind::Circle {
512            center,
513            radius,
514            normal: Vec3::Z,
515        })
516    }
517
518    /// Constructs a counter-clockwise [`EntityKind::Arc`] in the world XY plane (`normal = +Z`).
519    pub fn arc(center: Point3, radius: f64, start_angle: f64, end_angle: f64) -> Self {
520        Self::new(EntityKind::Arc {
521            center,
522            radius,
523            start_angle,
524            end_angle,
525            normal: Vec3::Z,
526        })
527    }
528
529    /// Constructs a left-baseline [`EntityKind::Text`] entity in the world XY plane (`normal = +Z`).
530    pub fn text(position: Point3, height: f64, value: impl Into<String>) -> Self {
531        Self::new(EntityKind::Text {
532            position,
533            end_point: None,
534            height,
535            rotation: 0.0,
536            width_factor: 1.0,
537            oblique: 0.0,
538            value: value.into(),
539            style: None,
540            halign: HAlign::Left,
541            valign: VAlign::Baseline,
542            normal: Vec3::Z,
543        })
544    }
545
546    /// Constructs a top-left [`EntityKind::MText`] entity from plain UTF-8 text.
547    pub fn mtext(position: Point3, height: f64, plain: impl Into<String>) -> Self {
548        let plain = plain.into();
549        let value = plain.replace('\n', "\\P");
550        Self::new(EntityKind::MText {
551            position,
552            height,
553            width: 0.0,
554            rotation: 0.0,
555            value,
556            plain,
557            style: None,
558            attachment: Attachment::TopLeft,
559            line_spacing: 1.0,
560            normal: Vec3::Z,
561        })
562    }
563
564    /// Constructs a unit-scale [`EntityKind::Insert`] block reference at `position`.
565    pub fn insert(block: impl Into<String>, position: Point3) -> Self {
566        Self::new(EntityKind::Insert {
567            block: block.into(),
568            position,
569            scale: Vec3::ONE,
570            rotation: 0.0,
571            normal: Vec3::Z,
572            columns: 1,
573            rows: 1,
574            column_spacing: 0.0,
575            row_spacing: 0.0,
576        })
577    }
578
579    /// Assigns the entity's layer name.
580    pub fn on_layer(mut self, layer: impl Into<String>) -> Self {
581        self.layer = Some(layer.into());
582        self
583    }
584
585    /// Assigns the entity's [`Color`].
586    pub fn with_color(mut self, color: Color) -> Self {
587        self.color = color;
588        self
589    }
590
591    /// Assigns the entity's linetype name.
592    pub fn with_linetype(mut self, linetype: impl Into<String>) -> Self {
593        self.linetype = Some(linetype.into());
594        self
595    }
596
597    /// Assigns the entity's [`Lineweight`].
598    pub fn with_lineweight(mut self, lineweight: Lineweight) -> Self {
599        self.lineweight = lineweight;
600        self
601    }
602
603    /// Sets [`Entity::visible`].
604    pub fn with_visible(mut self, visible: bool) -> Self {
605        self.visible = visible;
606        self
607    }
608
609    /// Inserts a key-value entry into [`Entity::props`].
610    pub fn with_prop(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
611        self.props.insert(key.into(), value.into());
612        self
613    }
614
615    /// Appends a non-graphic [`Attribute`] tag/value pair to [`Entity::attributes`].
616    pub fn with_attribute(mut self, tag: impl Into<String>, value: impl Into<Value>) -> Self {
617        self.attributes.push(Attribute {
618            tag: tag.into(),
619            value: value.into(),
620            invisible: true,
621            ..Attribute::default()
622        });
623        self
624    }
625}
626
627/// Geometry and type-specific data of an [`Entity`].
628#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
630#[serde(tag = "type", rename_all = "snake_case")]
631#[non_exhaustive]
632pub enum EntityKind {
633    /// A point.
634    Point {
635        /// Location.
636        position: Point3,
637    },
638    /// A straight segment.
639    Line {
640        /// Start point.
641        start: Point3,
642        /// End point.
643        end: Point3,
644    },
645    /// Connected segments, optionally with arc segments (bulge) and widths.
646    /// Covers DWG LWPOLYLINE/POLYLINE and DGN line string / shape.
647    Polyline {
648        /// Vertices in order.
649        vertices: Vec<Vertex>,
650        /// Last vertex connects back to the first.
651        closed: bool,
652        /// Plane normal; bulge arcs turn counter-clockwise about it. `+Z` for plain 2D data
653        /// and for non-planar 3D polylines (which have no bulges).
654        normal: Vec3,
655    },
656    /// A full circle.
657    Circle {
658        /// Center.
659        center: Point3,
660        /// Radius.
661        radius: f64,
662        /// Plane normal.
663        normal: Vec3,
664    },
665    /// A circular arc from `start_angle` counter-clockwise to `end_angle`.
666    Arc {
667        /// Center.
668        center: Point3,
669        /// Radius.
670        radius: f64,
671        /// Start angle in radians.
672        start_angle: f64,
673        /// End angle in radians.
674        end_angle: f64,
675        /// Plane normal.
676        normal: Vec3,
677    },
678    /// An ellipse or elliptical arc.
679    Ellipse {
680        /// Center.
681        center: Point3,
682        /// Vector from the center to the end of the major axis (its length is the semi-major axis).
683        major_axis: Vec3,
684        /// Minor / major axis ratio, in (0, 1].
685        ratio: f64,
686        /// Start parameter in radians (0 for a full ellipse).
687        start_param: f64,
688        /// End parameter in radians (2π for a full ellipse).
689        end_param: f64,
690        /// Plane normal.
691        normal: Vec3,
692    },
693    /// A B-spline / NURBS curve.
694    Spline {
695        /// Degree.
696        degree: u32,
697        /// Knot vector (may be empty when only fit points are known).
698        knots: Vec<f64>,
699        /// Control points.
700        control_points: Vec<Point3>,
701        /// Weights; empty for non-rational curves.
702        weights: Vec<f64>,
703        /// Fit points, if stored.
704        fit_points: Vec<Point3>,
705        /// Curve is closed / periodic.
706        closed: bool,
707    },
708    /// Single-line text.
709    Text {
710        /// Anchor point implied by `halign`/`valign`: the baseline start for left/baseline
711        /// text, otherwise the justification point (DXF/DWG second alignment point, group 11).
712        /// For `Aligned`/`Fit` text: the baseline start.
713        position: Point3,
714        /// Baseline end for `Aligned`/`Fit` text; `None` for every other alignment.
715        end_point: Option<Point3>,
716        /// Character height.
717        height: f64,
718        /// Rotation in radians.
719        rotation: f64,
720        /// Width factor (1.0 = normal).
721        width_factor: f64,
722        /// Oblique angle in radians.
723        oblique: f64,
724        /// Decoded text.
725        value: String,
726        /// Text style name.
727        style: Option<String>,
728        /// Horizontal alignment.
729        halign: HAlign,
730        /// Vertical alignment.
731        valign: VAlign,
732        /// Plane normal.
733        normal: Vec3,
734    },
735    /// Multi-line, formatted text. DGN text nodes map to this when they only hold text.
736    MText {
737        /// Insertion point.
738        position: Point3,
739        /// Character height.
740        height: f64,
741        /// Reference rectangle width, 0 when unconstrained.
742        width: f64,
743        /// Rotation in radians.
744        rotation: f64,
745        /// Text including format codes as stored.
746        value: String,
747        /// Text with format codes removed, lines separated by `\n`.
748        plain: String,
749        /// Text style name.
750        style: Option<String>,
751        /// Attachment point.
752        attachment: Attachment,
753        /// Line spacing factor.
754        line_spacing: f64,
755        /// Plane normal.
756        normal: Vec3,
757    },
758    /// A placed block (DWG INSERT, DGN shared cell instance).
759    /// Attribute values live in [`Entity::attributes`].
760    Insert {
761        /// Block name.
762        block: String,
763        /// Insertion point.
764        position: Point3,
765        /// Scale factors.
766        scale: Vec3,
767        /// Rotation in radians.
768        rotation: f64,
769        /// Plane normal.
770        normal: Vec3,
771        /// Array columns (1 = no array).
772        columns: u32,
773        /// Array rows (1 = no array).
774        rows: u32,
775        /// Column spacing.
776        column_spacing: f64,
777        /// Row spacing.
778        row_spacing: f64,
779    },
780    /// A filled or patterned area.
781    Hatch {
782        /// Boundary loops; the first is usually the outer one.
783        loops: Vec<HatchLoop>,
784        /// Solid fill.
785        solid: bool,
786        /// Pattern name, if patterned.
787        pattern: Option<String>,
788        /// Pattern scale.
789        pattern_scale: f64,
790        /// Pattern angle in radians.
791        pattern_angle: f64,
792        /// Plane normal.
793        normal: Vec3,
794    },
795    /// A dimension annotation.
796    Dimension {
797        /// Kind of dimension.
798        dimension_type: DimensionType,
799        /// Definition points in format order (see `props` for their roles).
800        points: Vec<Point3>,
801        /// Text middle point.
802        text_position: Option<Point3>,
803        /// Measured value in drawing units (or radians for angular).
804        measurement: Option<f64>,
805        /// Text override.
806        text: Option<String>,
807        /// Anonymous block holding the rendered dimension, if any.
808        block: Option<String>,
809        /// Dimension style name.
810        style: Option<String>,
811    },
812    /// A planar 3- or 4-sided face (DWG SOLID/TRACE/3DFACE).
813    Face {
814        /// Corner points (3 or 4).
815        points: Vec<Point3>,
816        /// The face is filled (SOLID/TRACE) rather than a wire face.
817        filled: bool,
818    },
819    /// A planar surface with optional holes, in world coordinates (WCS) and drawing units.
820    /// Each ring is explicitly closed by repeating its first point as its last point.
821    Polygon {
822        /// Closed outer boundary ring containing at least four positions.
823        exterior: Vec<Point3>,
824        /// Closed hole rings inside the exterior boundary.
825        interiors: Vec<Vec<Point3>>,
826    },
827    /// A leader line.
828    Leader {
829        /// Vertices from arrow tip to the end.
830        vertices: Vec<Point3>,
831        /// Draws an arrowhead at the first vertex.
832        arrowhead: bool,
833    },
834    /// A raster image reference (DWG IMAGE, DGN raster attachment).
835    Image {
836        /// Image file path as stored.
837        path: Option<String>,
838        /// Lower-left corner.
839        position: Point3,
840        /// Vector along the image bottom edge, covering the full width.
841        u_vector: Vec3,
842        /// Vector along the image left edge, covering the full height.
843        v_vector: Vec3,
844        /// Pixel size, when known.
845        size_px: Option<[u32; 2]>,
846    },
847    /// A paper-space viewport.
848    Viewport {
849        /// Center on the sheet.
850        center: Point3,
851        /// Width on the sheet.
852        width: f64,
853        /// Height on the sheet.
854        height: f64,
855        /// Model-space point shown at the center.
856        view_center: Point3,
857        /// Model-space height shown.
858        view_height: f64,
859    },
860    /// A polygon mesh or polyface.
861    Mesh {
862        /// Vertex positions.
863        vertices: Vec<Point3>,
864        /// Faces as vertex indices (0-based).
865        faces: Vec<Vec<u32>>,
866    },
867    /// Entities that belong together: DGN complex chains/shapes, cells, text nodes, groups.
868    /// Children are in the same coordinate space as the group.
869    Group {
870        /// What kind of grouping this is.
871        group_kind: GroupKind,
872        /// Name (cell name, group name).
873        name: Option<String>,
874        /// Origin (cell origin, text node origin).
875        origin: Option<Point3>,
876        /// Member entities.
877        children: Vec<Entity>,
878    },
879    /// A record the reader recognized but does not model; see `props` / `raw`.
880    Unknown {
881        /// Native type name or code, e.g. `"dgn.type_94"` or `"dwg.ACAD_TABLE"`.
882        type_name: String,
883    },
884}
885
886/// Polyline vertex.
887#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
888#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
889pub struct Vertex {
890    /// Position.
891    pub position: Point3,
892    /// Bulge of the segment that starts here: tan(included angle / 4), 0 = straight.
893    pub bulge: f64,
894    /// Start width of the segment that starts here.
895    pub start_width: f64,
896    /// End width of the segment that starts here.
897    pub end_width: f64,
898}
899
900impl Vertex {
901    /// A straight, zero-width vertex.
902    pub fn at(position: Point3) -> Self {
903        Self {
904            position,
905            ..Self::default()
906        }
907    }
908}
909
910/// Horizontal text alignment.
911#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
913#[serde(rename_all = "snake_case")]
914#[allow(missing_docs)]
915pub enum HAlign {
916    #[default]
917    Left,
918    Center,
919    Right,
920    Aligned,
921    Middle,
922    Fit,
923}
924
925/// Vertical text alignment.
926#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
927#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
928#[serde(rename_all = "snake_case")]
929#[allow(missing_docs)]
930pub enum VAlign {
931    #[default]
932    Baseline,
933    Bottom,
934    Middle,
935    Top,
936}
937
938/// Multi-line text attachment point.
939#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
940#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
941#[serde(rename_all = "snake_case")]
942#[allow(missing_docs)]
943pub enum Attachment {
944    #[default]
945    TopLeft,
946    TopCenter,
947    TopRight,
948    MiddleLeft,
949    MiddleCenter,
950    MiddleRight,
951    BottomLeft,
952    BottomCenter,
953    BottomRight,
954}
955
956/// Dimension kind.
957#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
958#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
959#[serde(rename_all = "snake_case")]
960#[allow(missing_docs)]
961pub enum DimensionType {
962    #[default]
963    Linear,
964    Aligned,
965    Angular,
966    Angular3Point,
967    Diameter,
968    Radius,
969    Ordinate,
970    ArcLength,
971    Other,
972}
973
974/// What a [`EntityKind::Group`] represents.
975#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
976#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
977#[serde(rename_all = "snake_case")]
978#[non_exhaustive]
979pub enum GroupKind {
980    /// DGN complex chain (open).
981    ComplexChain,
982    /// DGN complex shape (closed).
983    ComplexShape,
984    /// DGN text node.
985    TextNode,
986    /// DGN cell (children inline, already placed).
987    Cell,
988    /// Any other grouping.
989    #[default]
990    Other,
991}
992
993/// One hatch boundary loop.
994#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
995#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
996pub struct HatchLoop {
997    /// Edges in order.
998    pub edges: Vec<HatchEdge>,
999    /// Loop is the outermost boundary.
1000    pub external: bool,
1001}
1002
1003/// A hatch boundary edge.
1004#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1005#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1006#[serde(tag = "type", rename_all = "snake_case")]
1007#[allow(missing_docs)]
1008pub enum HatchEdge {
1009    Line {
1010        start: Point3,
1011        end: Point3,
1012    },
1013    Arc {
1014        center: Point3,
1015        radius: f64,
1016        start_angle: f64,
1017        end_angle: f64,
1018        ccw: bool,
1019    },
1020    Ellipse {
1021        center: Point3,
1022        major_axis: Vec3,
1023        ratio: f64,
1024        start_param: f64,
1025        end_param: f64,
1026        ccw: bool,
1027    },
1028    Spline {
1029        degree: u32,
1030        knots: Vec<f64>,
1031        control_points: Vec<Point3>,
1032        weights: Vec<f64>,
1033    },
1034    Polyline {
1035        vertices: Vec<Vertex>,
1036        closed: bool,
1037    },
1038}
1039
1040/// Color.
1041#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
1042#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1043#[serde(tag = "type", rename_all = "snake_case")]
1044pub enum Color {
1045    /// Use the layer color.
1046    #[default]
1047    ByLayer,
1048    /// Use the color of the inserting block reference.
1049    ByBlock,
1050    /// AutoCAD Color Index 1..=255. DGN palette indices are resolved to [`Color::Rgb`]
1051    /// by the DGN reader; the original index goes to `props["dgn.color_index"]`.
1052    Aci {
1053        /// Index.
1054        index: u8,
1055    },
1056    /// True color.
1057    Rgb {
1058        /// Red.
1059        r: u8,
1060        /// Green.
1061        g: u8,
1062        /// Blue.
1063        b: u8,
1064    },
1065}
1066
1067impl Color {
1068    /// Shorthand for `Color::Aci { index }`.
1069    pub const fn aci(index: u8) -> Self {
1070        Self::Aci { index }
1071    }
1072
1073    /// Shorthand for `Color::Rgb { r, g, b }`.
1074    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
1075        Self::Rgb { r, g, b }
1076    }
1077}
1078
1079/// Line weight.
1080#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
1081#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1082#[serde(tag = "type", content = "value", rename_all = "snake_case")]
1083pub enum Lineweight {
1084    /// Use the layer lineweight.
1085    #[default]
1086    ByLayer,
1087    /// Use the block reference lineweight.
1088    ByBlock,
1089    /// Application default.
1090    Default,
1091    /// Explicit width in millimeters. DGN weight steps are converted; the original goes to props.
1092    Millimeters(f64),
1093}
1094
1095/// Non-graphic data attached to an entity (DWG ATTRIB, DGN tag, item-type property).
1096#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1097#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1098#[non_exhaustive]
1099pub struct Attribute {
1100    /// Tag / property name.
1101    pub tag: String,
1102    /// Value.
1103    pub value: Value,
1104    /// Owning tag set / item type / definition name.
1105    pub set: Option<String>,
1106    /// Where the attribute text is displayed, if it is displayed.
1107    pub position: Option<Point3>,
1108    /// The attribute is not displayed.
1109    pub invisible: bool,
1110    /// Layer of the attribute's own record when the format stores one (a DGN tag
1111    /// element has its own level). `None` uses the owning entity's layer.
1112    #[serde(default, skip_serializing_if = "Option::is_none")]
1113    pub layer: Option<String>,
1114    /// How the value text is drawn at `position`; `None` when unknown or not drawn.
1115    #[serde(default, skip_serializing_if = "Option::is_none")]
1116    pub display: Option<AttributeDisplay>,
1117    /// Color of the attribute's own record when the format stores one that differs from
1118    /// the owning entity's (a DGN tag element has its own symbology; the DGN reader
1119    /// resolves it through the file's color table as it does for entities). `None` uses
1120    /// the owning entity's color.
1121    #[serde(default, skip_serializing_if = "Option::is_none")]
1122    pub color: Option<Color>,
1123    /// Lineweight of the attribute's own record when the format stores one that differs
1124    /// from the owning entity's. `None` uses the owning entity's lineweight.
1125    #[serde(default, skip_serializing_if = "Option::is_none")]
1126    pub lineweight: Option<Lineweight>,
1127    /// Format-specific data with no neutral field (e.g. `dgn.color_index`, `dgn.weight`).
1128    #[serde(default, skip_serializing_if = "Props::is_empty")]
1129    pub props: Props,
1130}
1131
1132/// Text presentation of a displayed attribute value.
1133#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1135#[non_exhaustive]
1136pub struct AttributeDisplay {
1137    /// Text height, in drawing units.
1138    pub height: f64,
1139    /// Character width, in drawing units (DGN stores it separately from the height).
1140    pub width: f64,
1141    /// Text style (DGN font) name; `None` leaves the choice to the writer's default.
1142    pub style: Option<String>,
1143    /// Horizontal alignment of the text about `Attribute::position`.
1144    pub halign: HAlign,
1145    /// Vertical alignment of the text about `Attribute::position`.
1146    pub valign: VAlign,
1147    /// Rotation about the drawing Z axis, in radians.
1148    pub rotation: f64,
1149}
1150
1151/// A loosely typed value for attributes and props.
1152#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1153#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1154#[serde(untagged)]
1155#[non_exhaustive]
1156pub enum Value {
1157    /// No value.
1158    #[default]
1159    Null,
1160    /// Boolean.
1161    Bool(bool),
1162    /// Integer.
1163    Int(i64),
1164    /// Floating point.
1165    Float(f64),
1166    /// Text.
1167    Text(String),
1168    /// Ordered list.
1169    List(Vec<Value>),
1170    /// Binary data.
1171    Bytes(Vec<u8>),
1172}
1173
1174impl Value {
1175    /// True when `self` is [`Value::Null`].
1176    pub const fn is_null(&self) -> bool {
1177        matches!(self, Self::Null)
1178    }
1179
1180    /// Returns the boolean when `self` is [`Value::Bool`].
1181    pub const fn as_bool(&self) -> Option<bool> {
1182        match self {
1183            Self::Bool(v) => Some(*v),
1184            _ => None,
1185        }
1186    }
1187
1188    /// Returns the integer when `self` is [`Value::Int`].
1189    pub const fn as_i64(&self) -> Option<i64> {
1190        match self {
1191            Self::Int(v) => Some(*v),
1192            _ => None,
1193        }
1194    }
1195
1196    /// Returns a floating-point number for [`Value::Float`] or lossless/cast [`Value::Int`].
1197    pub const fn as_f64(&self) -> Option<f64> {
1198        match self {
1199            Self::Float(v) => Some(*v),
1200            Self::Int(v) => Some(*v as f64),
1201            _ => None,
1202        }
1203    }
1204
1205    /// Returns the string slice when `self` is [`Value::Text`].
1206    pub fn as_str(&self) -> Option<&str> {
1207        match self {
1208            Self::Text(s) => Some(s.as_str()),
1209            _ => None,
1210        }
1211    }
1212
1213    /// Returns the slice when `self` is [`Value::List`].
1214    pub fn as_list(&self) -> Option<&[Value]> {
1215        match self {
1216            Self::List(items) => Some(items.as_slice()),
1217            _ => None,
1218        }
1219    }
1220
1221    /// Returns the byte slice when `self` is [`Value::Bytes`].
1222    pub fn as_bytes(&self) -> Option<&[u8]> {
1223        match self {
1224            Self::Bytes(bytes) => Some(bytes.as_slice()),
1225            _ => None,
1226        }
1227    }
1228}
1229
1230impl From<bool> for Value {
1231    fn from(v: bool) -> Self {
1232        Value::Bool(v)
1233    }
1234}
1235impl From<i64> for Value {
1236    fn from(v: i64) -> Self {
1237        Value::Int(v)
1238    }
1239}
1240impl From<i32> for Value {
1241    fn from(v: i32) -> Self {
1242        Value::Int(i64::from(v))
1243    }
1244}
1245impl From<i16> for Value {
1246    fn from(v: i16) -> Self {
1247        Value::Int(i64::from(v))
1248    }
1249}
1250impl From<u32> for Value {
1251    fn from(v: u32) -> Self {
1252        Value::Int(i64::from(v))
1253    }
1254}
1255impl From<u16> for Value {
1256    fn from(v: u16) -> Self {
1257        Value::Int(i64::from(v))
1258    }
1259}
1260impl From<u8> for Value {
1261    fn from(v: u8) -> Self {
1262        Value::Int(i64::from(v))
1263    }
1264}
1265impl From<f64> for Value {
1266    fn from(v: f64) -> Self {
1267        Value::Float(v)
1268    }
1269}
1270impl From<f32> for Value {
1271    fn from(v: f32) -> Self {
1272        Value::Float(f64::from(v))
1273    }
1274}
1275impl From<String> for Value {
1276    fn from(v: String) -> Self {
1277        Value::Text(v)
1278    }
1279}
1280impl From<&str> for Value {
1281    fn from(v: &str) -> Self {
1282        Value::Text(v.to_owned())
1283    }
1284}
1285impl From<Vec<u8>> for Value {
1286    fn from(v: Vec<u8>) -> Self {
1287        Value::Bytes(v)
1288    }
1289}
1290impl From<Vec<Value>> for Value {
1291    fn from(v: Vec<Value>) -> Self {
1292        Value::List(v)
1293    }
1294}
1295
1296/// Original bytes of a record, for lossless inspection.
1297#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1298#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1299pub struct Raw {
1300    /// Native type code (DGN element type, DWG object type).
1301    pub type_code: u32,
1302    /// Record bytes exactly as stored (after decompression).
1303    pub bytes: Vec<u8>,
1304}
1305
1306/// A recoverable problem found while reading.
1307#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1308#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1309#[non_exhaustive]
1310pub struct Warning {
1311    /// Stable machine-readable code, e.g. `"dgn.unknown_element"`.
1312    pub code: String,
1313    /// Human-readable explanation.
1314    pub message: String,
1315    /// Byte offset in the decoded stream, when meaningful.
1316    pub offset: Option<u64>,
1317    /// Native id of the affected object, when known.
1318    pub object: Option<u64>,
1319}