clairlune-render 0.36.0

Glyph atlas, palette-index compositor and PNG export for Clairlune ASCII-art wallpapers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Seamless GIF export.
//!
//! - One global palette: the scene palette (at most 255 colours, by
//!   construction) plus index 255 as the transparent colour. No per-frame
//!   quantisation, no dithering.
//! - Frame 0 is the full image. Every later frame is exactly one sub-image: the
//!   bounding box of pixels that changed, with unchanged pixels inside it set to
//!   the transparent index (helps LZW), `DisposalMethod::Keep`. A frame identical
//!   to the previous one is merged into the previous frame's delay.
//! - Delays are whole centiseconds, dithered so they sum exactly to the loop.
//! - The loop length is a multiple of the particle period, and the character
//!   follows its loop script (`Clock::Loop`), so the last frame flows into the
//!   first with no seam.

use crate::clock::Clock;
use crate::frame::render_frame_clocked;
use crate::palette::TRANSPARENT_INDEX;
use crate::{GlyphAtlas, IndexedImage, IndexedPalette, bake_static};
use clairlune_scene::particles::LOOP_MS;
use clairlune_scene::{BuildError, BuildOptions, SceneRecipe, Theme, build};
use std::fmt;
use std::io::Write;
use std::time::Instant;

/// Smoothness, capped by what GIF delays can express.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Smoothness {
    BatterySaver,
    Balanced,
    Smooth,
    VerySmooth,
    UltraSmooth,
}

impl Smoothness {
    /// Target delay per frame in centiseconds: about 6, 12, 25, 33 and 50 fps.
    pub fn gif_delay_cs(self) -> u32 {
        match self {
            Smoothness::BatterySaver => 16,
            Smoothness::Balanced => 8,
            Smoothness::Smooth => 4,
            Smoothness::VerySmooth => 3,
            Smoothness::UltraSmooth => 2,
        }
    }
}

/// Valid loop lengths: whole multiples of the particle period.
pub fn valid_loop_ms(loop_ms: u64) -> bool {
    loop_ms > 0 && loop_ms.is_multiple_of(LOOP_MS)
}

/// The longest journey loop a GIF holds whole; past it, a journey's GIF is
/// an excerpt of the length asked for (its land jumps where it repeats).
pub const JOURNEY_GIF_MAX_MS: u64 = 36_000;

/// The GIF's length: the one asked for, or a short journey's own loop.
fn gif_loop(journey: Option<&clairlune_scene::Journey>, asked: u64) -> u64 {
    match journey {
        Some(j) if j.loop_ms <= JOURNEY_GIF_MAX_MS => j.loop_ms,
        _ => asked,
    }
}

/// Per-frame delays in centiseconds that sum exactly to the loop, as even as
/// possible around the target (e.g. a mix of 16 and 17 cs).
pub fn frame_delays(loop_ms: u64, target_cs: u32) -> Vec<u16> {
    let total = loop_ms / 10;
    let n = ((total as f64 / f64::from(target_cs.max(1))).round() as u64).max(1);
    (0..n)
        .map(|i| ((i + 1) * total / n - i * total / n) as u16)
        .collect()
}

#[derive(Debug)]
pub enum GifError {
    Build(BuildError),
    Encode(gif::EncodingError),
    LoopLength(u64),
    TooLarge { width: u32, height: u32 },
}

impl fmt::Display for GifError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GifError::Build(e) => write!(f, "{e}"),
            GifError::Encode(e) => write!(f, "GIF encoding failed: {e}"),
            GifError::LoopLength(ms) => write!(
                f,
                "loop length {ms} ms isn't a multiple of the {LOOP_MS} ms particle period, so it couldn't loop seamlessly"
            ),
            GifError::TooLarge { width, height } => {
                write!(
                    f,
                    "{width}x{height} is larger than GIF allows (65535 px per side)"
                )
            }
        }
    }
}

impl std::error::Error for GifError {}

impl From<gif::EncodingError> for GifError {
    fn from(e: gif::EncodingError) -> Self {
        GifError::Encode(e)
    }
}

/// What an export produced.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GifStats {
    pub width: u32,
    pub height: u32,
    pub loop_ms: u64,
    pub frames_rendered: usize,
    pub frames_written: usize,
    pub elapsed_ms: u64,
}

/// Bounding box `(x0, y0, x1, y1)` (exclusive end) of pixels that differ.
fn changed_box(a: &IndexedImage, b: &IndexedImage) -> Option<(u32, u32, u32, u32)> {
    let w = a.width as usize;
    let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
    for (y, (ra, rb)) in a
        .pixels
        .chunks_exact(w)
        .zip(b.pixels.chunks_exact(w))
        .enumerate()
    {
        if ra == rb {
            continue;
        }
        let first = ra.iter().zip(rb).position(|(p, q)| p != q).unwrap();
        let last = w
            - 1
            - ra.iter()
                .rev()
                .zip(rb.iter().rev())
                .position(|(p, q)| p != q)
                .unwrap();
        x0 = x0.min(first);
        x1 = x1.max(last + 1);
        y0 = y0.min(y);
        y1 = y + 1;
    }
    (x0 != usize::MAX).then_some((x0 as u32, y0 as u32, x1 as u32, y1 as u32))
}

/// Renders a seamless looping GIF of a recipe.
pub fn encode_gif<W: Write>(
    recipe: &SceneRecipe,
    opts: &BuildOptions,
    loop_ms: u64,
    smoothness: Smoothness,
    out: W,
) -> Result<GifStats, GifError> {
    if !valid_loop_ms(loop_ms) {
        return Err(GifError::LoopLength(loop_ms));
    }
    if opts.width > u32::from(u16::MAX) || opts.height > u32::from(u16::MAX) {
        return Err(GifError::TooLarge {
            width: opts.width,
            height: opts.height,
        });
    }
    let started = Instant::now();
    let graph = build(recipe, opts).map_err(GifError::Build)?;
    let loop_ms = gif_loop(graph.journey.as_ref(), loop_ms);
    let atlas = GlyphAtlas::for_graph(&graph);
    let palette = IndexedPalette::for_graph(&graph);
    let background = bake_static(&graph, &atlas);
    let journey = crate::JourneyBake::new(&graph, &atlas);
    let clock = Clock::Loop(loop_ms);
    let (rendered, written) = encode_frames(
        opts.width,
        opts.height,
        &palette,
        loop_ms,
        smoothness,
        out,
        |t| match &journey {
            Some(j) => {
                let bg = j.background_at(&graph, &background, t);
                render_frame_clocked(&bg, &graph, &atlas, &palette, t, clock)
            }
            None => render_frame_clocked(&background, &graph, &atlas, &palette, t, clock),
        },
    )?;
    let stats = GifStats {
        width: opts.width,
        height: opts.height,
        loop_ms,
        frames_rendered: rendered,
        frames_written: written,
        elapsed_ms: started.elapsed().as_millis() as u64,
    };
    tracing::info!(
        target: "clairlune_render",
        seed = recipe.seed,
        recipe_hash = %recipe.hash_hex(),
        width = opts.width,
        height = opts.height,
        loop_ms,
        frames_rendered = stats.frames_rendered,
        frames_written = stats.frames_written,
        elapsed_ms = stats.elapsed_ms,
        "gif encoded"
    );
    Ok(stats)
}

/// Writes a looping GIF from a frame source: one global palette, changed
/// boxes only, identical frames merged. Returns frames rendered and written.
fn encode_frames<W: Write>(
    width: u32,
    height: u32,
    palette: &IndexedPalette,
    loop_ms: u64,
    smoothness: Smoothness,
    out: W,
    mut frame_at: impl FnMut(u64) -> IndexedImage,
) -> Result<(usize, usize), GifError> {
    let mut global = palette.rgb_bytes();
    global.resize(256 * 3, 0); // index 255 stays free as the transparent colour
    let (w16, h16) = (width as u16, height as u16);
    let mut enc = gif::Encoder::new(out, w16, h16, &global)?;
    enc.set_repeat(gif::Repeat::Infinite)?;
    let delays = frame_delays(loop_ms, smoothness.gif_delay_cs());
    let mut prev: Option<IndexedImage> = None;
    let mut pending: Option<gif::Frame<'static>> = None;
    let mut written = 0usize;
    let mut t_cs = 0u64;
    for &d in &delays {
        let img = frame_at(t_cs * 10);
        t_cs += u64::from(d);
        let frame = match &prev {
            None => gif::Frame {
                width: w16,
                height: h16,
                delay: d,
                dispose: gif::DisposalMethod::Keep,
                buffer: img.pixels.clone().into(),
                ..gif::Frame::default()
            },
            Some(p) => match changed_box(p, &img) {
                None => {
                    // Identical frame: extend the previous frame instead.
                    if let Some(f) = pending.as_mut() {
                        f.delay = f.delay.saturating_add(d);
                    }
                    continue;
                }
                Some((x0, y0, x1, y1)) => {
                    let (bw, bh) = (x1 - x0, y1 - y0);
                    let mut buf = Vec::with_capacity((bw * bh) as usize);
                    for y in y0..y1 {
                        let row = (y * img.width) as usize;
                        for x in x0..x1 {
                            let i = row + x as usize;
                            buf.push(if img.pixels[i] == p.pixels[i] {
                                TRANSPARENT_INDEX
                            } else {
                                img.pixels[i]
                            });
                        }
                    }
                    gif::Frame {
                        left: x0 as u16,
                        top: y0 as u16,
                        width: bw as u16,
                        height: bh as u16,
                        delay: d,
                        dispose: gif::DisposalMethod::Keep,
                        transparent: Some(TRANSPARENT_INDEX),
                        buffer: buf.into(),
                        ..gif::Frame::default()
                    }
                }
            },
        };
        if let Some(f) = pending.take() {
            enc.write_frame(&f)?;
            written += 1;
        }
        pending = Some(frame);
        prev = Some(img);
    }
    if let Some(f) = pending.take() {
        enc.write_frame(&f)?;
        written += 1;
    }
    drop(enc);
    Ok((delays.len(), written))
}

/// Exports a saved scene as a looping GIF, exactly as saved (no generator).
pub fn encode_package_gif<W: Write>(
    pkg: &crate::ScenePackage,
    theme: Theme,
    buddy: bool,
    loop_ms: u64,
    smoothness: Smoothness,
    signature: Option<&str>,
    out: W,
) -> Result<GifStats, GifError> {
    if !valid_loop_ms(loop_ms) {
        return Err(GifError::LoopLength(loop_ms));
    }
    if pkg.width > u32::from(u16::MAX) || pkg.height > u32::from(u16::MAX) {
        return Err(GifError::TooLarge {
            width: pkg.width,
            height: pkg.height,
        });
    }
    let palette = pkg
        .palette(theme)
        .ok_or(GifError::Build(BuildError::ThemeLocked(theme)))?
        .clone();
    let graph = pkg.graph(theme);
    let loop_ms = gif_loop(graph.and_then(|g| g.journey.as_ref()), loop_ms);
    let started = Instant::now();
    let clock = Clock::Loop(loop_ms);
    // Each frame signed the same way, so unchanged frames still merge.
    let signature = signature.and_then(|s| crate::Signature::new(pkg.width, pkg.height, s));
    let is_static = graph.is_some_and(|g| {
        g.emitters.is_empty() && g.journey.is_none() && (!buddy || g.character.is_none())
    });
    if is_static {
        let mut img = pkg
            .still(theme, buddy)
            .map(|(img, _)| img)
            .ok_or(GifError::Build(BuildError::ThemeLocked(theme)))?;
        if let Some(s) = &signature {
            s.apply(&mut img);
        }
        let mut global = palette.rgb_bytes();
        global.resize(256 * 3, 0);
        let (w16, h16) = (pkg.width as u16, pkg.height as u16);
        let mut enc = gif::Encoder::new(out, w16, h16, &global)?;
        enc.set_repeat(gif::Repeat::Infinite)?;
        let f = gif::Frame {
            width: w16,
            height: h16,
            delay: ((loop_ms / 10).min(u64::from(u16::MAX))) as u16,
            dispose: gif::DisposalMethod::Keep,
            buffer: img.pixels.into(),
            ..gif::Frame::default()
        };
        enc.write_frame(&f)?;
        drop(enc);
        return Ok(GifStats {
            width: pkg.width,
            height: pkg.height,
            loop_ms,
            frames_rendered: 1,
            frames_written: 1,
            elapsed_ms: started.elapsed().as_millis() as u64,
        });
    }
    let (rendered, written) = encode_frames(
        pkg.width,
        pkg.height,
        &palette,
        loop_ms,
        smoothness,
        out,
        |t| {
            let mut img = pkg
                .frame(theme, buddy, t, clock)
                .map(|(img, _)| img)
                .expect("theme checked above");
            if let Some(s) = &signature {
                s.apply(&mut img);
            }
            img
        },
    )?;
    Ok(GifStats {
        width: pkg.width,
        height: pkg.height,
        loop_ms,
        frames_rendered: rendered,
        frames_written: written,
        elapsed_ms: started.elapsed().as_millis() as u64,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn delays_sum_exactly_to_the_loop() {
        for loop_ms in [6000u64, 12000] {
            for s in [
                Smoothness::BatterySaver,
                Smoothness::Balanced,
                Smoothness::Smooth,
                Smoothness::VerySmooth,
                Smoothness::UltraSmooth,
            ] {
                let d = frame_delays(loop_ms, s.gif_delay_cs());
                assert_eq!(d.iter().map(|&x| u64::from(x)).sum::<u64>(), loop_ms / 10);
                let (min, max) = (*d.iter().min().unwrap(), *d.iter().max().unwrap());
                assert!(max - min <= 1, "{s:?}: delays {min}..{max}");
                assert!(u32::from(min) >= 2, "browsers clamp delays under 2 cs");
            }
        }
        // 6 s at Battery saver: 37.5 frames of 16 cs, so a 16/17 mix.
        let d = frame_delays(6000, 16);
        assert!(d.contains(&16) && d.contains(&15) || d.contains(&16) && d.contains(&17));
    }

    #[test]
    fn rejects_loops_that_cannot_be_seamless() {
        assert!(valid_loop_ms(6000) && valid_loop_ms(12000));
        assert!(!valid_loop_ms(3000) && !valid_loop_ms(10000) && !valid_loop_ms(0));
    }
}