Skip to main content

bootsplash/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5use core::ffi::c_void;
6
7use graphics::{
8    Color, Logo, LogoArmPose, LogoPose,
9    lvgl::{
10        _lv_obj_t, LV_PART_MAIN, lv_align_t_LV_ALIGN_CENTER, lv_anim_completed_cb_t,
11        lv_anim_delete, lv_anim_exec_xcb_t, lv_anim_init, lv_anim_set_completed_cb,
12        lv_anim_set_duration, lv_anim_set_exec_cb, lv_anim_set_repeat_count, lv_anim_set_values,
13        lv_anim_set_var, lv_anim_start, lv_anim_t, lv_obj_get_size, lv_obj_get_style_text_color,
14        lv_obj_get_width, lv_obj_set_align,
15    },
16};
17
18mod error;
19
20pub use error::{Error, Result};
21
22/// The symbol assembles itself, then a ripple runs clockwise around it.
23///
24/// Intro: the center square fades in, then each arm slides inward along its
25/// diagonal into place, one after the other in clockwise order. The intro ends
26/// on the exact brand symbol.
27///
28/// Loop: one arm at a time glides outward along its diagonal, briefly widening
29/// its separation, and returns; the next arm (clockwise) starts halfway through.
30/// The symbol is never rotated, recolored or closed up, and the arms are back
31/// in place between pulses.
32mod timeline {
33    /// Fixed-point unit for progress values.
34    pub const ONE: i32 = 1024;
35
36    pub const SQUARE_FADE: i32 = 240;
37    pub const ARM_DELAY: i32 = 150;
38    pub const ARM_STAGGER: i32 = 100;
39    pub const ARM_DURATION: i32 = 450;
40    pub const INTRO: i32 = ARM_DELAY + 3 * ARM_STAGGER + ARM_DURATION;
41
42    pub const PERIOD: i32 = 1600;
43    pub const PULSE: i32 = PERIOD / 2;
44    /// Opacity of an arm at the top of its pulse.
45    pub const PULSE_OPACITY: i32 = 180;
46
47    /// Clockwise rank of each arm in `LogoPose` order (TL, BL, BR, TR).
48    pub const CLOCKWISE_RANK: [i32; 4] = [0, 3, 2, 1];
49
50    /// Outward offset in pixels and opacity of an arm.
51    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
52    pub struct ArmState {
53        pub offset: i32,
54        pub opacity: u8,
55    }
56
57    pub const REST: ArmState = ArmState {
58        offset: 0,
59        opacity: 255,
60    };
61
62    fn progress(time: i32, start: i32, duration: i32) -> i32 {
63        ((time - start) * ONE / duration).clamp(0, ONE)
64    }
65
66    fn ease_out_cubic(progress: i32) -> i32 {
67        let remaining = ONE - progress;
68        ONE - remaining * remaining / ONE * remaining / ONE
69    }
70
71    /// Smooth 0 → 1 → 0 bump with zero slope at both ends.
72    fn bump(progress: i32) -> i32 {
73        let parabola = 4 * progress * (ONE - progress) / ONE;
74        parabola * parabola / ONE
75    }
76
77    /// Distance an arm travels during the intro.
78    pub fn intro_distance(size: i32) -> i32 {
79        size / 5
80    }
81
82    /// Distance an arm travels at the top of its pulse.
83    pub fn pulse_distance(size: i32) -> i32 {
84        (size / 20).max(1)
85    }
86
87    pub fn square_opacity(time: i32) -> u8 {
88        (progress(time, 0, SQUARE_FADE) * 255 / ONE) as u8
89    }
90
91    pub fn intro_arm(index: usize, time: i32, size: i32) -> ArmState {
92        let start = ARM_DELAY + CLOCKWISE_RANK[index] * ARM_STAGGER;
93        let eased = ease_out_cubic(progress(time, start, ARM_DURATION));
94
95        ArmState {
96            offset: (ONE - eased) * intro_distance(size) / ONE,
97            opacity: (eased * 255 / ONE) as u8,
98        }
99    }
100
101    /// State of an arm `time` milliseconds into a ripple cycle. During the first
102    /// cycle, arms whose turn has not come yet stay at rest.
103    pub fn loop_arm(index: usize, time: i32, size: i32, first_cycle: bool) -> ArmState {
104        let start = CLOCKWISE_RANK[index] * PERIOD / 4;
105        if first_cycle && time < start {
106            return REST;
107        }
108        let phase = (time - start).rem_euclid(PERIOD);
109        if phase >= PULSE {
110            return REST;
111        }
112        let amount = bump(phase * ONE / PULSE);
113
114        ArmState {
115            offset: amount * pulse_distance(size) / ONE,
116            opacity: (255 - amount * (255 - PULSE_OPACITY) / ONE) as u8,
117        }
118    }
119}
120
121use timeline::ArmState;
122
123fn arm_pose(state: ArmState) -> LogoArmPose {
124    LogoArmPose {
125        offset: state.offset as u16,
126        opacity: state.opacity,
127    }
128}
129
130/// Show the intro `time` milliseconds after it started.
131///
132/// # Safety
133/// `logo` must be a live [`Logo`] object and the caller must hold the LVGL lock.
134unsafe fn show_intro(logo: *mut _lv_obj_t, time: i32) {
135    unsafe {
136        let size = lv_obj_get_width(logo);
137        let arms = core::array::from_fn(|index| arm_pose(timeline::intro_arm(index, time, size)));
138        Logo::set_pose(
139            logo,
140            LogoPose {
141                arms,
142                center_opacity: timeline::square_opacity(time),
143            },
144        );
145    }
146}
147
148/// Show the ripple `time` milliseconds into a cycle.
149///
150/// # Safety
151/// `logo` must be a live [`Logo`] object and the caller must hold the LVGL lock.
152unsafe fn show_loop(logo: *mut _lv_obj_t, time: i32, first_cycle: bool) {
153    unsafe {
154        let size = lv_obj_get_width(logo);
155        let arms = core::array::from_fn(|index| {
156            arm_pose(timeline::loop_arm(index, time, size, first_cycle))
157        });
158        Logo::set_pose(
159            logo,
160            LogoPose {
161                arms,
162                center_opacity: 255,
163            },
164        );
165    }
166}
167
168unsafe extern "C" fn intro_callback(object: *mut c_void, value: i32) {
169    unsafe { show_intro(object as *mut _lv_obj_t, value) }
170}
171
172unsafe extern "C" fn first_cycle_callback(object: *mut c_void, value: i32) {
173    unsafe { show_loop(object as *mut _lv_obj_t, value, true) }
174}
175
176unsafe extern "C" fn cycle_callback(object: *mut c_void, value: i32) {
177    unsafe { show_loop(object as *mut _lv_obj_t, value, false) }
178}
179
180unsafe extern "C" fn intro_completed(animation: *mut lv_anim_t) {
181    unsafe {
182        start(
183            (*animation).var,
184            timeline::PERIOD,
185            Some(first_cycle_callback),
186            0,
187            Some(first_cycle_completed),
188        );
189    }
190}
191
192unsafe extern "C" fn first_cycle_completed(animation: *mut lv_anim_t) {
193    unsafe {
194        start(
195            (*animation).var,
196            timeline::PERIOD,
197            Some(cycle_callback),
198            u32::MAX,
199            None,
200        );
201    }
202}
203
204/// Start an animation driving `callback` with the elapsed time in milliseconds.
205///
206/// LVGL copies the descriptor, so it can live on the stack.
207unsafe fn start(
208    logo: *mut c_void,
209    duration: i32,
210    callback: lv_anim_exec_xcb_t,
211    repeat_count: u32,
212    completed: lv_anim_completed_cb_t,
213) {
214    unsafe {
215        let mut animation = lv_anim_t::default();
216        lv_anim_init(&mut animation);
217        lv_anim_set_var(&mut animation, logo);
218        lv_anim_set_values(&mut animation, 0, duration);
219        lv_anim_set_duration(&mut animation, duration as u32);
220        lv_anim_set_repeat_count(&mut animation, repeat_count);
221        lv_anim_set_exec_cb(&mut animation, callback);
222        lv_anim_set_completed_cb(&mut animation, completed);
223        lv_anim_start(&animation);
224    }
225}
226
227pub struct Bootsplash {
228    logo: Logo,
229}
230
231impl Bootsplash {
232    pub async fn new(graphics_manager: &'static graphics::Manager) -> Result<Self> {
233        let mut guard = graphics_manager.lock().await;
234        let current_screen =
235            guard.with_lvgl(|access| graphics_manager.get_current_screen(access))??;
236
237        // SAFETY: the guard keeps the active screen live for the raw setup.
238        unsafe {
239            let screen_size = lv_obj_get_size(current_screen);
240            let factor = Logo::get_factor(screen_size.scale(0.3)).max(1);
241
242            let foreground =
243                Color::from_lvgl_color(lv_obj_get_style_text_color(current_screen, LV_PART_MAIN));
244            let logo = Logo::new(current_screen, factor, foreground)?;
245
246            let object = logo.get_inner_object();
247            lv_obj_set_align(object, lv_align_t_LV_ALIGN_CENTER);
248            show_intro(object, 0);
249
250            start(
251                object as *mut c_void,
252                timeline::INTRO,
253                Some(intro_callback),
254                0,
255                Some(intro_completed),
256            );
257
258            Ok(Self { logo })
259        }
260    }
261
262    pub async fn stop(self, graphics_manager: &'static graphics::Manager) -> Result<()> {
263        let _lock = graphics_manager.lock().await;
264
265        unsafe {
266            let object = self.logo.get_inner_object() as *mut c_void;
267            lv_anim_delete(object, Some(intro_callback));
268            lv_anim_delete(object, Some(first_cycle_callback));
269            lv_anim_delete(object, Some(cycle_callback));
270        }
271
272        // Parameters drop after the body's locals, so the logo would otherwise
273        // be deleted after `_lock` is released.
274        drop(self.logo);
275
276        Ok(())
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::timeline::*;
283
284    const SIZE: i32 = 160;
285
286    #[test]
287    fn intro_starts_hidden_and_ends_on_the_exact_symbol() {
288        assert_eq!(square_opacity(0), 0);
289        assert_eq!(square_opacity(INTRO), 255);
290        for index in 0..4 {
291            let start = intro_arm(index, 0, SIZE);
292            assert_eq!(start.opacity, 0);
293            assert_eq!(start.offset, intro_distance(SIZE));
294            assert_eq!(intro_arm(index, INTRO, SIZE), REST);
295        }
296    }
297
298    #[test]
299    fn intro_assembles_arms_clockwise() {
300        // Top-left, then top-right, bottom-right and bottom-left.
301        let time = ARM_DELAY + ARM_STAGGER + ARM_STAGGER / 2;
302        let progress = |index| intro_arm(index, time, SIZE).opacity;
303        assert!(progress(0) > progress(3));
304        assert!(progress(3) > progress(2));
305        assert_eq!(progress(2), 0);
306        assert_eq!(progress(1), 0);
307    }
308
309    #[test]
310    fn ripple_moves_outward_only_and_joins_the_intro_smoothly() {
311        for first_cycle in [true, false] {
312            for index in 0..4 {
313                for time in (0..PERIOD).step_by(10) {
314                    let state = loop_arm(index, time, SIZE, first_cycle);
315                    assert!((0..=pulse_distance(SIZE)).contains(&state.offset));
316                    assert!(state.opacity as i32 >= PULSE_OPACITY);
317                }
318                // Both cycles start from, and every cycle wraps to, the rest pose.
319                assert_eq!(loop_arm(index, 0, SIZE, true), REST);
320            }
321        }
322        assert_eq!(loop_arm(0, 0, SIZE, false), REST);
323        // The pulse peaks halfway and the next arm clockwise follows it.
324        assert_eq!(
325            loop_arm(0, PULSE / 2, SIZE, false).offset,
326            pulse_distance(SIZE)
327        );
328        assert_eq!(
329            loop_arm(3, PERIOD / 4 + PULSE / 2, SIZE, false).offset,
330            pulse_distance(SIZE)
331        );
332        // Arms not yet reached in the first cycle stay put.
333        assert_eq!(loop_arm(1, PERIOD / 8, SIZE, true), REST);
334        assert_ne!(loop_arm(1, PERIOD / 8, SIZE, false), REST);
335    }
336}