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 = "macos")]
24pub mod mac;
25
26/// What a maximized or full-screen app pauses.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum CoverPolicy {
29    /// The monitor it covers.
30    #[default]
31    ThatMonitor,
32    /// Every monitor.
33    AllMonitors,
34    /// Nothing.
35    Off,
36}
37
38/// What one frame cost, for budgets and logs.
39#[derive(Clone, Copy, Debug, Default)]
40pub struct FrameStats {
41    /// Pixels uploaded or copied, over all monitors.
42    pub pixels: u64,
43    /// Rectangles uploaded or copied.
44    pub rects: usize,
45    /// Monitors paused because a window covers them.
46    pub covered: usize,
47    /// Paused everywhere: the session is locked or the displays are off.
48    pub away: bool,
49    /// Presents that waited over 50 ms for the swapchain (the compositor
50    /// holding frames back).
51    pub stalls: usize,
52    /// Time spent compositing, uploading and presenting.
53    pub busy: Duration,
54    /// Of which uploading, and drawing plus presenting.
55    pub upload: Duration,
56    pub present: Duration,
57}
58
59/// Plays one saved scene, one frame at a time.
60pub struct Player {
61    pkg: Arc<ScenePackage>,
62    theme: Theme,
63    buddy: bool,
64    frame: IncrementalFrame,
65    /// Palette index to 0RGB.
66    colors: [u32; 256],
67    /// Scene time when playback started (the hero time, so the first frame
68    /// is the still), and when that was.
69    t0: u64,
70    started: Instant,
71    /// `Clock::Live` (particles on the cell grid) or `Clock::Smooth`.
72    clock: Clock,
73}
74
75impl Player {
76    /// `None` if the scene has no such theme.
77    pub fn new(pkg: Arc<ScenePackage>, theme: Theme, buddy: bool) -> Option<Player> {
78        let frame = pkg.incremental(theme)?;
79        let mut colors = [0u32; 256];
80        for (i, c) in pkg.palette(theme)?.colors().iter().enumerate() {
81            colors[i] = (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b);
82        }
83        let t0 = pkg.hero_ms(theme)?;
84        Some(Player {
85            pkg,
86            theme,
87            buddy,
88            frame,
89            colors,
90            t0,
91            started: Instant::now(),
92            clock: Clock::Live,
93        })
94    }
95
96    /// Particles at sub-cell positions (`Clock::Smooth`), for presenters on
97    /// a GPU: a higher frame rate then moves them smoothly. Off by default,
98    /// so the first frame is the still exactly; the CPU fallback keeps it
99    /// off (PLAN.md section 4.4).
100    pub fn set_smooth(&mut self, on: bool) {
101        self.clock = if on { Clock::Smooth } else { Clock::Live };
102    }
103
104    pub fn size(&self) -> (u32, u32) {
105        (self.pkg.width, self.pkg.height)
106    }
107
108    /// The current frame as palette indices.
109    pub fn image(&self) -> &IndexedImage {
110        self.frame.image()
111    }
112
113    /// The palette as 0RGB, by index.
114    pub fn colors(&self) -> &[u32; 256] {
115        &self.colors
116    }
117
118    /// Scene time now: the hero time plus the time since playback started.
119    /// A pause only stops drawing; the next frame shows the time it is.
120    pub fn now_ms(&self) -> u64 {
121        self.t0 + self.started.elapsed().as_millis() as u64
122    }
123
124    /// Moves to `t_ms`; returns the rectangles that changed.
125    pub fn advance(&mut self, t_ms: u64) -> Vec<PixelRect> {
126        self.pkg
127            .advance(&mut self.frame, self.theme, self.buddy, t_ms, self.clock)
128            .unwrap_or_default()
129    }
130
131    /// Writes those rectangles of the current frame into a 0RGB buffer of the
132    /// frame's size.
133    pub fn write(&self, buf: &mut [u32], rects: &[PixelRect]) {
134        let img = self.frame.image();
135        let w = img.width as usize;
136        debug_assert_eq!(buf.len(), img.pixels.len());
137        for r in rects {
138            for y in r.y..r.y + r.h {
139                let a = y as usize * w + r.x as usize;
140                let b = a + r.w as usize;
141                for (out, &i) in buf[a..b].iter_mut().zip(&img.pixels[a..b]) {
142                    *out = self.colors[usize::from(i)];
143                }
144            }
145        }
146    }
147
148    /// One rectangle of the current frame as 0RGB pixels, row by row.
149    pub fn rect_pixels(&self, r: &PixelRect, out: &mut Vec<u32>) {
150        let img = self.frame.image();
151        let w = img.width as usize;
152        out.clear();
153        for y in r.y..r.y + r.h {
154            let a = y as usize * w + r.x as usize;
155            out.extend(
156                img.pixels[a..a + r.w as usize]
157                    .iter()
158                    .map(|&i| self.colors[usize::from(i)]),
159            );
160        }
161    }
162
163    /// Writes the whole current frame.
164    pub fn write_all(&self, buf: &mut [u32]) {
165        for (out, &i) in buf.iter_mut().zip(&self.frame.image().pixels) {
166            *out = self.colors[usize::from(i)];
167        }
168    }
169}
170
171/// Live frame rates, by their names in Settings (PLAN.md section 5.3).
172pub const SMOOTHNESS_FPS: [(u32, &str); 5] = [
173    (6, "Battery saver"),
174    (12, "Balanced"),
175    (24, "Smooth"),
176    (30, "Very smooth"),
177    (60, "Ultra smooth"),
178];
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use clairlune_render::to_rgba;
184    use clairlune_scene::{Aspect, ContentContext, compose};
185
186    fn player() -> Player {
187        let r = compose(42, Aspect::from_size(320, 180), &ContentContext::default());
188        let pkg = Arc::new(ScenePackage::capture(&r, 320, 180).unwrap());
189        let theme = pkg.themes()[0];
190        Player::new(pkg, theme, true).unwrap()
191    }
192
193    fn rgb(buf: &[u32]) -> Vec<u8> {
194        buf.iter()
195            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255])
196            .collect()
197    }
198
199    #[test]
200    fn the_first_frame_is_the_still_and_updates_keep_the_buffer_exact() {
201        let mut p = player();
202        let (w, h) = p.size();
203        let mut buf = vec![0u32; (w * h) as usize];
204        let t0 = p.t0;
205        let rects = p.advance(t0);
206        p.write_all(&mut buf);
207        let _ = rects;
208        let (still, palette) = p.pkg.still(p.theme, true).unwrap();
209        assert_eq!(rgb(&buf), to_rgba(&still, palette));
210        // Then only the changed rects, as a presenter does.
211        for k in 1..40u64 {
212            let t = t0 + k * 83;
213            let rects = p.advance(t);
214            p.write(&mut buf, &rects);
215            let (full, palette) = p.pkg.frame(p.theme, true, t, Clock::Live).unwrap();
216            assert_eq!(rgb(&buf), to_rgba(&full, palette), "t {t}");
217        }
218    }
219}