Skip to main content

dragon/
dragon.rs

1//! The dragon demo.
2//!
3//!   cargo run --example dragon                       # live reveal in your terminal
4//!   cargo run --example dragon -- --snapshots        # staged text frames (no TTY needed)
5//!   cargo run --example dragon -- --art path/to.txt  # bring your own ASCII art
6//!
7//! By default it reveals a procedurally generated serpent, a single, perfectly
8//! 8-connected stroke, so the geodesic spine-trace paints it tip-to-tip. Point
9//! `--art` at any file to watch arbitrary art reveal (imperfect art leans on the
10//! island fallback and still looks intentional).
11
12use std::io::IsTerminal;
13
14use inkling::{
15    art::Art,
16    frame,
17    ordering::{Geodesic, GeodesicReport, Ordering},
18};
19
20fn main() {
21    let args: Vec<String> = std::env::args().skip(1).collect();
22    let snapshots = args.iter().any(|a| a == "--snapshots");
23
24    let art = match arg_value(&args, "--art") {
25        Some(path) => match std::fs::read_to_string(&path) {
26            Ok(text) => Art::parse(&text),
27            Err(e) => {
28                eprintln!("inkling: could not read {path}: {e}");
29                std::process::exit(1);
30            }
31        },
32        None => Art::parse(&serpent(64, 13)),
33    };
34
35    let ordering = Geodesic::default();
36    let GeodesicReport {
37        ink_cells,
38        connected_cells,
39        spine_length,
40    } = ordering.diagnose(&art);
41    let ranks = ordering.rank(&art);
42
43    eprintln!(
44        "inkling · {ink_cells} ink cells · {connected_cells} on the spine \
45         ({:.0}% connected) · spine length {spine_length}",
46        100.0 * connected_cells as f32 / ink_cells.max(1) as f32,
47    );
48
49    // Headless / piped / explicit: print staged text frames and exit.
50    if snapshots || !std::io::stdout().is_terminal() {
51        for p in [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] {
52            println!("\n── progress {:>3.0}% {}", p * 100.0, "─".repeat(28));
53            print!("{}", frame::to_string(&art, &ranks, p));
54        }
55        return;
56    }
57
58    #[cfg(feature = "terminal")]
59    {
60        use inkling::{
61            easing::Easing,
62            render::{animate, Style},
63        };
64        use std::time::Duration;
65        if let Err(e) = animate(
66            &art,
67            &ranks,
68            Style::default(),
69            Duration::from_millis(3500),
70            Easing::EaseInOutCubic,
71        ) {
72            eprintln!("inkling: render error: {e}");
73        }
74    }
75}
76
77/// Read the value following `key` in `args` (supports `--key value` and `--key=value`).
78fn arg_value(args: &[String], key: &str) -> Option<String> {
79    let mut it = args.iter();
80    while let Some(a) = it.next() {
81        if a == key {
82            return it.next().cloned();
83        }
84        if let Some(v) = a.strip_prefix(&format!("{key}=")) {
85            return Some(v.to_string());
86        }
87    }
88    None
89}
90
91/// Generate an Eastern-style serpent as a single 8-connected stroke: a sine-wave
92/// body with crest spikes and a small head. Connectivity is guaranteed by
93/// filling any vertical gap between adjacent columns, so the spine-trace reveals
94/// it flawlessly from tail to head.
95// Columns are scanned by index because each row `y` is *computed* from `x`
96// (y = sine(x)); writing `grid[y][x]` is the clearest expression of that.
97#[allow(clippy::needless_range_loop)]
98fn serpent(width: usize, height: usize) -> String {
99    use std::f32::consts::TAU;
100
101    let amp = ((height as f32) - 3.0).max(1.0) / 2.0;
102    let mid = (height as f32 - 1.0) / 2.0;
103    let period = (width as f32) / 2.0; // two coils across the width
104
105    let y_at = |x: usize| -> usize {
106        let yf = mid - amp * ((x as f32) / period * TAU).sin();
107        yf.round().clamp(0.0, height as f32 - 1.0) as usize
108    };
109
110    let mut grid = vec![vec![' '; width]; height];
111    let mut prev_y = y_at(0);
112    for x in 0..width {
113        let y = y_at(x);
114        // Bridge any vertical gap so the body is one continuous stroke.
115        if x > 0 && y.abs_diff(prev_y) > 1 {
116            for row in grid[y.min(prev_y)..=y.max(prev_y)].iter_mut() {
117                if row[x] == ' ' {
118                    row[x] = '|';
119                }
120            }
121        }
122        grid[y][x] = match prev_y {
123            _ if x == 0 => '~',
124            py if y < py => '/',
125            py if y > py => '\\',
126            _ => '~',
127        };
128        prev_y = y;
129    }
130
131    // Spikes on the crests (local highs), one row above the body.
132    for x in 1..width.saturating_sub(1) {
133        let y = y_at(x);
134        if y > 0 && y < y_at(x - 1) && y <= y_at(x + 1) {
135            grid[y - 1][x] = '^';
136        }
137    }
138
139    // A small head at the leading (right) tip.
140    let (hx, hy) = (width - 1, y_at(width - 1));
141    grid[hy][hx] = '>';
142    if hy > 0 {
143        grid[hy - 1][hx.saturating_sub(1)] = 'o'; // eye
144    }
145
146    grid.into_iter()
147        .map(|row| row.into_iter().collect::<String>())
148        .collect::<Vec<_>>()
149        .join("\n")
150}