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