Skip to main content

clairlune_live/
lib.rs

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