ttui 2.0.0

A terminal UI framework built from first principles: direct control over text rendering, color, pane layout, and multiplexing.
Documentation
//! Deterministic camera viewport and brightness scaling — used for
//! panning/zooming a rendered buffer and for boot-sequence fades.

use crate::buffer::{Buffer, Cell};
use crate::easing::scale_color;

/// A 2D viewport position and zoom level over a source `Buffer`.
pub struct Camera {
    /// Source-buffer x position the viewport starts at.
    pub x: f32,
    /// Source-buffer y position the viewport starts at.
    pub y: f32,
    /// Zoom factor — 1.0 is 1:1, 2.0 duplicates each source cell
    /// across a 2x2 output block.
    pub zoom: f32,
}

impl Camera {
    /// Creates a camera at `(x, y)` with the given `zoom`.
    pub fn new(x: f32, y: f32, zoom: f32) -> Self {
        Camera { x, y, zoom }
    }
}

/// Crops and resamples `source` into a `width`x`height` buffer as
/// seen through `camera` — duplicates cells when `camera.zoom > 1.0`.
pub fn viewport(source: &Buffer, camera: &Camera, width: u16, height: u16) -> Buffer {
    let mut out = Buffer::new(width, height);
    for y in 0..height {
        for x in 0..width {
            let src_x = (camera.x + x as f32 / camera.zoom).floor();
            let src_y = (camera.y + y as f32 / camera.zoom).floor();
            if src_x >= 0.0
                && src_y >= 0.0
                && (src_x as u16) < source.width
                && (src_y as u16) < source.height
            {
                out.set(x, y, source.get(src_x as u16, src_y as u16).clone());
            }
        }
    }
    out
}

/// Scales every Rgb cell's color toward black by `factor` (0 = no
/// change, 1 = fully black). Non-Rgb colors are left unchanged.
///
/// # Note the inverted convention
///
/// `factor` is *how much to dim*, which is the **opposite** of
/// [`crate::easing::scale_color`]'s `factor` (where 1.0 means unchanged
/// and 0.0 means black). `dim` delegates to it as
/// `scale_color(c, 1.0 - factor)`.
///
/// This inversion has already misled a reader once: during the
/// investigation for #139, `dim(&scratch, 1.0)` was read as "full
/// brightness" when it means "fully black", and produced an analysis
/// that had to be corrected mid-flight. The signature is kept as-is
/// because flipping it would be a breaking change to a shipped API, so
/// the trap is documented rather than removed.
///
/// `factor` is clamped to `0.0..=1.0`. That clamp is load-bearing:
/// `easing::scale_color` is deliberately unclamped and will brighten a
/// color given a factor above 1.0, so without the clamp a negative
/// `factor` here would make the buffer brighter instead of darker.
pub fn dim(buf: &Buffer, factor: f32) -> Buffer {
    // Load-bearing: `easing::scale_color` is deliberately unclamped, so
    // without this a negative `factor` would *brighten* the buffer.
    let factor = factor.clamp(0.0, 1.0);
    let mut out = Buffer::new(buf.width, buf.height);
    for y in 0..buf.height {
        for x in 0..buf.width {
            let cell = buf.get(x, y);
            out.set(
                x,
                y,
                Cell {
                    fg: scale_color(cell.fg, 1.0 - factor),
                    bg: scale_color(cell.bg, 1.0 - factor),
                    ..cell.clone()
                },
            );
        }
    }
    out
}

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

    fn labeled(symbol: char) -> Cell {
        Cell {
            symbol,
            alpha: 1.0,
            ..Default::default()
        }
    }

    #[test]
    fn viewport_at_zoom_one_crops_a_window_at_the_camera_position() {
        let mut source = Buffer::new(10, 10);
        source.set(3, 4, labeled('A'));
        source.set(4, 4, labeled('B'));
        let camera = Camera::new(3.0, 4.0, 1.0);

        let out = viewport(&source, &camera, 5, 3);

        assert_eq!(out.get(0, 0).symbol, 'A');
        assert_eq!(out.get(1, 0).symbol, 'B');
    }

    #[test]
    fn viewport_at_zoom_two_duplicates_each_source_cell_across_two_output_cells() {
        let mut source = Buffer::new(4, 1);
        source.set(0, 0, labeled('A'));
        source.set(1, 0, labeled('B'));
        let camera = Camera::new(0.0, 0.0, 2.0);

        let out = viewport(&source, &camera, 4, 1);

        assert_eq!(out.get(0, 0).symbol, 'A');
        assert_eq!(out.get(1, 0).symbol, 'A');
        assert_eq!(out.get(2, 0).symbol, 'B');
        assert_eq!(out.get(3, 0).symbol, 'B');
    }

    #[test]
    fn viewport_with_an_out_of_bounds_camera_does_not_panic() {
        let source = Buffer::new(4, 4);
        let camera = Camera::new(-5.0, -5.0, 1.0);

        let out = viewport(&source, &camera, 3, 3);

        assert_eq!(*out.get(0, 0), Cell::default());
    }

    #[test]
    fn dim_at_factor_zero_leaves_rgb_cells_unchanged() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell {
                symbol: 'X',
                fg: Color::Rgb {
                    r: 100,
                    g: 150,
                    b: 200,
                },
                bg: Color::Rgb {
                    r: 10,
                    g: 20,
                    b: 30,
                },
                alpha: 1.0,
                ..Default::default()
            },
        );

        let out = dim(&buf, 0.0);

        assert_eq!(
            out.get(0, 0).fg,
            Color::Rgb {
                r: 100,
                g: 150,
                b: 200
            }
        );
        assert_eq!(
            out.get(0, 0).bg,
            Color::Rgb {
                r: 10,
                g: 20,
                b: 30
            }
        );
        assert_eq!(out.get(0, 0).symbol, 'X');
    }

    #[test]
    fn dim_at_factor_one_drives_rgb_cells_to_black() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell {
                fg: Color::Rgb {
                    r: 100,
                    g: 150,
                    b: 200,
                },
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            },
        );

        let out = dim(&buf, 1.0);

        assert_eq!(out.get(0, 0).fg, Color::Rgb { r: 0, g: 0, b: 0 });
    }

    #[test]
    fn dim_at_factor_half_halves_each_channel() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell {
                fg: Color::Rgb {
                    r: 100,
                    g: 150,
                    b: 200,
                },
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            },
        );

        let out = dim(&buf, 0.5);

        assert_eq!(
            out.get(0, 0).fg,
            Color::Rgb {
                r: 50,
                g: 75,
                b: 100
            }
        );
    }

    #[test]
    fn dim_leaves_non_rgb_colors_unaffected() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell {
                fg: Color::Red,
                bg: Color::Reset,
                symbol: 'Y',
                alpha: 1.0,
                ..Default::default()
            },
        );

        let out = dim(&buf, 1.0);

        assert_eq!(out.get(0, 0).fg, Color::Red);
        assert_eq!(out.get(0, 0).bg, Color::Reset);
    }

    #[test]
    fn dim_clamps_factors_outside_zero_to_one_rather_than_brightening() {
        let mut buf = Buffer::new(1, 1);
        buf.set(
            0,
            0,
            Cell {
                fg: Color::Rgb {
                    r: 100,
                    g: 150,
                    b: 200,
                },
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            },
        );

        // Above 1.0 saturates at fully black rather than going past it.
        assert_eq!(dim(&buf, 2.0).get(0, 0).fg, Color::Rgb { r: 0, g: 0, b: 0 });

        // Below 0.0 leaves the color alone. This is the load-bearing half:
        // `easing::scale_color` is deliberately unclamped and will happily
        // brighten, so `dim` clamping first is the only thing stopping a
        // negative factor from producing a *brighter* buffer.
        assert_eq!(
            dim(&buf, -1.0).get(0, 0).fg,
            Color::Rgb {
                r: 100,
                g: 150,
                b: 200
            }
        );
    }
}