Skip to main content

gpui_material_foundation/shape/
morph.rs

1use gpui::{Bounds, Pixels, px};
2use gpui_material_theme::PolygonRole;
3use polymorpher::{Cubic, Morph, RoundedPolygon, geometry::Point as PolygonPoint};
4
5use super::polygon::{ShapePolygon, cubic_center};
6use super::{Outline, Shape, ShapeFit};
7
8/// A reusable morph between any two [`ShapePolygon`] contours.
9///
10/// Uses `polymorpher`'s feature-matched morph when both endpoints are non-degenerate
11/// `RoundedPolygon`s and falls back to perimeter-length cubic alignment for arbitrary
12/// cubic contours or degenerate geometry.
13#[derive(Clone)]
14pub struct ShapeMorph {
15    kind: MorphKind,
16}
17
18#[derive(Clone)]
19enum MorphKind {
20    FeatureMatched(Morph),
21    PerimeterAligned(Vec<(Cubic, Cubic)>),
22}
23
24impl ShapeMorph {
25    /// Creates a reusable morph between any two shapes (such as
26    /// [`MaterialShape`](gpui_material_theme::MaterialShape), [`PolygonRole`], or
27    /// [`ShapePolygon`]).
28    pub fn new(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
29        let start = start.into();
30        let end = end.into();
31        let kind = match (start.as_rounded(), end.as_rounded()) {
32            (Some(from), Some(to))
33                if is_valid_morph_polygon(from) && is_valid_morph_polygon(to) =>
34            {
35                MorphKind::FeatureMatched(Morph::new(from.clone(), to.clone()))
36            }
37            _ => MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
38        };
39        Self { kind }
40    }
41
42    /// Creates a morph aligned strictly by normalized perimeter length, preserving exact
43    /// endpoint curves with bounded cubic count even for arbitrary concave polygons.
44    pub fn perimeter_aligned(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
45        let start = start.into();
46        let end = end.into();
47        Self {
48            kind: MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
49        }
50    }
51
52    /// Samples the interpolated normalized contour at `progress` (clamped to `0..=1`).
53    pub fn sample_polygon(&self, progress: f32) -> ShapePolygon {
54        ShapePolygon::from_cubics(self.as_cubics(clamp_progress(progress)))
55    }
56
57    /// Fits the sampled shape inside `bounds` while preserving aspect ratio.
58    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
59        self.sample_with(bounds, progress, ShapeFit::Contain, 0.)
60    }
61
62    /// Samples the morph into `bounds` with explicit fit mode and clockwise rotation in radians.
63    pub fn sample_with(
64        &self,
65        bounds: Bounds<Pixels>,
66        progress: f32,
67        fit: ShapeFit,
68        rotation_radians: f32,
69    ) -> Option<Shape> {
70        Shape::from_cubics(
71            self.as_cubics(clamp_progress(progress)),
72            bounds,
73            fit,
74            rotation_radians,
75        )
76    }
77
78    fn as_cubics(&self, progress: f32) -> Vec<Cubic> {
79        match &self.kind {
80            MorphKind::FeatureMatched(morph) => morph.as_cubics(progress),
81            MorphKind::PerimeterAligned(pairs) => pairs
82                .iter()
83                .map(|(a, b)| {
84                    Cubic::new(
85                        a.anchor0().lerp(b.anchor0(), progress),
86                        a.control0().lerp(b.control0(), progress),
87                        a.control1().lerp(b.control1(), progress),
88                        a.anchor1().lerp(b.anchor1(), progress),
89                    )
90                })
91                .collect(),
92        }
93    }
94}
95
96/// A reusable multi-step sequence of [`ShapeMorph`] transitions.
97#[derive(Clone)]
98pub struct ShapeMorphSequence {
99    steps: Vec<ShapeMorph>,
100    wrap: Option<ShapeMorph>,
101    rotation_scale: f32,
102    control_radius: Option<f32>,
103}
104
105impl ShapeMorphSequence {
106    /// Builds a feature-matched morph sequence from at least two shapes.
107    /// When `looping` is `true`, adds a wrap transition from the last shape back to the first.
108    pub fn new(
109        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
110        looping: bool,
111    ) -> Option<Self> {
112        Self::build(shapes, looping, false)
113    }
114
115    /// Builds a perimeter-aligned morph sequence from at least two shapes.
116    pub fn perimeter_aligned(
117        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
118        looping: bool,
119    ) -> Option<Self> {
120        Self::build(shapes, looping, true)
121    }
122
123    fn build(
124        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
125        looping: bool,
126        perimeter_aligned: bool,
127    ) -> Option<Self> {
128        let polygons: Vec<ShapePolygon> = shapes.into_iter().map(Into::into).collect();
129        if polygons.len() < 2 {
130            return None;
131        }
132        let make = |a: &ShapePolygon, b: &ShapePolygon| {
133            if perimeter_aligned {
134                ShapeMorph::perimeter_aligned(a.clone(), b.clone())
135            } else {
136                ShapeMorph::new(a.clone(), b.clone())
137            }
138        };
139        let steps = polygons
140            .windows(2)
141            .map(|pair| make(&pair[0], &pair[1]))
142            .collect();
143        let wrap = looping.then(|| make(polygons.last().unwrap(), &polygons[0]));
144        let rotation_scale = polygons
145            .iter()
146            .fold(1_f32, |scale, polygon| scale.min(polygon.rotation_scale()));
147        let control_radius = perimeter_aligned.then(|| {
148            polygons
149                .iter()
150                .map(ShapePolygon::control_point_radius)
151                .fold(0_f32, f32::max)
152        });
153        Some(Self {
154            steps,
155            wrap,
156            rotation_scale,
157            control_radius,
158        })
159    }
160
161    /// Number of endpoint shapes in this sequence.
162    pub fn len(&self) -> usize {
163        self.steps.len() + 1
164    }
165
166    /// Always `false` because valid sequences contain at least two shapes.
167    pub fn is_empty(&self) -> bool {
168        false
169    }
170
171    /// Number of morph transitions (`len() - 1` when open, `len()` when looping).
172    pub fn step_count(&self) -> usize {
173        self.steps.len() + usize::from(self.wrap.is_some())
174    }
175
176    /// Returns `true` when the sequence wraps from its last shape back to the first.
177    pub fn is_looping(&self) -> bool {
178        self.wrap.is_some()
179    }
180
181    /// Minimum rotation-safe scale factor across all shapes in the sequence.
182    pub fn rotation_scale(&self) -> f32 {
183        self.rotation_scale
184    }
185
186    /// Samples the open progression across `[0, 1]` from the first shape to the last.
187    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
188        let value = clamp_progress(progress);
189        let phase = value * self.steps.len() as f32;
190        let index = (phase as usize).min(self.steps.len() - 1);
191        self.sample_step(index, phase - index as f32, bounds, ShapeFit::Contain, 0.)
192    }
193
194    /// Samples a specific transition step at `progress` in `0..=1`.
195    pub fn sample_step(
196        &self,
197        step: usize,
198        progress: f32,
199        bounds: Bounds<Pixels>,
200        fit: ShapeFit,
201        rotation_radians: f32,
202    ) -> Option<Shape> {
203        let morph = self.morph_for_step(step)?;
204        morph.sample_with(bounds, progress, fit, rotation_radians)
205    }
206
207    /// Samples a specific transition step as a reusable [`ShapePolygon`].
208    pub fn sample_step_polygon(&self, step: usize, progress: f32) -> Option<ShapePolygon> {
209        let morph = self.morph_for_step(step)?;
210        Some(morph.sample_polygon(progress))
211    }
212
213    /// Samples a transition step centered on its live cubic bounding box and scaled to
214    /// fit safely inside a circular envelope of diameter `extent` under arbitrary rotation.
215    ///
216    /// Used by `LoadingIndicator` to keep rotating Material and custom morph sequences
217    /// strictly inside their active footprint without resizing shared endpoints.
218    pub fn sample_step_in_envelope(
219        &self,
220        step: usize,
221        progress: f32,
222        bounds: Bounds<Pixels>,
223        extent: Pixels,
224        rotation_radians: f32,
225    ) -> Option<Shape> {
226        if !rotation_radians.is_finite() {
227            return None;
228        }
229        let morph = self.morph_for_step(step)?;
230        let cubics = morph.as_cubics(clamp_progress(progress));
231        if cubics.is_empty() {
232            return None;
233        }
234        let pivot = cubic_center(&cubics);
235        let side = bounds.size.width.min(bounds.size.height);
236        let extent = side.min(extent);
237        if !(extent > px(0.) && extent < px(f32::INFINITY)) {
238            return None;
239        }
240        let mut target_side = extent * self.rotation_scale;
241        if let Some(radius) = self.control_radius {
242            let radius = radius + (pivot - PolygonPoint::splat(0.5)).length();
243            if radius > f32::EPSILON {
244                target_side = target_side.min(extent / (2. * radius));
245            }
246        }
247        let scale = f32::from(target_side) / f32::from(side);
248        Shape::new(Outline {
249            cubics,
250            bounds,
251            fit: ShapeFit::Contain,
252            rotation: rotation_radians,
253            pivot,
254            scale,
255            rounded_rect: None,
256        })
257    }
258
259    fn morph_for_step(&self, step: usize) -> Option<&ShapeMorph> {
260        if self.wrap.is_some() {
261            let count = self.steps.len() + 1;
262            let index = step % count;
263            self.steps.get(index).or(self.wrap.as_ref())
264        } else {
265            self.steps.get(step)
266        }
267    }
268}
269
270/// A reusable morph between two pinned Material polygon roles.
271#[derive(Clone)]
272pub struct PolygonMorph(ShapeMorph);
273
274impl PolygonMorph {
275    /// Creates a reusable morph between two Material [`PolygonRole`] endpoints.
276    pub fn new(start: PolygonRole, end: PolygonRole) -> Self {
277        Self(ShapeMorph::new(start, end))
278    }
279
280    /// Fits the sampled polygon inside the bounds while preserving aspect ratio.
281    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
282        self.0.sample(bounds, progress)
283    }
284}
285
286fn is_valid_morph_polygon(polygon: &RoundedPolygon) -> bool {
287    if polygon.cubics.len() < 2 {
288        return false;
289    }
290    let size = polygon.aabb(true).size();
291    size.width.is_finite()
292        && size.height.is_finite()
293        && size.width > 1e-4
294        && size.height > 1e-4
295        && polygon.center.x.is_finite()
296        && polygon.center.y.is_finite()
297        && polygon.cubics.iter().all(|cubic| {
298            [
299                cubic.anchor0(),
300                cubic.control0(),
301                cubic.control1(),
302                cubic.anchor1(),
303            ]
304            .into_iter()
305            .all(|point| point.x.is_finite() && point.y.is_finite())
306        })
307}
308
309fn clamp_progress(progress: f32) -> f32 {
310    if progress.is_finite() {
311        progress.clamp(0., 1.)
312    } else {
313        0.
314    }
315}
316
317fn align_perimeter(start: &[Cubic], end: &[Cubic]) -> Vec<(Cubic, Cubic)> {
318    let mut starts = weighted_segments(start).into_iter();
319    let mut ends = weighted_segments(end).into_iter();
320    let (mut from, mut to) = (starts.next(), ends.next());
321    let mut position = 0.;
322    let mut pairs = Vec::new();
323    while let (Some(mut a), Some(mut b)) = (from, to) {
324        let boundary = a.0.min(b.0);
325        let first = split_until(&mut a, position, boundary);
326        let last = split_until(&mut b, position, boundary);
327        pairs.push((first, last));
328        from = if boundary == a.0 {
329            starts.next()
330        } else {
331            Some(a)
332        };
333        to = if boundary == b.0 {
334            ends.next()
335        } else {
336            Some(b)
337        };
338        position = boundary;
339    }
340    pairs
341}
342
343fn weighted_segments(cubics: &[Cubic]) -> Vec<(f64, Cubic)> {
344    let mut cumulative = 0.;
345    let mut segments: Vec<_> = cubics
346        .iter()
347        .map(|cubic| {
348            let samples = [
349                cubic.anchor0(),
350                cubic.point_on_curve(0.25),
351                cubic.point_on_curve(0.5),
352                cubic.point_on_curve(0.75),
353                cubic.anchor1(),
354            ];
355            cumulative += samples
356                .windows(2)
357                .map(|points| f64::from((points[1] - points[0]).length()))
358                .sum::<f64>();
359            (cumulative, *cubic)
360        })
361        .collect();
362    if cumulative > 0. {
363        for (end, _) in &mut segments {
364            *end /= cumulative;
365        }
366    }
367    segments
368}
369
370fn split_until(segment: &mut (f64, Cubic), from: f64, until: f64) -> Cubic {
371    if until == segment.0 {
372        return segment.1;
373    }
374    let (head, tail) = segment
375        .1
376        .split(((until - from) / (segment.0 - from)) as f32);
377    segment.1 = tail;
378    head
379}