Skip to main content

rscad_csg_bsp/primitives/
polygon.rs

1use crate::*;
2use nalgebra::Point;
3use num_traits::real::Real;
4
5/// Create a regular polygon with `sides` sides inscribed in a circle of the given `radius`.
6///
7/// The polygon lies in the XZ plane, centered at the origin.
8/// This is the BSP equivalent of `rscad_core::Polygon<N>` / `PolygonDynamic`.
9pub fn regular_polygon<T: Number>(radius: T, sides: usize) -> Csg<T> {
10    let sides_t = T::from(sides).expect("Failed to convert sides to generic T");
11    let pi = T::PI();
12    let two = T::one() + T::one();
13    let two_pi = two * pi;
14    Csg::from_polygons([Polygon::from_points(
15        (0..sides)
16            .flat_map(|v| T::from(v))
17            .map(|side| {
18                let angle = two_pi * side / sides_t;
19                Point::from([
20                    radius * Real::cos(angle),
21                    T::zero(),
22                    radius * Real::sin(angle),
23                ])
24            })
25            .collect::<Vec<_>>(),
26    )
27    .expect("Impossible")])
28}