Skip to main content

cadkit_core/
doc_ops.rs

1//! High-level in-place [`Document`] and [`Entity`] operations: affine transforms, unit
2//! conversion, insert explosion, group flattening, curve tessellation, layer filtering, and
3//! unused-definition purging.
4
5use std::collections::{HashMap, HashSet};
6use std::f64::consts::TAU;
7
8use crate::error::{Error, Result};
9use crate::geom::{Point3, Vec3};
10use crate::geom_ops::{
11    EllipseArc, Transform, arbitrary_axes, conjugate_to_axes, interpolate_fit_points, nurbs_flatten,
12};
13use crate::model::{
14    Attribute, Block, Color, Document, Entity, EntityKind, HatchEdge, HatchLoop, LengthUnit,
15    Lineweight, ModelKind, Units, Vertex,
16};
17use crate::ops::{
18    DEFAULT_MAX_WORK, SPLINE_SAMPLES, WalkStats, circle_arc, full_ellipse_arc, segment_arc,
19};
20
21/// Counts of unreferenced definitions removed by [`Document::purge_unused`].
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub struct PurgeStats {
24    /// Unused [`Block`] definitions removed.
25    pub blocks: usize,
26    /// Unused [`crate::Layer`] definitions removed.
27    pub layers: usize,
28    /// Unused [`crate::Linetype`] definitions removed.
29    pub linetypes: usize,
30    /// Unused [`crate::TextStyle`] definitions removed.
31    pub text_styles: usize,
32}
33
34/// Maps a transformed [`EllipseArc`] back into [`EntityKind::Circle`], [`EntityKind::Arc`], or
35/// [`EntityKind::Ellipse`] depending on whether the transformed axes stay circular.
36fn arc_or_ellipse_kind(ea: &EllipseArc, fallback_normal: Vec3, full_loop: bool) -> EntityKind {
37    let raw_cross = ea.u.cross(ea.v);
38    let mut new_normal = raw_cross
39        .normalized()
40        .or_else(|| fallback_normal.normalized())
41        .unwrap_or(Vec3::Z);
42    let (mut n_ax, mut n_ay, _) = arbitrary_axes(new_normal);
43    let u2_check = (ea.u.dot(n_ax), ea.u.dot(n_ay));
44    let v2_check = (ea.v.dot(n_ax), ea.v.dot(n_ay));
45    let det = u2_check.0 * v2_check.1 - u2_check.1 * v2_check.0;
46    if det < 0.0 && ea.sweep() >= 0.0 || det > 0.0 && ea.sweep() < 0.0 {
47        new_normal = -new_normal;
48        (n_ax, n_ay, _) = arbitrary_axes(new_normal);
49    }
50
51    let u2 = (ea.u.dot(n_ax), ea.u.dot(n_ay));
52    let v2 = (ea.v.dot(n_ax), ea.v.dot(n_ay));
53    let ru = u2.0.hypot(u2.1);
54    let rv = v2.0.hypot(v2.1);
55    let ortho = u2.0 * v2.0 + u2.1 * v2.1;
56    let scale_ref = ru.max(rv).max(1.0);
57    let is_circular =
58        (ru - rv).abs() <= 1e-9 * scale_ref && ortho.abs() <= 1e-9 * scale_ref * scale_ref;
59
60    if is_circular {
61        let radius = 0.5 * (ru + rv);
62        if full_loop {
63            return EntityKind::Circle {
64                center: ea.center,
65                radius,
66                normal: new_normal,
67            };
68        }
69        let p0 = ea.point(ea.t0) - ea.center;
70        let p1 = ea.point(ea.t1) - ea.center;
71        let start_angle = p0.dot(n_ay).atan2(p0.dot(n_ax)).rem_euclid(TAU);
72        let end_angle = p1.dot(n_ay).atan2(p1.dot(n_ax)).rem_euclid(TAU);
73        return EntityKind::Arc {
74            center: ea.center,
75            radius,
76            start_angle,
77            end_angle,
78            normal: new_normal,
79        };
80    }
81
82    let (semi_major, semi_minor, rot) = conjugate_to_axes(u2, v2);
83    let major_dir = n_ax * rot.cos() + n_ay * rot.sin();
84    let major_axis = major_dir * semi_major;
85    let ratio = if semi_major > 1e-12 {
86        (semi_minor / semi_major).clamp(1e-9, 1.0)
87    } else {
88        1.0
89    };
90    if full_loop {
91        return EntityKind::Ellipse {
92            center: ea.center,
93            major_axis,
94            ratio,
95            start_param: 0.0,
96            end_param: TAU,
97            normal: new_normal,
98        };
99    }
100    let minor_dir = new_normal.cross(major_dir).normalized().unwrap_or(Vec3::Y);
101    let param_of = |p: Point3| -> f64 {
102        let d = p - ea.center;
103        let x = d.dot(major_dir) / semi_major.max(1e-12);
104        let y = d.dot(minor_dir) / semi_minor.max(1e-12);
105        y.atan2(x).rem_euclid(TAU)
106    };
107    EntityKind::Ellipse {
108        center: ea.center,
109        major_axis,
110        ratio,
111        start_param: param_of(ea.point(ea.t0)),
112        end_param: param_of(ea.point(ea.t1)),
113        normal: new_normal,
114    }
115}
116
117fn transform_plane_frame(normal: Vec3, rotation: f64, tf: &Transform) -> (Vec3, f64, f64, f64) {
118    let (ax, ay, az) = arbitrary_axes(normal);
119    let (s, c) = rotation.sin_cos();
120    let dir_x = tf.apply_vector(ax * c + ay * s);
121    let dir_y = tf.apply_vector(ay * c - ax * s);
122    let mut new_normal = dir_x
123        .cross(dir_y)
124        .normalized()
125        .or_else(|| tf.apply_vector(az).normalized())
126        .unwrap_or(Vec3::Z);
127    if dir_x.cross(dir_y).dot(new_normal) < 0.0 {
128        new_normal = -new_normal;
129    }
130    let (n_ax, n_ay, _) = arbitrary_axes(new_normal);
131    let new_rot = dir_x.dot(n_ay).atan2(dir_x.dot(n_ax));
132    let sx = dir_x.length();
133    let sy = dir_y.length();
134    (new_normal, new_rot, sx, sy)
135}
136
137fn transform_hatch_edge(
138    edge: &HatchEdge,
139    old_normal: Vec3,
140    new_normal: Vec3,
141    tf: &Transform,
142) -> HatchEdge {
143    let (old_ax, old_ay, _) = arbitrary_axes(old_normal);
144    let tx = tf.apply_vector(old_ax);
145    let ty = tf.apply_vector(old_ay);
146    let flipped = tx.cross(ty).dot(new_normal) < 0.0;
147    let width_scale = 0.5 * (tx.length() + ty.length());
148
149    match edge {
150        HatchEdge::Line { start, end } => HatchEdge::Line {
151            start: tf.apply_point(*start),
152            end: tf.apply_point(*end),
153        },
154        HatchEdge::Arc {
155            center,
156            radius,
157            start_angle,
158            end_angle,
159            ccw,
160        } => {
161            let (s, en) = if *ccw {
162                (*start_angle, *end_angle)
163            } else {
164                (*end_angle, *start_angle)
165            };
166            let ea = circle_arc(*center, *radius, s, en, old_normal, tf);
167            match arc_or_ellipse_kind(
168                &ea,
169                new_normal,
170                (*end_angle - *start_angle).abs() >= TAU - 1e-9,
171            ) {
172                EntityKind::Circle { center, radius, .. } => HatchEdge::Arc {
173                    center,
174                    radius,
175                    start_angle: 0.0,
176                    end_angle: TAU,
177                    ccw: !flipped ^ !*ccw,
178                },
179                EntityKind::Arc {
180                    center,
181                    radius,
182                    start_angle: ns,
183                    end_angle: ne,
184                    ..
185                } => {
186                    let out_ccw = *ccw ^ flipped;
187                    let (a0, a1) = if out_ccw { (ns, ne) } else { (ne, ns) };
188                    HatchEdge::Arc {
189                        center,
190                        radius,
191                        start_angle: a0,
192                        end_angle: a1,
193                        ccw: out_ccw,
194                    }
195                }
196                EntityKind::Ellipse {
197                    center,
198                    major_axis,
199                    ratio,
200                    start_param,
201                    end_param,
202                    ..
203                } => {
204                    let out_ccw = *ccw ^ flipped;
205                    let (p0, p1) = if out_ccw {
206                        (start_param, end_param)
207                    } else {
208                        (end_param, start_param)
209                    };
210                    HatchEdge::Ellipse {
211                        center,
212                        major_axis,
213                        ratio,
214                        start_param: p0,
215                        end_param: p1,
216                        ccw: out_ccw,
217                    }
218                }
219                _ => edge.clone(),
220            }
221        }
222        HatchEdge::Ellipse {
223            center,
224            major_axis,
225            ratio,
226            start_param,
227            end_param,
228            ccw,
229        } => {
230            let (s, en) = if *ccw {
231                (*start_param, *end_param)
232            } else {
233                (*end_param, *start_param)
234            };
235            let ea = full_ellipse_arc(*center, *major_axis, *ratio, old_normal, s, en, tf);
236            let full = (*end_param - *start_param).abs() >= TAU - 1e-9;
237            match arc_or_ellipse_kind(&ea, new_normal, full) {
238                EntityKind::Circle { center, radius, .. } => HatchEdge::Ellipse {
239                    center,
240                    major_axis: arbitrary_axes(new_normal).0 * radius,
241                    ratio: 1.0,
242                    start_param: 0.0,
243                    end_param: TAU,
244                    ccw: *ccw ^ flipped,
245                },
246                EntityKind::Ellipse {
247                    center,
248                    major_axis,
249                    ratio,
250                    start_param: ns,
251                    end_param: ne,
252                    ..
253                } => {
254                    let out_ccw = *ccw ^ flipped;
255                    let (p0, p1) = if full {
256                        (0.0, TAU)
257                    } else if out_ccw {
258                        (ns, ne)
259                    } else {
260                        (ne, ns)
261                    };
262                    HatchEdge::Ellipse {
263                        center,
264                        major_axis,
265                        ratio,
266                        start_param: p0,
267                        end_param: p1,
268                        ccw: out_ccw,
269                    }
270                }
271                _ => edge.clone(),
272            }
273        }
274        HatchEdge::Spline {
275            degree,
276            knots,
277            control_points,
278            weights,
279        } => HatchEdge::Spline {
280            degree: *degree,
281            knots: knots.clone(),
282            control_points: control_points.iter().map(|p| tf.apply_point(*p)).collect(),
283            weights: weights.clone(),
284        },
285        HatchEdge::Polyline { vertices, closed } => HatchEdge::Polyline {
286            vertices: vertices
287                .iter()
288                .map(|v| Vertex {
289                    position: tf.apply_point(v.position),
290                    bulge: if flipped { -v.bulge } else { v.bulge },
291                    start_width: v.start_width * width_scale,
292                    end_width: v.end_width * width_scale,
293                })
294                .collect(),
295            closed: *closed,
296        },
297    }
298}
299
300fn transform_attribute(attr: &Attribute, tf: &Transform) -> Attribute {
301    let mut out = attr.clone();
302    if let Some(pos) = out.position {
303        out.position = Some(tf.apply_point(pos));
304    }
305    if let Some(disp) = &mut out.display {
306        let (_, new_rot, sx, sy) = transform_plane_frame(Vec3::Z, disp.rotation, tf);
307        let h_scale = if sy > 0.0 && sy.is_finite() { sy } else { 1.0 };
308        let w_scale = if sx > 0.0 && sx.is_finite() {
309            sx
310        } else {
311            h_scale
312        };
313        disp.height *= h_scale;
314        disp.width *= w_scale;
315        disp.rotation = new_rot;
316    }
317    out
318}
319
320/// Format props that hold directions in the entity's coordinates: the end tangents of a
321/// DGN type 11 curve (`cadkit-dgn`), which the DXF writer emits as SPLINE groups 12/13.
322const DIRECTION_PROPS: [&str; 2] = ["dgn.curve_start_tangent", "dgn.curve_end_tangent"];
323
324/// The props of an entity mapped by `tf`. Format props are copied unchanged, except
325/// [`DIRECTION_PROPS`]: they would describe the untransformed geometry, so they are dropped
326/// unless the linear part of `tf` is a positive uniform scale (directions and the
327/// dimensionless slopes stay as they are).
328fn transformed_props(props: &crate::model::Props, tf: &Transform) -> crate::model::Props {
329    let mut out = props.clone();
330    let s = tf.x.x;
331    let keeps_directions = s.is_finite()
332        && s > 0.0
333        && tf.x == Vec3::new(s, 0.0, 0.0)
334        && tf.y == Vec3::new(0.0, s, 0.0)
335        && tf.z == Vec3::new(0.0, 0.0, s);
336    if !keeps_directions {
337        for key in DIRECTION_PROPS {
338            out.remove(key);
339        }
340    }
341    out
342}
343
344impl Entity {
345    /// Returns a copy of this entity with its geometry and displayed attributes mapped by `tf`.
346    ///
347    /// Circles and circular arcs that undergo anisotropic scaling are promoted to exact
348    /// [`EntityKind::Ellipse`] entities. Format `props` are copied unchanged, except the
349    /// direction props `dgn.curve_start_tangent` / `dgn.curve_end_tangent`, which are
350    /// dropped unless `tf` only translates and scales uniformly by a positive factor.
351    pub fn transformed(&self, tf: &Transform) -> Entity {
352        let kind = match &self.kind {
353            EntityKind::Point { position } => EntityKind::Point {
354                position: tf.apply_point(*position),
355            },
356            EntityKind::Line { start, end } => EntityKind::Line {
357                start: tf.apply_point(*start),
358                end: tf.apply_point(*end),
359            },
360            EntityKind::Polyline {
361                vertices,
362                closed,
363                normal,
364            } => {
365                let (new_normal, _, sx, sy) = transform_plane_frame(*normal, 0.0, tf);
366                let (old_ax, old_ay, _) = arbitrary_axes(*normal);
367                let flipped = tf
368                    .apply_vector(old_ax)
369                    .cross(tf.apply_vector(old_ay))
370                    .dot(new_normal)
371                    < 0.0;
372                let w_scale = 0.5 * (sx + sy);
373                EntityKind::Polyline {
374                    vertices: vertices
375                        .iter()
376                        .map(|v| Vertex {
377                            position: tf.apply_point(v.position),
378                            bulge: if flipped { -v.bulge } else { v.bulge },
379                            start_width: v.start_width * w_scale,
380                            end_width: v.end_width * w_scale,
381                        })
382                        .collect(),
383                    closed: *closed,
384                    normal: new_normal,
385                }
386            }
387            EntityKind::Circle {
388                center,
389                radius,
390                normal,
391            } => {
392                let ea = circle_arc(*center, *radius, 0.0, 0.0, *normal, tf);
393                arc_or_ellipse_kind(&ea, tf.apply_vector(*normal), true)
394            }
395            EntityKind::Arc {
396                center,
397                radius,
398                start_angle,
399                end_angle,
400                normal,
401            } => {
402                let ea = circle_arc(*center, *radius, *start_angle, *end_angle, *normal, tf);
403                let full = (*end_angle - *start_angle).abs() >= TAU - 1e-9;
404                arc_or_ellipse_kind(&ea, tf.apply_vector(*normal), full)
405            }
406            EntityKind::Ellipse {
407                center,
408                major_axis,
409                ratio,
410                start_param,
411                end_param,
412                normal,
413            } => {
414                let ea = full_ellipse_arc(
415                    *center,
416                    *major_axis,
417                    *ratio,
418                    *normal,
419                    *start_param,
420                    *end_param,
421                    tf,
422                );
423                let full = (*end_param - *start_param).abs() >= TAU - 1e-9;
424                arc_or_ellipse_kind(&ea, tf.apply_vector(*normal), full)
425            }
426            EntityKind::Spline {
427                degree,
428                knots,
429                control_points,
430                weights,
431                fit_points,
432                closed,
433            } => EntityKind::Spline {
434                degree: *degree,
435                knots: knots.clone(),
436                control_points: control_points.iter().map(|p| tf.apply_point(*p)).collect(),
437                weights: weights.clone(),
438                fit_points: fit_points.iter().map(|p| tf.apply_point(*p)).collect(),
439                closed: *closed,
440            },
441            EntityKind::Text {
442                position,
443                end_point,
444                height,
445                rotation,
446                width_factor,
447                oblique,
448                value,
449                style,
450                halign,
451                valign,
452                normal,
453            } => {
454                let (new_normal, new_rot, sx, sy) = transform_plane_frame(*normal, *rotation, tf);
455                let h_scale = if sy > 0.0 && sy.is_finite() { sy } else { 1.0 };
456                let wf_scale = if sy > 1e-12 && sx > 0.0 && sx.is_finite() {
457                    sx / sy
458                } else {
459                    1.0
460                };
461                EntityKind::Text {
462                    position: tf.apply_point(*position),
463                    end_point: end_point.map(|p| tf.apply_point(p)),
464                    height: *height * h_scale,
465                    rotation: new_rot,
466                    width_factor: *width_factor * wf_scale,
467                    oblique: *oblique,
468                    value: value.clone(),
469                    style: style.clone(),
470                    halign: *halign,
471                    valign: *valign,
472                    normal: new_normal,
473                }
474            }
475            EntityKind::MText {
476                position,
477                height,
478                width,
479                rotation,
480                value,
481                plain,
482                style,
483                attachment,
484                line_spacing,
485                normal,
486            } => {
487                let (new_normal, new_rot, sx, sy) = transform_plane_frame(*normal, *rotation, tf);
488                let h_scale = if sy > 0.0 && sy.is_finite() { sy } else { 1.0 };
489                let w_scale = if sx > 0.0 && sx.is_finite() {
490                    sx
491                } else {
492                    h_scale
493                };
494                EntityKind::MText {
495                    position: tf.apply_point(*position),
496                    height: *height * h_scale,
497                    width: *width * w_scale,
498                    rotation: new_rot,
499                    value: value.clone(),
500                    plain: plain.clone(),
501                    style: style.clone(),
502                    attachment: *attachment,
503                    line_spacing: *line_spacing,
504                    normal: new_normal,
505                }
506            }
507            EntityKind::Insert {
508                block,
509                position,
510                scale,
511                rotation,
512                normal,
513                columns,
514                rows,
515                column_spacing,
516                row_spacing,
517            } => {
518                let (new_normal, new_rot, sx, sy) = transform_plane_frame(*normal, *rotation, tf);
519                let sz = tf
520                    .apply_vector(normal.normalized().unwrap_or(Vec3::Z))
521                    .length();
522                let det_sign = if tf.determinant() < 0.0 { -1.0 } else { 1.0 };
523                EntityKind::Insert {
524                    block: block.clone(),
525                    position: tf.apply_point(*position),
526                    scale: Vec3::new(
527                        scale.x * sx * det_sign,
528                        scale.y * sy,
529                        scale.z * sz.max(1e-12),
530                    ),
531                    rotation: new_rot,
532                    normal: new_normal,
533                    columns: *columns,
534                    rows: *rows,
535                    column_spacing: *column_spacing * sx,
536                    row_spacing: *row_spacing * sy,
537                }
538            }
539            EntityKind::Hatch {
540                loops,
541                solid,
542                pattern,
543                pattern_scale,
544                pattern_angle,
545                normal,
546            } => {
547                let (new_normal, new_angle, sx, sy) =
548                    transform_plane_frame(*normal, *pattern_angle, tf);
549                let p_scale = 0.5 * (sx + sy);
550                EntityKind::Hatch {
551                    loops: loops
552                        .iter()
553                        .map(|l| HatchLoop {
554                            edges: l
555                                .edges
556                                .iter()
557                                .map(|e| transform_hatch_edge(e, *normal, new_normal, tf))
558                                .collect(),
559                            external: l.external,
560                        })
561                        .collect(),
562                    solid: *solid,
563                    pattern: pattern.clone(),
564                    pattern_scale: if *solid {
565                        1.0
566                    } else {
567                        *pattern_scale * p_scale
568                    },
569                    pattern_angle: if *solid { 0.0 } else { new_angle },
570                    normal: new_normal,
571                }
572            }
573            EntityKind::Dimension {
574                dimension_type,
575                points,
576                text_position,
577                measurement,
578                text,
579                block,
580                style,
581            } => {
582                let linear_scale = (tf.x.length() + tf.y.length() + tf.z.length()) / 3.0;
583                let scaled_measurement = measurement.map(|m| match dimension_type {
584                    crate::DimensionType::Angular | crate::DimensionType::Angular3Point => m,
585                    _ => m * linear_scale,
586                });
587                EntityKind::Dimension {
588                    dimension_type: *dimension_type,
589                    points: points.iter().map(|p| tf.apply_point(*p)).collect(),
590                    text_position: text_position.map(|p| tf.apply_point(p)),
591                    measurement: scaled_measurement,
592                    text: text.clone(),
593                    block: block.clone(),
594                    style: style.clone(),
595                }
596            }
597            EntityKind::Face { points, filled } => EntityKind::Face {
598                points: points.iter().map(|p| tf.apply_point(*p)).collect(),
599                filled: *filled,
600            },
601            EntityKind::Polygon {
602                exterior,
603                interiors,
604            } => {
605                let flip = tf.determinant() < 0.0;
606                let map_ring = |ring: &[Point3]| -> Vec<Point3> {
607                    let mut out: Vec<Point3> = ring.iter().map(|p| tf.apply_point(*p)).collect();
608                    if flip {
609                        out.reverse();
610                    }
611                    out
612                };
613                EntityKind::Polygon {
614                    exterior: map_ring(exterior),
615                    interiors: interiors.iter().map(|r| map_ring(r)).collect(),
616                }
617            }
618            EntityKind::Leader {
619                vertices,
620                arrowhead,
621            } => EntityKind::Leader {
622                vertices: vertices.iter().map(|p| tf.apply_point(*p)).collect(),
623                arrowhead: *arrowhead,
624            },
625            EntityKind::Image {
626                path,
627                position,
628                u_vector,
629                v_vector,
630                size_px,
631            } => EntityKind::Image {
632                path: path.clone(),
633                position: tf.apply_point(*position),
634                u_vector: tf.apply_vector(*u_vector),
635                v_vector: tf.apply_vector(*v_vector),
636                size_px: *size_px,
637            },
638            EntityKind::Viewport {
639                center,
640                width,
641                height,
642                view_center,
643                view_height,
644            } => EntityKind::Viewport {
645                center: tf.apply_point(*center),
646                width: *width,
647                height: *height,
648                view_center: tf.apply_point(*view_center),
649                view_height: *view_height * tf.y.length().max(1e-12),
650            },
651            EntityKind::Mesh { vertices, faces } => EntityKind::Mesh {
652                vertices: vertices.iter().map(|p| tf.apply_point(*p)).collect(),
653                faces: faces.clone(),
654            },
655            EntityKind::Group {
656                group_kind,
657                name,
658                origin,
659                children,
660            } => EntityKind::Group {
661                group_kind: *group_kind,
662                name: name.clone(),
663                origin: origin.map(|p| tf.apply_point(p)),
664                children: children.iter().map(|c| c.transformed(tf)).collect(),
665            },
666            EntityKind::Unknown { type_name } => EntityKind::Unknown {
667                type_name: type_name.clone(),
668            },
669        };
670
671        Entity {
672            id: self.id,
673            layer: self.layer.clone(),
674            color: self.color,
675            linetype: self.linetype.clone(),
676            lineweight: self.lineweight,
677            visible: self.visible,
678            kind,
679            attributes: self
680                .attributes
681                .iter()
682                .map(|a| transform_attribute(a, tf))
683                .collect(),
684            props: transformed_props(&self.props, tf),
685            raw: None,
686        }
687    }
688}
689
690/// Scales an entity's coordinates and linear extents by `factor` during unit conversion while
691/// keeping [`EntityKind::Insert::scale`] dimensionless (since [`Block`] definitions are scaled too).
692fn scale_entity_units(entity: &Entity, factor: f64, tf: &Transform) -> Entity {
693    match &entity.kind {
694        EntityKind::Insert {
695            block,
696            position,
697            scale,
698            rotation,
699            normal,
700            columns,
701            rows,
702            column_spacing,
703            row_spacing,
704        } => Entity {
705            id: entity.id,
706            layer: entity.layer.clone(),
707            color: entity.color,
708            linetype: entity.linetype.clone(),
709            lineweight: entity.lineweight,
710            visible: entity.visible,
711            kind: EntityKind::Insert {
712                block: block.clone(),
713                position: tf.apply_point(*position),
714                scale: *scale,
715                rotation: *rotation,
716                normal: *normal,
717                columns: *columns,
718                rows: *rows,
719                column_spacing: *column_spacing * factor,
720                row_spacing: *row_spacing * factor,
721            },
722            attributes: entity
723                .attributes
724                .iter()
725                .map(|a| transform_attribute(a, tf))
726                .collect(),
727            props: entity.props.clone(),
728            raw: None,
729        },
730        EntityKind::Group {
731            group_kind,
732            name,
733            origin,
734            children,
735        } => Entity {
736            id: entity.id,
737            layer: entity.layer.clone(),
738            color: entity.color,
739            linetype: entity.linetype.clone(),
740            lineweight: entity.lineweight,
741            visible: entity.visible,
742            kind: EntityKind::Group {
743                group_kind: *group_kind,
744                name: name.clone(),
745                origin: origin.map(|p| tf.apply_point(p)),
746                children: children
747                    .iter()
748                    .map(|c| scale_entity_units(c, factor, tf))
749                    .collect(),
750            },
751            attributes: entity
752                .attributes
753                .iter()
754                .map(|a| transform_attribute(a, tf))
755                .collect(),
756            props: entity.props.clone(),
757            raw: None,
758        },
759        _ => entity.transformed(tf),
760    }
761}
762
763fn tessellate_arc(arc: &EllipseArc, max_sagitta: f64) -> Vec<Point3> {
764    let sweep = arc.sweep().abs();
765    let r = arc.u.length().max(arc.v.length());
766    let tol = if max_sagitta.is_finite() && max_sagitta > 0.0 {
767        max_sagitta
768    } else {
769        (r * 0.01).max(1e-3)
770    };
771    let steps = if r > tol && r > 1e-12 {
772        let half_theta = (1.0 - tol / r).clamp(-1.0, 1.0).acos();
773        let step_angle = (2.0 * half_theta).max(1e-6);
774        ((sweep / step_angle).ceil() as usize).clamp(4, 4096)
775    } else {
776        8
777    };
778    let mut pts = Vec::with_capacity(steps + 1);
779    for i in 0..=steps {
780        let t = arc.t0 + (arc.t1 - arc.t0) * (i as f64) / (steps as f64);
781        pts.push(arc.point(t));
782    }
783    pts
784}
785
786fn tessellate_entity_in_place(entity: &mut Entity, tolerance: f64) {
787    let id = Transform::identity();
788    match &mut entity.kind {
789        EntityKind::Circle {
790            center,
791            radius,
792            normal,
793        } => {
794            let ea = circle_arc(*center, *radius, 0.0, 0.0, *normal, &id);
795            let mut pts = tessellate_arc(&ea, tolerance);
796            if pts.len() > 2 {
797                pts.pop();
798            }
799            entity.kind = EntityKind::Polyline {
800                vertices: pts.into_iter().map(Vertex::at).collect(),
801                closed: true,
802                normal: *normal,
803            };
804        }
805        EntityKind::Arc {
806            center,
807            radius,
808            start_angle,
809            end_angle,
810            normal,
811        } => {
812            let ea = circle_arc(*center, *radius, *start_angle, *end_angle, *normal, &id);
813            let pts = tessellate_arc(&ea, tolerance);
814            entity.kind = EntityKind::Polyline {
815                vertices: pts.into_iter().map(Vertex::at).collect(),
816                closed: false,
817                normal: *normal,
818            };
819        }
820        EntityKind::Ellipse {
821            center,
822            major_axis,
823            ratio,
824            start_param,
825            end_param,
826            normal,
827        } => {
828            let ea = full_ellipse_arc(
829                *center,
830                *major_axis,
831                *ratio,
832                *normal,
833                *start_param,
834                *end_param,
835                &id,
836            );
837            let closed = (*end_param - *start_param).abs() >= TAU - 1e-9;
838            let mut pts = tessellate_arc(&ea, tolerance);
839            if closed && pts.len() > 2 {
840                pts.pop();
841            }
842            entity.kind = EntityKind::Polyline {
843                vertices: pts.into_iter().map(Vertex::at).collect(),
844                closed,
845                normal: *normal,
846            };
847        }
848        EntityKind::Spline {
849            degree,
850            knots,
851            control_points,
852            weights,
853            fit_points,
854            closed,
855        } => {
856            let samples = if tolerance.is_finite() && tolerance > 0.0 {
857                SPLINE_SAMPLES.max(24)
858            } else {
859                SPLINE_SAMPLES
860            };
861            let pts = if control_points.len() >= 2 {
862                nurbs_flatten(*degree, knots, control_points, weights, samples)
863            } else if let Some((deg, iknots, ictrl)) = interpolate_fit_points(fit_points, *closed) {
864                nurbs_flatten(deg, &iknots, &ictrl, &[], samples)
865            } else {
866                fit_points.clone()
867            };
868            if pts.len() >= 2 {
869                entity.kind = EntityKind::Polyline {
870                    vertices: pts.into_iter().map(Vertex::at).collect(),
871                    closed: *closed,
872                    normal: Vec3::Z,
873                };
874            }
875        }
876        EntityKind::Polyline {
877            vertices,
878            closed,
879            normal,
880        } => {
881            if vertices.iter().any(|v| v.bulge.abs() > 1e-12) && vertices.len() >= 2 {
882                let n = vertices.len();
883                let segs = if *closed { n } else { n - 1 };
884                let mut out: Vec<Vertex> = Vec::with_capacity(n * 2);
885                for i in 0..segs {
886                    let (Some(a), Some(b)) = (vertices.get(i), vertices.get((i + 1) % n)) else {
887                        continue;
888                    };
889                    if let Some(arc) = segment_arc(a, b, *normal, &id) {
890                        let pts = tessellate_arc(&arc, tolerance);
891                        let end_idx = pts.len().saturating_sub(1);
892                        for pt in pts.into_iter().take(end_idx) {
893                            out.push(Vertex {
894                                position: pt,
895                                bulge: 0.0,
896                                start_width: a.start_width,
897                                end_width: a.end_width,
898                            });
899                        }
900                    } else {
901                        out.push(Vertex { bulge: 0.0, ..*a });
902                    }
903                }
904                if !*closed && let Some(last) = vertices.last() {
905                    out.push(Vertex {
906                        bulge: 0.0,
907                        ..*last
908                    });
909                }
910                *vertices = out;
911            }
912        }
913        EntityKind::Group { children, .. } => {
914            for child in children {
915                tessellate_entity_in_place(child, tolerance);
916            }
917        }
918        _ => {}
919    }
920}
921
922fn flatten_list(
923    entities: Vec<Entity>,
924    inherited_layer: Option<&str>,
925    inherited_color: Color,
926    inherited_lw: Lineweight,
927    depth: u32,
928    out: &mut Vec<Entity>,
929) {
930    for mut e in entities {
931        if matches!(e.layer.as_deref(), None | Some("0"))
932            && let Some(l) = inherited_layer
933        {
934            e.layer = Some(l.to_owned());
935        }
936        if e.color == Color::ByBlock && inherited_color != Color::ByBlock {
937            e.color = inherited_color;
938        }
939        if e.lineweight == Lineweight::ByBlock && inherited_lw != Lineweight::ByBlock {
940            e.lineweight = inherited_lw;
941        }
942        match e.kind {
943            EntityKind::Group { children, .. } if depth < 64 => {
944                let child_layer = e.layer.as_deref().or(inherited_layer);
945                flatten_list(children, child_layer, e.color, e.lineweight, depth + 1, out);
946            }
947            _ => out.push(e),
948        }
949    }
950}
951
952fn retain_layer_list(entities: &mut Vec<Entity>, keep: &mut impl FnMut(&str) -> bool) {
953    entities.retain_mut(|e| {
954        if let EntityKind::Group { children, .. } = &mut e.kind {
955            retain_layer_list(children, keep);
956            if children.is_empty() {
957                return false;
958            }
959        }
960        let layer = e.layer.as_deref().unwrap_or("0");
961        keep(layer)
962    });
963}
964
965fn collect_refs<'a>(
966    entities: &'a [Entity],
967    blocks: &mut Vec<&'a str>,
968    layers: &mut HashSet<&'a str>,
969    linetypes: &mut HashSet<&'a str>,
970    styles: &mut HashSet<&'a str>,
971) {
972    let mut stack: Vec<&'a [Entity]> = vec![entities];
973    while let Some(slice) = stack.pop() {
974        for e in slice {
975            layers.insert(e.layer.as_deref().unwrap_or("0"));
976            if let Some(lt) = e.linetype.as_deref() {
977                linetypes.insert(lt);
978            }
979            for attr in &e.attributes {
980                if let Some(al) = attr.layer.as_deref() {
981                    layers.insert(al);
982                }
983                if let Some(disp) = &attr.display
984                    && let Some(st) = disp.style.as_deref()
985                {
986                    styles.insert(st);
987                }
988            }
989            match &e.kind {
990                EntityKind::Insert { block, .. } => blocks.push(block.as_str()),
991                EntityKind::Dimension { block, style, .. } => {
992                    if let Some(b) = block.as_deref() {
993                        blocks.push(b);
994                    }
995                    if let Some(s) = style.as_deref() {
996                        styles.insert(s);
997                    }
998                }
999                EntityKind::Text { style, .. } | EntityKind::MText { style, .. } => {
1000                    if let Some(s) = style.as_deref() {
1001                        styles.insert(s);
1002                    }
1003                }
1004                EntityKind::Group { children, .. } if !children.is_empty() => {
1005                    stack.push(children);
1006                }
1007                _ => {}
1008            }
1009        }
1010    }
1011}
1012
1013struct Exploder<'a> {
1014    blocks: HashMap<&'a str, &'a Block>,
1015    max_depth: u32,
1016    work_left: u64,
1017    work_spent: u64,
1018    truncated: bool,
1019    stack: Vec<&'a str>,
1020}
1021
1022impl<'a> Exploder<'a> {
1023    fn charge(&mut self, cost: u64) -> bool {
1024        if self.truncated {
1025            return false;
1026        }
1027        if cost > self.work_left {
1028            self.work_left = 0;
1029            self.truncated = true;
1030            return false;
1031        }
1032        self.work_left -= cost;
1033        self.work_spent += cost;
1034        true
1035    }
1036
1037    #[allow(clippy::too_many_arguments)]
1038    fn expand_list<'b>(
1039        &mut self,
1040        list: &'b [Entity],
1041        tf: &Transform,
1042        depth: u32,
1043        inherited_layer: Option<&'b str>,
1044        block_color: Option<Color>,
1045        block_lw: Option<Lineweight>,
1046        out: &mut Vec<Entity>,
1047    ) {
1048        for e in list {
1049            if !self.charge(1) {
1050                out.push(e.transformed(tf));
1051                continue;
1052            }
1053            let effective_layer: Option<&'b str> = match e.layer.as_deref() {
1054                None | Some("0") => inherited_layer.or(e.layer.as_deref()),
1055                Some(l) => Some(l),
1056            };
1057            let resolved_color = match e.color {
1058                Color::ByBlock => block_color.unwrap_or(Color::ByLayer),
1059                other => other,
1060            };
1061            let resolved_lw = match e.lineweight {
1062                Lineweight::ByBlock => block_lw.unwrap_or(Lineweight::ByLayer),
1063                other => other,
1064            };
1065
1066            match &e.kind {
1067                EntityKind::Insert {
1068                    block,
1069                    position,
1070                    scale,
1071                    rotation,
1072                    normal,
1073                    columns,
1074                    rows,
1075                    column_spacing,
1076                    row_spacing,
1077                } => {
1078                    let Some(def) = self.blocks.get(block.as_str()).copied() else {
1079                        let mut fallback = e.transformed(tf);
1080                        fallback.layer = effective_layer.map(str::to_owned);
1081                        fallback.color = resolved_color;
1082                        fallback.lineweight = resolved_lw;
1083                        out.push(fallback);
1084                        continue;
1085                    };
1086                    if depth >= self.max_depth || self.stack.contains(&def.name.as_str()) {
1087                        let mut fallback = e.transformed(tf);
1088                        fallback.layer = effective_layer.map(str::to_owned);
1089                        fallback.color = resolved_color;
1090                        fallback.lineweight = resolved_lw;
1091                        out.push(fallback);
1092                        continue;
1093                    }
1094                    let child_inherited = match e.layer.as_deref() {
1095                        None | Some("0") => inherited_layer,
1096                        Some(l) => Some(l),
1097                    };
1098                    self.stack.push(def.name.as_str());
1099                    'cells: for r in 0..(*rows).max(1) {
1100                        for c in 0..(*columns).max(1) {
1101                            if !self.charge(1) {
1102                                break 'cells;
1103                            }
1104                            let offset = Vec3::new(
1105                                f64::from(c) * *column_spacing,
1106                                f64::from(r) * *row_spacing,
1107                                0.0,
1108                            );
1109                            let local = Transform::from_insert_offset(
1110                                *position,
1111                                *scale,
1112                                *rotation,
1113                                *normal,
1114                                def.base_point,
1115                                offset,
1116                            );
1117                            let child_tf = tf.compose(&local);
1118                            self.expand_list(
1119                                &def.entities,
1120                                &child_tf,
1121                                depth + 1,
1122                                child_inherited,
1123                                Some(resolved_color),
1124                                Some(resolved_lw),
1125                                out,
1126                            );
1127                        }
1128                    }
1129                    self.stack.pop();
1130
1131                    // Visible attributes with display geometry become standalone text entities.
1132                    for attr in &e.attributes {
1133                        if attr.invisible {
1134                            continue;
1135                        }
1136                        let (Some(pos), Some(disp), Some(val)) =
1137                            (attr.position, attr.display.as_ref(), attr.value.as_str())
1138                        else {
1139                            continue;
1140                        };
1141                        if val.is_empty() || disp.height <= 0.0 {
1142                            continue;
1143                        }
1144                        let wf = if disp.width > 0.0 {
1145                            disp.width / disp.height
1146                        } else {
1147                            1.0
1148                        };
1149                        let attr_entity = Entity {
1150                            id: None,
1151                            layer: attr
1152                                .layer
1153                                .clone()
1154                                .or_else(|| effective_layer.map(str::to_owned)),
1155                            // The attribute record's own symbology wins; `ByBlock` and `None`
1156                            // take the insert's.
1157                            color: match attr.color {
1158                                Some(Color::ByBlock) | None => resolved_color,
1159                                Some(own) => own,
1160                            },
1161                            linetype: None,
1162                            lineweight: match attr.lineweight {
1163                                Some(Lineweight::ByBlock) | None => resolved_lw,
1164                                Some(own) => own,
1165                            },
1166                            visible: e.visible,
1167                            kind: EntityKind::Text {
1168                                position: pos,
1169                                end_point: None,
1170                                height: disp.height,
1171                                rotation: disp.rotation,
1172                                width_factor: wf,
1173                                oblique: 0.0,
1174                                value: val.to_owned(),
1175                                style: disp.style.clone(),
1176                                halign: disp.halign,
1177                                valign: disp.valign,
1178                                normal: Vec3::Z,
1179                            },
1180                            attributes: Vec::new(),
1181                            props: Default::default(),
1182                            raw: None,
1183                        };
1184                        out.push(attr_entity.transformed(tf));
1185                    }
1186                }
1187                _ => {
1188                    let mut mapped = e.transformed(tf);
1189                    mapped.layer = effective_layer.map(str::to_owned);
1190                    mapped.color = resolved_color;
1191                    mapped.lineweight = resolved_lw;
1192                    out.push(mapped);
1193                }
1194            }
1195        }
1196    }
1197}
1198
1199impl Document {
1200    /// Applies an affine [`Transform`] in-place to all design-space models (`ModelKind::Model`,
1201    /// or all models if no `ModelKind::Model` exists).
1202    ///
1203    /// Block definitions remain in block-local coordinates while [`EntityKind::Insert`] entities
1204    /// absorb the world-space transform into their placement, scale, and rotation.
1205    pub fn transform(&mut self, tf: &Transform) {
1206        let has_design = self.models.iter().any(|m| m.kind == ModelKind::Model);
1207        for model in &mut self.models {
1208            if has_design && model.kind != ModelKind::Model {
1209                continue;
1210            }
1211            for entity in &mut model.entities {
1212                *entity = entity.transformed(tf);
1213            }
1214        }
1215    }
1216
1217    /// Converts all drawing coordinates, block definitions, linetype dash patterns, and fixed
1218    /// text-style heights from [`Document::units`] to `target`, returning the applied scale factor.
1219    ///
1220    /// Returns [`Error::Unsupported`] if either [`Document::units`] or `target` has no known
1221    /// meter conversion scale (such as [`LengthUnit::Unitless`]).
1222    pub fn convert_units(&mut self, target: LengthUnit) -> Result<f64> {
1223        let src_m = self.units.meters_per_unit().ok_or_else(|| {
1224            Error::Unsupported(
1225                "cannot convert units of a unitless document; set Document::units first".into(),
1226            )
1227        })?;
1228        let dst_m = target.meters().ok_or_else(|| {
1229            Error::Unsupported(format!(
1230                "target unit '{}' does not have a fixed meter scale",
1231                target.as_str()
1232            ))
1233        })?;
1234        let factor = src_m / dst_m;
1235        if !factor.is_finite() || factor <= 0.0 {
1236            return Err(Error::Unsupported(
1237                "unit conversion produced a non-finite scale factor".into(),
1238            ));
1239        }
1240        if (factor - 1.0).abs() > 1e-15 {
1241            let tf = Transform::uniform_scale(factor);
1242            for block in &mut self.blocks {
1243                block.base_point = tf.apply_point(block.base_point);
1244                for entity in &mut block.entities {
1245                    *entity = scale_entity_units(entity, factor, &tf);
1246                }
1247            }
1248            let has_design = self.models.iter().any(|m| m.kind == ModelKind::Model);
1249            for model in &mut self.models {
1250                if has_design && model.kind != ModelKind::Model {
1251                    continue;
1252                }
1253                for entity in &mut model.entities {
1254                    *entity = scale_entity_units(entity, factor, &tf);
1255                }
1256            }
1257            for lt in &mut self.linetypes {
1258                for dash in &mut lt.pattern {
1259                    *dash *= factor;
1260                }
1261            }
1262            for ts in &mut self.text_styles {
1263                if ts.height > 0.0 {
1264                    ts.height *= factor;
1265                }
1266            }
1267        }
1268        self.units = Units {
1269            unit: target,
1270            meters_per_unit: Some(dst_m),
1271        };
1272        Ok(factor)
1273    }
1274
1275    /// Expands [`EntityKind::Insert`] block references in every model into world-space entities
1276    /// up to `max_depth`, resolving `ByBlock` symbology and `"0"` layer inheritance.
1277    ///
1278    /// Missing blocks, cyclic references, and inserts deeper than `max_depth` are kept intact.
1279    /// Work is bounded by [`DEFAULT_MAX_WORK`].
1280    pub fn explode_inserts(&mut self, max_depth: u32) -> WalkStats {
1281        let mut block_map: HashMap<&str, &Block> = HashMap::new();
1282        for b in &self.blocks {
1283            block_map.entry(b.name.as_str()).or_insert(b);
1284        }
1285        let mut exploder = Exploder {
1286            blocks: block_map,
1287            max_depth,
1288            work_left: DEFAULT_MAX_WORK,
1289            work_spent: 0,
1290            truncated: false,
1291            stack: Vec::new(),
1292        };
1293        let old_models: Vec<Vec<Entity>> = self
1294            .models
1295            .iter_mut()
1296            .map(|m| std::mem::take(&mut m.entities))
1297            .collect();
1298        let mut new_models = Vec::with_capacity(old_models.len());
1299        let id = Transform::identity();
1300        for entities in old_models {
1301            let mut expanded = Vec::with_capacity(entities.len());
1302            exploder.expand_list(&entities, &id, 0, None, None, None, &mut expanded);
1303            new_models.push(expanded);
1304        }
1305        drop(exploder.blocks);
1306        let stats = WalkStats {
1307            truncated: exploder.truncated,
1308            work: exploder.work_spent,
1309        };
1310        for (model, entities) in self.models.iter_mut().zip(new_models) {
1311            model.entities = entities;
1312        }
1313        stats
1314    }
1315
1316    /// Flattens [`EntityKind::Group`] hierarchies into their parent entity lists across all models
1317    /// and block definitions, propagating inherited layers and `ByBlock` symbology.
1318    pub fn flatten_groups(&mut self) {
1319        for model in &mut self.models {
1320            let old = std::mem::take(&mut model.entities);
1321            let mut out = Vec::with_capacity(old.len());
1322            flatten_list(old, None, Color::ByLayer, Lineweight::ByLayer, 0, &mut out);
1323            model.entities = out;
1324        }
1325        for block in &mut self.blocks {
1326            let old = std::mem::take(&mut block.entities);
1327            let mut out = Vec::with_capacity(old.len());
1328            flatten_list(old, None, Color::ByBlock, Lineweight::ByBlock, 0, &mut out);
1329            block.entities = out;
1330        }
1331    }
1332
1333    /// Converts curved entities (`Circle`, `Arc`, `Ellipse`, `Spline`, and bulged `Polyline`
1334    /// segments) across all models and blocks into straight-segment [`EntityKind::Polyline`]s
1335    /// within chordal error `tolerance`.
1336    pub fn tessellate_curves(&mut self, tolerance: f64) {
1337        for model in &mut self.models {
1338            for entity in &mut model.entities {
1339                tessellate_entity_in_place(entity, tolerance);
1340            }
1341        }
1342        for block in &mut self.blocks {
1343            for entity in &mut block.entities {
1344                tessellate_entity_in_place(entity, tolerance);
1345            }
1346        }
1347    }
1348
1349    /// Retains only layers and model entities whose effective layer name satisfies `keep`.
1350    pub fn retain_layers(&mut self, mut keep: impl FnMut(&str) -> bool) {
1351        self.layers.retain(|l| keep(&l.name));
1352        for model in &mut self.models {
1353            retain_layer_list(&mut model.entities, &mut keep);
1354        }
1355    }
1356
1357    /// Removes unreferenced [`Block`], [`crate::Layer`] (except `"0"`), [`crate::Linetype`], and
1358    /// [`crate::TextStyle`] table entries, returning counts of purged definitions.
1359    pub fn purge_unused(&mut self) -> PurgeStats {
1360        let mut used_blocks: HashSet<&str> = HashSet::new();
1361        let mut used_layers: HashSet<&str> = HashSet::new();
1362        let mut used_linetypes: HashSet<&str> = HashSet::new();
1363        let mut used_styles: HashSet<&str> = HashSet::new();
1364
1365        let block_lookup: HashMap<&str, &Block> =
1366            self.blocks.iter().map(|b| (b.name.as_str(), b)).collect();
1367        let mut pending_blocks: Vec<&str> = Vec::new();
1368
1369        for model in &self.models {
1370            collect_refs(
1371                &model.entities,
1372                &mut pending_blocks,
1373                &mut used_layers,
1374                &mut used_linetypes,
1375                &mut used_styles,
1376            );
1377        }
1378        while let Some(bname) = pending_blocks.pop() {
1379            if !used_blocks.insert(bname) {
1380                continue;
1381            }
1382            if let Some(def) = block_lookup.get(bname) {
1383                collect_refs(
1384                    &def.entities,
1385                    &mut pending_blocks,
1386                    &mut used_layers,
1387                    &mut used_linetypes,
1388                    &mut used_styles,
1389                );
1390            }
1391        }
1392
1393        let used_blocks_owned: HashSet<String> =
1394            used_blocks.into_iter().map(str::to_owned).collect();
1395        let used_layers_owned: HashSet<String> =
1396            used_layers.into_iter().map(str::to_owned).collect();
1397        let mut used_linetypes_owned: HashSet<String> =
1398            used_linetypes.into_iter().map(str::to_owned).collect();
1399        let used_styles_owned: HashSet<String> =
1400            used_styles.into_iter().map(str::to_owned).collect();
1401
1402        let blocks_before = self.blocks.len();
1403        self.blocks.retain(|b| used_blocks_owned.contains(&b.name));
1404
1405        let layers_before = self.layers.len();
1406        self.layers
1407            .retain(|l| l.name == "0" || used_layers_owned.contains(&l.name));
1408        for l in &self.layers {
1409            if let Some(lt) = &l.linetype {
1410                used_linetypes_owned.insert(lt.clone());
1411            }
1412        }
1413
1414        let linetypes_before = self.linetypes.len();
1415        self.linetypes
1416            .retain(|lt| used_linetypes_owned.contains(&lt.name));
1417
1418        let styles_before = self.text_styles.len();
1419        self.text_styles
1420            .retain(|ts| used_styles_owned.contains(&ts.name));
1421
1422        PurgeStats {
1423            blocks: blocks_before - self.blocks.len(),
1424            layers: layers_before - self.layers.len(),
1425            linetypes: linetypes_before - self.linetypes.len(),
1426            text_styles: styles_before - self.text_styles.len(),
1427        }
1428    }
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433    use super::*;
1434    use crate::model::{
1435        AttributeDisplay, GroupKind, HAlign, Layer, Linetype, TextStyle, VAlign, Value,
1436    };
1437
1438    #[test]
1439    fn anisotropic_circle_promotes_to_ellipse_and_uniform_stays_circle() {
1440        let c = Entity::circle(Point3::xy(1.0, 2.0), 5.0);
1441        let uniform = c.transformed(&Transform::uniform_scale(2.0));
1442        assert_eq!(
1443            uniform.kind,
1444            EntityKind::Circle {
1445                center: Point3::xy(2.0, 4.0),
1446                radius: 10.0,
1447                normal: Vec3::Z,
1448            }
1449        );
1450
1451        let stretched = c.transformed(&Transform::scaling(2.0, 1.0, 1.0));
1452        match stretched.kind {
1453            EntityKind::Ellipse {
1454                center,
1455                major_axis,
1456                ratio,
1457                ..
1458            } => {
1459                assert_eq!(center, Point3::xy(2.0, 2.0));
1460                assert!((major_axis.length() - 10.0).abs() < 1e-9);
1461                assert!((ratio - 0.5).abs() < 1e-9);
1462            }
1463            other => panic!("expected Ellipse, got {other:?}"),
1464        }
1465    }
1466
1467    #[test]
1468    fn convert_units_scales_blocks_and_models_without_double_scaling_inserts() {
1469        let mut doc = Document::new();
1470        doc.units = Units::from_insunits(4); // Millimeter
1471        doc.blocks.push(Block {
1472            name: "DOOR".into(),
1473            base_point: Point3::ZERO,
1474            entities: vec![Entity::line(Point3::ZERO, Point3::xy(900.0, 0.0))],
1475            ..Block::default()
1476        });
1477        doc.linetypes.push(Linetype {
1478            name: "DASHED".into(),
1479            pattern: vec![10.0, -5.0],
1480            ..Linetype::default()
1481        });
1482        doc.model_space_mut()
1483            .entities
1484            .push(Entity::insert("DOOR", Point3::xy(3000.0, 0.0)));
1485
1486        let factor = doc.convert_units(LengthUnit::Meter).unwrap();
1487        assert!((factor - 0.001).abs() < 1e-12);
1488        assert_eq!(doc.units.unit, LengthUnit::Meter);
1489        assert_eq!(doc.linetypes[0].pattern, vec![0.01, -0.005]);
1490
1491        let bb = doc.bbox(0).unwrap();
1492        assert!((bb.min.x - 3.0).abs() < 1e-9);
1493        assert!((bb.max.x - 3.9).abs() < 1e-9);
1494    }
1495
1496    #[test]
1497    fn explode_inserts_flatten_groups_tessellate_retain_and_purge() {
1498        let mut doc = Document::new();
1499        doc.layers.push(Layer {
1500            name: "WALLS".into(),
1501            visible: true,
1502            ..Layer::default()
1503        });
1504        doc.layers.push(Layer {
1505            name: "UNUSED_LAYER".into(),
1506            visible: true,
1507            ..Layer::default()
1508        });
1509        doc.linetypes.push(Linetype {
1510            name: "UNUSED_LT".into(),
1511            ..Linetype::default()
1512        });
1513        doc.text_styles.push(TextStyle {
1514            name: "UNUSED_STYLE".into(),
1515            ..TextStyle::default()
1516        });
1517        doc.blocks.push(Block {
1518            name: "SYM".into(),
1519            entities: vec![Entity::circle(Point3::ZERO, 2.0).with_color(Color::ByBlock)],
1520            ..Block::default()
1521        });
1522        doc.blocks.push(Block {
1523            name: "UNUSED_BLK".into(),
1524            ..Block::default()
1525        });
1526
1527        let mut ins = Entity::insert("SYM", Point3::xy(10.0, 20.0))
1528            .on_layer("WALLS")
1529            .with_color(Color::aci(1));
1530        ins.attributes.push(Attribute {
1531            tag: "ID".into(),
1532            value: "R-1".into(),
1533            position: Some(Point3::xy(10.0, 22.0)),
1534            invisible: false,
1535            display: Some(AttributeDisplay {
1536                height: 1.5,
1537                width: 1.5,
1538                style: None,
1539                halign: HAlign::Center,
1540                valign: VAlign::Middle,
1541                rotation: 0.0,
1542            }),
1543            ..Attribute::default()
1544        });
1545
1546        let grp = Entity::new(EntityKind::Group {
1547            group_kind: GroupKind::Cell,
1548            name: Some("G".into()),
1549            origin: None,
1550            children: vec![Entity::line(Point3::ZERO, Point3::xy(1.0, 1.0)).on_layer("OTHER")],
1551        });
1552        doc.model_space_mut().entities.extend([ins, grp]);
1553
1554        let stats = doc.explode_inserts(8);
1555        assert!(!stats.truncated);
1556        doc.flatten_groups();
1557        assert_eq!(doc.model_space().unwrap().entities.len(), 3); // circle + attr text + flattened line
1558
1559        doc.retain_layers(|l| l == "WALLS");
1560        assert_eq!(doc.model_space().unwrap().entities.len(), 2);
1561
1562        doc.tessellate_curves(0.05);
1563        assert!(matches!(
1564            doc.model_space().unwrap().entities[0].kind,
1565            EntityKind::Polyline { closed: true, .. }
1566        ));
1567
1568        let purged = doc.purge_unused();
1569        assert_eq!(purged.blocks, 2); // SYM was exploded, UNUSED_BLK never used!
1570        assert_eq!(purged.linetypes, 1);
1571        assert_eq!(purged.text_styles, 1);
1572    }
1573
1574    #[test]
1575    fn exploded_attributes_keep_their_own_symbology() {
1576        let display = || AttributeDisplay {
1577            height: 1.0,
1578            width: 1.0,
1579            style: None,
1580            halign: HAlign::Left,
1581            valign: VAlign::Baseline,
1582            rotation: 0.0,
1583        };
1584        let attribute = |tag: &str| Attribute {
1585            tag: tag.into(),
1586            value: "v".into(),
1587            position: Some(Point3::xy(1.0, 1.0)),
1588            display: Some(display()),
1589            ..Attribute::default()
1590        };
1591        let mut doc = Document::new();
1592        doc.blocks.push(Block {
1593            name: "B".into(),
1594            ..Block::default()
1595        });
1596        let mut ins = Entity::insert("B", Point3::ZERO)
1597            .with_color(Color::aci(1))
1598            .with_lineweight(Lineweight::Millimeters(0.25));
1599        let mut own = attribute("OWN");
1600        own.color = Some(Color::aci(5));
1601        own.lineweight = Some(Lineweight::Millimeters(0.7));
1602        let mut by_block = attribute("BYBLOCK");
1603        by_block.color = Some(Color::ByBlock);
1604        by_block.lineweight = Some(Lineweight::ByBlock);
1605        ins.attributes = vec![own, by_block, attribute("NONE")];
1606        doc.model_space_mut().entities.push(ins);
1607        doc.explode_inserts(8);
1608        let symbology: Vec<(Color, Lineweight)> = doc
1609            .model_space()
1610            .unwrap()
1611            .entities
1612            .iter()
1613            .map(|e| (e.color, e.lineweight))
1614            .collect();
1615        assert_eq!(
1616            symbology,
1617            vec![
1618                (Color::aci(5), Lineweight::Millimeters(0.7)),
1619                (Color::aci(1), Lineweight::Millimeters(0.25)),
1620                (Color::aci(1), Lineweight::Millimeters(0.25)),
1621            ]
1622        );
1623    }
1624
1625    #[test]
1626    fn curve_tangent_props_do_not_outlive_a_turn() {
1627        let mut spline = Entity::line(Point3::ZERO, Point3::xy(1.0, 0.0));
1628        for key in DIRECTION_PROPS {
1629            spline.props.insert(
1630                key.into(),
1631                Value::List(vec![
1632                    Value::Float(1.0),
1633                    Value::Float(0.0),
1634                    Value::Float(0.0),
1635                ]),
1636            );
1637        }
1638        spline.props.insert("dgn.level_id".into(), Value::Int(3));
1639        let kept = |e: &Entity| DIRECTION_PROPS.map(|k| e.props.contains_key(k));
1640        // Translation and positive uniform scale keep directions and slopes.
1641        let mut moved = Transform::uniform_scale(2.5);
1642        moved.t = Vec3::new(4.0, -1.0, 0.0);
1643        assert_eq!(kept(&spline.transformed(&moved)), [true, true]);
1644        // A turn, a mirror or a non-uniform scale drops them; other props stay.
1645        let mut turned = Transform::uniform_scale(1.0);
1646        turned.x = Vec3::new(0.0, 1.0, 0.0);
1647        turned.y = Vec3::new(-1.0, 0.0, 0.0);
1648        for tf in [
1649            turned,
1650            Transform::scaling(-1.0, 1.0, 1.0),
1651            Transform::scaling(2.0, 1.0, 1.0),
1652        ] {
1653            let out = spline.transformed(&tf);
1654            assert_eq!(kept(&out), [false, false]);
1655            assert_eq!(out.props.get("dgn.level_id"), Some(&Value::Int(3)));
1656        }
1657    }
1658}