Skip to main content

rust_glass/
material.rs

1//! The glass material: corner shapes, material parameters and presets, and
2//! glass elements ready to paint.
3
4use crate::color::Color;
5use crate::geometry::{Rect, Vec2, lerp, vec2};
6
7/// The shape of a rectangle's corners.
8///
9/// Rounded corners are continuous: the curvature ramps up instead of jumping
10/// where the straight edge ends, as on Apple platforms. A plain number
11/// converts to [`Corner::Radius`].
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub enum Corner {
14    /// Continuous corners that look like a circular corner of this radius.
15    Radius(f32),
16    /// Fully rounded ends, slightly squared off the way iOS draws them.
17    Capsule,
18    /// A capsule of size `base` stretched to the size of the rectangle, each
19    /// axis on its own. `power` above 2 squares the shoulders off.
20    Stretched {
21        /// Size of the capsule before stretching.
22        base: Vec2,
23        /// Exponent of the corner curve. 2 is a circle.
24        power: f32,
25    },
26    /// Circular corners of this radius, without the continuous curve.
27    Circular(f32),
28}
29
30impl From<f32> for Corner {
31    fn from(radius: f32) -> Self {
32        Corner::Radius(radius)
33    }
34}
35
36impl Corner {
37    /// Returns the corner radii and the exponent of the corner curve for a
38    /// rectangle of `size`.
39    pub fn resolve(self, size: Vec2) -> (Vec2, f32) {
40        let half = Vec2::splat(size.x.min(size.y) * 0.5);
41        match self {
42            Corner::Capsule => {
43                // Extend the curve along the long side for a smooth transition.
44                let mut r = half * 1.16;
45                r = r.min(size * 0.5);
46                // Nearly square shapes stay circles.
47                let k = ((size.x.max(size.y) / size.x.min(size.y).max(0.1)) - 1.0).clamp(0.0, 0.3) / 0.3;
48                (half.lerp(r, k), lerp(2.0, 2.18, k))
49            }
50            Corner::Stretched { base, power } => {
51                let (r, _) = Corner::Capsule.resolve(base);
52                (vec2(r.x * size.x / base.x.max(0.1), r.y * size.y / base.y.max(0.1)), power)
53            }
54            Corner::Radius(r) => {
55                // A superellipse of extent 1.35r and exponent 2.83 touches a
56                // circle of radius r on the diagonal.
57                let want = r * 1.35;
58                let room = (half.x - r).max(0.0) / (want - r).max(0.01);
59                let k = room.clamp(0.0, 1.0);
60                (Vec2::splat(lerp(r.min(half.x), want, k).max(0.01)), lerp(2.0, 2.83, k))
61            }
62            Corner::Circular(r) => (Vec2::splat(r.min(half.x)), 2.0),
63        }
64    }
65}
66
67/// The optical parameters of glass. Lengths are in points.
68///
69/// The surface is flat in the middle and curves down near its outline.
70/// Light passing through the curved part bends towards the middle, so the
71/// edge shows the backdrop from further inside. Start from a preset such as
72/// [`Material::REGULAR`] and change what you need.
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct Material {
75    /// How far the curved edge bends the backdrop towards the middle.
76    pub refraction: f32,
77    /// Width of the curved edge, measured inwards from the outline.
78    pub depth: f32,
79    /// Bend in the opposite direction, in a thin ring right at the outline.
80    pub outer_refraction: f32,
81    /// Width of the outer ring.
82    pub outer_depth: f32,
83    /// Outward bend in a wide zone further in, like the raised shoulder of a
84    /// drop of liquid.
85    pub pinch: f32,
86    /// Width of the pinch zone.
87    pub pinch_width: f32,
88    /// 0 bends equally in all directions. At 1 the main bend works only
89    /// sideways and the pinch only up and down.
90    pub sideways: f32,
91    /// Separation of colors at the edge, as a fraction of the bend.
92    pub dispersion: f32,
93    /// 0 separates colors evenly around the outline. At 1 only the corners
94    /// do, with the order of the colors alternating from corner to corner.
95    pub corner_dispersion: f32,
96    /// Blur radius of the backdrop.
97    pub blur: f32,
98    /// Magnification of the backdrop. 1 shows it at its real size.
99    pub magnify: f32,
100    /// Range the backdrop brightness is mapped to on light glass, as
101    /// `(darkest, brightest)`.
102    pub light_range: (f32, f32),
103    /// Range the backdrop brightness is mapped to on dark glass.
104    pub dark_range: (f32, f32),
105    /// Color saturation of the backdrop. 1 keeps it unchanged.
106    pub saturation: f32,
107    /// Strength of the bright edge that catches the light.
108    pub rim: f32,
109    /// Width of the bright edge.
110    pub rim_width: f32,
111    /// Part of the bright edge that shows all around, whatever the light
112    /// direction.
113    pub rim_base: f32,
114    /// Strength of the thin dark line just inside the outline.
115    pub dark_edge: f32,
116    /// Light from the surroundings that spills onto the edge.
117    pub light_spill: f32,
118    /// Glow on the side facing away from the light.
119    pub inner_glow: f32,
120    /// Shade on the side facing the light.
121    pub inner_shadow: f32,
122    /// Opacity of the drop shadow.
123    pub shadow: f32,
124    /// Blur radius of the drop shadow.
125    pub shadow_radius: f32,
126    /// Downward offset of the drop shadow.
127    pub shadow_y: f32,
128    /// How much of the color of the light passing through the shadow carries,
129    /// from 0 (gray) to 1.
130    pub shadow_tint: f32,
131    /// Colored glass. The alpha is the strength of the color.
132    pub tint: Option<Color>,
133    /// How much the tint follows the brightness of the backdrop. 0 is a flat
134    /// fill.
135    pub tint_follow: f32,
136    /// How much [`Theme::glass_tint`](crate::Theme::glass_tint) and reduced
137    /// transparency change this material, from 0 to 1. Use 0 for glass that
138    /// must stay clear, such as a lens above its own label.
139    pub glass_tint_response: f32,
140}
141
142impl Material {
143    /// Controls and bars. Readable over any content.
144    pub const REGULAR: Material = Material {
145        refraction: 17.0,
146        depth: 13.0,
147        outer_refraction: 3.0,
148        outer_depth: 4.0,
149        pinch: 0.0,
150        pinch_width: 20.0,
151        sideways: 0.0,
152        dispersion: 0.10,
153        corner_dispersion: 0.0,
154        blur: 4.2,
155        magnify: 1.0,
156        light_range: (0.62, 1.0),
157        dark_range: (0.06, 0.52),
158        saturation: 1.45,
159        rim: 0.75,
160        rim_width: 0.8,
161        rim_base: 0.34,
162        dark_edge: 0.22,
163        light_spill: 0.18,
164        inner_glow: 0.16,
165        inner_shadow: 0.05,
166        shadow: 0.16,
167        shadow_radius: 16.0,
168        shadow_y: 6.0,
169        shadow_tint: 0.35,
170        tint: None,
171        tint_follow: 1.0,
172        glass_tint_response: 1.0,
173    };
174
175    /// Clear glass that stays transparent, for controls over photos and video.
176    pub const CLEAR: Material = Material {
177        refraction: 24.0,
178        depth: 18.0,
179        outer_refraction: 4.0,
180        outer_depth: 4.0,
181        dispersion: 0.20,
182        blur: 0.5,
183        light_range: (0.10, 1.0),
184        dark_range: (0.04, 0.92),
185        saturation: 1.25,
186        rim: 0.85,
187        inner_glow: 0.12,
188        inner_shadow: 0.07,
189        ..Material::REGULAR
190    };
191
192    /// Menus, sheets, windows and panels: thicker, with a deeper shadow and
193    /// softer light.
194    pub const THICK: Material = Material {
195        refraction: 34.0,
196        depth: 26.0,
197        outer_refraction: 4.0,
198        outer_depth: 5.0,
199        dispersion: 0.10,
200        blur: 11.0,
201        light_range: (0.68, 1.0),
202        dark_range: (0.09, 0.44),
203        saturation: 1.6,
204        shadow: 0.26,
205        shadow_radius: 34.0,
206        shadow_y: 14.0,
207        light_spill: 0.26,
208        inner_glow: 0.10,
209        ..Material::REGULAR
210    };
211
212    /// The lens a slider, switch or segment thumb turns into while it is held.
213    pub const LENS: Material = Material {
214        refraction: 20.0,
215        depth: 9.4,
216        outer_refraction: 6.0,
217        outer_depth: 1.6,
218        dispersion: 0.17,
219        blur: 0.0,
220        light_range: (0.15, 1.0),
221        dark_range: (0.06, 1.0),
222        saturation: 1.06,
223        rim: 1.0,
224        rim_width: 0.75,
225        rim_base: 0.06,
226        dark_edge: 0.92,
227        light_spill: 0.0,
228        inner_glow: 0.20,
229        inner_shadow: 0.09,
230        shadow: 0.17,
231        shadow_radius: 9.0,
232        shadow_y: 5.0,
233        shadow_tint: 0.95,
234        glass_tint_response: 0.0,
235        ..Material::REGULAR
236    };
237
238    /// The selection of a tab bar while it is held: a clear blob that stands
239    /// out from the bar. A thin rim shows the bar from further inside, and
240    /// the wide zone behind it pulls the edge of the bar inwards.
241    pub const BLOB: Material = Material {
242        refraction: 20.0,
243        depth: 3.5,
244        outer_refraction: 0.0,
245        outer_depth: 2.0,
246        pinch: 4.1,
247        pinch_width: 20.0,
248        dispersion: 0.75,
249        corner_dispersion: 1.0,
250        light_range: (0.0, 1.0),
251        dark_range: (0.0, 1.0),
252        saturation: 1.05,
253        rim: 0.85,
254        rim_width: 0.6,
255        rim_base: 0.62,
256        dark_edge: 0.0,
257        inner_glow: 0.05,
258        inner_shadow: 0.0,
259        shadow: 0.13,
260        shadow_radius: 11.0,
261        shadow_y: 5.0,
262        shadow_tint: 0.2,
263        ..Material::LENS
264    };
265
266    /// Bends the tab labels under [`Material::BLOB`]: near its outline they
267    /// smear inwards.
268    pub const BLOB_LABELS: Material = Material {
269        refraction: 23.0,
270        depth: 16.0,
271        outer_refraction: 0.0,
272        pinch: 0.0,
273        sideways: 0.5,
274        dispersion: 0.18,
275        corner_dispersion: 0.0,
276        saturation: 1.0,
277        inner_glow: 0.0,
278        shadow: 0.0,
279        ..Material::BLOB
280    };
281
282    /// Glass that only blurs: no bend, edge, light, shadow or tint. See
283    /// [`Painter::blur`](crate::Painter::blur).
284    pub fn blur(radius: f32) -> Material {
285        Material {
286            refraction: 0.0,
287            depth: 0.1,
288            outer_refraction: 0.0,
289            outer_depth: 0.1,
290            pinch: 0.0,
291            dispersion: 0.0,
292            corner_dispersion: 0.0,
293            blur: radius,
294            magnify: 1.0,
295            light_range: (0.0, 1.0),
296            dark_range: (0.0, 1.0),
297            saturation: 1.0,
298            rim: 0.0,
299            rim_base: 0.0,
300            dark_edge: 0.0,
301            light_spill: 0.0,
302            inner_glow: 0.0,
303            inner_shadow: 0.0,
304            shadow: 0.0,
305            shadow_radius: 0.0,
306            shadow_y: 0.0,
307            shadow_tint: 0.0,
308            tint: None,
309            glass_tint_response: 0.0,
310            ..Material::REGULAR
311        }
312    }
313
314    /// Returns the material colored with `color`. Its alpha is the strength.
315    pub fn tinted(mut self, color: Color) -> Self {
316        self.tint = Some(color);
317        self
318    }
319
320    /// Returns a material that looks the same on an element `k` times as
321    /// large.
322    pub fn scaled(mut self, k: f32) -> Material {
323        self.refraction *= k;
324        self.depth *= k;
325        self.outer_refraction *= k;
326        self.outer_depth *= k;
327        self.pinch *= k;
328        self.pinch_width *= k;
329        self.rim_width *= k.max(1.0).sqrt();
330        self.shadow_radius *= k;
331        self.shadow_y *= k;
332        self
333    }
334
335    /// Mixes towards `other`: `t` = 0 gives `self`, 1 gives `other`. Used
336    /// when one kind of glass turns into another.
337    pub fn lerp(&self, other: &Material, t: f32) -> Material {
338        let o = other;
339        let l = |a: f32, b: f32| lerp(a, b, t);
340        let l2 = |a: (f32, f32), b: (f32, f32)| (l(a.0, b.0), l(a.1, b.1));
341        Material {
342            refraction: l(self.refraction, o.refraction),
343            depth: l(self.depth, o.depth),
344            outer_refraction: l(self.outer_refraction, o.outer_refraction),
345            outer_depth: l(self.outer_depth, o.outer_depth),
346            pinch: l(self.pinch, o.pinch),
347            pinch_width: l(self.pinch_width, o.pinch_width),
348            sideways: l(self.sideways, o.sideways),
349            dispersion: l(self.dispersion, o.dispersion),
350            corner_dispersion: l(self.corner_dispersion, o.corner_dispersion),
351            blur: l(self.blur, o.blur),
352            magnify: l(self.magnify, o.magnify),
353            light_range: l2(self.light_range, o.light_range),
354            dark_range: l2(self.dark_range, o.dark_range),
355            saturation: l(self.saturation, o.saturation),
356            rim: l(self.rim, o.rim),
357            rim_width: l(self.rim_width, o.rim_width),
358            rim_base: l(self.rim_base, o.rim_base),
359            dark_edge: l(self.dark_edge, o.dark_edge),
360            light_spill: l(self.light_spill, o.light_spill),
361            inner_glow: l(self.inner_glow, o.inner_glow),
362            inner_shadow: l(self.inner_shadow, o.inner_shadow),
363            shadow: l(self.shadow, o.shadow),
364            shadow_radius: l(self.shadow_radius, o.shadow_radius),
365            shadow_y: l(self.shadow_y, o.shadow_y),
366            shadow_tint: l(self.shadow_tint, o.shadow_tint),
367            tint: match (self.tint, o.tint) {
368                (None, None) => None,
369                (Some(a), Some(b)) => Some(a.lerp(b, t)),
370                (Some(a), None) => Some(a.fade(1.0 - t)),
371                (None, Some(b)) => Some(b.fade(t)),
372            },
373            tint_follow: l(self.tint_follow, o.tint_follow),
374            glass_tint_response: l(self.glass_tint_response, o.glass_tint_response),
375        }
376    }
377}
378
379/// One shape of a glass element. Shapes of one element that come close fuse
380/// like drops of liquid.
381#[derive(Clone, Copy, Debug)]
382pub struct GlassShape {
383    /// Where the shape is.
384    pub rect: Rect,
385    /// Its corners.
386    pub corner: Corner,
387    /// A color for this shape only, instead of the material tint.
388    pub tint: Option<Color>,
389}
390
391impl GlassShape {
392    /// Creates a shape.
393    pub fn new(rect: Rect, corner: impl Into<Corner>) -> Self {
394        Self { rect, corner: corner.into(), tint: None }
395    }
396    /// Colors this shape only.
397    pub fn tint(mut self, color: Option<Color>) -> Self {
398        self.tint = color;
399        self
400    }
401}
402
403/// A glass element ready to paint with [`Painter::glass`](crate::Painter::glass).
404///
405/// Call [`Context::prepare_glass`](crate::Context::prepare_glass) before
406/// painting, so the element adapts to what is behind it.
407#[derive(Clone, Debug)]
408pub struct Glass {
409    /// The shapes of the element. Usually one.
410    pub shapes: Vec<GlassShape>,
411    /// The material.
412    pub material: Material,
413    /// Distance in points at which neighbouring shapes start to merge.
414    pub fuse: f32,
415    /// How formed the element is, from 0 (absent) to 1. It scales the optics,
416    /// not just the opacity, so glass appears by thickening.
417    pub presence: f32,
418    /// 0 uses the light range of the material, 1 the dark range.
419    pub darkness: f32,
420    /// Extra shadow over busy content.
421    pub shadow_boost: f32,
422    /// Even brightening, used as press feedback.
423    pub brightness: f32,
424    /// Extra rotation of the highlights, in radians.
425    pub light_bend: f32,
426    /// Measure the backdrop for this slot.
427    pub(crate) stat_key: Option<u64>,
428}
429
430impl Glass {
431    /// Creates an element of one shape.
432    pub fn new(rect: Rect, corner: impl Into<Corner>, material: Material) -> Self {
433        Self::group(vec![GlassShape::new(rect, corner)], material)
434    }
435    /// Creates an element of several shapes that fuse where they come close.
436    pub fn group(shapes: Vec<GlassShape>, material: Material) -> Self {
437        Self {
438            shapes,
439            material,
440            fuse: 12.0,
441            presence: 1.0,
442            darkness: 0.0,
443            shadow_boost: 0.0,
444            brightness: 0.0,
445            light_bend: 0.0,
446            stat_key: None,
447        }
448    }
449    /// Sets [`Glass::presence`].
450    pub fn presence(mut self, presence: f32) -> Self {
451        self.presence = presence.clamp(0.0, 1.0);
452        self
453    }
454    /// Sets [`Glass::fuse`].
455    pub fn fuse(mut self, distance: f32) -> Self {
456        self.fuse = distance;
457        self
458    }
459    /// Sets [`Glass::darkness`].
460    pub fn darkness(mut self, darkness: f32) -> Self {
461        self.darkness = darkness.clamp(0.0, 1.0);
462        self
463    }
464    /// Returns the rectangle around all shapes.
465    pub fn bounds(&self) -> Rect {
466        self.shapes.iter().fold(Rect::NOTHING, |a, s| a.union(s.rect))
467    }
468}