Skip to main content

xpict_core/geom/
ops.rs

1//! Thin wrappers over `i_overlay` (boolean ops, simplify, outline / stroke).
2
3use i_overlay::core::fill_rule::FillRule;
4use i_overlay::core::overlay_rule::OverlayRule;
5use i_overlay::float::simplify::SimplifyShape;
6use i_overlay::float::single::SingleFloatOverlay;
7use i_overlay::i_shape::float::area::Area;
8use i_overlay::mesh::float::outline::offset::OutlineOffset;
9use i_overlay::mesh::float::stroke::offset::StrokeOffset;
10use i_overlay::mesh::float::style::{LineCap, LineJoin, OutlineStyle, StrokeStyle};
11
12use super::{capsule_polygon, circle_polygon, polygon_to_svg_d};
13
14type Contour = Vec<[f64; 2]>;
15type OverlayShape = Vec<Contour>;
16type Shapes = Vec<OverlayShape>;
17
18/// Multipolygon ink / halo geometry.
19#[derive(Clone, Debug, Default)]
20pub struct Shape {
21    shapes: Shapes,
22}
23
24fn pt(p: (f64, f64)) -> [f64; 2] {
25    [p.0, p.1]
26}
27
28fn xy(p: [f64; 2]) -> (f64, f64) {
29    (p[0], p[1])
30}
31
32impl Shape {
33    fn wrap(shapes: Shapes) -> Self {
34        Self { shapes }
35    }
36
37    pub fn empty() -> Self {
38        Self::wrap(Vec::new())
39    }
40
41    pub fn is_empty(&self) -> bool {
42        self.shapes.is_empty() || self.shapes.iter().all(|s| s.is_empty() || s[0].len() < 3)
43    }
44
45    /// Single exterior ring (lib-simplify cleans winding / collinear).
46    pub fn from_ring(ring: &[(f64, f64)]) -> Self {
47        if ring.len() < 3 {
48            return Self::empty();
49        }
50        let c: Contour = ring.iter().copied().map(pt).collect();
51        Self::wrap(c.simplify_shape(FillRule::NonZero))
52    }
53
54    /// Independent contours → even-odd / XOR shape (glyph counters).
55    pub fn from_contours_evenodd(contours: &[Vec<(f64, f64)>]) -> Self {
56        let parts: Vec<Contour> = contours
57            .iter()
58            .filter(|r| r.len() >= 3)
59            .map(|r| r.iter().copied().map(pt).collect())
60            .collect();
61        if parts.is_empty() {
62            return Self::empty();
63        }
64        Self::wrap(parts.simplify_shape(FillRule::EvenOdd))
65    }
66
67    pub fn disk(cx: f64, cy: f64, radius: f64, quad_segs: u32) -> Self {
68        Self::from_ring(&circle_polygon(cx, cy, radius, quad_segs))
69    }
70
71    pub fn capsule(x1: f64, y1: f64, x2: f64, y2: f64, radius: f64) -> Self {
72        Self::from_ring(&capsule_polygon(x1, y1, x2, y2, radius, 8))
73    }
74
75    pub fn polyline_buffer(pts: &[(f64, f64)], radius: f64) -> Self {
76        if pts.len() < 2 || radius <= 0.0 {
77            return Self::empty();
78        }
79        if pts.len() == 2 {
80            return Self::capsule(pts[0].0, pts[0].1, pts[1].0, pts[1].1, radius);
81        }
82        let path: Contour = pts.iter().copied().map(pt).collect();
83        let r = radius.max(0.05) * 0.2;
84        let style = StrokeStyle::new(radius * 2.0)
85            .line_join(LineJoin::Round(r))
86            .start_cap(LineCap::Round(r))
87            .end_cap(LineCap::Round(r));
88        Self::wrap(path.stroke(style, false))
89    }
90
91    pub fn multipoint_buffer(pts: &[(f64, f64)], radius: f64) -> Self {
92        pts.iter().fold(Self::empty(), |acc, &(x, y)| {
93            acc.union(&Self::disk(x, y, radius, 8))
94        })
95    }
96
97    pub fn annular(cx: f64, cy: f64, r: f64, stroke_width: f64) -> Self {
98        if r <= 0.0 || stroke_width <= 0.0 {
99            return Self::empty();
100        }
101        let outer = Self::disk(cx, cy, r + 0.5 * stroke_width, 16);
102        let inner_r = r - 0.5 * stroke_width;
103        if inner_r > 1e-6 {
104            outer.difference(&Self::disk(cx, cy, inner_r, 16))
105        } else {
106            outer
107        }
108    }
109
110    fn overlay_with(&self, other: &Self, rule: OverlayRule) -> Self {
111        Self::wrap(self.shapes.overlay(&other.shapes, rule, FillRule::NonZero))
112    }
113
114    pub fn union(&self, other: &Self) -> Self {
115        if self.is_empty() {
116            return other.clone();
117        }
118        if other.is_empty() {
119            return self.clone();
120        }
121        self.overlay_with(other, OverlayRule::Union)
122    }
123
124    pub fn difference(&self, other: &Self) -> Self {
125        if self.is_empty() {
126            return Self::empty();
127        }
128        if other.is_empty() {
129            return self.clone();
130        }
131        self.overlay_with(other, OverlayRule::Difference)
132    }
133
134    pub fn xor(&self, other: &Self) -> Self {
135        self.overlay_with(other, OverlayRule::Xor)
136    }
137
138    /// Outline offset (`dist` may be negative).
139    pub fn buffer(&self, dist: f64) -> Self {
140        if self.is_empty() || dist.abs() < 1e-15 {
141            return self.clone();
142        }
143        let join = LineJoin::Round((dist.abs() * 0.35).max(0.25));
144        Self::wrap(
145            self.shapes
146                .outline(&OutlineStyle::new(dist).line_join(join)),
147        )
148    }
149
150    /// `i_overlay::SimplifyShape` (collinear cleanup; holes stay valid).
151    pub fn simplify(&self) -> Self {
152        if self.is_empty() {
153            return Self::empty();
154        }
155        Self::wrap(self.shapes.simplify_shape(FillRule::NonZero))
156    }
157
158    pub fn point_count(&self) -> usize {
159        self.shapes
160            .iter()
161            .flat_map(|s| s.iter())
162            .map(|c| c.len())
163            .sum()
164    }
165
166    /// White knockout: simplify, then outline offset.
167    pub fn halo(&self, dist: f64) -> Self {
168        if self.is_empty() || dist <= 0.0 {
169            return Self::empty();
170        }
171        self.simplify().buffer(dist)
172    }
173
174    pub fn has_holes(&self) -> bool {
175        self.shapes.iter().any(|s| s.len() > 1)
176    }
177
178    pub fn translate(&self, dx: f64, dy: f64) -> Self {
179        let mut shapes = self.shapes.clone();
180        for p in shapes.iter_mut().flatten().flatten() {
181            p[0] += dx;
182            p[1] += dy;
183        }
184        Self::wrap(shapes)
185    }
186
187    pub fn scale(&self, sx: f64, sy: f64, ox: f64, oy: f64) -> Self {
188        let mut shapes = self.shapes.clone();
189        for p in shapes.iter_mut().flatten().flatten() {
190            p[0] = ox + (p[0] - ox) * sx;
191            p[1] = oy + (p[1] - oy) * sy;
192        }
193        // Negative scale flips winding — lib simplify restores topology.
194        Self::wrap(shapes).simplify()
195    }
196
197    pub fn bounds(&self) -> Option<(f64, f64, f64, f64)> {
198        let mut iter = self.shapes.iter().flatten().flatten();
199        let first = iter.next()?;
200        let (mut minx, mut miny, mut maxx, mut maxy) = (first[0], first[1], first[0], first[1]);
201        for p in iter {
202            minx = minx.min(p[0]);
203            miny = miny.min(p[1]);
204            maxx = maxx.max(p[0]);
205            maxy = maxy.max(p[1]);
206        }
207        Some((minx, miny, maxx, maxy))
208    }
209
210    pub fn area(&self) -> f64 {
211        self.shapes.area().abs()
212    }
213
214    pub fn centroid(&self) -> Option<(f64, f64)> {
215        let (minx, miny, maxx, maxy) = self.bounds()?;
216        Some(((minx + maxx) * 0.5, (miny + maxy) * 0.5))
217    }
218
219    pub fn contains(&self, x: f64, y: f64) -> bool {
220        // Even-odd over all contours in each shape (holes flip).
221        self.shapes.iter().any(|shape| {
222            shape
223                .iter()
224                .filter(|c| c.len() >= 3)
225                .fold(false, |inside, c| inside ^ point_in_ring(x, y, c))
226        })
227    }
228
229    pub fn to_svg_d(&self) -> String {
230        self.shapes
231            .iter()
232            .flatten()
233            .filter(|c| c.len() >= 3)
234            .map(|c| {
235                let ring: Vec<(f64, f64)> = c.iter().copied().map(xy).collect();
236                polygon_to_svg_d(&ring)
237            })
238            .filter(|d| !d.is_empty())
239            .collect::<Vec<_>>()
240            .join(" ")
241    }
242
243    /// Leftmost horizontal chord length at `y` (stem-width helper).
244    pub fn horizontal_span_at(&self, y: f64) -> f64 {
245        let mut xs = Vec::new();
246        for contour in self.shapes.iter().flatten() {
247            let n = contour.len();
248            for i in 0..n {
249                let a = contour[i];
250                let b = contour[(i + 1) % n];
251                if (a[1] - y) * (b[1] - y) > 0.0 || (a[1] - b[1]).abs() < 1e-15 {
252                    continue;
253                }
254                let t = (y - a[1]) / (b[1] - a[1]);
255                if (0.0..=1.0).contains(&t) {
256                    xs.push(a[0] + t * (b[0] - a[0]));
257                }
258            }
259        }
260        if xs.len() < 2 {
261            return 0.0;
262        }
263        xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
264        xs.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
265        if xs.len() < 2 {
266            0.0
267        } else {
268            xs[1] - xs[0]
269        }
270    }
271
272    #[allow(clippy::type_complexity)]
273    pub fn polygons_rings(&self) -> Vec<(Vec<(f64, f64)>, Vec<Vec<(f64, f64)>>)> {
274        self.shapes
275            .iter()
276            .filter(|s| !s.is_empty())
277            .map(|shape| {
278                let exterior: Vec<(f64, f64)> = shape[0].iter().copied().map(xy).collect();
279                let holes: Vec<Vec<(f64, f64)>> = shape[1..]
280                    .iter()
281                    .map(|c| c.iter().copied().map(xy).collect())
282                    .collect();
283                (exterior, holes)
284            })
285            .collect()
286    }
287}
288
289fn point_in_ring(x: f64, y: f64, ring: &Contour) -> bool {
290    let n = ring.len();
291    let mut inside = false;
292    let mut j = n - 1;
293    for i in 0..n {
294        let (xi, yi) = (ring[i][0], ring[i][1]);
295        let (xj, yj) = (ring[j][0], ring[j][1]);
296        if ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi + f64::EPSILON) + xi) {
297            inside = !inside;
298        }
299        j = i;
300    }
301    inside
302}