Skip to main content

clairlune_render/
img2ascii.rs

1//! Image-to-ASCII conversion and custom ASCII wallpaper packaging.
2//!
3//! Converts an arbitrary RGBA image into:
4//! - plain multi-line ASCII/Unicode text (`.txt` / clipboard),
5//! - an anti-aliased RGBA image (including transparent background when asked),
6//! - a genuine [`ScenePackage`] (with both light and dark themes when using a
7//!   Clairlune palette or photo colours, plus optional live weather particles),
8//!   playable natively in Still, Live, Library, Archive, Timeline and GIF export.
9
10use crate::IndexedImage;
11use crate::atlas::GlyphAtlas;
12use crate::package::{CustomTheme, ScenePackage};
13use crate::palette::{IndexedPalette, SPRITE_BASE, TRANSPARENT_INDEX, ink_level};
14use crate::sign::SIGNATURE;
15use clairlune_scene::graph::{ADVANCE_RATIO, FONT_TO_CELL, GridSpec, Lighting, SceneGraph};
16use clairlune_scene::particles::{
17    CALM_PACE, Emitter, EmitterKind, LOOP_MS, WeatherKind, ember_set, hero_time, weather_set,
18};
19use clairlune_scene::recipe::{Composition, PalettePick};
20use clairlune_scene::{
21    Aspect, GENERATOR_VERSION, PaletteFamily, Rgb, SceneRecipe, Theme, TimeOfDay,
22};
23use serde::{Deserialize, Serialize};
24use std::collections::HashMap;
25
26/// Archetype marker stored on custom image-to-ASCII recipes.
27pub const PHOTO_ARCHETYPE: &str = "photo";
28
29/// Decoded RGBA8 source image, row-major (`width * height * 4` bytes).
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct RgbaImage {
32    pub width: u32,
33    pub height: u32,
34    pub pixels: Vec<u8>,
35}
36
37impl RgbaImage {
38    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, String> {
39        let want = (width as usize)
40            .checked_mul(height as usize)
41            .and_then(|n| n.checked_mul(4))
42            .ok_or_else(|| "image dimensions overflow".to_string())?;
43        if width == 0 || height == 0 || pixels.len() != want {
44            return Err(format!(
45                "invalid RGBA image buffer ({} bytes for {width}x{height})",
46                pixels.len()
47            ));
48        }
49        Ok(Self {
50            width,
51            height,
52            pixels,
53        })
54    }
55
56    /// Downscales the image if its longest side exceeds `max_side`, keeping
57    /// saved archive/library copies compact while preserving full ASCII detail.
58    pub fn capped(&self, max_side: u32) -> Self {
59        let longest = self.width.max(self.height);
60        if longest <= max_side || max_side == 0 {
61            return self.clone();
62        }
63        let nw = ((u64::from(self.width) * u64::from(max_side)) / u64::from(longest)).max(1) as u32;
64        let nh =
65            ((u64::from(self.height) * u64::from(max_side)) / u64::from(longest)).max(1) as u32;
66        let mut out = vec![0u8; (nw * nh * 4) as usize];
67        for y in 0..nh {
68            let y0 = f64::from(y) * f64::from(self.height) / f64::from(nh);
69            let y1 = f64::from(y + 1) * f64::from(self.height) / f64::from(nh);
70            for x in 0..nw {
71                let x0 = f64::from(x) * f64::from(self.width) / f64::from(nw);
72                let x1 = f64::from(x + 1) * f64::from(self.width) / f64::from(nw);
73                let s = sample_box(self, x0, y0, x1, y1);
74                let idx = ((y * nw + x) * 4) as usize;
75                out[idx..idx + 4].copy_from_slice(&[s.r, s.g, s.b, s.a]);
76            }
77        }
78        Self {
79            width: nw,
80            height: nh,
81            pixels: out,
82        }
83    }
84}
85
86/// Line-height / character aspect ratio for standalone `.txt` and PNG output.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum RowDensity {
90    /// Matches Clairlune's JetBrains Mono cell geometry (`0.54`).
91    #[default]
92    Auto,
93    /// Tighter terminal spacing (`0.45`).
94    Compact,
95    /// Classic 1:2 terminal cell (`0.50`).
96    Standard,
97    /// Looser editor/prose line spacing (`0.62`).
98    Tall,
99}
100
101impl RowDensity {
102    /// Width-to-height ratio of one character cell.
103    pub fn cell_aspect(self) -> f64 {
104        match self {
105            RowDensity::Auto => ADVANCE_RATIO * FONT_TO_CELL,
106            RowDensity::Compact => 0.45,
107            RowDensity::Standard => 0.50,
108            RowDensity::Tall => 0.62,
109        }
110    }
111}
112
113/// Character ramp ordered from heaviest ink to lightest (`' '` last in the UI).
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "snake_case")]
116pub enum RampPreset {
117    #[default]
118    Standard,
119    Detailed,
120    Dither,
121    Braille,
122    Blocks,
123    Lines,
124    Kana,
125    Shapes,
126    Hex,
127    Custom,
128}
129
130impl RampPreset {
131    pub const ALL: [RampPreset; 10] = [
132        RampPreset::Standard,
133        RampPreset::Detailed,
134        RampPreset::Dither,
135        RampPreset::Braille,
136        RampPreset::Blocks,
137        RampPreset::Lines,
138        RampPreset::Kana,
139        RampPreset::Shapes,
140        RampPreset::Hex,
141        RampPreset::Custom,
142    ];
143
144    pub fn label(self) -> &'static str {
145        match self {
146            RampPreset::Standard => "Standard, 10 levels",
147            RampPreset::Detailed => "Detailed, 70 levels",
148            RampPreset::Dither => "Dithered, 7 levels",
149            RampPreset::Braille => "Braille, 2×4 dots",
150            RampPreset::Blocks => "Blocks, 5 levels",
151            RampPreset::Lines => "Box lines, 8 levels",
152            RampPreset::Kana => "Katakana, 10 levels",
153            RampPreset::Shapes => "Geometric shapes, 9 levels",
154            RampPreset::Hex => "Hex digits, 9 levels",
155            RampPreset::Custom => "Custom ramp",
156        }
157    }
158
159    /// Characters ordered heaviest to lightest (as shown in the UI).
160    pub fn heavy_to_light(self, custom: &str) -> Vec<char> {
161        let s = match self {
162            RampPreset::Standard => "@%#*+=-:. ",
163            RampPreset::Detailed => {
164                "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,\"^`'. "
165            }
166            RampPreset::Dither => "■●━▪•· ",
167            RampPreset::Braille => "⣿⣷⣯⣟⡿⢿⣻⣽⣾⣶⣦⣤⣄⣀⡀ ",
168            RampPreset::Blocks => "█▓▒░ ",
169            RampPreset::Lines => "╬╋╪┼═─· ",
170            RampPreset::Kana => "ヰモムヌメミニー・ ",
171            RampPreset::Shapes => "■●◆▪▫○◦· ",
172            RampPreset::Hex => "8BECF731 ",
173            RampPreset::Custom => {
174                let mut chars: Vec<char> = custom.chars().collect();
175                if chars.is_empty() {
176                    chars = "@%#*+=-:. ".chars().collect();
177                } else if !chars.contains(&' ') {
178                    chars.push(' ');
179                }
180                return chars;
181            }
182        };
183        s.chars().collect()
184    }
185
186    /// Characters ordered lightest (`' '`) to heaviest (for density indexing).
187    pub fn light_to_heavy(self, custom: &str) -> Vec<char> {
188        let mut v = self.heavy_to_light(custom);
189        v.reverse();
190        v
191    }
192
193    /// Matching Clairlune letter set for ambient weather particles.
194    pub fn weather_letters(self) -> &'static str {
195        match self {
196            RampPreset::Braille => "braille",
197            RampPreset::Blocks => "blocks",
198            RampPreset::Lines => "lines",
199            RampPreset::Kana => "kana",
200            RampPreset::Shapes => "shapes",
201            RampPreset::Hex => "hex",
202            _ => "text",
203        }
204    }
205}
206
207/// How the converted ASCII art is coloured and backed.
208#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(tag = "kind", content = "palette", rename_all = "snake_case")]
210pub enum AsciiColorMode {
211    /// One of Clairlune's 12 palettes (both light and dark themes).
212    Palette(String),
213    /// Pure black background (`#000000`) with white characters.
214    Black,
215    /// Pure white background (`#FFFFFF`) with black characters.
216    White,
217    /// Transparent background on PNG export; dark polarity by default.
218    None,
219    /// Each character takes its colour from the source image.
220    Photo,
221}
222
223impl Default for AsciiColorMode {
224    fn default() -> Self {
225        AsciiColorMode::Palette("classic".into())
226    }
227}
228
229/// How an image fits a monitor whose aspect ratio differs from the image's.
230#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(rename_all = "snake_case")]
232pub enum FitMode {
233    #[default]
234    Cover,
235    Contain,
236}
237
238/// Full user-configurable settings for an image-to-ASCII conversion.
239#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
240pub struct AsciiConfig {
241    /// Number of columns across (`20..=320`).
242    pub columns: u32,
243    #[serde(default)]
244    pub row_density: RowDensity,
245    #[serde(default)]
246    pub ramp: RampPreset,
247    #[serde(default = "default_custom_ramp")]
248    pub custom_ramp: String,
249    /// Contrast percentage (`50..=250`; `100` is neutral, `120` is crisp).
250    pub contrast: i32,
251    /// Brightness shift (`-100..=100`; `0` is neutral).
252    pub brightness: i32,
253    /// Invert light/dark polarity.
254    #[serde(default)]
255    pub invert: bool,
256    #[serde(default)]
257    pub color_mode: AsciiColorMode,
258    /// Optional ambient weather id (`"none"`, `"snow"`, `"fireflies"`, ...).
259    #[serde(default = "none_weather")]
260    pub weather: String,
261    #[serde(default)]
262    pub fit: FitMode,
263}
264
265fn default_custom_ramp() -> String {
266    "@%#*+=-:. ".into()
267}
268
269fn none_weather() -> String {
270    "none".into()
271}
272
273impl Default for AsciiConfig {
274    fn default() -> Self {
275        Self {
276            columns: 110,
277            row_density: RowDensity::Auto,
278            ramp: RampPreset::Standard,
279            custom_ramp: default_custom_ramp(),
280            contrast: 120,
281            brightness: 0,
282            invert: false,
283            color_mode: AsciiColorMode::Palette("classic".into()),
284            weather: none_weather(),
285            fit: FitMode::Contain,
286        }
287    }
288}
289
290impl AsciiConfig {
291    /// Whether `theme` uses dark-background polarity (characters represent light)
292    /// before applying `self.invert`.
293    pub fn dark_canvas(&self, theme: Theme) -> bool {
294        match &self.color_mode {
295            AsciiColorMode::Black | AsciiColorMode::None => true,
296            AsciiColorMode::White => false,
297            AsciiColorMode::Palette(_) | AsciiColorMode::Photo => theme == Theme::Dark,
298        }
299    }
300}
301
302/// Converted character grid with per-cell colour, opacity and plain text.
303#[derive(Clone, Debug)]
304pub struct AsciiArt {
305    pub cols: u32,
306    pub rows: u32,
307    pub chars: Vec<char>,
308    pub colors: Vec<[u8; 3]>,
309    /// Sampled source alpha (`0..=255`) per cell.
310    pub alphas: Vec<u8>,
311    /// Multi-line text (`\n`-separated rows, trailing spaces trimmed on empty right margins
312    /// kept uniform as exact `cols` characters per row so alignment never shifts).
313    pub text: String,
314}
315
316#[derive(Clone, Copy, Default)]
317struct Sample {
318    r: u8,
319    g: u8,
320    b: u8,
321    a: u8,
322}
323
324/// Exact area-weighted box average over `[x0, x1] x [y0, y1]` in source pixel space.
325fn sample_box(src: &RgbaImage, x0: f64, y0: f64, x1: f64, y1: f64) -> Sample {
326    let w = src.width as i32;
327    let h = src.height as i32;
328    let x0 = x0.clamp(0.0, f64::from(src.width));
329    let y0 = y0.clamp(0.0, f64::from(src.height));
330    let x1 = x1.clamp(x0, f64::from(src.width));
331    let y1 = y1.clamp(y0, f64::from(src.height));
332    let ix0 = (x0.floor() as i32).clamp(0, w - 1);
333    let iy0 = (y0.floor() as i32).clamp(0, h - 1);
334    let ix1 = (x1.ceil() as i32).clamp(ix0 + 1, w);
335    let iy1 = (y1.ceil() as i32).clamp(iy0 + 1, h);
336
337    let mut wr = 0.0;
338    let mut wg = 0.0;
339    let mut wb = 0.0;
340    let mut wa = 0.0;
341    let mut w_rgb = 0.0;
342    let mut w_tot = 0.0;
343
344    for py in iy0..iy1 {
345        let oy = (f64::from(py + 1).min(y1) - f64::from(py).max(y0)).max(0.0);
346        if oy <= 0.0 {
347            continue;
348        }
349        for px in ix0..ix1 {
350            let ox = (f64::from(px + 1).min(x1) - f64::from(px).max(x0)).max(0.0);
351            let area = ox * oy;
352            if area <= 0.0 {
353                continue;
354            }
355            let idx = ((py as u32 * src.width + px as u32) * 4) as usize;
356            let r = f64::from(src.pixels[idx]);
357            let g = f64::from(src.pixels[idx + 1]);
358            let b = f64::from(src.pixels[idx + 2]);
359            let a = f64::from(src.pixels[idx + 3]);
360            let alpha_w = area * (a / 255.0);
361            wr += r * alpha_w;
362            wg += g * alpha_w;
363            wb += b * alpha_w;
364            w_rgb += alpha_w;
365            wa += a * area;
366            w_tot += area;
367        }
368    }
369    if w_tot <= 0.0 {
370        return Sample::default();
371    }
372    let a = (wa / w_tot).round().clamp(0.0, 255.0) as u8;
373    if w_rgb <= 1e-6 {
374        return Sample {
375            r: 0,
376            g: 0,
377            b: 0,
378            a,
379        };
380    }
381    Sample {
382        r: (wr / w_rgb).round().clamp(0.0, 255.0) as u8,
383        g: (wg / w_rgb).round().clamp(0.0, 255.0) as u8,
384        b: (wb / w_rgb).round().clamp(0.0, 255.0) as u8,
385        a,
386    }
387}
388
389/// Applies brightness (`-100..=100`), contrast (`50..=250`), alpha compositing
390/// over the canvas polarity, and optional inversion to produce ink density in `0..=1`.
391fn ink_density(s: Sample, config: &AsciiConfig, dark_canvas: bool) -> f64 {
392    if s.a < 16 {
393        return 0.0;
394    }
395    let alpha = f64::from(s.a) / 255.0;
396    let bg_luma = if dark_canvas { 0.0 } else { 1.0 };
397    let raw_luma =
398        (0.2126 * f64::from(s.r) + 0.7152 * f64::from(s.g) + 0.0722 * f64::from(s.b)) / 255.0;
399    let luma = raw_luma * alpha + bg_luma * (1.0 - alpha);
400    let bright = luma + f64::from(config.brightness.clamp(-100, 100)) / 180.0;
401    let contrast = f64::from(config.contrast.clamp(40, 300)) / 100.0;
402    let adjusted = ((bright - 0.5) * contrast + 0.5).clamp(0.0, 1.0);
403    let polarity = if dark_canvas {
404        adjusted
405    } else {
406        1.0 - adjusted
407    };
408    if config.invert {
409        1.0 - polarity
410    } else {
411        polarity
412    }
413}
414
415/// Converts `src` using its natural aspect ratio (for the Studio preview, `.txt`
416/// export and standalone PNG export).
417pub fn convert_standalone(src: &RgbaImage, config: &AsciiConfig, theme: Theme) -> AsciiArt {
418    let cols = config.columns.clamp(20, 320);
419    let img_aspect = f64::from(src.height) / f64::from(src.width.max(1));
420    let rows = ((f64::from(cols) * img_aspect * config.row_density.cell_aspect()).round() as u32)
421        .clamp(8, 320);
422    convert_grid(src, config, theme, cols, rows, None)
423}
424
425/// Converts `src` onto a fixed `(cols, rows)` wallpaper grid, cropping (`Cover`)
426/// or centring (`Contain`) according to `config.fit` and cell pixel aspect `cell_w / cell_h`.
427pub fn convert_for_grid(
428    src: &RgbaImage,
429    config: &AsciiConfig,
430    theme: Theme,
431    cols: u32,
432    rows: u32,
433    cell_w: u32,
434    cell_h: u32,
435) -> AsciiArt {
436    let grid_px_w = f64::from(cols * cell_w.max(1));
437    let grid_px_h = f64::from(rows * cell_h.max(1));
438    convert_grid(src, config, theme, cols, rows, Some((grid_px_w, grid_px_h)))
439}
440
441fn convert_grid(
442    src: &RgbaImage,
443    config: &AsciiConfig,
444    theme: Theme,
445    cols: u32,
446    rows: u32,
447    screen_px: Option<(f64, f64)>,
448) -> AsciiArt {
449    let dark_canvas = config.dark_canvas(theme);
450    let ramp = config.ramp.light_to_heavy(&config.custom_ramp);
451    let n = (cols * rows) as usize;
452    let mut chars = vec![' '; n];
453    let mut colors = vec![[0u8; 3]; n];
454    let mut alphas = vec![0u8; n];
455
456    let sw = f64::from(src.width);
457    let sh = f64::from(src.height);
458
459    // Map cell coordinates [0..cols] x [0..rows] into source pixel space.
460    // Either full source (standalone), Cover crop, or Contain letterbox.
461    let (crop_x, crop_y, crop_w, crop_h, dst_x0, dst_y0, dst_w, dst_h) = match screen_px {
462        None => (0.0, 0.0, sw, sh, 0.0, 0.0, f64::from(cols), f64::from(rows)),
463        Some((gw, gh)) => {
464            let src_ratio = sw / sh.max(1.0);
465            let dst_ratio = gw / gh.max(1.0);
466            match config.fit {
467                FitMode::Cover => {
468                    if src_ratio > dst_ratio {
469                        let cw = sh * dst_ratio;
470                        (
471                            (sw - cw) * 0.5,
472                            0.0,
473                            cw,
474                            sh,
475                            0.0,
476                            0.0,
477                            f64::from(cols),
478                            f64::from(rows),
479                        )
480                    } else {
481                        let ch = sw / dst_ratio;
482                        (
483                            0.0,
484                            (sh - ch) * 0.5,
485                            sw,
486                            ch,
487                            0.0,
488                            0.0,
489                            f64::from(cols),
490                            f64::from(rows),
491                        )
492                    }
493                }
494                FitMode::Contain => {
495                    if src_ratio > dst_ratio {
496                        let dh = f64::from(rows) * (dst_ratio / src_ratio);
497                        (
498                            0.0,
499                            0.0,
500                            sw,
501                            sh,
502                            0.0,
503                            (f64::from(rows) - dh) * 0.5,
504                            f64::from(cols),
505                            dh.max(1.0),
506                        )
507                    } else {
508                        let dw = f64::from(cols) * (src_ratio / dst_ratio);
509                        (
510                            0.0,
511                            0.0,
512                            sw,
513                            sh,
514                            (f64::from(cols) - dw) * 0.5,
515                            0.0,
516                            dw.max(1.0),
517                            f64::from(rows),
518                        )
519                    }
520                }
521            }
522        }
523    };
524
525    const BAYER_2X4: [[f64; 2]; 4] = [[-0.07, 0.02], [0.05, -0.04], [-0.02, 0.07], [0.04, -0.05]];
526    const BRAILLE_BITS: [[u8; 2]; 4] = [[0, 3], [1, 4], [2, 5], [6, 7]];
527
528    for row in 0..rows {
529        let ry0 = f64::from(row);
530        let ry1 = f64::from(row + 1);
531        if ry1 <= dst_y0 || ry0 >= dst_y0 + dst_h {
532            continue;
533        }
534        let u_y0 = ((ry0 - dst_y0) / dst_h).clamp(0.0, 1.0);
535        let u_y1 = ((ry1 - dst_y0) / dst_h).clamp(0.0, 1.0);
536        let sy0 = crop_y + u_y0 * crop_h;
537        let sy1 = crop_y + u_y1 * crop_h;
538
539        for col in 0..cols {
540            let cx0 = f64::from(col);
541            let cx1 = f64::from(col + 1);
542            if cx1 <= dst_x0 || cx0 >= dst_x0 + dst_w {
543                continue;
544            }
545            let u_x0 = ((cx0 - dst_x0) / dst_w).clamp(0.0, 1.0);
546            let u_x1 = ((cx1 - dst_x0) / dst_w).clamp(0.0, 1.0);
547            let sx0 = crop_x + u_x0 * crop_w;
548            let sx1 = crop_x + u_x1 * crop_w;
549
550            let idx = (row * cols + col) as usize;
551            let cell_sample = sample_box(src, sx0, sy0, sx1, sy1);
552            alphas[idx] = cell_sample.a;
553            if cell_sample.a < 16 {
554                continue;
555            }
556            colors[idx] = readable_photo_rgb(cell_sample, dark_canvas);
557
558            if config.ramp == RampPreset::Braille {
559                // 2x4 sub-cell braille sampling for sharp edges and stippled gradients.
560                let mut mask = 0u8;
561                let mut sum = 0.0;
562                for (dy, bit_row) in BRAILLE_BITS.iter().enumerate() {
563                    let by0 = sy0 + (sy1 - sy0) * (dy as f64 / 4.0);
564                    let by1 = sy0 + (sy1 - sy0) * ((dy + 1) as f64 / 4.0);
565                    for (dx, &bit) in bit_row.iter().enumerate() {
566                        let bx0 = sx0 + (sx1 - sx0) * (dx as f64 / 2.0);
567                        let bx1 = sx0 + (sx1 - sx0) * ((dx + 1) as f64 / 2.0);
568                        let sub = sample_box(src, bx0, by0, bx1, by1);
569                        let d = ink_density(sub, config, dark_canvas);
570                        sum += d;
571                        if d + BAYER_2X4[dy][dx] >= 0.34 {
572                            mask |= 1 << bit;
573                        }
574                    }
575                }
576                if mask == 0 && sum / 8.0 > 0.14 {
577                    mask = 1 << 6;
578                }
579                chars[idx] = if mask == 0 {
580                    ' '
581                } else {
582                    char::from_u32(0x2800 + u32::from(mask)).unwrap_or(' ')
583                };
584            } else {
585                let d = ink_density(cell_sample, config, dark_canvas);
586                let max_i = ramp.len().saturating_sub(1);
587                let ri = (d * max_i as f64).round().clamp(0.0, max_i as f64) as usize;
588                chars[idx] = ramp[ri];
589            }
590        }
591    }
592
593    let mut text = String::with_capacity(((cols + 1) * rows) as usize);
594    for r in 0..rows {
595        if r > 0 {
596            text.push('\n');
597        }
598        let start = (r * cols) as usize;
599        let line: String = chars[start..start + cols as usize].iter().collect();
600        text.push_str(line.trim_end_matches(' '));
601    }
602
603    AsciiArt {
604        cols,
605        rows,
606        chars,
607        colors,
608        alphas,
609        text,
610    }
611}
612
613/// Ensures photo-coloured glyphs keep legible contrast against the chosen canvas.
614fn readable_photo_rgb(s: Sample, dark_canvas: bool) -> [u8; 3] {
615    let luma = (u32::from(s.r) * 2126 + u32::from(s.g) * 7152 + u32::from(s.b) * 722) / 10_000;
616    if dark_canvas && luma < 48 {
617        let lift = (48 - luma) as u8;
618        [
619            s.r.saturating_add(lift),
620            s.g.saturating_add(lift),
621            s.b.saturating_add(lift),
622        ]
623    } else if !dark_canvas && luma > 212 {
624        let drop = (luma - 212) as u8;
625        [
626            s.r.saturating_sub(drop),
627            s.g.saturating_sub(drop),
628            s.b.saturating_sub(drop),
629        ]
630    } else {
631        [s.r, s.g, s.b]
632    }
633}
634
635/// Resolves the `PaletteFamily` for a `(color_mode, theme)` pair.
636pub fn resolve_family(mode: &AsciiColorMode, theme: Theme) -> PaletteFamily {
637    match mode {
638        AsciiColorMode::Palette(set) => clairlune_scene::palette::families_in(set, theme)
639            .next()
640            .copied()
641            .or_else(|| {
642                clairlune_scene::palette::families_for(theme)
643                    .next()
644                    .copied()
645            })
646            .expect("classic palette exists"),
647        AsciiColorMode::Black | AsciiColorMode::None => PaletteFamily {
648            id: "ascii_black",
649            set: "classic",
650            theme: Theme::Dark,
651            bg_edge: Rgb::hex(0x000000),
652            bg_center: Rgb::hex(0x000000),
653            ink: Rgb::hex(0xF2F2F2),
654            accent: Rgb::hex(0xFF9646),
655            ember: Rgb::hex(0xFFB066),
656            glow_strength: 0.14,
657            tint_strength: 0.50,
658        },
659        AsciiColorMode::White => PaletteFamily {
660            id: "ascii_white",
661            set: "classic",
662            theme: Theme::Light,
663            bg_edge: Rgb::hex(0xFFFFFF),
664            bg_center: Rgb::hex(0xFFFFFF),
665            ink: Rgb::hex(0x141414),
666            accent: Rgb::hex(0xD9652B),
667            ember: Rgb::hex(0xCF5320),
668            glow_strength: 0.10,
669            tint_strength: 0.45,
670        },
671        AsciiColorMode::Photo => match theme {
672            Theme::Dark => PaletteFamily {
673                id: "photo_dark",
674                set: "classic",
675                theme: Theme::Dark,
676                bg_edge: Rgb::hex(0x0B0C10),
677                bg_center: Rgb::hex(0x13151C),
678                ink: Rgb::hex(0xE9E5D7),
679                accent: Rgb::hex(0xFF9646),
680                ember: Rgb::hex(0xFFA65C),
681                glow_strength: 0.16,
682                tint_strength: 0.55,
683            },
684            Theme::Light => PaletteFamily {
685                id: "photo_light",
686                set: "classic",
687                theme: Theme::Light,
688                bg_edge: Rgb::hex(0xEAE6DC),
689                bg_center: Rgb::hex(0xF6F3EC),
690                ink: Rgb::hex(0x1C1A17),
691                accent: Rgb::hex(0xD9652B),
692                ember: Rgb::hex(0xCF5320),
693                glow_strength: 0.10,
694                tint_strength: 0.50,
695            },
696        },
697    }
698}
699
700/// Rasterizes every unique character in `chars` in chunks of `<= 200` glyphs,
701/// returning `(per_cell_glyph_id, contiguous_masks)` with `0` reserved for `' '`.
702fn rasterize_unique_chars(
703    chars: &[char],
704    cell_w: u32,
705    cell_h: u32,
706    font_px: f64,
707) -> (Vec<u16>, Vec<u8>) {
708    let mut unique: Vec<char> = vec![' '];
709    let mut map: HashMap<char, u16> = HashMap::new();
710    map.insert(' ', 0);
711    let mut ids = Vec::with_capacity(chars.len());
712    for &c in chars {
713        let id = if let Some(&id) = map.get(&c) {
714            id
715        } else {
716            let id = unique.len() as u16;
717            unique.push(c);
718            map.insert(c, id);
719            id
720        };
721        ids.push(id);
722    }
723    let cell_len = (cell_w * cell_h) as usize;
724    let mut all_masks = vec![0u8; unique.len() * cell_len];
725    for (chunk_idx, chunk) in unique.chunks(200).enumerate() {
726        let atlas = GlyphAtlas::for_char_set(chunk, cell_w, cell_h, font_px);
727        for (local_i, _) in chunk.iter().enumerate() {
728            let global_i = chunk_idx * 200 + local_i;
729            all_masks[global_i * cell_len..(global_i + 1) * cell_len]
730                .copy_from_slice(atlas.mask(local_i as u8));
731        }
732    }
733    (ids, all_masks)
734}
735
736/// Renders `art` to an RGBA8 image (`width, height, pixels`), supporting
737/// transparent backgrounds (`AsciiColorMode::None`), photo colours, palettes,
738/// and optional corner signature on opaque exports.
739pub fn render_rgba(
740    art: &AsciiArt,
741    config: &AsciiConfig,
742    theme: Theme,
743    cell_h: u32,
744    sign: bool,
745) -> (u32, u32, Vec<u8>) {
746    let cell_h = cell_h.max(8);
747    let cell_w = ((f64::from(cell_h) * FONT_TO_CELL * ADVANCE_RATIO).round() as u32).max(4);
748    let pad_x = cell_w * 2;
749    let pad_y = cell_h;
750    let width = art.cols * cell_w + pad_x * 2;
751    let height = art.rows * cell_h + pad_y * 2;
752
753    let transparent = config.color_mode == AsciiColorMode::None;
754    let family = resolve_family(&config.color_mode, theme);
755    let lighting = Lighting {
756        vignette_cx: f64::from(width) * 0.5,
757        vignette_cy: f64::from(height) * 0.5,
758        vignette_rx: f64::from(width) * 0.78,
759        vignette_ry: f64::from(height) * 0.78,
760        glow: None,
761    };
762
763    let mut rgba = vec![0u8; (width * height * 4) as usize];
764    if !transparent {
765        let flat = matches!(
766            config.color_mode,
767            AsciiColorMode::Black | AsciiColorMode::White
768        );
769        for y in 0..height {
770            let rt = lighting.row_terms(y);
771            for x in 0..width {
772                let bg = if flat {
773                    family.bg_center
774                } else {
775                    let b = lighting.band_in_row(&rt, x).min(3);
776                    family.bg_edge.mix(family.bg_center, f64::from(b) / 3.0)
777                };
778                let o = ((y * width + x) * 4) as usize;
779                rgba[o] = bg.r;
780                rgba[o + 1] = bg.g;
781                rgba[o + 2] = bg.b;
782                rgba[o + 3] = 255;
783            }
784        }
785    }
786
787    let font_px = f64::from(cell_h) * FONT_TO_CELL;
788    let (glyph_ids, all_masks) = rasterize_unique_chars(&art.chars, cell_w, cell_h, font_px);
789    let cell_len = (cell_w * cell_h) as usize;
790
791    for row in 0..art.rows {
792        for col in 0..art.cols {
793            let ci = (row * art.cols + col) as usize;
794            let gid = glyph_ids[ci] as usize;
795            if gid == 0 {
796                continue;
797            }
798            let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
799            let ink = if config.color_mode == AsciiColorMode::Photo {
800                let [r, g, b] = art.colors[ci];
801                Rgb { r, g, b }
802            } else {
803                family.ink
804            };
805            let x0 = pad_x + col * cell_w;
806            let y0 = pad_y + row * cell_h;
807            for my in 0..cell_h {
808                for mx in 0..cell_w {
809                    let a = mask[(my * cell_w + mx) as usize];
810                    if a == 0 {
811                        continue;
812                    }
813                    let o = (((y0 + my) * width + (x0 + mx)) * 4) as usize;
814                    if transparent {
815                        rgba[o] = ink.r;
816                        rgba[o + 1] = ink.g;
817                        rgba[o + 2] = ink.b;
818                        rgba[o + 3] = a;
819                    } else {
820                        let t = f64::from(a) / 255.0;
821                        let cur = Rgb {
822                            r: rgba[o],
823                            g: rgba[o + 1],
824                            b: rgba[o + 2],
825                        };
826                        let m = cur.mix(ink, t);
827                        rgba[o] = m.r;
828                        rgba[o + 1] = m.g;
829                        rgba[o + 2] = m.b;
830                        rgba[o + 3] = 255;
831                    }
832                }
833            }
834        }
835    }
836
837    if sign && !transparent {
838        stamp_rgba_signature(&mut rgba, width, height, family.ink);
839    }
840
841    (width, height, rgba)
842}
843
844fn stamp_rgba_signature(rgba: &mut [u8], width: u32, height: u32, ink: Rgb) {
845    let spec = clairlune_scene::grid_spec(width, height);
846    let chars: Vec<char> = SIGNATURE.chars().collect();
847    let n = chars.len() as u32;
848    if spec.cols < 2 * (n + 3) || spec.rows < 6 {
849        return;
850    }
851    let Ok(atlas) = GlyphAtlas::with_chars(
852        crate::atlas::FONT_DATA,
853        &chars,
854        spec.cell_w,
855        spec.cell_h,
856        spec.font_px,
857    ) else {
858        return;
859    };
860    let x0 = spec.origin_x + (spec.cols - n - 2) * spec.cell_w;
861    let y0 = spec.origin_y + (spec.rows - 2) * spec.cell_h;
862    for c in 0..n {
863        let mask = atlas.mask(c as u8);
864        for my in 0..spec.cell_h {
865            for mx in 0..spec.cell_w {
866                let a = mask[(my * spec.cell_w + mx) as usize];
867                if a == 0 {
868                    continue;
869                }
870                let px = x0 + c * spec.cell_w + mx;
871                let py = y0 + my;
872                if px >= width || py >= height {
873                    continue;
874                }
875                let o = ((py * width + px) * 4) as usize;
876                let cur = Rgb {
877                    r: rgba[o],
878                    g: rgba[o + 1],
879                    b: rgba[o + 2],
880                };
881                let m = cur.mix(ink, (f64::from(a) / 255.0) * 0.65);
882                rgba[o] = m.r;
883                rgba[o + 1] = m.g;
884                rgba[o + 2] = m.b;
885            }
886        }
887    }
888}
889
890/// Encodes an RGBA8 image buffer as a PNG.
891pub fn encode_rgba_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
892    let mut out = Vec::new();
893    {
894        let mut enc = png::Encoder::new(&mut out, width, height);
895        enc.set_color(png::ColorType::Rgba);
896        enc.set_depth(png::BitDepth::Eight);
897        let mut writer = enc.write_header().map_err(|e| e.to_string())?;
898        writer.write_image_data(rgba).map_err(|e| e.to_string())?;
899    }
900    Ok(out)
901}
902
903/// Builds a frozen [`ScenePackage`] at `(width, height)` for a user image,
904/// complete with both themes (unless fixed to Black or White) and optional
905/// live weather particles.
906pub fn build_photo_package(
907    src: &RgbaImage,
908    config: &AsciiConfig,
909    width: u32,
910    height: u32,
911    seed: u64,
912) -> Result<ScenePackage, String> {
913    if width < 160 || height < 90 {
914        return Err(format!("{width}x{height} is too small (minimum 160x90)"));
915    }
916
917    let wanted_cols = config.columns.clamp(24, 320);
918    let max_cell_w = (width / wanted_cols).max(3);
919    let cell_h_from_cols =
920        ((f64::from(max_cell_w) / (ADVANCE_RATIO * FONT_TO_CELL)).round() as u32).max(6);
921    let font_px = f64::from(cell_h_from_cols) * FONT_TO_CELL;
922    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32)
923        .clamp(3, width)
924        .min(max_cell_w);
925    let cell_h = cell_h_from_cols.min(height);
926    let cols = (width / cell_w).max(1);
927    let rows = (height / cell_h).max(1);
928    let grid = GridSpec {
929        cols,
930        rows,
931        cell_w,
932        cell_h,
933        origin_x: (width - cols * cell_w) / 2,
934        origin_y: (height - rows * cell_h) / 2,
935        font_px,
936    };
937
938    let themes_to_build: &[Theme] = match config.color_mode {
939        AsciiColorMode::Black => &[Theme::Dark],
940        AsciiColorMode::White => &[Theme::Light],
941        AsciiColorMode::Palette(_) | AsciiColorMode::None | AsciiColorMode::Photo => {
942            &[Theme::Dark, Theme::Light]
943        }
944    };
945
946    let letters = config.ramp.weather_letters();
947    let weather_atlas = GlyphAtlas::for_letters(&grid, letters);
948    let embers = ember_set(seed, CALM_PACE);
949    let t_hero_ms = hero_time(&embers);
950    let aspect = f64::from(width) / f64::from(height);
951    let unit = f64::from(width.min(height));
952
953    let mut emitters = Vec::new();
954    if let Some(kind) = WeatherKind::from_id(&config.weather) {
955        emitters.push(Emitter {
956            kind: EmitterKind::Weather(kind),
957            origin_x: 0.0,
958            origin_y: 0.0,
959            unit,
960            intensity: 1.0,
961            embers: Vec::new(),
962            drops: weather_set(kind, seed, aspect, CALM_PACE),
963            size: (f64::from(width), f64::from(height)),
964            pace: CALM_PACE,
965        });
966    }
967
968    let mut custom_themes = Vec::with_capacity(themes_to_build.len());
969    for &theme in themes_to_build {
970        let tod = match theme {
971            Theme::Dark => TimeOfDay::Night,
972            Theme::Light => TimeOfDay::Morning,
973        };
974        let family = resolve_family(&config.color_mode, theme);
975        let art = convert_for_grid(src, config, theme, cols, rows, cell_w, cell_h);
976        let lighting = Lighting {
977            vignette_cx: f64::from(width) * 0.5,
978            vignette_cy: f64::from(height) * 0.5,
979            vignette_rx: f64::from(width) * 0.78,
980            vignette_ry: f64::from(height) * 0.78,
981            glow: None,
982        };
983
984        let graph = SceneGraph {
985            width,
986            height,
987            theme,
988            tod,
989            buddy: false,
990            seed,
991            family,
992            grid,
993            cells: Vec::new(),
994            lighting,
995            activity: None,
996            props: Vec::new(),
997            unattended: Vec::new(),
998            character: None,
999            emitters: emitters.clone(),
1000            ground_y: height as i32,
1001            t_hero_ms,
1002            loop_ms: LOOP_MS,
1003            pace: CALM_PACE,
1004            generator: GENERATOR_VERSION,
1005            letters: if letters == "text" {
1006                String::new()
1007            } else {
1008                letters.to_string()
1009            },
1010            water: None,
1011            journey: None,
1012            zoom: 1.0,
1013        };
1014
1015        let (background, palette) = bake_ascii_theme(&art, config, &graph);
1016        custom_themes.push(CustomTheme {
1017            theme,
1018            graph,
1019            palette,
1020            atlas: weather_atlas.clone(),
1021            background,
1022            hero_ms: t_hero_ms,
1023        });
1024    }
1025
1026    let (light_family, dark_family) = match &config.color_mode {
1027        AsciiColorMode::Palette(set) => {
1028            let l = clairlune_scene::palette::families_in(set, Theme::Light)
1029                .next()
1030                .map_or("paper_day", |f| f.id);
1031            let d = clairlune_scene::palette::families_in(set, Theme::Dark)
1032                .next()
1033                .map_or("ember_night", |f| f.id);
1034            (l.to_string(), d.to_string())
1035        }
1036        _ => ("paper_day".to_string(), "ember_night".to_string()),
1037    };
1038
1039    let recipe = SceneRecipe {
1040        generator_version: GENERATOR_VERSION,
1041        seed,
1042        aspect: Aspect::from_size(width, height),
1043        content_ctx_hash: format!("{seed:016x}"),
1044        activity: None,
1045        archetype: PHOTO_ARCHETYPE.into(),
1046        light_tod: themes_to_build
1047            .contains(&Theme::Light)
1048            .then_some(TimeOfDay::Morning),
1049        dark_tod: themes_to_build
1050            .contains(&Theme::Dark)
1051            .then_some(TimeOfDay::Night),
1052        platform: "none".into(),
1053        props: Vec::new(),
1054        weather: config.weather.clone(),
1055        composition: Composition {
1056            horizon_pm: 800,
1057            focus_x_pm: 500,
1058            gap_pm: 500,
1059            shape_pow_pm: 1000,
1060            platform_margin_pm: 0,
1061            cliff_layers: 0,
1062            prop_left: false,
1063            motion_speed_cc: 0,
1064            pace_half_pm: 0,
1065            fly_lift_pm: 0,
1066            journey_ms: 0,
1067            journey_pace_c: 0,
1068            landmark: String::new(),
1069        },
1070        palette: PalettePick {
1071            light: light_family,
1072            dark: dark_family,
1073        },
1074        look: "line".into(),
1075        contrast: "normal".into(),
1076        zoom: "close".into(),
1077        letters: letters.into(),
1078    };
1079
1080    ScenePackage::from_custom(recipe, width, height, custom_themes).map_err(|e| e.to_string())
1081}
1082
1083fn bake_ascii_theme(
1084    art: &AsciiArt,
1085    config: &AsciiConfig,
1086    graph: &SceneGraph,
1087) -> (IndexedImage, IndexedPalette) {
1088    let mut img = IndexedImage::new(graph.width, graph.height);
1089    let w = graph.width as usize;
1090    let flat_bg = matches!(
1091        config.color_mode,
1092        AsciiColorMode::Black | AsciiColorMode::White | AsciiColorMode::None
1093    );
1094    if flat_bg {
1095        img.pixels.fill(3); // uniform bg_center band
1096    } else {
1097        for (y, row) in img.pixels.chunks_exact_mut(w).enumerate() {
1098            graph.lighting.fill_row(y as u32, row);
1099        }
1100    }
1101
1102    let g = &graph.grid;
1103    let (cw, ch) = (g.cell_w as usize, g.cell_h as usize);
1104    let cell_len = cw * ch;
1105    let (glyph_ids, all_masks) = rasterize_unique_chars(&art.chars, g.cell_w, g.cell_h, g.font_px);
1106
1107    if config.color_mode == AsciiColorMode::Photo {
1108        let (palette, cell_slots) = build_photo_palette(graph, art);
1109        for row in 0..g.rows {
1110            for col in 0..g.cols {
1111                let ci = (row * g.cols + col) as usize;
1112                let gid = glyph_ids[ci] as usize;
1113                if gid == 0 {
1114                    continue;
1115                }
1116                let base_slot = cell_slots[ci];
1117                let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
1118                let x0 = g.origin_x as usize + col as usize * cw;
1119                let y0 = g.origin_y as usize + row as usize * ch;
1120                for my in 0..ch {
1121                    let line = (y0 + my) * w + x0;
1122                    for mx in 0..cw {
1123                        let a = mask[my * cw + mx];
1124                        // 3 anti-aliasing levels per quantized colour: faint, medium, full.
1125                        let step = if a < 48 {
1126                            continue;
1127                        } else if a < 128 {
1128                            0
1129                        } else if a < 205 {
1130                            1
1131                        } else {
1132                            2
1133                        };
1134                        img.pixels[line + mx] = base_slot + step;
1135                    }
1136                }
1137            }
1138        }
1139        return (img, palette);
1140    }
1141
1142    let palette = IndexedPalette::for_graph(graph);
1143    for row in 0..g.rows {
1144        for col in 0..g.cols {
1145            let ci = (row * g.cols + col) as usize;
1146            let gid = glyph_ids[ci] as usize;
1147            if gid == 0 {
1148                continue;
1149            }
1150            let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
1151            let x0 = g.origin_x as usize + col as usize * cw;
1152            let y0 = g.origin_y as usize + row as usize * ch;
1153            for my in 0..ch {
1154                let line = (y0 + my) * w + x0;
1155                for mx in 0..cw {
1156                    let a = mask[my * cw + mx];
1157                    if a == 0 {
1158                        continue;
1159                    }
1160                    let level = ink_level(a, 255);
1161                    if level > 0 {
1162                        let band = img.pixels[line + mx];
1163                        img.pixels[line + mx] = IndexedPalette::ink(band, level);
1164                    }
1165                }
1166            }
1167        }
1168    }
1169    (img, palette)
1170}
1171
1172/// Builds an `IndexedPalette` whose `0..104` entries keep standard background,
1173/// ink and ember ramps (for vignette, live weather and signatures) and whose
1174/// `104..248` entries hold up to 48 median-cut photo colours × 3 AA blend steps.
1175fn build_photo_palette(graph: &SceneGraph, art: &AsciiArt) -> (IndexedPalette, Vec<u8>) {
1176    let base = IndexedPalette::for_graph(graph);
1177    let mut colors = base.colors()[..SPRITE_BASE as usize].to_vec();
1178
1179    let active: Vec<[u8; 3]> = art
1180        .chars
1181        .iter()
1182        .zip(&art.colors)
1183        .filter(|(ch, _)| **ch != ' ')
1184        .map(|(_, &rgb)| rgb)
1185        .collect();
1186
1187    let centroids = median_cut(&active, 48);
1188    let bg = graph.family.bg_center;
1189    for &[r, g, b] in &centroids {
1190        let target = Rgb { r, g, b };
1191        for t in [0.38, 0.70, 1.0] {
1192            colors.push(bg.mix(target, t));
1193        }
1194    }
1195    debug_assert!(colors.len() < TRANSPARENT_INDEX as usize);
1196
1197    let cell_slots = art
1198        .colors
1199        .iter()
1200        .map(|rgb| {
1201            let best = centroids
1202                .iter()
1203                .enumerate()
1204                .min_by_key(|(_, c)| color_dist2(*rgb, **c))
1205                .map_or(0, |(i, _)| i);
1206            SPRITE_BASE + (best as u8) * 3
1207        })
1208        .collect();
1209
1210    (IndexedPalette::from_colors(colors), cell_slots)
1211}
1212
1213fn color_dist2(a: [u8; 3], b: [u8; 3]) -> u32 {
1214    let dr = i32::from(a[0]) - i32::from(b[0]);
1215    let dg = i32::from(a[1]) - i32::from(b[1]);
1216    let db = i32::from(a[2]) - i32::from(b[2]);
1217    (dr * dr * 2 + dg * dg * 4 + db * db) as u32
1218}
1219
1220/// Deterministic median-cut colour quantizer producing `1..=max_colors` RGB centroids.
1221fn median_cut(samples: &[[u8; 3]], max_colors: usize) -> Vec<[u8; 3]> {
1222    if samples.is_empty() {
1223        return vec![[220, 220, 220]];
1224    }
1225    let mut buckets: Vec<Vec<[u8; 3]>> = vec![samples.to_vec()];
1226    while buckets.len() < max_colors {
1227        let Some((split_idx, axis)) = buckets
1228            .iter()
1229            .enumerate()
1230            .filter(|(_, b)| b.len() >= 2)
1231            .filter_map(|(i, b)| {
1232                let (mut rmin, mut rmax) = (255u8, 0u8);
1233                let (mut gmin, mut gmax) = (255u8, 0u8);
1234                let (mut bmin, mut bmax) = (255u8, 0u8);
1235                for c in b {
1236                    rmin = rmin.min(c[0]);
1237                    rmax = rmax.max(c[0]);
1238                    gmin = gmin.min(c[1]);
1239                    gmax = gmax.max(c[1]);
1240                    bmin = bmin.min(c[2]);
1241                    bmax = bmax.max(c[2]);
1242                }
1243                let ranges = [rmax - rmin, gmax - gmin, bmax - bmin];
1244                let (axis, &span) = ranges.iter().enumerate().max_by_key(|(_, s)| *s)?;
1245                (span > 0).then_some((i, axis, u32::from(span) * (b.len() as u32).ilog2().max(1)))
1246            })
1247            .max_by_key(|&(_, _, score)| score)
1248            .map(|(i, axis, _)| (i, axis))
1249        else {
1250            break;
1251        };
1252
1253        let mut bucket = buckets.swap_remove(split_idx);
1254        bucket.sort_by_key(|c| (c[axis], c[0], c[1], c[2]));
1255        let mid = bucket.len() / 2;
1256        let right = bucket.split_off(mid);
1257        buckets.push(bucket);
1258        buckets.push(right);
1259    }
1260
1261    buckets
1262        .into_iter()
1263        .filter(|b| !b.is_empty())
1264        .map(|b| {
1265            let n = b.len() as u64;
1266            let (sr, sg, sb) = b.iter().fold((0u64, 0u64, 0u64), |(r, g, bl), c| {
1267                (
1268                    r + u64::from(c[0]),
1269                    g + u64::from(c[1]),
1270                    bl + u64::from(c[2]),
1271                )
1272            });
1273            [
1274                ((sr + n / 2) / n) as u8,
1275                ((sg + n / 2) / n) as u8,
1276                ((sb + n / 2) / n) as u8,
1277            ]
1278        })
1279        .collect()
1280}
1281
1282/// Number of built-in procedural showcase images for the Studio's Inspire button.
1283pub const INSPIRE_COUNT: usize = 4;
1284
1285/// Generates one of the built-in showcase images (`360 x 240` RGBA) in pure Rust.
1286pub fn inspire_sample(index: usize, buddy: bool) -> (&'static str, RgbaImage) {
1287    let (w, h) = (360u32, 240u32);
1288    let mut px = vec![0u8; (w * h * 4) as usize];
1289    let which = index % INSPIRE_COUNT;
1290    let title = match which {
1291        0 => "Sample 1 · Crescent & peaks",
1292        1 => "Sample 2 · Sunset horizon",
1293        2 => "Sample 3 · Faceted ring",
1294        _ if buddy => "Sample 4 · Clawd by starlight",
1295        _ => "Sample 4 · Spiral nebula",
1296    };
1297
1298    for y in 0..h {
1299        let ny = f64::from(y) / f64::from(h);
1300        for x in 0..w {
1301            let nx = f64::from(x) / f64::from(w);
1302            let [r, g, b] = match which {
1303                0 => sample_crescent_peaks(nx, ny),
1304                1 => sample_sunset(nx, ny),
1305                2 => sample_torus(nx, ny),
1306                _ if buddy => sample_clawd_card(nx, ny),
1307                _ => sample_nebula(nx, ny),
1308            };
1309            let o = ((y * w + x) * 4) as usize;
1310            px[o] = r;
1311            px[o + 1] = g;
1312            px[o + 2] = b;
1313            px[o + 3] = 255;
1314        }
1315    }
1316    (
1317        title,
1318        RgbaImage {
1319            width: w,
1320            height: h,
1321            pixels: px,
1322        },
1323    )
1324}
1325
1326fn sample_crescent_peaks(nx: f64, ny: f64) -> [u8; 3] {
1327    // Sky gradient + crescent moon + twin alpine ridges + lake reflection.
1328    let water_y = 0.72;
1329    let (ux, uy, mir) = if ny > water_y {
1330        let ripple = ((ny - water_y) * 190.0).sin() * 0.008;
1331        (
1332            (nx + ripple).clamp(0.0, 1.0),
1333            (water_y - (ny - water_y) * 0.88).clamp(0.0, water_y),
1334            true,
1335        )
1336    } else {
1337        (nx, ny, false)
1338    };
1339
1340    // Crescent moon at (0.66, 0.27)
1341    let dx = (ux - 0.66) * 1.5;
1342    let dy = uy - 0.27;
1343    let d_outer = (dx * dx + dy * dy).sqrt();
1344    let d_cut = ((dx - 0.065) * (dx - 0.065) + (dy + 0.025) * (dy + 0.025)).sqrt();
1345
1346    let ridge_far = 0.56
1347        - 0.19 * (1.0 - ((ux - 0.28).abs() * 3.4).min(1.0))
1348        - 0.14 * (1.0 - ((ux - 0.74).abs() * 3.8).min(1.0))
1349        + 0.02 * (ux * 38.0).sin();
1350    let ridge_near =
1351        0.68 - 0.26 * (1.0 - ((ux - 0.42).abs() * 2.8).min(1.0)) - 0.03 * (ux * 29.0).cos();
1352
1353    let mut rgb = if uy > ridge_near {
1354        let slope = if ux < 0.42 { 0.52 } else { 0.88 };
1355        let v = (52.0 + slope * 78.0 * (1.0 - (uy - ridge_near) * 1.9).clamp(0.2, 1.0)) as u8;
1356        [v.saturating_sub(12), v, v.saturating_add(18)]
1357    } else if uy > ridge_far {
1358        let v = (34.0 + (0.72 - uy) * 95.0) as u8;
1359        [v.saturating_sub(8), v, v.saturating_add(24)]
1360    } else if d_outer < 0.145 && d_cut > 0.125 {
1361        [248, 236, 198]
1362    } else {
1363        let glow = (1.0 - (d_outer / 0.42).min(1.0)) * 52.0;
1364        let base = 10.0 + uy * 26.0 + glow;
1365        [
1366            base as u8,
1367            (base * 1.1) as u8,
1368            (base * 1.45).min(255.0) as u8,
1369        ]
1370    };
1371    if mir {
1372        rgb = [
1373            (u16::from(rgb[0]) * 6 / 10) as u8,
1374            (u16::from(rgb[1]) * 7 / 10) as u8,
1375            (u16::from(rgb[2]) * 8 / 10) as u8,
1376        ];
1377    }
1378    rgb
1379}
1380
1381fn sample_sunset(nx: f64, ny: f64) -> [u8; 3] {
1382    let horizon = 0.62;
1383    let dx = (nx - 0.5) * 1.5;
1384    let dy = ny - 0.44;
1385    let d = (dx * dx + dy * dy).sqrt();
1386    if ny < horizon {
1387        if d < 0.24 {
1388            // Striped retro sun
1389            let band = ((ny - 0.34) * 55.0) as i32;
1390            if ny > 0.38 && band % 3 == 0 {
1391                return [38, 18, 52];
1392            }
1393            let t = ((ny - 0.20) / 0.30).clamp(0.0, 1.0);
1394            return [252, (225.0 - t * 115.0) as u8, (95.0 + t * 45.0) as u8];
1395        }
1396        let hill = horizon - 0.08 * (nx * 9.0).sin().abs() - 0.04 * (nx * 21.0 + 1.0).sin().abs();
1397        if ny > hill {
1398            return [24, 16, 36];
1399        }
1400        let t = (ny / horizon).clamp(0.0, 1.0);
1401        [
1402            (28.0 + t * 140.0) as u8,
1403            (20.0 + t * 62.0) as u8,
1404            (58.0 + t * 55.0) as u8,
1405        ]
1406    } else {
1407        let depth = (ny - horizon) / (1.0 - horizon);
1408        let sun_col = (1.0 - ((nx - 0.5).abs() * (3.2 + depth * 3.0)).min(1.0)).max(0.0);
1409        let wave = ((depth * 85.0 + nx * 18.0).sin() * 0.5 + 0.5) * sun_col;
1410        [
1411            (22.0 + wave * 220.0) as u8,
1412            (18.0 + wave * 120.0) as u8,
1413            (44.0 + wave * 65.0 + (1.0 - depth) * 28.0) as u8,
1414        ]
1415    }
1416}
1417
1418fn sample_torus(nx: f64, ny: f64) -> [u8; 3] {
1419    let u = (nx - 0.5) * 2.4;
1420    let v = (ny - 0.5) * 1.65;
1421    // Tilted 3D ring normal approximation
1422    let r = (u * u + (v * 1.28) * (v * 1.28)).sqrt();
1423    let major = 0.62;
1424    let minor = 0.25;
1425    let dr = r - major;
1426    let inside = minor * minor - dr * dr;
1427    if inside <= 0.0 {
1428        let vignette = (1.0 - (r * 0.6).min(1.0)) * 22.0;
1429        return [
1430            vignette as u8,
1431            (vignette * 1.05) as u8,
1432            (vignette * 1.25) as u8,
1433        ];
1434    }
1435    let nz = inside.sqrt() / minor;
1436    let inv_r = if r > 1e-4 { 1.0 / r } else { 0.0 };
1437    let nx3 = (dr / minor) * (u * inv_r);
1438    let ny3 = (dr / minor) * (v * 1.28 * inv_r);
1439    let diff = (-0.52 * nx3 - 0.58 * ny3 + 0.62 * nz).max(0.06);
1440    let spec = diff.powi(6) * 0.55;
1441    let l = (diff * 0.85 + spec).clamp(0.0, 1.0);
1442    [
1443        (30.0 + l * 220.0) as u8,
1444        (38.0 + l * 198.0) as u8,
1445        (54.0 + l * 175.0) as u8,
1446    ]
1447}
1448
1449fn sample_clawd_card(nx: f64, ny: f64) -> [u8; 3] {
1450    // Pixel-art Clawd silhouette centred over a warm campfire halo.
1451    let gx = (nx * 45.0).floor() as i32 - 22;
1452    let gy = (ny * 30.0).floor() as i32 - 15;
1453    // Body [-7..=7, -5..=2], arms [-9..-7] & [8..10] at [-2..=1], legs at [-6,-5], [-2,-1], [1,2], [5,6] at [3..=5]
1454    let in_body = (-7..=7).contains(&gx) && (-5..=2).contains(&gy);
1455    let in_arms = ((-9..=-8).contains(&gx) || (8..=9).contains(&gx)) && (-2..=1).contains(&gy);
1456    let in_legs = ([-6, -5, -2, -1, 2, 3, 5, 6].contains(&gx)) && (3..=5).contains(&gy);
1457    let in_eyes = ([-4, -3, 3, 4].contains(&gx)) && gy == -2;
1458
1459    if in_eyes {
1460        return [24, 18, 16];
1461    }
1462    if in_body || in_arms {
1463        let top = if gy <= -4 { 24 } else { 0 };
1464        return [226u8.saturating_add(top), 132u8.saturating_add(top / 2), 98];
1465    }
1466    if in_legs {
1467        return [184, 94, 69];
1468    }
1469    if gy == 6 && (-14..=14).contains(&gx) {
1470        return [120, 112, 98];
1471    }
1472    let d = ((nx - 0.5) * (nx - 0.5) * 1.6 + (ny - 0.52) * (ny - 0.52)).sqrt();
1473    let glow = (1.0 - (d / 0.55).min(1.0)).powi(2);
1474    [
1475        (10.0 + glow * 85.0) as u8,
1476        (12.0 + glow * 48.0) as u8,
1477        (18.0 + glow * 28.0) as u8,
1478    ]
1479}
1480
1481fn sample_nebula(nx: f64, ny: f64) -> [u8; 3] {
1482    let dx = (nx - 0.5) * 1.6;
1483    let dy = ny - 0.5;
1484    let r = (dx * dx + dy * dy).sqrt();
1485    let a = dy.atan2(dx);
1486    let arm = ((2.0 * a - r * 11.0).cos() * 0.5 + 0.5).powi(3);
1487    let core = (1.0 - (r / 0.55).min(1.0)).powi(2);
1488    let v = (core * 0.85 + arm * (1.0 - (r / 0.72).min(1.0)) * 0.75).clamp(0.0, 1.0);
1489    [
1490        (12.0 + v * 235.0) as u8,
1491        (14.0 + v * 195.0) as u8,
1492        (24.0 + v * 240.0) as u8,
1493    ]
1494}
1495
1496#[cfg(test)]
1497mod tests {
1498    use super::*;
1499    use crate::clock::Clock;
1500
1501    fn split_gradient() -> RgbaImage {
1502        let (w, h) = (80, 48);
1503        let mut px = Vec::with_capacity((w * h * 4) as usize);
1504        for y in 0..h {
1505            for x in 0..w {
1506                let v = (x * 255 / (w - 1)) as u8;
1507                let r = v;
1508                let g = (y * 255 / (h - 1)) as u8;
1509                let b = 255 - v;
1510                px.extend_from_slice(&[r, g, b, 255]);
1511            }
1512        }
1513        RgbaImage::new(w, h, px).unwrap()
1514    }
1515
1516    #[test]
1517    fn dark_and_light_polarities_invert_character_weights() {
1518        let src = split_gradient();
1519        let mut cfg = AsciiConfig {
1520            columns: 40,
1521            color_mode: AsciiColorMode::Black,
1522            ..AsciiConfig::default()
1523        };
1524        let on_black = convert_standalone(&src, &cfg, Theme::Dark);
1525        let last = (on_black.cols * on_black.rows - 1) as usize;
1526        assert_eq!(on_black.chars[0], ' ');
1527        assert_eq!(on_black.chars[last], '@');
1528
1529        cfg.color_mode = AsciiColorMode::White;
1530        let on_white = convert_standalone(&src, &cfg, Theme::Light);
1531        assert_eq!(on_white.chars[0], '@');
1532        assert_eq!(on_white.chars[last], ' ');
1533    }
1534
1535    #[test]
1536    fn braille_and_custom_ramps_produce_expected_characters() {
1537        let src = split_gradient();
1538        let braille_cfg = AsciiConfig {
1539            columns: 32,
1540            ramp: RampPreset::Braille,
1541            ..AsciiConfig::default()
1542        };
1543        let braille = convert_standalone(&src, &braille_cfg, Theme::Dark);
1544        assert!(
1545            braille
1546                .chars
1547                .iter()
1548                .any(|&c| ('\u{2801}'..='\u{28FF}').contains(&c))
1549        );
1550
1551        let custom_cfg = AsciiConfig {
1552            columns: 32,
1553            ramp: RampPreset::Custom,
1554            custom_ramp: "#. ".into(),
1555            ..AsciiConfig::default()
1556        };
1557        let custom = convert_standalone(&src, &custom_cfg, Theme::Dark);
1558        assert!(custom.chars.iter().all(|c| ['#', '.', ' '].contains(c)));
1559    }
1560
1561    #[test]
1562    fn none_background_exports_transparent_rgba_png() {
1563        let src = split_gradient();
1564        let cfg = AsciiConfig {
1565            columns: 30,
1566            color_mode: AsciiColorMode::None,
1567            ..AsciiConfig::default()
1568        };
1569        let art = convert_standalone(&src, &cfg, Theme::Dark);
1570        let (w, h, rgba) = render_rgba(&art, &cfg, Theme::Dark, 12, true);
1571        assert_eq!(rgba[3], 0, "top-left margin pixel must be transparent");
1572        assert!(
1573            rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 200),
1574            "ink pixels must be opaque"
1575        );
1576        let png = encode_rgba_png(w, h, &rgba).unwrap();
1577        assert!(png.starts_with(b"\x89PNG"));
1578    }
1579
1580    #[test]
1581    fn photo_packages_save_load_and_animate_weather_in_palette_and_photo_modes() {
1582        let (_, src) = inspire_sample(0, true);
1583        let dir = std::env::temp_dir().join(format!("clairlune-img2ascii-{}", std::process::id()));
1584        let _ = std::fs::remove_dir_all(&dir);
1585
1586        for (idx, mode) in [
1587            AsciiColorMode::Palette("nord".into()),
1588            AsciiColorMode::Photo,
1589            AsciiColorMode::Black,
1590        ]
1591        .into_iter()
1592        .enumerate()
1593        {
1594            let cfg = AsciiConfig {
1595                columns: 80,
1596                ramp: RampPreset::Detailed,
1597                color_mode: mode,
1598                weather: "snow".into(),
1599                ..AsciiConfig::default()
1600            };
1601            let pkg = build_photo_package(&src, &cfg, 640, 360, 12345).unwrap();
1602            let sub = dir.join(format!("mode-{idx}"));
1603            pkg.save(&sub).unwrap();
1604            let loaded = ScenePackage::load(&sub).unwrap();
1605            let theme = loaded.themes()[0];
1606            let (still, pal) = loaded.still(theme, false).unwrap();
1607            assert_eq!((still.width, still.height), (640, 360));
1608            assert!(pal.len() <= 255);
1609
1610            let mut inc = loaded.incremental(theme).unwrap();
1611            let dirty = loaded
1612                .advance(&mut inc, theme, false, 1500, Clock::Smooth)
1613                .unwrap();
1614            assert!(!dirty.is_empty(), "snow weather should animate frames");
1615        }
1616
1617        let _ = std::fs::remove_dir_all(&dir);
1618    }
1619}