Skip to main content

cranpose_render_common/
layer_shadow.rs

1//! Elevation shadows as Jetpack Compose draws them: Android's renderer and
2//! Compose Multiplatform's both light a layer from one point above the window
3//! and hand the caster to Skia's `SkShadowUtils`, which draws an ambient and a
4//! spot shadow. The constants below are theirs.
5
6use cranpose_ui_graphics::{Color, CornerRadii, GraphicsLayer, Rect, RoundedCornerShape};
7
8use crate::layer_transform::layer_uniform_scale;
9
10const MIN_LAYER_SHADOW_SCALE: f32 = 0.1;
11/// The share of a shadow color's alpha each pass keeps: Android's
12/// `ambientShadowAlpha` and `spotShadowAlpha` theme values, which Compose
13/// Multiplatform copies.
14const AMBIENT_SHADOW_ALPHA: f32 = 0.039;
15const SPOT_SHADOW_ALPHA: f32 = 0.19;
16/// Where the light sits, in dp: `light_y`, `light_z` and `light_radius`.
17const LIGHT_Y: f32 = 0.0;
18const LIGHT_Z: f32 = 500.0;
19const LIGHT_RADIUS: f32 = 800.0;
20/// The window size, in dp, at which the light stands at `LIGHT_Z`; larger
21/// windows raise it, smaller ones lower it, against shadow distortion.
22const LIGHT_Z_REFERENCE: f32 = 450.0;
23/// The most an ambient shadow reaches past its caster, in pixels: Skia's
24/// `kMaxAmbientRadius`.
25const MAX_AMBIENT_REACH_PIXELS: f32 = 150.0;
26/// Skia's falloff table: 128 texels of `exp(-4 (1 - x)^2) - 0.018`, read
27/// with linear filtering at the ramp's coordinate.
28const FALLOFF_TEXELS: f32 = 128.0;
29const FALLOFF_FLOOR: f32 = 0.018;
30
31/// The light elevation shadows are cast by, in the units and coordinates the
32/// shadow is collected in.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct ShadowLight {
35    pub x: f32,
36    pub y: f32,
37    pub z: f32,
38    pub radius: f32,
39    /// Device pixels per unit: Skia scales the ambient penumbra by the
40    /// caster's height in pixels.
41    pub pixels_per_unit: f32,
42}
43
44impl ShadowLight {
45    /// The light over a window `width × height` units in size whose origin
46    /// is the collection origin, where one dp is `units_per_dp` units. Matches
47    /// Kotlin: `ThreadedRenderer.setLightCenter` on Android and its copy in
48    /// Compose Multiplatform's `GraphicsLayerOwnerLayer.skiko.kt`.
49    pub fn for_window(width: f32, height: f32, units_per_dp: f32, pixels_per_unit: f32) -> Self {
50        let units_per_dp = units_per_dp.max(f32::EPSILON);
51        let window_dp = width.min(height).max(0.0) / units_per_dp;
52        let adjustment = (window_dp / LIGHT_Z_REFERENCE + 2.0) / 3.0;
53        Self {
54            x: width / 2.0,
55            y: LIGHT_Y * units_per_dp,
56            z: LIGHT_Z * units_per_dp * adjustment,
57            radius: LIGHT_RADIUS * units_per_dp,
58            pixels_per_unit,
59        }
60    }
61
62    /// The same light seen from a space whose origin sits at `origin` in
63    /// this one and whose units are `scale` of this one's.
64    pub fn in_space(self, origin_x: f32, origin_y: f32, scale: f32) -> Self {
65        let scale = scale.max(MIN_LAYER_SHADOW_SCALE);
66        Self {
67            x: (self.x - origin_x) / scale,
68            y: (self.y - origin_y) / scale,
69            z: self.z / scale,
70            radius: self.radius / scale,
71            pixels_per_unit: self.pixels_per_unit * scale,
72        }
73    }
74}
75
76/// One pass of a shadow as Skia's `ShadowCircularRRectOp` draws it: a round
77/// rect whose penumbra rises from its outer edge, `bounds`, toward the umbra
78/// `umbra_inset` in. Corners are fans of triangles whose offsets the GPU
79/// interpolates, so a corner is a quarter circle where the umbra meets its
80/// radius and a skewed one where the blur is wider. Every length is in the
81/// space the shadow is collected in.
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct ShadowRRect {
84    /// The penumbra's outer edge.
85    pub bounds: Rect,
86    /// The outer corner radii: top-left, top-right, bottom-right,
87    /// bottom-left.
88    pub radii: [f32; 4],
89    /// How far in from `bounds` the ramp runs, at most half the smaller side.
90    pub umbra_inset: f32,
91    /// The ramp's coordinate at the umbra: the umbra inset over the blur.
92    pub distance_correction: f32,
93    /// The part an opaque caster covers, which the shadow leaves undrawn.
94    pub hole: Option<ShadowHole>,
95}
96
97/// The round rect inside a shadow that it leaves undrawn: `bounds` of the
98/// shadow inset by `inset`, its corners rounded at `radius`.
99#[derive(Clone, Copy, Debug, PartialEq)]
100pub struct ShadowHole {
101    pub inset: f32,
102    pub radius: f32,
103}
104
105impl ShadowRRect {
106    /// The shadow `outer` casts with a ramp `blur` wide: Skia's fill of a
107    /// circle or round rect, or for `inset_width` within half its smaller
108    /// side, its stroke, which leaves the middle to the caster.
109    fn new(outer: Rect, radii: [f32; 4], blur: f32, inset_width: f32) -> Option<Self> {
110        let half_side = 0.5 * outer.width.min(outer.height);
111        if half_side <= 0.0 || blur <= 0.0 {
112            return None;
113        }
114        let largest = radii.into_iter().fold(0.0, f32::max);
115        let circle = (outer.width - outer.height).abs() <= f32::EPSILON * outer.width
116            && largest >= half_side;
117        let (umbra_inset, hole) = if circle {
118            let inner = half_side - inset_width;
119            let hole = (inner > 0.0).then_some(ShadowHole {
120                inset: inset_width,
121                radius: inner,
122            });
123            (half_side, hole)
124        } else {
125            let umbra = largest.max(blur);
126            let hole = (inset_width <= half_side).then(|| ShadowHole {
127                inset: inset_width.max(umbra.min(half_side)),
128                radius: 0.0,
129            });
130            (umbra.min(half_side), hole)
131        };
132        Some(Self {
133            bounds: outer,
134            radii: if circle { [half_side; 4] } else { radii },
135            umbra_inset,
136            distance_correction: umbra_inset / blur,
137            hole: hole.filter(|hole| hole.inset < half_side),
138        })
139    }
140
141    /// The same shadow in a space whose units are `scale` of this one's.
142    pub fn scaled(self, scale: f32) -> Self {
143        Self {
144            bounds: Rect {
145                x: self.bounds.x * scale,
146                y: self.bounds.y * scale,
147                width: self.bounds.width * scale,
148                height: self.bounds.height * scale,
149            },
150            radii: self.radii.map(|radius| radius * scale),
151            umbra_inset: self.umbra_inset * scale,
152            distance_correction: self.distance_correction,
153            hole: self.hole.map(|hole| ShadowHole {
154                inset: hole.inset * scale,
155                radius: hole.radius * scale,
156            }),
157        }
158    }
159
160    /// The same shadow moved by `dx`, `dy`.
161    pub fn translated(self, dx: f32, dy: f32) -> Self {
162        Self {
163            bounds: self.bounds.translate(dx, dy),
164            ..self
165        }
166    }
167
168    /// The rect the hole spans, when there is one.
169    pub fn hole_rect(&self) -> Option<Rect> {
170        self.hole.map(|hole| Rect {
171            x: self.bounds.x + hole.inset,
172            y: self.bounds.y + hole.inset,
173            width: self.bounds.width - 2.0 * hole.inset,
174            height: self.bounds.height - 2.0 * hole.inset,
175        })
176    }
177
178    /// How much of the shadow's color the point `x`, `y` takes: the falloff
179    /// at the offset Skia's mesh interpolates there, zero outside the shadow
180    /// and in its hole.
181    pub fn coverage(&self, x: f32, y: f32) -> f32 {
182        let bounds = self.bounds;
183        let right_edge = bounds.x + bounds.width;
184        let bottom_edge = bounds.y + bounds.height;
185        if x < bounds.x || y < bounds.y || x >= right_edge || y >= bottom_edge {
186            return 0.0;
187        }
188        if let (Some(hole), Some(rect)) = (self.hole, self.hole_rect())
189            && rounded_rect_contains(rect, hole.radius, x, y)
190        {
191            return 0.0;
192        }
193        let umbra = self.umbra_inset;
194        let left = bounds.x + umbra - x;
195        let right = x - (right_edge - umbra);
196        let top = bounds.y + umbra - y;
197        let bottom = y - (bottom_edge - umbra);
198        let corner = match (left > right, top > bottom) {
199            (true, true) => 0,
200            (false, true) => 1,
201            (false, false) => 2,
202            (true, false) => 3,
203        };
204        let offset = fan_offset(
205            left.max(right).max(0.0),
206            top.max(bottom).max(0.0),
207            umbra,
208            self.radii[corner],
209        );
210        shadow_falloff(self.distance_correction * (1.0 - offset))
211    }
212}
213
214fn rounded_rect_contains(rect: Rect, radius: f32, x: f32, y: f32) -> bool {
215    let half_width = 0.5 * rect.width;
216    let half_height = 0.5 * rect.height;
217    let dx = (x - rect.x - half_width).abs() - (half_width - radius);
218    let dy = (y - rect.y - half_height).abs() - (half_height - radius);
219    let outside = (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt();
220    outside + dx.max(dy).min(0.0) - radius < 0.0
221}
222
223/// The length of the offset Skia's corner fan interpolates at `along` and
224/// `across`, a point's distances out from the umbra's corner toward the two
225/// edges, for an umbra inset `umbra` and a corner radius `radius`: 0 at the
226/// umbra and 1 on the outer edge. The fan's triangles meet the edge at the
227/// umbra line, at `umbra - radius` along it and at the corner, whose offsets
228/// Skia skews when the umbra is deeper than the radius.
229pub fn fan_offset(along: f32, across: f32, umbra: f32, radius: f32) -> f32 {
230    let (a, b) = if along >= across {
231        (along, across)
232    } else {
233        (across, along)
234    };
235    if a <= 0.0 || umbra <= 0.0 {
236        return 0.0;
237    }
238    let length = (2.0 * (radius * radius + umbra * umbra)).sqrt();
239    let outer = [(radius - umbra) / length, (-radius - umbra) / length];
240    let straight = umbra - radius;
241    let [x, y] = if b * umbra <= a * straight {
242        let toward_curve = if straight > 0.0 { b / straight } else { 0.0 };
243        let toward_edge = a / umbra - toward_curve;
244        [
245            toward_curve * outer[0],
246            -toward_edge + toward_curve * outer[1],
247        ]
248    } else {
249        let diagonal = umbra / (std::f32::consts::SQRT_2 * (radius - umbra) - radius);
250        let toward_curve = (a - b) / radius;
251        let toward_corner = a / umbra - toward_curve;
252        [
253            toward_curve * outer[0] + toward_corner * diagonal,
254            toward_curve * outer[1] + toward_corner * diagonal,
255        ]
256    };
257    (x * x + y * y).sqrt()
258}
259
260/// Skia's penumbra falloff at `x`, the ramp's coordinate: 0 on the outer
261/// edge, 1 where the shadow is whole, read as its table is.
262pub fn shadow_falloff(x: f32) -> f32 {
263    let texel = ((x * FALLOFF_TEXELS - 0.5) / (FALLOFF_TEXELS - 1.0)).clamp(0.0, 1.0);
264    let distance = 1.0 - texel;
265    ((-4.0 * distance * distance).exp() - FALLOFF_FLOOR).max(0.0)
266}
267
268#[derive(Clone, Copy, Debug, Default, PartialEq)]
269pub struct LayerShadowGeometry {
270    pub ambient: Option<(ShadowRRect, Color)>,
271    pub spot: Option<(ShadowRRect, Color)>,
272}
273
274impl LayerShadowGeometry {
275    /// Each pass with the color it draws, ambient first.
276    pub fn passes(&self) -> impl Iterator<Item = (ShadowRRect, Color)> {
277        self.ambient.into_iter().chain(self.spot)
278    }
279}
280
281fn outset(rect: Rect, amount: f32) -> Rect {
282    Rect {
283        x: rect.x - amount,
284        y: rect.y - amount,
285        width: rect.width + amount * 2.0,
286        height: rect.height + amount * 2.0,
287    }
288}
289
290fn corner_radii(radii: CornerRadii) -> [f32; 4] {
291    [
292        radii.top_left,
293        radii.top_right,
294        radii.bottom_right,
295        radii.bottom_left,
296    ]
297}
298
299/// `color` at the alpha Android's renderer gives a pass: the theme's
300/// `share` as a byte, times the caster's alpha, times the color's alpha
301/// byte, truncated to a byte (`multiplyAlpha` in
302/// `ReorderBarrierDrawables.cpp`).
303fn pass_color(color: Color, share: f32, caster_alpha: f32) -> Option<Color> {
304    let share_byte = (share * 255.0).floor();
305    let color_byte = (color.a().clamp(0.0, 1.0) * 255.0).round();
306    let byte = (color_byte * share_byte / 255.0 * caster_alpha).floor();
307    (byte > 0.0).then(|| Color(color.r(), color.g(), color.b(), byte / 255.0))
308}
309
310/// Whether the caster covers the middle of its shadow: an opaque one that
311/// keeps its rect upright. Skia fills the shadow of any other.
312fn caster_occludes(layer: &GraphicsLayer) -> bool {
313    layer.alpha >= 1.0
314        && layer.rotation_x.abs() <= f32::EPSILON
315        && layer.rotation_y.abs() <= f32::EPSILON
316        && layer.rotation_z.abs() <= f32::EPSILON
317}
318
319/// How far the spot shadow strays from its caster at a corner: Skia's
320/// `maxOffset`, the manhattan distance for a rect and for a round rect the
321/// corner centers' distance plus the radii's difference.
322fn spot_stray(caster: Rect, spot: Rect, caster_radius: f32, spot_radius: f32) -> f32 {
323    if caster_radius <= 0.0 {
324        return (spot.x - caster.x)
325            .abs()
326            .max((spot.y - caster.y).abs())
327            .max((spot.x + spot.width - caster.x - caster.width).abs())
328            .max((spot.y + spot.height - caster.y - caster.height).abs());
329    }
330    let grown = spot_radius - caster_radius;
331    let upper = [spot.x - caster.x + grown, spot.y - caster.y + grown];
332    let lower = [
333        spot.x + spot.width - caster.x - caster.width - grown,
334        spot.y + spot.height - caster.y - caster.height - grown,
335    ];
336    let length = |[x, y]: [f32; 2]| x * x + y * y;
337    length(upper).max(length(lower)).sqrt() + grown
338}
339
340/// The ambient and spot passes of `layer`'s shadow over `transformed_bounds`
341/// with the corners `caster` rounds it at, lit by `light`. Matches Skia's
342/// `SurfaceDrawContext::drawFastShadow` and `SkDrawShadowMetrics`.
343pub fn layer_shadow_geometry(
344    layer: &GraphicsLayer,
345    transformed_bounds: Rect,
346    caster: Option<RoundedCornerShape>,
347    light: ShadowLight,
348) -> LayerShadowGeometry {
349    if layer.shadow_elevation <= 0.0 {
350        return LayerShadowGeometry::default();
351    }
352
353    let scale = layer_uniform_scale(layer).max(MIN_LAYER_SHADOW_SCALE);
354    let height = layer.shadow_elevation * scale;
355    let caster_alpha = layer.alpha.clamp(0.0, 1.0);
356    let radii = caster.map_or([0.0; 4], |shape| corner_radii(shape.radii()));
357    let occludes = caster_occludes(layer);
358    let pixels_per_unit = light.pixels_per_unit.max(f32::EPSILON);
359
360    // The ambient shadow reaches half the height past the caster, its
361    // penumbra widened by the height in pixels.
362    let reach = (height * 0.5).min(MAX_AMBIENT_REACH_PIXELS / pixels_per_unit);
363    let ambient_outer = outset(transformed_bounds, reach);
364    let ambient = pass_color(
365        layer.ambient_shadow_color,
366        AMBIENT_SHADOW_ALPHA,
367        caster_alpha,
368    )
369    .and_then(|color| {
370        let blur = reach * (1.0 + height * pixels_per_unit / 128.0);
371        let inset = if occludes { reach } else { ambient_outer.width };
372        ShadowRRect::new(ambient_outer, radii.map(|r| r + reach), blur, inset)
373            .map(|shadow| (shadow, color))
374    });
375
376    // The spot shadow is the caster projected from the light onto the
377    // plane below it: every point moves away from the light by the height's
378    // share of the light's, and the penumbra is the light's radius times it.
379    let depth = light.z - height;
380    let z_ratio = if depth > f32::EPSILON {
381        (height / depth).clamp(0.0, 0.95)
382    } else {
383        0.95
384    };
385    let spot_scale = 1.0 + z_ratio;
386    let spot_blur = light.radius * z_ratio;
387    let projected = Rect {
388        x: transformed_bounds.x + z_ratio * (transformed_bounds.x - light.x),
389        y: transformed_bounds.y + z_ratio * (transformed_bounds.y - light.y),
390        width: transformed_bounds.width * spot_scale,
391        height: transformed_bounds.height * spot_scale,
392    };
393    let spot =
394        pass_color(layer.spot_shadow_color, SPOT_SHADOW_ALPHA, caster_alpha).and_then(|color| {
395            let caster_radius = radii.into_iter().fold(0.0, f32::max);
396            let inset = spot_blur
397                + if occludes {
398                    spot_blur.max(spot_stray(
399                        transformed_bounds,
400                        projected,
401                        caster_radius,
402                        caster_radius * spot_scale,
403                    ))
404                } else {
405                    projected.width
406                };
407            ShadowRRect::new(
408                outset(projected, spot_blur),
409                radii.map(|r| r * spot_scale + spot_blur),
410                2.0 * spot_blur,
411                inset,
412            )
413            .map(|shadow| (shadow, color))
414        });
415
416    LayerShadowGeometry { ambient, spot }
417}
418
419#[cfg(test)]
420#[path = "tests/layer_shadow_tests.rs"]
421mod tests;