gpui_material_foundation/shape/
morph.rs1use std::panic::{AssertUnwindSafe, catch_unwind};
2
3use gpui::{Bounds, Pixels, px};
4use gpui_material_theme::PolygonRole;
5use polymorpher::{Cubic, Morph, geometry::Point as PolygonPoint};
6
7use super::polygon::{ShapePolygon, cubic_center};
8use super::{Outline, Shape, ShapeFit};
9
10#[derive(Clone)]
16pub struct ShapeMorph {
17 kind: MorphKind,
18}
19
20#[derive(Clone)]
21enum MorphKind {
22 FeatureMatched(Morph),
23 PerimeterAligned(Vec<(Cubic, Cubic)>),
24}
25
26impl ShapeMorph {
27 pub fn new(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
31 let start = start.into();
32 let end = end.into();
33 let kind = match (start.as_rounded(), end.as_rounded()) {
34 (Some(from), Some(to)) => {
35 match catch_unwind(AssertUnwindSafe(|| Morph::new(from.clone(), to.clone()))) {
36 Ok(morph) => MorphKind::FeatureMatched(morph),
37 Err(_) => {
38 MorphKind::PerimeterAligned(align_perimeter(&from.cubics, &to.cubics))
39 }
40 }
41 }
42 _ => MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
43 };
44 Self { kind }
45 }
46
47 pub fn perimeter_aligned(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
50 let start = start.into();
51 let end = end.into();
52 Self {
53 kind: MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
54 }
55 }
56
57 pub fn sample_polygon(&self, progress: f32) -> ShapePolygon {
59 ShapePolygon::from_cubics(self.as_cubics(clamp_progress(progress)))
60 }
61
62 pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
64 self.sample_with(bounds, progress, ShapeFit::Contain, 0.)
65 }
66
67 pub fn sample_with(
69 &self,
70 bounds: Bounds<Pixels>,
71 progress: f32,
72 fit: ShapeFit,
73 rotation_radians: f32,
74 ) -> Option<Shape> {
75 Shape::from_cubics(
76 self.as_cubics(clamp_progress(progress)),
77 bounds,
78 fit,
79 rotation_radians,
80 )
81 }
82
83 fn as_cubics(&self, progress: f32) -> Vec<Cubic> {
84 match &self.kind {
85 MorphKind::FeatureMatched(morph) => morph.as_cubics(progress),
86 MorphKind::PerimeterAligned(pairs) => pairs
87 .iter()
88 .map(|(a, b)| {
89 Cubic::new(
90 a.anchor0().lerp(b.anchor0(), progress),
91 a.control0().lerp(b.control0(), progress),
92 a.control1().lerp(b.control1(), progress),
93 a.anchor1().lerp(b.anchor1(), progress),
94 )
95 })
96 .collect(),
97 }
98 }
99}
100
101#[derive(Clone)]
103pub struct ShapeMorphSequence {
104 steps: Vec<ShapeMorph>,
105 wrap: Option<ShapeMorph>,
106 rotation_scale: f32,
107 control_radius: Option<f32>,
108}
109
110impl ShapeMorphSequence {
111 pub fn new(
114 shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
115 looping: bool,
116 ) -> Option<Self> {
117 Self::build(shapes, looping, false)
118 }
119
120 pub fn perimeter_aligned(
122 shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
123 looping: bool,
124 ) -> Option<Self> {
125 Self::build(shapes, looping, true)
126 }
127
128 fn build(
129 shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
130 looping: bool,
131 perimeter_aligned: bool,
132 ) -> Option<Self> {
133 let polygons: Vec<ShapePolygon> = shapes.into_iter().map(Into::into).collect();
134 if polygons.len() < 2 {
135 return None;
136 }
137 let make = |a: &ShapePolygon, b: &ShapePolygon| {
138 if perimeter_aligned {
139 ShapeMorph::perimeter_aligned(a.clone(), b.clone())
140 } else {
141 ShapeMorph::new(a.clone(), b.clone())
142 }
143 };
144 let steps = polygons
145 .windows(2)
146 .map(|pair| make(&pair[0], &pair[1]))
147 .collect();
148 let wrap = looping.then(|| make(polygons.last().unwrap(), &polygons[0]));
149 let rotation_scale = polygons
150 .iter()
151 .fold(1_f32, |scale, polygon| scale.min(polygon.rotation_scale()));
152 let control_radius = perimeter_aligned.then(|| {
153 polygons
154 .iter()
155 .map(ShapePolygon::control_point_radius)
156 .fold(0_f32, f32::max)
157 });
158 Some(Self {
159 steps,
160 wrap,
161 rotation_scale,
162 control_radius,
163 })
164 }
165
166 pub fn len(&self) -> usize {
168 self.steps.len() + 1
169 }
170
171 pub fn is_empty(&self) -> bool {
173 false
174 }
175
176 pub fn step_count(&self) -> usize {
178 self.steps.len() + usize::from(self.wrap.is_some())
179 }
180
181 pub fn is_looping(&self) -> bool {
183 self.wrap.is_some()
184 }
185
186 pub fn rotation_scale(&self) -> f32 {
188 self.rotation_scale
189 }
190
191 pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
193 let value = clamp_progress(progress);
194 let phase = value * self.steps.len() as f32;
195 let index = (phase as usize).min(self.steps.len() - 1);
196 self.sample_step(index, phase - index as f32, bounds, ShapeFit::Contain, 0.)
197 }
198
199 pub fn sample_step(
201 &self,
202 step: usize,
203 progress: f32,
204 bounds: Bounds<Pixels>,
205 fit: ShapeFit,
206 rotation_radians: f32,
207 ) -> Option<Shape> {
208 let morph = self.morph_for_step(step)?;
209 morph.sample_with(bounds, progress, fit, rotation_radians)
210 }
211
212 pub fn sample_step_polygon(&self, step: usize, progress: f32) -> Option<ShapePolygon> {
214 let morph = self.morph_for_step(step)?;
215 Some(morph.sample_polygon(progress))
216 }
217
218 pub fn sample_step_in_envelope(
224 &self,
225 step: usize,
226 progress: f32,
227 bounds: Bounds<Pixels>,
228 extent: Pixels,
229 rotation_radians: f32,
230 ) -> Option<Shape> {
231 if !rotation_radians.is_finite() {
232 return None;
233 }
234 let morph = self.morph_for_step(step)?;
235 let cubics = morph.as_cubics(clamp_progress(progress));
236 if cubics.is_empty() {
237 return None;
238 }
239 let pivot = cubic_center(&cubics);
240 let side = bounds.size.width.min(bounds.size.height);
241 let extent = side.min(extent);
242 if !(extent > px(0.) && extent < px(f32::INFINITY)) {
243 return None;
244 }
245 let mut target_side = extent * self.rotation_scale;
246 if let Some(radius) = self.control_radius {
247 let radius = radius + (pivot - PolygonPoint::splat(0.5)).length();
248 if radius > f32::EPSILON {
249 target_side = target_side.min(extent / (2. * radius));
250 }
251 }
252 let scale = f32::from(target_side) / f32::from(side);
253 Shape::new(Outline {
254 cubics,
255 bounds,
256 fit: ShapeFit::Contain,
257 rotation: rotation_radians,
258 pivot,
259 scale,
260 })
261 }
262
263 fn morph_for_step(&self, step: usize) -> Option<&ShapeMorph> {
264 if self.wrap.is_some() {
265 let count = self.steps.len() + 1;
266 let index = step % count;
267 self.steps.get(index).or(self.wrap.as_ref())
268 } else {
269 self.steps.get(step)
270 }
271 }
272}
273
274#[derive(Clone)]
276pub struct PolygonMorph(ShapeMorph);
277
278impl PolygonMorph {
279 pub fn new(start: PolygonRole, end: PolygonRole) -> Self {
281 Self(ShapeMorph::new(start, end))
282 }
283
284 pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
286 self.0.sample(bounds, progress)
287 }
288}
289
290fn clamp_progress(progress: f32) -> f32 {
291 if progress.is_finite() {
292 progress.clamp(0., 1.)
293 } else {
294 0.
295 }
296}
297
298fn align_perimeter(start: &[Cubic], end: &[Cubic]) -> Vec<(Cubic, Cubic)> {
299 let mut starts = weighted_segments(start).into_iter();
300 let mut ends = weighted_segments(end).into_iter();
301 let (mut from, mut to) = (starts.next(), ends.next());
302 let mut position = 0.;
303 let mut pairs = Vec::new();
304 while let (Some(mut a), Some(mut b)) = (from, to) {
305 let boundary = a.0.min(b.0);
306 let first = split_until(&mut a, position, boundary);
307 let last = split_until(&mut b, position, boundary);
308 pairs.push((first, last));
309 from = if boundary == a.0 {
310 starts.next()
311 } else {
312 Some(a)
313 };
314 to = if boundary == b.0 {
315 ends.next()
316 } else {
317 Some(b)
318 };
319 position = boundary;
320 }
321 pairs
322}
323
324fn weighted_segments(cubics: &[Cubic]) -> Vec<(f64, Cubic)> {
325 let mut cumulative = 0.;
326 let mut segments: Vec<_> = cubics
327 .iter()
328 .map(|cubic| {
329 let samples = [
330 cubic.anchor0(),
331 cubic.point_on_curve(0.25),
332 cubic.point_on_curve(0.5),
333 cubic.point_on_curve(0.75),
334 cubic.anchor1(),
335 ];
336 cumulative += samples
337 .windows(2)
338 .map(|points| f64::from((points[1] - points[0]).length()))
339 .sum::<f64>();
340 (cumulative, *cubic)
341 })
342 .collect();
343 if cumulative > 0. {
344 for (end, _) in &mut segments {
345 *end /= cumulative;
346 }
347 }
348 segments
349}
350
351fn split_until(segment: &mut (f64, Cubic), from: f64, until: f64) -> Cubic {
352 if until == segment.0 {
353 return segment.1;
354 }
355 let (head, tail) = segment
356 .1
357 .split(((until - from) / (segment.0 - from)) as f32);
358 segment.1 = tail;
359 head
360}