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    pub fn bounds(&self) -> Bounds<Pixels> {
161        self.outline.bounds
162    }
163
164    /// Returns the tessellated fill mesh shared by painting, clipping, and hit testing.
165    pub fn fill_path(&self) -> &Path<Pixels> {
166        &self.fill
167    }
168
169    /// Builds a stroked outline path for this shape at the requested logical pixel width.
170    pub fn stroke_path(&self, width: Pixels) -> Option<Path<Pixels>> {
171        let raw = f32::from(width);
172        if !raw.is_finite() || raw <= 0. {
173            return None;
174        }
175        let bits = raw.to_bits();
176        if let Some((cached_bits, cached_path)) = self.stroke_cache.get()
177            && *cached_bits == bits
178        {
179            return Some(cached_path.clone());
180        }
181        let path = self.outline.path(PathBuilder::stroke(width))?;
182        let _ = self.stroke_cache.set((bits, path.clone()));
183        Some(path)
184    }
185
186    /// Returns whether `position` lies inside this shape's tessellated fill mesh.
187    pub fn contains(&self, position: Point<Pixels>) -> bool {
188        contains_fill(&self.fill, position)
189    }
190
191    /// Shape-aware hit test against the tessellated mesh with an optional outward `slop`
192    /// tolerance in logical pixels. Non-finite coordinates return `false`.
193    pub fn hit_test(&self, position: Point<Pixels>, slop: Pixels) -> bool {
194        if !f32::from(position.x).is_finite() || !f32::from(position.y).is_finite() {
195            return false;
196        }
197        if self.contains(position) {
198            return true;
199        }
200        let slop = f32::from(slop);
201        if !slop.is_finite() || slop <= 0. {
202            return false;
203        }
204        let min_x = f32::from(self.fill.bounds.left()) - slop;
205        let max_x = f32::from(self.fill.bounds.right()) + slop;
206        let min_y = f32::from(self.fill.bounds.top()) - slop;
207        let max_y = f32::from(self.fill.bounds.bottom()) + slop;
208        let px_x = f32::from(position.x);
209        let px_y = f32::from(position.y);
210        if px_x < min_x || px_x > max_x || px_y < min_y || px_y > max_y {
211            return false;
212        }
213        let limit_sq = slop * slop;
214        self.fill
215            .vertices
216            .as_chunks::<3>()
217            .0
218            .iter()
219            .any(|triangle| {
220                let a = triangle[0].xy_position;
221                let b = triangle[1].xy_position;
222                let c = triangle[2].xy_position;
223                if cross(b - a, c - a).abs() <= f32::EPSILON {
224                    return false;
225                }
226                segment_distance_sq(position, a, b) <= limit_sq
227                    || segment_distance_sq(position, b, c) <= limit_sq
228                    || segment_distance_sq(position, c, a) <= limit_sq
229            })
230    }
231
232    /// Returns whether this shape's fill mesh intersects the axis-aligned rectangle `rect`.
233    pub fn intersects_bounds(&self, rect: Bounds<Pixels>) -> bool {
234        if !rect_is_valid(rect) || !bounds_overlap(self.fill.bounds, rect) {
235            return false;
236        }
237        let mut polygon = Vec::with_capacity(8);
238        let mut scratch = Vec::with_capacity(8);
239        for triangle in self.fill.vertices.as_chunks::<3>().0 {
240            let [a, b, c] = triangle.each_ref().map(|vertex| vertex.xy_position);
241            if triangle_disjoint_from_rect([a, b, c], rect)
242                || cross(b - a, c - a).abs() <= f32::EPSILON
243            {
244                continue;
245            }
246            polygon.clear();
247            polygon.extend([a, b, c]);
248            clip_polygon_to_rect(&mut polygon, &mut scratch, rect);
249            if polygon.len() >= 3 && polygon_area(&polygon).abs() > f32::EPSILON {
250                return true;
251            }
252        }
253        false
254    }
255
256    /// Clips an axis-aligned rectangle against this shape's fill mesh.
257    pub fn clip_rect(&self, rect: Bounds<Pixels>) -> Path<Pixels> {
258        clip_rect_fill(&self.fill, rect)
259    }
260
261    /// Clips a disc centered at `origin` with logical `radius` against this shape's fill mesh.
262    pub fn clip_disc(&self, origin: Point<Pixels>, radius: Pixels) -> Path<Pixels> {
263        clipped_ripple(&self.fill, origin, radius)
264    }
265
266    /// Clips a convex polygon (in either winding order) against this shape's fill mesh.
267    pub fn clip_convex_polygon(&self, vertices: &[Point<Pixels>]) -> Path<Pixels> {
268        clip_convex_polygon_fill(&self.fill, vertices)
269    }
270
271    /// Clips an arbitrary tessellated GPUI [`Path`] (convex or concave) against this shape's
272    /// fill mesh, returning the exact geometric intersection.
273    pub fn clip_path(&self, source: &Path<Pixels>) -> Path<Pixels> {
274        clip_path_fill(&self.fill, source)
275    }
276
277    /// Builds an EvenOdd exterior mask representing `outer \ self` within `outer`.
278    ///
279    /// Because GPUI's native `ContentMask` is rectangular, painting this exterior mask
280    /// in a uniform parent backdrop color visually clips arbitrary child elements to the
281    /// exact non-rectangular shape contour.
282    pub fn exterior_mask(&self, outer: Bounds<Pixels>) -> Option<Path<Pixels>> {
283        if !rect_is_valid(outer) {
284            return None;
285        }
286        let contained = self.fill.bounds.left() >= outer.left()
287            && self.fill.bounds.right() <= outer.right()
288            && self.fill.bounds.top() >= outer.top()
289            && self.fill.bounds.bottom() <= outer.bottom();
290        let mask_outer = if contained {
291            outer
292        } else {
293            outer.union(&self.fill.bounds)
294        };
295        let mut builder = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions::even_odd()));
296        builder.move_to(mask_outer.origin);
297        builder.line_to(mask_outer.top_right());
298        builder.line_to(mask_outer.bottom_right());
299        builder.line_to(mask_outer.bottom_left());
300        builder.close();
301        if !self.outline.add_to_builder(&mut builder) {
302            return None;
303        }
304        let mask = builder.build().ok()?;
305        if contained {
306            Some(mask)
307        } else {
308            Some(clip_rect_fill(&mask, outer))
309        }
310    }
311
312    pub fn paint(&self, color: Hsla, window: &mut Window) {
313        window.paint_path(self.fill.clone(), color);
314    }
315
316    /// Paints a stroked outline around this shape.
317    pub fn paint_stroke(&self, width: Pixels, color: Hsla, window: &mut Window) {
318        if let Some(path) = self.stroke_path(width) {
319            window.paint_path(path, color);
320        }
321    }
322
323    /// Paints `path` clipped to this shape's fill mesh.
324    pub fn paint_clipped(&self, path: &Path<Pixels>, color: Hsla, window: &mut Window) {
325        let clipped = self.clip_path(path);
326        if !clipped.vertices.is_empty() {
327            window.paint_path(clipped, color);
328        }
329    }
330
331    /// Paints `rect` clipped to this shape's fill mesh.
332    pub fn paint_clipped_rect(&self, rect: Bounds<Pixels>, color: Hsla, window: &mut Window) {
333        let clipped = self.clip_rect(rect);
334        if !clipped.vertices.is_empty() {
335            window.paint_path(clipped, color);
336        }
337    }
338
339    /// Paints a disc clipped to this shape's fill mesh.
340    pub fn paint_clipped_disc(
341        &self,
342        origin: Point<Pixels>,
343        radius: Pixels,
344        color: Hsla,
345        window: &mut Window,
346    ) {
347        self.paint_ripple(origin, radius, color, window);
348    }
349
350    /// Paints the EvenOdd exterior mask `outer \ self` in `backdrop` to visually clip
351    /// overflowing children to this shape on a uniform background.
352    pub fn paint_backdrop_mask(&self, outer: Bounds<Pixels>, backdrop: Hsla, window: &mut Window) {
353        if let Some(mask) = self.exterior_mask(outer)
354            && !mask.vertices.is_empty()
355        {
356            window.paint_path(mask, backdrop);
357        }
358    }
359
360    /// Approximates a shape-matched elevation shadow with three translucent fills.
361    pub fn paint_shadow(&self, elevation: f32, scale: f32, shadow: Hsla, window: &mut Window) {
362        let dp = elevation * scale;
363        if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
364            return;
365        }
366        for (offset_y, spread, alpha) in [
367            (dp * 0.45, dp * 0.35, 0.08),
368            (dp * 0.25, dp * 0.18, 0.10),
369            (scale.min(dp * 0.5), dp * 0.06, 0.12),
370        ] {
371            let expanded = Bounds::new(
372                self.outline.bounds.origin + point(px(-spread), px(offset_y - spread)),
373                size(
374                    self.outline.bounds.size.width + px(spread * 2.),
375                    self.outline.bounds.size.height + px(spread * 2.),
376                ),
377            );
378            let layer = Outline {
379                bounds: expanded,
380                ..self.outline.clone()
381            };
382            if let Some(path) = layer.path(PathBuilder::fill()) {
383                window.paint_path(path, shadow.opacity(alpha));
384            }
385        }
386    }
387
388    pub(crate) fn paint_ring(&self, width: Pixels, color: Hsla, window: &mut Window) {
389        self.paint_stroke(width, color, window);
390    }
391
392    pub(crate) fn paint_ripple(
393        &self,
394        origin: Point<Pixels>,
395        radius: Pixels,
396        color: Hsla,
397        window: &mut Window,
398    ) {
399        let path = self.clip_disc(origin, radius);
400        if !path.vertices.is_empty() {
401            window.paint_path(path, color);
402        }
403    }
404}