Skip to main content

clairlune_live/
lib.rs

1//! Clairlune's live wallpaper (PLAN.md sections 2 and 5.3): a saved scene
2//! plays behind the desktop icons.
3//!
4//! [`Player`] keeps the frame between ticks with the incremental compositor
5//! and writes only the rectangles that changed into a 0RGB buffer, which the
6//! presenter copies to the screen as damage. The pixels come from the same
7//! compositor as the still PNG, with the same palette, so the first live
8//! frame (at the hero time) is the static wallpaper, except that on a GPU
9//! the particles sit at their own sub-cell positions ([`Player::set_smooth`])
10//! instead of the cell grid.
11
12use clairlune_render::clock::Clock;
13use clairlune_render::{IncrementalFrame, IndexedImage, PixelRect, ScenePackage};
14use clairlune_scene::Theme;
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18#[cfg(windows)]
19pub mod d3d11;
20#[cfg(windows)]
21pub mod desktop;
22pub mod gpu;
23#[cfg(target_os = "linux")]
24pub mod linux;
25#[cfg(target_os = "macos")]
26pub mod mac;
27
28/// What a maximized or full-screen app pauses.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum CoverPolicy {
31    /// The monitor it covers.
32    #[default]
33    ThatMonitor,
34    /// Every monitor.
35    AllMonitors,
36    /// Nothing.
37    Off,
38}
39
40/// What one frame cost, for budgets and logs.
41#[derive(Clone, Copy, Debug, Default)]
42pub struct FrameStats {
43    /// Pixels uploaded or copied, over all monitors.
44    pub pixels: u64,
45    /// Rectangles uploaded or copied.
46    pub rects: usize,
47    /// Monitors paused because a window covers them.
48    pub covered: usize,
49    /// Paused everywhere: the session is locked or the displays are off.
50    pub away: bool,
51    /// Presents that waited over 50 ms for the swapchain (the compositor
52    /// holding frames back).
53    pub stalls: usize,
54    /// Time spent compositing, uploading and presenting.
55    pub busy: Duration,
56    /// Of which uploading, and drawing plus presenting.
57    pub upload: Duration,
58    pub present: Duration,
59}
60
61/// Plays one saved scene, one frame at a time.
62pub struct Player {
63    pkg: Arc<ScenePackage>,
64    theme: Theme,
65    buddy: bool,
66    frame: IncrementalFrame,
67    /// Palette index to 0RGB.
68    colors: [u32; 256],
69    /// Scene time when playback started (the hero time, so the first frame
70    /// is the still), and when that was.
71    t0: u64,
72    started: Instant,
73    /// `Clock::Live` (particles on the cell grid) or `Clock::Smooth`.
74    clock: Clock,
75    /// The part of the frame this player shows (one monitor of a scene
76    /// spread over several); the whole frame otherwise.
77    view: PixelRect,
78}
79
80impl Player {
81    /// `None` if the scene has no such theme.
82    pub fn new(pkg: Arc<ScenePackage>, theme: Theme, buddy: bool) -> Option<Player> {
83        let view = PixelRect {
84            x: 0,
85            y: 0,
86            w: pkg.width,
87            h: pkg.height,
88        };
89        Self::new_view(pkg, theme, buddy, view)
90    }
91
92    /// A player showing only `view` of the scene's frame (span mode: each
93    /// monitor shows its part of one scene). Every method then works in the
94    /// view's own coordinates. `None` if the scene has no such theme or the
95    /// view isn't inside the frame.
96    pub fn new_view(
97        pkg: Arc<ScenePackage>,
98        theme: Theme,
99        buddy: bool,
100        view: PixelRect,
101    ) -> Option<Player> {
102        if view.w == 0 || view.h == 0 || view.x + view.w > pkg.width || view.y + view.h > pkg.height
103        {
104            return None;
105        }
106        let frame = pkg.incremental(theme)?;
107        let mut colors = [0u32; 256];
108        for (i, c) in pkg.palette(theme)?.colors().iter().enumerate() {
109            colors[i] = (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b);
110        }
111        let t0 = pkg.hero_ms(theme)?;
112        Some(Player {
113            pkg,
114            theme,
115            buddy,
116            frame,
117            colors,
118            t0,
119            started: Instant::now(),
120            clock: Clock::Live,
121            view,
122        })
123    }
124
125    /// Particles at sub-cell positions (`Clock::Smooth`), for presenters on
126    /// a GPU: a higher frame rate then moves them smoothly. Off by default,
127    /// so the first frame is the still exactly; the CPU fallback keeps it
128    /// off (PLAN.md section 4.4).
129    pub fn set_smooth(&mut self, on: bool) {
130        self.clock = if on { Clock::Smooth } else { Clock::Live };
131    }
132
133    /// Another player of the same scene at the same moment, showing `view`
134    /// of it (one scene on several screens, each showing its part). `None`
135    /// if the view isn't inside the frame.
136    pub fn with_view(&self, view: PixelRect) -> Option<Player> {
137        let mut p = Player::new_view(self.pkg.clone(), self.theme, self.buddy, view)?;
138        p.t0 = self.t0;
139        p.started = self.started;
140        p.clock = self.clock;
141        Some(p)
142    }
143
144    /// Whether the scene is a journey (its whole frame moves every tick).
145    pub fn is_journey(&self) -> bool {
146        self.pkg
147            .graph(self.theme)
148            .is_some_and(|g| g.journey.is_some())
149    }
150
151    /// The size of what this player shows.
152    pub fn size(&self) -> (u32, u32) {
153        (self.view.w, self.view.h)
154    }
155
156    /// The whole current frame as palette indices (not just the view).
157    pub fn image(&self) -> &IndexedImage {
158        self.frame.image()
159    }
160
161    /// Palette indices of `w` pixels of row `y` from column `x`, in the
162    /// view's coordinates.
163    pub fn index_row(&self, x: u32, y: u32, w: u32) -> &[u8] {
164        let img = self.frame.image();
165        let a = (self.view.y + y) as usize * img.width as usize + (self.view.x + x) as usize;
166        &img.pixels[a..a + w as usize]
167    }
168
169    /// The palette as 0RGB, by index.
170    pub fn colors(&self) -> &[u32; 256] {
171        &self.colors
172    }
173
174    /// Scene time now: the hero time plus the time since playback started.
175    /// A pause only stops drawing; the next frame shows the time it is.
176    pub fn now_ms(&self) -> u64 {
177        self.t0 + self.started.elapsed().as_millis() as u64
178    }
179
180    /// Moves to `t_ms`; returns the rectangles that changed, in the view's
181    /// coordinates (changes outside the view are left out).
182    pub fn advance(&mut self, t_ms: u64) -> Vec<PixelRect> {
183        let rects = self
184            .pkg
185            .advance(&mut self.frame, self.theme, self.buddy, t_ms, self.clock)
186            .unwrap_or_default();
187        let v = self.view;
188        if (v.x, v.y, v.w, v.h) == (0, 0, self.pkg.width, self.pkg.height) {
189            return rects;
190        }
191        rects
192            .iter()
193            .filter_map(|r| {
194                let x0 = r.x.max(v.x);
195                let y0 = r.y.max(v.y);
196                let x1 = (r.x + r.w).min(v.x + v.w);
197                let y1 = (r.y + r.h).min(v.y + v.h);
198                (x1 > x0 && y1 > y0).then(|| PixelRect {
199                    x: x0 - v.x,
200                    y: y0 - v.y,
201                    w: x1 - x0,
202                    h: y1 - y0,
203                })
204            })
205            .collect()
206    }
207
208    /// Writes those rectangles (view coordinates) of the current frame into
209    /// a 0RGB buffer of the view's size.
210    pub fn write(&self, buf: &mut [u32], rects: &[PixelRect]) {
211        let w = self.view.w as usize;
212        debug_assert_eq!(buf.len(), w * self.view.h as usize);
213        for r in rects {
214            for y in r.y..r.y + r.h {
215                let a = y as usize * w + r.x as usize;
216                let row = self.index_row(r.x, y, r.w);
217                for (out, &i) in buf[a..a + r.w as usize].iter_mut().zip(row) {
218                    *out = self.colors[usize::from(i)];
219                }
220            }
221        }
222    }
223
224    /// One rectangle (view coordinates) of the current frame as 0RGB
225    /// pixels, row by row.
226    pub fn rect_pixels(&self, r: &PixelRect, out: &mut Vec<u32>) {
227        out.clear();
228        for y in r.y..r.y + r.h {
229            out.extend(
230                self.index_row(r.x, y, r.w)
231                    .iter()
232                    .map(|&i| self.colors[usize::from(i)]),
233            );
234        }
235    }
236
237    /// Writes the whole view.
238    pub fn write_all(&self, buf: &mut [u32]) {
239        let whole = PixelRect {
240            x: 0,
241            y: 0,
242            w: self.view.w,
243            h: self.view.h,
244        };
245        self.write(buf, &[whole]);
246    }
247}
248
249/// The highest frame rate for a journey: its land moves, so every frame is
250/// the whole screen, and Very smooth already scrolls evenly.
251pub const JOURNEY_MAX_FPS: u32 = 30;
252
253/// Live frame rates, by their names in Settings (PLAN.md section 5.3).
254pub const SMOOTHNESS_FPS: [(u32, &str); 5] = [
255    (6, "Battery saver"),
256    (12, "Balanced"),
257    (24, "Smooth"),
258    (30, "Very smooth"),
259    (60, "Ultra smooth"),
260];
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use clairlune_render::to_rgba;
266    use clairlune_scene::{Aspect, ContentContext, compose};
267
268    fn player() -> Player {
269        let r = compose(42, Aspect::from_size(320, 180), &ContentContext::default());
270        let pkg = Arc::new(ScenePackage::capture(&r, 320, 180).unwrap());
271        let theme = pkg.themes()[0];
272        Player::new(pkg, theme, true).unwrap()
273    }
274
275    fn rgb(buf: &[u32]) -> Vec<u8> {
276        buf.iter()
277            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255])
278            .collect()
279    }
280
281    #[test]
282    fn the_first_frame_is_the_still_and_updates_keep_the_buffer_exact() {
283        let mut p = player();
284        let (w, h) = p.size();
285        let mut buf = vec![0u32; (w * h) as usize];
286        let t0 = p.t0;
287        let rects = p.advance(t0);
288        p.write_all(&mut buf);
289        let _ = rects;
290        let (still, palette) = p.pkg.still(p.theme, true).unwrap();
291        assert_eq!(rgb(&buf), to_rgba(&still, palette));
292        // Then only the changed rects, as a presenter does.
293        for k in 1..40u64 {
294            let t = t0 + k * 83;
295            let rects = p.advance(t);
296            p.write(&mut buf, &rects);
297            let (full, palette) = p.pkg.frame(p.theme, true, t, Clock::Live).unwrap();
298            assert_eq!(rgb(&buf), to_rgba(&full, palette), "t {t}");
299        }
300    }
301
302    /// Span mode: a player showing part of a wide scene keeps a buffer of
303    /// just that part exact, from its own changed rects, like a whole-frame
304    /// player does.
305    #[test]
306    fn a_view_shows_its_part_of_the_frame_exactly() {
307        let (w, h) = (640, 180);
308        let r = compose(7, Aspect::from_size(w, h), &ContentContext::default());
309        let pkg = Arc::new(ScenePackage::capture(&r, w, h).unwrap());
310        let theme = pkg.themes()[0];
311        // The right half, as a second monitor of the same height.
312        let view = PixelRect {
313            x: 320,
314            y: 0,
315            w: 320,
316            h: 180,
317        };
318        let mut p = Player::new_view(pkg.clone(), theme, true, view).unwrap();
319        assert_eq!(p.size(), (320, 180));
320        let mut buf = vec![0u32; 320 * 180];
321        let t0 = p.t0;
322        p.advance(t0);
323        p.write_all(&mut buf);
324        let crop = |t: u64| -> Vec<u32> {
325            let (full, palette) = pkg.frame(theme, true, t, Clock::Live).unwrap();
326            let colors: Vec<u32> = palette
327                .colors()
328                .iter()
329                .map(|c| (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b))
330                .collect();
331            (0..180)
332                .flat_map(|y| (320..640).map(move |x| (x, y)))
333                .map(|(x, y)| colors[usize::from(full.pixels[y * 640 + x])])
334                .collect()
335        };
336        assert_eq!(buf, crop(t0));
337        for k in 1..40u64 {
338            let t = t0 + k * 83;
339            let rects = p.advance(t);
340            assert!(rects.iter().all(|r| r.x + r.w <= 320 && r.y + r.h <= 180));
341            p.write(&mut buf, &rects);
342            assert_eq!(buf, crop(t), "t {t}");
343        }
344        // A view outside the frame is refused.
345        let outside = PixelRect {
346            x: 400,
347            y: 0,
348            w: 320,
349            h: 180,
350        };
351        assert!(Player::new_view(pkg, theme, true, outside).is_none());
352    }
353}