use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::geom::{Point3, Vec3};
pub type Props = BTreeMap<String, Value>;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Document {
pub source: SourceInfo,
pub units: Units,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub blocks: Vec<Block>,
pub models: Vec<Model>,
pub props: Props,
pub warnings: Vec<Warning>,
}
impl Document {
pub fn new() -> Self {
Self::default()
}
pub fn model_space(&self) -> Option<&Model> {
self.models
.iter()
.find(|m| m.kind == ModelKind::Model)
.or_else(|| self.models.first())
}
pub fn model_space_mut(&mut self) -> &mut Model {
if self.models.is_empty() {
self.models.push(Model {
name: "Model".to_owned(),
kind: ModelKind::Model,
..Model::default()
});
}
let idx = self
.models
.iter()
.position(|m| m.kind == ModelKind::Model)
.unwrap_or(0);
#[allow(clippy::expect_used)]
self.models
.get_mut(idx)
.expect("idx is in bounds of non-empty models")
}
pub fn layouts(&self) -> impl Iterator<Item = &Model> {
self.models.iter().filter(|m| m.kind != ModelKind::Model)
}
pub fn all_entities(&self) -> impl Iterator<Item = &Entity> {
self.models.iter().flat_map(|m| m.entities.iter())
}
pub fn entities_on_layer<'a>(
&'a self,
layer: &'a str,
) -> impl Iterator<Item = &'a Entity> + 'a {
self.all_entities()
.filter(move |e| e.layer.as_deref().unwrap_or("0") == layer)
}
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name == name).or_else(|| {
self.layers
.iter()
.find(|l| l.name.eq_ignore_ascii_case(name))
})
}
pub fn block(&self, name: &str) -> Option<&Block> {
self.blocks.iter().find(|b| b.name == name).or_else(|| {
self.blocks
.iter()
.find(|b| b.name.eq_ignore_ascii_case(name))
})
}
pub fn entity_count(&self) -> usize {
fn count_slice(slice: &[Entity]) -> usize {
let mut total = 0usize;
let mut stack: Vec<&[Entity]> = vec![slice];
while let Some(items) = stack.pop() {
total = total.saturating_add(items.len());
for e in items {
if let EntityKind::Group { children, .. } = &e.kind {
if !children.is_empty() {
stack.push(children);
}
}
}
}
total
}
self.models.iter().fold(0usize, |acc, m| {
acc.saturating_add(count_slice(&m.entities))
})
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SourceInfo {
pub format: Format,
pub version: String,
pub application: Option<String>,
pub codepage: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Summary {
pub format: Format,
pub version: String,
pub is_3d: Option<bool>,
pub units: Option<Units>,
pub codepage: Option<String>,
pub application: Option<String>,
}
impl Summary {
#[must_use]
pub fn new(format: Format, version: impl Into<String>) -> Self {
Self {
format,
version: version.into(),
is_3d: None,
units: None,
codepage: None,
application: None,
}
}
#[must_use]
pub fn with_is_3d(mut self, is_3d: Option<bool>) -> Self {
self.is_3d = is_3d;
self
}
#[must_use]
pub fn with_units(mut self, units: Option<Units>) -> Self {
self.units = units;
self
}
#[must_use]
pub fn with_codepage(mut self, codepage: Option<String>) -> Self {
self.codepage = codepage;
self
}
#[must_use]
pub fn with_application(mut self, application: Option<String>) -> Self {
self.application = application;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Format {
#[default]
Unknown,
Dwg,
Dxf,
DgnV7,
DgnV8,
CityGml,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct Units {
pub unit: LengthUnit,
pub meters_per_unit: Option<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum LengthUnit {
#[default]
Unitless,
Inch,
Foot,
Mile,
Millimeter,
Centimeter,
Meter,
Kilometer,
Microinch,
Mil,
Yard,
Angstrom,
Nanometer,
Micrometer,
Decimeter,
Decameter,
Hectometer,
Gigameter,
AstronomicalUnit,
LightYear,
Parsec,
UsSurveyFoot,
Custom,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Layer {
pub name: String,
pub id: Option<u64>,
pub color: Color,
pub linetype: Option<String>,
pub lineweight: Lineweight,
pub visible: bool,
pub frozen: bool,
pub locked: bool,
pub plottable: bool,
pub description: Option<String>,
pub props: Props,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Linetype {
pub name: String,
pub description: Option<String>,
pub pattern: Vec<f64>,
pub props: Props,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TextStyle {
pub name: String,
pub font: Option<String>,
pub height: f64,
pub width_factor: f64,
pub oblique: f64,
pub props: Props,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Block {
pub name: String,
pub id: Option<u64>,
pub base_point: Point3,
pub entities: Vec<Entity>,
pub is_xref: bool,
pub xref_path: Option<String>,
pub description: Option<String>,
pub props: Props,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Model {
pub name: String,
pub id: Option<u64>,
pub kind: ModelKind,
pub is_3d: bool,
pub entities: Vec<Entity>,
pub props: Props,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelKind {
#[default]
Model,
Layout,
Sheet,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entity {
pub id: Option<u64>,
pub layer: Option<String>,
pub color: Color,
pub linetype: Option<String>,
pub lineweight: Lineweight,
pub visible: bool,
pub kind: EntityKind,
pub attributes: Vec<Attribute>,
pub props: Props,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw: Option<Raw>,
}
impl Entity {
pub fn new(kind: EntityKind) -> Self {
Self {
id: None,
layer: None,
color: Color::ByLayer,
linetype: None,
lineweight: Lineweight::ByLayer,
visible: true,
kind,
attributes: Vec::new(),
props: Props::new(),
raw: None,
}
}
pub fn point(position: Point3) -> Self {
Self::new(EntityKind::Point { position })
}
pub fn line(start: Point3, end: Point3) -> Self {
Self::new(EntityKind::Line { start, end })
}
pub fn polyline(points: impl IntoIterator<Item = Point3>, closed: bool) -> Self {
Self::new(EntityKind::Polyline {
vertices: points.into_iter().map(Vertex::at).collect(),
closed,
normal: Vec3::Z,
})
}
pub fn circle(center: Point3, radius: f64) -> Self {
Self::new(EntityKind::Circle {
center,
radius,
normal: Vec3::Z,
})
}
pub fn arc(center: Point3, radius: f64, start_angle: f64, end_angle: f64) -> Self {
Self::new(EntityKind::Arc {
center,
radius,
start_angle,
end_angle,
normal: Vec3::Z,
})
}
pub fn text(position: Point3, height: f64, value: impl Into<String>) -> Self {
Self::new(EntityKind::Text {
position,
end_point: None,
height,
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
value: value.into(),
style: None,
halign: HAlign::Left,
valign: VAlign::Baseline,
normal: Vec3::Z,
})
}
pub fn mtext(position: Point3, height: f64, plain: impl Into<String>) -> Self {
let plain = plain.into();
let value = plain.replace('\n', "\\P");
Self::new(EntityKind::MText {
position,
height,
width: 0.0,
rotation: 0.0,
value,
plain,
style: None,
attachment: Attachment::TopLeft,
line_spacing: 1.0,
normal: Vec3::Z,
})
}
pub fn insert(block: impl Into<String>, position: Point3) -> Self {
Self::new(EntityKind::Insert {
block: block.into(),
position,
scale: Vec3::ONE,
rotation: 0.0,
normal: Vec3::Z,
columns: 1,
rows: 1,
column_spacing: 0.0,
row_spacing: 0.0,
})
}
pub fn on_layer(mut self, layer: impl Into<String>) -> Self {
self.layer = Some(layer.into());
self
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn with_linetype(mut self, linetype: impl Into<String>) -> Self {
self.linetype = Some(linetype.into());
self
}
pub fn with_lineweight(mut self, lineweight: Lineweight) -> Self {
self.lineweight = lineweight;
self
}
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
pub fn with_prop(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.props.insert(key.into(), value.into());
self
}
pub fn with_attribute(mut self, tag: impl Into<String>, value: impl Into<Value>) -> Self {
self.attributes.push(Attribute {
tag: tag.into(),
value: value.into(),
invisible: true,
..Attribute::default()
});
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EntityKind {
Point {
position: Point3,
},
Line {
start: Point3,
end: Point3,
},
Polyline {
vertices: Vec<Vertex>,
closed: bool,
normal: Vec3,
},
Circle {
center: Point3,
radius: f64,
normal: Vec3,
},
Arc {
center: Point3,
radius: f64,
start_angle: f64,
end_angle: f64,
normal: Vec3,
},
Ellipse {
center: Point3,
major_axis: Vec3,
ratio: f64,
start_param: f64,
end_param: f64,
normal: Vec3,
},
Spline {
degree: u32,
knots: Vec<f64>,
control_points: Vec<Point3>,
weights: Vec<f64>,
fit_points: Vec<Point3>,
closed: bool,
},
Text {
position: Point3,
end_point: Option<Point3>,
height: f64,
rotation: f64,
width_factor: f64,
oblique: f64,
value: String,
style: Option<String>,
halign: HAlign,
valign: VAlign,
normal: Vec3,
},
MText {
position: Point3,
height: f64,
width: f64,
rotation: f64,
value: String,
plain: String,
style: Option<String>,
attachment: Attachment,
line_spacing: f64,
normal: Vec3,
},
Insert {
block: String,
position: Point3,
scale: Vec3,
rotation: f64,
normal: Vec3,
columns: u32,
rows: u32,
column_spacing: f64,
row_spacing: f64,
},
Hatch {
loops: Vec<HatchLoop>,
solid: bool,
pattern: Option<String>,
pattern_scale: f64,
pattern_angle: f64,
normal: Vec3,
},
Dimension {
dimension_type: DimensionType,
points: Vec<Point3>,
text_position: Option<Point3>,
measurement: Option<f64>,
text: Option<String>,
block: Option<String>,
style: Option<String>,
},
Face {
points: Vec<Point3>,
filled: bool,
},
Polygon {
exterior: Vec<Point3>,
interiors: Vec<Vec<Point3>>,
},
Leader {
vertices: Vec<Point3>,
arrowhead: bool,
},
Image {
path: Option<String>,
position: Point3,
u_vector: Vec3,
v_vector: Vec3,
size_px: Option<[u32; 2]>,
},
Viewport {
center: Point3,
width: f64,
height: f64,
view_center: Point3,
view_height: f64,
},
Mesh {
vertices: Vec<Point3>,
faces: Vec<Vec<u32>>,
},
Group {
group_kind: GroupKind,
name: Option<String>,
origin: Option<Point3>,
children: Vec<Entity>,
},
Unknown {
type_name: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct Vertex {
pub position: Point3,
pub bulge: f64,
pub start_width: f64,
pub end_width: f64,
}
impl Vertex {
pub fn at(position: Point3) -> Self {
Self {
position,
..Self::default()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum HAlign {
#[default]
Left,
Center,
Right,
Aligned,
Middle,
Fit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum VAlign {
#[default]
Baseline,
Bottom,
Middle,
Top,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum Attachment {
#[default]
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum DimensionType {
#[default]
Linear,
Aligned,
Angular,
Angular3Point,
Diameter,
Radius,
Ordinate,
ArcLength,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupKind {
ComplexChain,
ComplexShape,
TextNode,
Cell,
#[default]
Other,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HatchLoop {
pub edges: Vec<HatchEdge>,
pub external: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum HatchEdge {
Line {
start: Point3,
end: Point3,
},
Arc {
center: Point3,
radius: f64,
start_angle: f64,
end_angle: f64,
ccw: bool,
},
Ellipse {
center: Point3,
major_axis: Vec3,
ratio: f64,
start_param: f64,
end_param: f64,
ccw: bool,
},
Spline {
degree: u32,
knots: Vec<f64>,
control_points: Vec<Point3>,
weights: Vec<f64>,
},
Polyline {
vertices: Vec<Vertex>,
closed: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Color {
#[default]
ByLayer,
ByBlock,
Aci {
index: u8,
},
Rgb {
r: u8,
g: u8,
b: u8,
},
}
impl Color {
pub const fn aci(index: u8) -> Self {
Self::Aci { index }
}
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self::Rgb { r, g, b }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum Lineweight {
#[default]
ByLayer,
ByBlock,
Default,
Millimeters(f64),
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Attribute {
pub tag: String,
pub value: Value,
pub set: Option<String>,
pub position: Option<Point3>,
pub invisible: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<AttributeDisplay>,
#[serde(default, skip_serializing_if = "Props::is_empty")]
pub props: Props,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct AttributeDisplay {
pub height: f64,
pub width: f64,
pub style: Option<String>,
pub halign: HAlign,
pub valign: VAlign,
pub rotation: f64,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
#[default]
Null,
Bool(bool),
Int(i64),
Float(f64),
Text(String),
List(Vec<Value>),
Bytes(Vec<u8>),
}
impl Value {
pub const fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
pub const fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(v) => Some(*v),
_ => None,
}
}
pub const fn as_i64(&self) -> Option<i64> {
match self {
Self::Int(v) => Some(*v),
_ => None,
}
}
pub const fn as_f64(&self) -> Option<f64> {
match self {
Self::Float(v) => Some(*v),
Self::Int(v) => Some(*v as f64),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Text(s) => Some(s.as_str()),
_ => None,
}
}
pub fn as_list(&self) -> Option<&[Value]> {
match self {
Self::List(items) => Some(items.as_slice()),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<&[u8]> {
match self {
Self::Bytes(bytes) => Some(bytes.as_slice()),
_ => None,
}
}
}
impl From<bool> for Value {
fn from(v: bool) -> Self {
Value::Bool(v)
}
}
impl From<i64> for Value {
fn from(v: i64) -> Self {
Value::Int(v)
}
}
impl From<i32> for Value {
fn from(v: i32) -> Self {
Value::Int(i64::from(v))
}
}
impl From<i16> for Value {
fn from(v: i16) -> Self {
Value::Int(i64::from(v))
}
}
impl From<u32> for Value {
fn from(v: u32) -> Self {
Value::Int(i64::from(v))
}
}
impl From<u16> for Value {
fn from(v: u16) -> Self {
Value::Int(i64::from(v))
}
}
impl From<u8> for Value {
fn from(v: u8) -> Self {
Value::Int(i64::from(v))
}
}
impl From<f64> for Value {
fn from(v: f64) -> Self {
Value::Float(v)
}
}
impl From<f32> for Value {
fn from(v: f32) -> Self {
Value::Float(f64::from(v))
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Value::Text(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Value::Text(v.to_owned())
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Self {
Value::Bytes(v)
}
}
impl From<Vec<Value>> for Value {
fn from(v: Vec<Value>) -> Self {
Value::List(v)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Raw {
pub type_code: u32,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Warning {
pub code: String,
pub message: String,
pub offset: Option<u64>,
pub object: Option<u64>,
}