Skip to main content

gpui_material_foundation/
shape.rs

1mod clip;
2mod morph;
3mod polygon;
4#[cfg(test)]
5mod tests;
6
7use gpui::{
8    Bounds, FillOptions, Hsla, Path, PathBuilder, PathStyle, Pixels, Point, Window, point, px, size,
9};
10use gpui_material_theme::{CornerShape, Direction, MaterialShape};
11use polymorpher::{Cubic, geometry::Point as PolygonPoint};
12
13use clip::{
14    bounds_overlap, clip_convex_polygon_fill, clip_path_fill, clip_polygon_to_rect, clip_rect_fill,
15    contains_fill, cross, polygon_area, rect_is_valid, segment_distance_sq,
16    triangle_disjoint_from_rect,
17};
18use polygon::rounded_rect_cubics;
19
20pub(crate) use clip::clipped_ripple;
21pub use morph::{PolygonMorph, ShapeMorph, ShapeMorphSequence};
22pub use polygon::ShapePolygon;
23
24/// How a normalized polygon contour maps into layout bounds.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub enum ShapeFit {
27    /// Fits the centered unit square inside the shorter side while preserving aspect ratio.
28    #[default]
29    Contain,
30    /// Scales independently to fill the width and height of the bounds.
31    Stretch,
32}
33
34/// A prepared shape with a shared mesh for drawing, clipping, hit testing, and effects.
35#[derive(Clone)]
36pub struct Shape {
37    outline: Outline,
38    fill: Path<Pixels>,
39    stroke_cache: std::sync::OnceLock<(u32, Path<Pixels>)>,
40}
41
42#[derive(Clone)]
43struct Outline {
44    cubics: Vec<Cubic>,
45    bounds: Bounds<Pixels>,
46    fit: ShapeFit,
47    rotation: f32,
48    pivot: PolygonPoint,
49    scale: f32,
50}
51
52impl Outline {
53    fn add_to_builder(&self, builder: &mut PathBuilder) -> bool {
54        let size = self.bounds.size;
55        let side = size.width.min(size.height);
56        if !(side > px(0.) && side < px(f32::INFINITY))
57            || !self.rotation.is_finite()
58            || !self.scale.is_finite()
59            || self.scale <= 0.
60        {
61            return false;
62        }
63        let Some(first) = self.cubics.first() else {
64            return false;
65        };
66        let center = self.bounds.center();
67        let (width, height) = match self.fit {
68            ShapeFit::Contain => (side, side),
69            ShapeFit::Stretch => (size.width, size.height),
70        };
71        let (sin, cos) = self.rotation.sin_cos();
72        let project = |p: PolygonPoint| {
73            let dx = p.x - self.pivot.x;
74            let dy = p.y - self.pivot.y;
75            let (rx, ry) = if self.rotation == 0. {
76                (dx, dy)
77            } else {
78                (cos * dx - sin * dy, sin * dx + cos * dy)
79            };
80            center + point(width * (self.scale * rx), height * (self.scale * ry))
81        };
82        builder.move_to(project(first.anchor0()));
83        for cubic in &self.cubics {
84            builder.cubic_bezier_to(
85                project(cubic.anchor1()),
86                project(cubic.control0()),
87                project(cubic.control1()),
88            );
89        }
90        builder.close();
91        true
92    }
93
94    fn path(&self, mut builder: PathBuilder) -> Option<Path<Pixels>> {
95        if !self.add_to_builder(&mut builder) {
96            return None;
97        }
98        builder.build().ok()
99    }
100}
101
102impl Shape {
103    /// Resolves Material corner radii against the actual bounds and direction.
104    pub fn rounded(
105        bounds: Bounds<Pixels>,
106        corners: CornerShape,
107        direction: Direction,
108    ) -> Option<Self> {
109        let width = f32::from(bounds.size.width);
110        let height = f32::from(bounds.size.height);
111        let cubics = rounded_rect_cubics(width, height, corners, direction)?;
112        Self::new(Outline {
113            cubics,
114            bounds,
115            fit: ShapeFit::Stretch,
116            rotation: 0.,
117            pivot: PolygonPoint::splat(0.5),
118            scale: 1.,
119        })
120    }
121
122    /// Prepares one of the 35 Material 3 Expressive shapes fitted inside `bounds`.
123    pub fn material(bounds: Bounds<Pixels>, shape: MaterialShape) -> Option<Self> {
124        ShapePolygon::material(shape).to_shape(bounds)
125    }
126
127    /// Prepares any reusable [`ShapePolygon`] inside `bounds`.
128    pub fn polygon(bounds: Bounds<Pixels>, polygon: &ShapePolygon, fit: ShapeFit) -> Option<Self> {
129        polygon.to_shape_with(bounds, fit, 0.)
130    }
131
132    fn from_cubics(
133        cubics: Vec<Cubic>,
134        bounds: Bounds<Pixels>,
135        fit: ShapeFit,
136        rotation_radians: f32,
137    ) -> Option<Self> {
138        if !rotation_radians.is_finite() {
139            return None;
140        }
141        Self::new(Outline {
142            cubics,
143            bounds,
144            fit,
145            rotation: rotation_radians,
146            pivot: PolygonPoint::splat(0.5),
147            scale: 1.,
148        })
149    }
150
151    fn new(outline: Outline) -> Option<Self> {
152        let fill = outline.path(PathBuilder::fill())?;
153        Some(Self {
154            outline,
155            fill,
156            stroke_cache: std::sync::OnceLock::new(),
157        })
158    }
159
160    /// Returns the laid-out bounds that this shape was fitted into.
161    pub fn bounds(&self) -> Bounds<Pixels> {
162        self.outline.bounds
163    }
164
165    /// Returns the tessellated fill mesh shared by painting, clipping, and hit testing.
166    pub fn fill_path(&self) -> &Path<Pixels> {
167        &self.fill
168    }
169
170    /// Builds a stroked outline path for this shape at the requested logical pixel width.
171    pub fn stroke_path(&self, width: Pixels) -> Option<Path<Pixels>> {
172        let raw = f32::from(width);
173        if !raw.is_finite() || raw <= 0. {
174            return None;
175        }
176        let bits = raw.to_bits();
177        if let Some((cached_bits, cached_path)) = self.stroke_cache.get()
178            && *cached_bits == bits
179        {
180            return Some(cached_path.clone());
181        }
182        let path = self.outline.path(PathBuilder::stroke(width))?;
183        let _ = self.stroke_cache.set((bits, path.clone()));
184        Some(path)
185    }
186
187    /// Returns whether `position` lies inside this shape's tessellated fill mesh.
188    pub fn contains(&self, position: Point<Pixels>) -> bool {
189        contains_fill(&self.fill, position)
190    }
191
192    /// Shape-aware hit test against the tessellated mesh with an optional outward `slop`
193    /// tolerance in logical pixels. Non-finite coordinates return `false`.
194    pub fn hit_test(&self, position: Point<Pixels>, slop: Pixels) -> bool {
195        if !f32::from(position.x).is_finite() || !f32::from(position.y).is_finite() {
196            return false;
197        }
198        if self.contains(position) {
199            return true;
200        }
201        let slop = f32::from(slop);
202        if !slop.is_finite() || slop <= 0. {
203            return false;
204        }
205        let min_x = f32::from(self.fill.bounds.left()) - slop;
206        let max_x = f32::from(self.fill.bounds.right()) + slop;
207        let min_y = f32::from(self.fill.bounds.top()) - slop;
208        let max_y = f32::from(self.fill.bounds.bottom()) + slop;
209        let px_x = f32::from(position.x);
210        let px_y = f32::from(position.y);
211        if px_x < min_x || px_x > max_x || px_y < min_y || px_y > max_y {
212            return false;
213        }
214        let limit_sq = slop * slop;
215        self.fill
216            .vertices
217            .as_chunks::<3>()
218            .0
219            .iter()
220            .any(|triangle| {
221                let a = triangle[0].xy_position;
222                let b = triangle[1].xy_position;
223                let c = triangle[2].xy_position;
224                if cross(b - a, c - a).abs() <= f32::EPSILON {
225                    return false;
226                }
227                segment_distance_sq(position, a, b) <= limit_sq
228                    || segment_distance_sq(position, b, c) <= limit_sq
229                    || segment_distance_sq(position, c, a) <= limit_sq
230            })
231    }
232
233    /// Returns whether this shape's fill mesh intersects the axis-aligned rectangle `rect`.
234    pub fn intersects_bounds(&self, rect: Bounds<Pixels>) -> bool {
235        if !rect_is_valid(rect) || !bounds_overlap(self.fill.bounds, rect) {
236            return false;
237        }
238        let mut polygon = Vec::with_capacity(8);
239        let mut scratch = Vec::with_capacity(8);
240        for triangle in self.fill.vertices.as_chunks::<3>().0 {
241            let [a, b, c] = triangle.each_ref().map(|vertex| vertex.xy_position);
242            if triangle_disjoint_from_rect([a, b, c], rect)
243                || cross(b - a, c - a).abs() <= f32::EPSILON
244            {
245                continue;
246            }
247            polygon.clear();
248            polygon.extend([a, b, c]);
249            clip_polygon_to_rect(&mut polygon, &mut scratch, rect);
250            if polygon.len() >= 3 && polygon_area(&polygon).abs() > f32::EPSILON {
251                return true;
252            }
253        }
254        false
255    }
256
257    /// Clips an axis-aligned rectangle against this shape's fill mesh.
258    pub fn clip_rect(&self, rect: Bounds<Pixels>) -> Path<Pixels> {
259        clip_rect_fill(&self.fill, rect)
260    }
261
262    /// Clips a disc centered at `origin` with logical `radius` against this shape's fill mesh.
263    pub fn clip_disc(&self, origin: Point<Pixels>, radius: Pixels) -> Path<Pixels> {
264        clipped_ripple(&self.fill, origin, radius)
265    }
266
267    /// Clips a convex polygon (in either winding order) against this shape's fill mesh.
268    pub fn clip_convex_polygon(&self, vertices: &[Point<Pixels>]) -> Path<Pixels> {
269        clip_convex_polygon_fill(&self.fill, vertices)
270    }
271
272    /// Clips an arbitrary tessellated GPUI [`Path`] (convex or concave) against this shape's
273    /// fill mesh, returning the exact geometric intersection.
274    pub fn clip_path(&self, source: &Path<Pixels>) -> Path<Pixels> {
275        clip_path_fill(&self.fill, source)
276    }
277
278    /// Builds an EvenOdd exterior mask representing `outer \ self` within `outer`.
279    ///
280    /// Because GPUI's native `ContentMask` is rectangular, painting this exterior mask
281    /// in a uniform parent backdrop color visually clips arbitrary child elements to the
282    /// exact non-rectangular shape contour.
283    pub fn exterior_mask(&self, outer: Bounds<Pixels>) -> Option<Path<Pixels>> {
284        if !rect_is_valid(outer) {
285            return None;
286        }
287        let contained = self.fill.bounds.left() >= outer.left()
288            && self.fill.bounds.right() <= outer.right()
289            && self.fill.bounds.top() >= outer.top()
290            && self.fill.bounds.bottom() <= outer.bottom();
291        let mask_outer = if contained {
292            outer
293        } else {
294            outer.union(&self.fill.bounds)
295        };
296        let mut builder = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions::even_odd()));
297        builder.move_to(mask_outer.origin);
298        builder.line_to(mask_outer.top_right());
299        builder.line_to(mask_outer.bottom_right());
300        builder.line_to(mask_outer.bottom_left());
301        builder.close();
302        if !self.outline.add_to_builder(&mut builder) {
303            return None;
304        }
305        let mask = builder.build().ok()?;
306        if contained {
307            Some(mask)
308        } else {
309            Some(clip_rect_fill(&mask, outer))
310        }
311    }
312
313    /// Paints the tessellated fill mesh with `color`.
314    pub fn paint(&self, color: Hsla, window: &mut Window) {
315        window.paint_path(self.fill.clone(), color);
316    }
317
318    /// Paints a stroked outline around this shape.
319    pub fn paint_stroke(&self, width: Pixels, color: Hsla, window: &mut Window) {
320        if let Some(path) = self.stroke_path(width) {
321            window.paint_path(path, color);
322        }
323    }
324
325    /// Paints `path` clipped to this shape's fill mesh.
326    pub fn paint_clipped(&self, path: &Path<Pixels>, color: Hsla, window: &mut Window) {
327        let clipped = self.clip_path(path);
328        if !clipped.vertices.is_empty() {
329            window.paint_path(clipped, color);
330        }
331    }
332
333    /// Paints `rect` clipped to this shape's fill mesh.
334    pub fn paint_clipped_rect(&self, rect: Bounds<Pixels>, color: Hsla, window: &mut Window) {
335        let clipped = self.clip_rect(rect);
336        if !clipped.vertices.is_empty() {
337            window.paint_path(clipped, color);
338        }
339    }
340
341    /// Paints a disc clipped to this shape's fill mesh.
342    pub fn paint_clipped_disc(
343        &self,
344        origin: Point<Pixels>,
345        radius: Pixels,
346        color: Hsla,
347        window: &mut Window,
348    ) {
349        self.paint_ripple(origin, radius, color, window);
350    }
351
352    /// Paints the EvenOdd exterior mask `outer \ self` in `backdrop` to visually clip
353    /// overflowing children to this shape on a uniform background.
354    pub fn paint_backdrop_mask(&self, outer: Bounds<Pixels>, backdrop: Hsla, window: &mut Window) {
355        if let Some(mask) = self.exterior_mask(outer)
356            && !mask.vertices.is_empty()
357        {
358            window.paint_path(mask, backdrop);
359        }
360    }
361
362    /// Approximates a shape-matched elevation shadow with three translucent fills.
363    pub fn paint_shadow(&self, elevation: f32, scale: f32, shadow: Hsla, window: &mut Window) {
364        let dp = elevation * scale;
365        if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
366            return;
367        }
368        for (offset_y, spread, alpha) in [
369            (dp * 0.45, dp * 0.35, 0.08),
370            (dp * 0.25, dp * 0.18, 0.10),
371            (scale.min(dp * 0.5), dp * 0.06, 0.12),
372        ] {
373            let expanded = Bounds::new(
374                self.outline.bounds.origin + point(px(-spread), px(offset_y - spread)),
375                size(
376                    self.outline.bounds.size.width + px(spread * 2.),
377                    self.outline.bounds.size.height + px(spread * 2.),
378                ),
379            );
380            let layer = Outline {
381                bounds: expanded,
382                ..self.outline.clone()
383            };
384            if let Some(path) = layer.path(PathBuilder::fill()) {
385                window.paint_path(path, shadow.opacity(alpha));
386            }
387        }
388    }
389
390    pub(crate) fn paint_ring(&self, width: Pixels, color: Hsla, window: &mut Window) {
391        self.paint_stroke(width, color, window);
392    }
393
394    pub(crate) fn paint_ripple(
395        &self,
396        origin: Point<Pixels>,
397        radius: Pixels,
398        color: Hsla,
399        window: &mut Window,
400    ) {
401        let path = self.clip_disc(origin, radius);
402        if !path.vertices.is_empty() {
403            window.paint_path(path, color);
404        }
405    }
406}