microcad_core/geo2d/
mod.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! 2D Geometry
5
6mod bounds;
7mod circle;
8mod collection;
9mod geometry;
10mod line;
11mod primitives;
12mod size;
13
14use crate::*;
15
16pub use bounds::*;
17pub use circle::*;
18pub use collection::*;
19use geo::AffineTransform;
20pub use geometry::*;
21pub use line::*;
22pub use primitives::*;
23pub use size::*;
24
25/// Trait to render a [`Geometry2D`] into a multi polygon.
26pub trait RenderToMultiPolygon: Sized {
27    /// Render geometry into a [`Polygon`].
28    ///
29    /// Implement this method if the geometry only returns a single polygon.
30    /// Line geometry returns [`None`].
31    fn render_to_polygon(&self, _: &RenderResolution) -> Option<Polygon> {
32        None
33    }
34
35    /// Render a geometry into a new multi polygon.
36    ///
37    /// This method uses [`RenderToMultiPolygon::render_to_existing_multi_polygon`] and does not need to be reimplemented.  
38    fn render_to_multi_polygon(&self, resolution: &RenderResolution) -> MultiPolygon {
39        let mut polygons = geo::MultiPolygon(vec![]);
40        self.render_to_existing_multi_polygon(resolution, &mut polygons);
41        polygons
42    }
43
44    /// Render a geometry into a new multi polygon and attaches it to a list of existing polygons.
45    ///
46    /// Reimplement this function preferably if the geometry returns more than one polygon.
47    fn render_to_existing_multi_polygon(
48        &self,
49        resolution: &RenderResolution,
50        polygons: &mut MultiPolygon,
51    ) {
52        if let Some(polygon) = self.render_to_polygon(resolution) {
53            polygons.0.push(polygon);
54        }
55    }
56}
57
58/// Trait to return all points of 2D geometry.
59pub trait FetchPoints2D {
60    /// Returns all points.
61    fn fetch_points_2d(&self) -> Vec<Vec2>;
62}
63
64/// Transformed version of a 2D geometry.
65pub trait Transformed2D<T = Self> {
66    /// Transform from matrix.
67    fn transformed_2d(&self, render_resolution: &RenderResolution, mat: &Mat3) -> T;
68}
69
70/// Convert a [`Mat3`]` into an affine transform.
71pub(crate) fn mat3_to_affine_transform(mat: &Mat3) -> AffineTransform {
72    geo::AffineTransform::new(mat.x.x, mat.y.x, mat.z.x, mat.x.y, mat.y.y, mat.z.y)
73}