geodesic-wallpaper 1.6.1

Animated Windows desktop wallpaper that draws glowing geodesics flowing over curved 3D surfaces (torus, Klein bottle, pseudosphere and more), rendered with wgpu. Also renders PNGs and GIFs headless.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Animation export: renders a sequence of PNG frames by interpolating parameters over time.
//!
//! This module provides [`AnimationExporter`] which drives parameter interpolation
//! across `N` frames and writes numbered PNG files to an output directory.
//!
//! # Supported animated parameters
//!
//! | `AnimationParameter` | Description |
//! |---------------------|-------------|
//! | `RotationAngle` | Camera orbit angle (radians) |
//! | `Scale` | Overall scene scale |
//! | `ColorHue` | Hue rotation of the color palette (degrees 0..360) |
//! | `WindingNumber` | Symmetry winding parameter (integer-like, interpolated) |
//!
//! # Interpolation modes
//!
//! - `Linear` — evenly spaced between `start` and `end`
//! - `Sinusoidal` — smooth oscillation: `start + (end - start) * 0.5 * (1 - cos(π·t))`
//!
//! # CLI
//!
//! ```text
//! geodesic-wallpaper --animate --frames 60 --fps 30 --out-dir ./frames
//! ```
//!
//! # Example
//!
//! ```no_run
//! use geodesic_wallpaper::animation::{
//!     AnimationConfig, AnimationExporter, AnimationParameter, FrameInterpolator,
//!     InterpolationMode,
//! };
//! use std::path::PathBuf;
//!
//! let config = AnimationConfig {
//!     frames: 60,
//!     fps: 30,
//!     width: 1920,
//!     height: 1080,
//!     output_dir: PathBuf::from("./frames"),
//! };
//! let interp = FrameInterpolator::new(
//!     AnimationParameter::RotationAngle,
//!     0.0,
//!     std::f64::consts::TAU,
//!     InterpolationMode::Linear,
//! );
//! let exporter = AnimationExporter::new(config, vec![interp]);
//! // exporter.export(|values, path| { /* render frame */ Ok(()) }).unwrap();
//! ```

use std::io;
use std::path::{Path, PathBuf};
use std::time::Instant;

// ── AnimationParameter ────────────────────────────────────────────────────────

/// The parameter to animate over the frame sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AnimationParameter {
    /// Camera orbit angle in radians.
    RotationAngle,
    /// Uniform scene scale factor.
    Scale,
    /// Hue rotation applied to the color palette (degrees, 0..360).
    ColorHue,
    /// Symmetry winding number (integer-like, real-valued during interpolation).
    WindingNumber,
}

// ── Interpolation ─────────────────────────────────────────────────────────────

/// How to interpolate between start and end values over the animation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterpolationMode {
    /// Even linear spacing: `value = start + (end - start) * t`.
    Linear,
    /// Smooth cosine easing: `value = start + (end - start) * 0.5 * (1 − cos(π·t))`.
    Sinusoidal,
}

/// Interpolates a single animation parameter across the frame range.
#[derive(Debug, Clone)]
pub struct FrameInterpolator {
    /// The parameter this interpolator controls.
    pub parameter: AnimationParameter,
    /// Value at frame 0.
    pub start: f64,
    /// Value at the last frame.
    pub end: f64,
    /// Interpolation curve.
    pub mode: InterpolationMode,
}

impl FrameInterpolator {
    /// Create a new frame interpolator.
    pub fn new(
        parameter: AnimationParameter,
        start: f64,
        end: f64,
        mode: InterpolationMode,
    ) -> Self {
        Self {
            parameter,
            start,
            end,
            mode,
        }
    }

    /// Evaluate the parameter at a normalised time `t ∈ [0, 1]`.
    pub fn evaluate(&self, t: f64) -> f64 {
        let t = t.clamp(0.0, 1.0);
        let eased = match self.mode {
            InterpolationMode::Linear => t,
            InterpolationMode::Sinusoidal => 0.5 * (1.0 - (std::f64::consts::PI * t).cos()),
        };
        self.start + (self.end - self.start) * eased
    }
}

// ── Configuration ─────────────────────────────────────────────────────────────

/// Configuration for an animation export.
#[derive(Debug, Clone)]
pub struct AnimationConfig {
    /// Number of frames to render.
    pub frames: usize,
    /// Playback frame rate (used for duration calculation only; does not affect PNG output rate).
    pub fps: u32,
    /// Frame width in pixels.
    pub width: u32,
    /// Frame height in pixels.
    pub height: u32,
    /// Directory to write PNG frames into.
    pub output_dir: PathBuf,
}

impl Default for AnimationConfig {
    fn default() -> Self {
        Self {
            frames: 60,
            fps: 30,
            width: 1920,
            height: 1080,
            output_dir: PathBuf::from("./frames"),
        }
    }
}

impl AnimationConfig {
    /// Animation duration in seconds.
    pub fn duration_secs(&self) -> f64 {
        self.frames as f64 / self.fps.max(1) as f64
    }
}

// ── Stats ─────────────────────────────────────────────────────────────────────

/// Statistics from a completed animation export.
#[derive(Debug, Clone, Default)]
pub struct AnimationStats {
    /// Number of frames written to disk.
    pub frames_written: usize,
    /// Total wall-clock duration of the export in milliseconds.
    pub duration_ms: u64,
    /// Average time per frame in milliseconds.
    pub avg_frame_ms: f64,
}

// ── Error ─────────────────────────────────────────────────────────────────────

/// Errors that can occur during animation export.
#[derive(Debug)]
pub enum ExportError {
    /// An I/O operation failed.
    Io(io::Error),
    /// The caller's render callback returned an error.
    Render(String),
    /// Invalid configuration (e.g. zero frames).
    InvalidConfig(String),
}

impl std::fmt::Display for ExportError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExportError::Io(e) => write!(f, "IO error: {e}"),
            ExportError::Render(s) => write!(f, "render error: {s}"),
            ExportError::InvalidConfig(s) => write!(f, "invalid config: {s}"),
        }
    }
}

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

impl From<io::Error> for ExportError {
    fn from(e: io::Error) -> Self {
        ExportError::Io(e)
    }
}

// ── AnimationExporter ─────────────────────────────────────────────────────────

/// Renders a sequence of frames by interpolating parameters and invoking a callback.
///
/// The caller supplies a render function `render_frame(frame_index, param_values, output_path) -> Result<(), String>`.
/// `param_values` maps each [`AnimationParameter`] to its current value.
pub struct AnimationExporter {
    config: AnimationConfig,
    interpolators: Vec<FrameInterpolator>,
}

impl AnimationExporter {
    /// Create a new exporter with the given configuration and interpolators.
    pub fn new(config: AnimationConfig, interpolators: Vec<FrameInterpolator>) -> Self {
        Self {
            config,
            interpolators,
        }
    }

    /// Return the path for a given frame index: `{output_dir}/frame_{NNNN}.png`.
    pub fn frame_path(&self, frame_index: usize) -> PathBuf {
        self.config
            .output_dir
            .join(format!("frame_{:04}.png", frame_index))
    }

    /// Evaluate all interpolators at the given frame index.
    ///
    /// Returns a `Vec` of `(AnimationParameter, value)` pairs.
    pub fn param_values_at(&self, frame_index: usize) -> Vec<(AnimationParameter, f64)> {
        let t = if self.config.frames <= 1 {
            0.0
        } else {
            frame_index as f64 / (self.config.frames - 1) as f64
        };
        self.interpolators
            .iter()
            .map(|interp| (interp.parameter, interp.evaluate(t)))
            .collect()
    }

    /// Export the animation by calling `render_frame` for each frame.
    ///
    /// `render_frame(frame_index, param_values, output_path)` should write a PNG
    /// to `output_path` and return `Ok(())` on success.
    ///
    /// Frames are named `frame_0000.png` through `frame_NNNN.png`.
    pub fn export<F>(&self, mut render_frame: F) -> Result<AnimationStats, ExportError>
    where
        F: FnMut(usize, &[(AnimationParameter, f64)], &Path) -> Result<(), String>,
    {
        if self.config.frames == 0 {
            return Err(ExportError::InvalidConfig("frames must be > 0".to_string()));
        }

        // Ensure output directory exists
        std::fs::create_dir_all(&self.config.output_dir)?;

        let start = Instant::now();
        let mut frames_written = 0usize;

        for frame_idx in 0..self.config.frames {
            let params = self.param_values_at(frame_idx);
            let output_path = self.frame_path(frame_idx);

            render_frame(frame_idx, &params, &output_path).map_err(ExportError::Render)?;

            frames_written += 1;
        }

        let duration_ms = start.elapsed().as_millis() as u64;
        let avg_frame_ms = if frames_written > 0 {
            duration_ms as f64 / frames_written as f64
        } else {
            0.0
        };

        Ok(AnimationStats {
            frames_written,
            duration_ms,
            avg_frame_ms,
        })
    }

    /// Write a `width` x `height` gradient test frame as a PNG (useful for
    /// testing the exporter without a GPU).
    pub fn write_test_frame(path: &Path, width: u32, height: u32) -> Result<(), ExportError> {
        let mut pixels = vec![255u8; (width * height * 4) as usize];
        // Fill a simple gradient for visual interest
        for y in 0..height {
            for x in 0..width {
                let idx = ((y * width + x) * 4) as usize;
                pixels[idx] = (x * 255 / width.max(1)) as u8; // R
                pixels[idx + 1] = (y * 255 / height.max(1)) as u8; // G
                pixels[idx + 2] = 128; // B
                pixels[idx + 3] = 255; // A
            }
        }

        crate::export::save_rgba_png(path, width, height, &pixels)
            .map(|_| ())
            .map_err(|e| match e {
                crate::export::ExportError::Io(io) => ExportError::Io(io),
                other => ExportError::Render(other.to_string()),
            })
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_linear_interpolation_endpoints() {
        let interp = FrameInterpolator::new(
            AnimationParameter::RotationAngle,
            0.0,
            1.0,
            InterpolationMode::Linear,
        );
        assert!((interp.evaluate(0.0) - 0.0).abs() < 1e-12);
        assert!((interp.evaluate(1.0) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_linear_interpolation_midpoint() {
        let interp = FrameInterpolator::new(
            AnimationParameter::Scale,
            0.0,
            2.0,
            InterpolationMode::Linear,
        );
        assert!((interp.evaluate(0.5) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_sinusoidal_interpolation_endpoints() {
        let interp = FrameInterpolator::new(
            AnimationParameter::ColorHue,
            0.0,
            360.0,
            InterpolationMode::Sinusoidal,
        );
        assert!((interp.evaluate(0.0) - 0.0).abs() < 1e-9);
        assert!((interp.evaluate(1.0) - 360.0).abs() < 1e-9);
    }

    #[test]
    fn test_sinusoidal_interpolation_midpoint() {
        // At t=0.5: eased = 0.5*(1-cos(π*0.5)) = 0.5*(1-0) = 0.5
        let interp = FrameInterpolator::new(
            AnimationParameter::Scale,
            0.0,
            1.0,
            InterpolationMode::Sinusoidal,
        );
        assert!((interp.evaluate(0.5) - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_interpolation_clamps_t() {
        let interp = FrameInterpolator::new(
            AnimationParameter::Scale,
            1.0,
            2.0,
            InterpolationMode::Linear,
        );
        assert!((interp.evaluate(-1.0) - 1.0).abs() < 1e-12);
        assert!((interp.evaluate(2.0) - 2.0).abs() < 1e-12);
    }

    #[test]
    fn test_animation_config_duration() {
        let cfg = AnimationConfig {
            frames: 60,
            fps: 30,
            ..AnimationConfig::default()
        };
        assert!((cfg.duration_secs() - 2.0).abs() < 1e-12);
    }

    #[test]
    fn test_animation_config_duration_zero_fps() {
        let cfg = AnimationConfig {
            frames: 30,
            fps: 0,
            ..AnimationConfig::default()
        };
        // fps clamped to 1 → duration = 30s
        assert!((cfg.duration_secs() - 30.0).abs() < 1e-12);
    }

    #[test]
    fn test_frame_path_format() {
        let exporter = AnimationExporter::new(
            AnimationConfig {
                output_dir: PathBuf::from("/tmp/test"),
                ..AnimationConfig::default()
            },
            vec![],
        );
        let p = exporter.frame_path(42);
        assert!(p.to_string_lossy().contains("frame_0042.png"));
    }

    #[test]
    fn test_param_values_at_first_frame() {
        let interp = FrameInterpolator::new(
            AnimationParameter::RotationAngle,
            1.0,
            5.0,
            InterpolationMode::Linear,
        );
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 10,
                ..AnimationConfig::default()
            },
            vec![interp],
        );
        let vals = exporter.param_values_at(0);
        assert_eq!(vals.len(), 1);
        assert!((vals[0].1 - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_param_values_at_last_frame() {
        let interp = FrameInterpolator::new(
            AnimationParameter::RotationAngle,
            1.0,
            5.0,
            InterpolationMode::Linear,
        );
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 10,
                ..AnimationConfig::default()
            },
            vec![interp],
        );
        let vals = exporter.param_values_at(9);
        assert!((vals[0].1 - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_export_zero_frames_error() {
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 0,
                ..AnimationConfig::default()
            },
            vec![],
        );
        let result = exporter.export(|_, _, _| Ok(()));
        assert!(matches!(result, Err(ExportError::InvalidConfig(_))));
    }

    #[test]
    fn test_export_writes_correct_frame_count() {
        let dir = tempfile::tempdir().unwrap();
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 5,
                fps: 10,
                width: 4,
                height: 4,
                output_dir: dir.path().to_path_buf(),
            },
            vec![],
        );
        let stats = exporter.export(|_, _, _| Ok(())).unwrap();
        assert_eq!(stats.frames_written, 5);
    }

    #[test]
    fn test_export_propagates_render_error() {
        let dir = tempfile::tempdir().unwrap();
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 3,
                ..AnimationConfig::default().with_dir(dir.path())
            },
            vec![],
        );
        let result = exporter.export(|i, _, _| {
            if i == 1 {
                Err("render failed at frame 1".to_string())
            } else {
                Ok(())
            }
        });
        assert!(matches!(result, Err(ExportError::Render(_))));
    }

    #[test]
    fn test_write_test_frame_produces_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_frame.png");
        AnimationExporter::write_test_frame(&path, 4, 4).unwrap();
        assert!(path.exists());
        let meta = std::fs::metadata(&path).unwrap();
        assert!(meta.len() > 8, "PNG file should have content");
    }

    #[test]
    fn test_write_test_frame_valid_png_signature() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sig_test.png");
        AnimationExporter::write_test_frame(&path, 2, 2).unwrap();
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(
            &bytes[..8],
            &[137, 80, 78, 71, 13, 10, 26, 10],
            "PNG signature mismatch"
        );
    }

    #[test]
    fn test_animation_stats_default() {
        let stats = AnimationStats::default();
        assert_eq!(stats.frames_written, 0);
        assert_eq!(stats.duration_ms, 0);
        assert_eq!(stats.avg_frame_ms, 0.0);
    }

    #[test]
    fn test_multiple_interpolators() {
        let interps = vec![
            FrameInterpolator::new(
                AnimationParameter::RotationAngle,
                0.0,
                6.28,
                InterpolationMode::Linear,
            ),
            FrameInterpolator::new(
                AnimationParameter::ColorHue,
                0.0,
                360.0,
                InterpolationMode::Sinusoidal,
            ),
        ];
        let exporter = AnimationExporter::new(
            AnimationConfig {
                frames: 4,
                ..AnimationConfig::default()
            },
            interps,
        );
        let vals = exporter.param_values_at(2);
        assert_eq!(vals.len(), 2);
        assert_eq!(vals[0].0, AnimationParameter::RotationAngle);
        assert_eq!(vals[1].0, AnimationParameter::ColorHue);
    }
}

// ── Helper extension trait for testing ───────────────────────────────────────

impl AnimationConfig {
    fn with_dir(mut self, dir: &Path) -> Self {
        self.output_dir = dir.to_path_buf();
        self
    }
}