Skip to main content

blit_gui/
path.rs

1use alloc::vec::Vec;
2use core::{
3    hash::{Hash, Hasher},
4    ops::Deref,
5};
6
7use blit::{FrameSlice, HasFrameStore, LogicalPoint, LogicalRect, Paint};
8
9use crate::{
10    color::Color,
11    display_list::{Compare, DisplayList},
12    rectangle::FrameFill,
13    style::Fill,
14};
15
16// todo: dashes
17
18blit::builder! {
19    /// filled or stroked vector path in logical coordinates
20    ///
21    /// subpaths are closed implicitly when filled
22    #[derive(Clone, Copy, Debug, PartialEq)]
23    pub struct Path<'a> {
24        new(verbs: &'a [Verb], points: &'a [LogicalPoint]),
25        #[into]
26        fill: Fill<'a> = Fill::Solid(Color::TRANSPARENT),
27        rule: FillRule = FillRule::NonZero,
28        /// paints the stroke outline with the fill instead of the interior
29        #[into]
30        stroke: Option<Stroke> = None,
31        opacity: f32 = 1.0,
32    }
33}
34
35impl Path<'_> {
36    /// stores borrowed geometry in the context and paints the result
37    pub fn paint<C: HasFrameStore + Paint<FramePath, Scalar = f32>>(self, context: &mut C) {
38        if self.fill == Fill::Solid(Color::TRANSPARENT) || self.opacity <= 0.0 {
39            return;
40        }
41        let Some(bounds) = self.bounds() else {
42            return;
43        };
44        let verbs = context.store_mut().slice_from(self.verbs);
45        let points = context.store_mut().slice_from(self.points);
46        let stored = FramePath {
47            verbs,
48            points,
49            fill: FrameFill::new(self.fill, context),
50            rule: self.rule,
51            stroke: self.stroke,
52            opacity: self.opacity,
53        };
54        context.paint(bounds, &stored);
55    }
56
57    /// conservative bounds of all points or none when the geometry is malformed or empty
58    pub fn bounds(&self) -> Option<LogicalRect> {
59        let count = self.verbs.iter().map(|verb| verb.points()).sum::<usize>();
60        if count != self.points.len() || self.points.is_empty() {
61            return None;
62        }
63        let mut min = [f32::INFINITY; 2];
64        let mut max = [f32::NEG_INFINITY; 2];
65        for point in self.points {
66            if !point.x.is_finite() || !point.y.is_finite() {
67                return None;
68            }
69            min = [min[0].min(point.x), min[1].min(point.y)];
70            max = [max[0].max(point.x), max[1].max(point.y)];
71        }
72        // miters reach furthest and square caps reach half the width diagonally
73        let outset = self.stroke.map_or(0.0, |stroke| {
74            let reach = match stroke.join {
75                Join::Miter => stroke.miter_limit.max(core::f32::consts::SQRT_2),
76                Join::Bevel | Join::Round => core::f32::consts::SQRT_2,
77            };
78            0.5 * stroke.width * reach
79        });
80        Some(LogicalRect {
81            x: min[0] - outset,
82            y: min[1] - outset,
83            width: max[0] - min[0] + 2.0 * outset,
84            height: max[1] - min[1] + 2.0 * outset,
85        })
86    }
87}
88
89blit::builder! {
90    #[derive(Clone, Copy, Debug, PartialEq)]
91    pub struct Stroke {
92        new(width: f32),
93        join: Join = Join::Miter,
94        cap: Cap = Cap::Butt,
95        /// miter length over width before a miter join falls back to bevel
96        miter_limit: f32 = 4.0,
97    }
98}
99
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
101pub enum Join {
102    Bevel,
103    #[default]
104    Miter,
105    Round,
106}
107
108#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
109pub enum Cap {
110    #[default]
111    Butt,
112    Square,
113    Round,
114}
115
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub enum Verb {
118    Move,
119    Line,
120    Quad,
121    Cubic,
122    Close,
123}
124
125impl Verb {
126    pub const fn points(self) -> usize {
127        match self {
128            Self::Move | Self::Line => 1,
129            Self::Quad => 2,
130            Self::Cubic => 3,
131            Self::Close => 0,
132        }
133    }
134}
135
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum FillRule {
138    #[default]
139    NonZero,
140    EvenOdd,
141}
142
143/// builds path geometry in owned or borrowed buffers
144#[derive(Clone, Debug, Default, PartialEq)]
145pub struct PathBuilder<V = Vec<Verb>, P = Vec<LogicalPoint>> {
146    pub verbs: V,
147    pub points: P,
148}
149
150impl PathBuilder {
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    pub fn clear(&mut self) {
156        self.verbs.clear();
157        self.points.clear();
158    }
159}
160
161impl PathBuilder<blit::Scratch<'_, Verb>, blit::Scratch<'_, LogicalPoint>> {
162    pub fn clear(&mut self) {
163        self.verbs.clear();
164        self.points.clear();
165    }
166}
167
168impl<V, P> PathBuilder<V, P>
169where
170    V: Deref<Target = [Verb]> + Extend<Verb>,
171    P: Deref<Target = [LogicalPoint]> + Extend<LogicalPoint>,
172{
173    pub fn path(&self) -> Path<'_> {
174        Path::new(&self.verbs, &self.points)
175    }
176
177    pub fn move_to(&mut self, x: f32, y: f32) -> &mut Self {
178        self.verbs.extend([Verb::Move]);
179        self.points.extend([LogicalPoint { x, y }]);
180        self
181    }
182
183    pub fn line_to(&mut self, x: f32, y: f32) -> &mut Self {
184        self.verbs.extend([Verb::Line]);
185        self.points.extend([LogicalPoint { x, y }]);
186        self
187    }
188
189    pub fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) -> &mut Self {
190        self.verbs.extend([Verb::Quad]);
191        self.points
192            .extend([LogicalPoint { x: cx, y: cy }, LogicalPoint { x, y }]);
193        self
194    }
195
196    pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) -> &mut Self {
197        self.verbs.extend([Verb::Cubic]);
198        self.points.extend([
199            LogicalPoint { x: c1x, y: c1y },
200            LogicalPoint { x: c2x, y: c2y },
201            LogicalPoint { x, y },
202        ]);
203        self
204    }
205
206    pub fn close(&mut self) -> &mut Self {
207        self.verbs.extend([Verb::Close]);
208        self
209    }
210
211    /// clockwise rectangle subpath
212    pub fn rect(&mut self, area: LogicalRect) -> &mut Self {
213        let (right, bottom) = (area.x + area.width, area.y + area.height);
214        self.move_to(area.x, area.y)
215            .line_to(right, area.y)
216            .line_to(right, bottom)
217            .line_to(area.x, bottom)
218            .close()
219    }
220
221    /// clockwise circle subpath from four cubic arcs
222    pub fn circle(&mut self, x: f32, y: f32, radius: f32) -> &mut Self {
223        let k = radius * 0.552_284_8;
224        self.move_to(x + radius, y)
225            .cubic_to(x + radius, y + k, x + k, y + radius, x, y + radius)
226            .cubic_to(x - k, y + radius, x - radius, y + k, x - radius, y)
227            .cubic_to(x - radius, y - k, x - k, y - radius, x, y - radius)
228            .cubic_to(x + k, y - radius, x + radius, y - k, x + radius, y)
229            .close()
230    }
231}
232
233impl Hash for Path<'_> {
234    fn hash<H: Hasher>(&self, state: &mut H) {
235        self.verbs.hash(state);
236        self.points.len().hash(state);
237        for point in self.points {
238            [point.x, point.y]
239                .map(|value| if value == 0.0 { 0 } else { value.to_bits() })
240                .hash(state);
241        }
242        self.fill.hash(state);
243        self.rule.hash(state);
244        if let Some(stroke) = self.stroke {
245            [stroke.width, stroke.miter_limit]
246                .map(|value| if value == 0.0 { 0 } else { value.to_bits() })
247                .hash(state);
248            (stroke.join, stroke.cap).hash(state);
249        }
250        state.write_u32(if self.opacity == 0.0 { 0 } else { self.opacity.to_bits() });
251    }
252}
253
254/// path slices stored in a rendering context
255#[derive(Clone, Copy)]
256pub struct FramePath {
257    pub verbs: FrameSlice<Verb>,
258    pub points: FrameSlice<LogicalPoint>,
259    pub fill: FrameFill,
260    pub rule: FillRule,
261    pub stroke: Option<Stroke>,
262    pub opacity: f32,
263}
264
265impl FramePath {
266    pub fn view<'a>(&self, list: &'a DisplayList) -> Path<'a> {
267        Path {
268            verbs: list.store().view(self.verbs),
269            points: list.store().view(self.points),
270            fill: self.fill.view(list),
271            rule: self.rule,
272            stroke: self.stroke,
273            opacity: self.opacity,
274        }
275    }
276}
277
278impl Compare for FramePath {
279    fn equal(a: &Self, left: &DisplayList, b: &Self, right: &DisplayList) -> bool {
280        a.view(left) == b.view(right)
281    }
282
283    fn hash(input: &Self, list: &DisplayList, state: &mut impl Hasher) {
284        input.view(list).hash(state);
285    }
286}