wtrenderlib 0.1.0

Dependency-free terminal rendering primitives for RGB and RGBA frames
Documentation
use std::io::Write;

use crate::{FrameView, RenderOptions, Result, RgbaBackground, resize_frame};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnicodeOptions {
    pub render_options: RenderOptions,
    pub hide_cursor: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QuadrantOptions {
    pub render_options: RenderOptions,
    pub hide_cursor: bool,
}

pub fn render_unicode<W: Write>(
    frame: FrameView<'_>,
    output: &mut W,
    options: UnicodeOptions,
) -> Result<()> {
    if options.hide_cursor {
        output.write_all(b"\x1b[?25l")?;
    }
    let resized = resize_frame(
        frame,
        options.render_options.width,
        options.render_options.height.saturating_mul(2),
        options.render_options.resize,
        RgbaBackground(options.render_options.background),
    )?;
    let view = resized.as_view();
    for y in (0..view.height()).step_by(2) {
        for x in 0..view.width() {
            let top = view.pixel(x, y).expect("validated output coordinate");
            let bottom = if y + 1 < view.height() {
                view.pixel(x, y + 1).expect("validated output coordinate")
            } else {
                &options.render_options.background
            };
            write!(
                output,
                "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m▀",
                top[0], top[1], top[2], bottom[0], bottom[1], bottom[2]
            )?;
        }
        if y + 2 < view.height() {
            output.write_all(b"\n")?;
        }
    }
    finish(output, options.hide_cursor)
}

pub fn render_unicode_quadrant<W: Write>(
    frame: FrameView<'_>,
    output: &mut W,
    options: QuadrantOptions,
) -> Result<()> {
    if options.hide_cursor {
        output.write_all(b"\x1b[?25l")?;
    }
    let width = options
        .render_options
        .width
        .checked_mul(2)
        .ok_or(crate::Error::DimensionOverflow)?;
    let height = options
        .render_options
        .height
        .checked_mul(2)
        .ok_or(crate::Error::DimensionOverflow)?;
    let resized = resize_frame(
        frame,
        width,
        height,
        options.render_options.resize,
        RgbaBackground(options.render_options.background),
    )?;
    let view = resized.as_view();
    for cell_y in 0..options.render_options.height {
        for cell_x in 0..options.render_options.width {
            let mut selected = Vec::new();
            let mut unselected = Vec::new();
            let mut mask = 0_u8;
            for (dy, dx, bit) in [(0, 0, 1_u8), (0, 1, 2), (1, 0, 4), (1, 1, 8)] {
                let pixel = view
                    .pixel(cell_x * 2 + dx, cell_y * 2 + dy)
                    .expect("validated output coordinate");
                let luminance = (u16::from(pixel[0]) * 77
                    + u16::from(pixel[1]) * 150
                    + u16::from(pixel[2]) * 29)
                    / 256;
                if luminance >= 128 {
                    mask |= bit;
                    selected.push(pixel);
                } else {
                    unselected.push(pixel);
                }
            }
            let foreground = average(&selected, options.render_options.background);
            let background = average(&unselected, options.render_options.background);
            write!(
                output,
                "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}",
                foreground[0],
                foreground[1],
                foreground[2],
                background[0],
                background[1],
                background[2],
                quadrant_glyph(mask)
            )?;
        }
        if cell_y + 1 < options.render_options.height {
            output.write_all(b"\n")?;
        }
    }
    finish(output, options.hide_cursor)
}

fn finish<W: Write>(output: &mut W, hide_cursor: bool) -> Result<()> {
    output.write_all(b"\x1b[0m")?;
    if hide_cursor {
        output.write_all(b"\x1b[?25h")?;
    }
    Ok(())
}

fn average(pixels: &[&[u8]], fallback: [u8; 3]) -> [u8; 3] {
    if pixels.is_empty() {
        return fallback;
    }
    let mut sum = [0_u32; 3];
    for pixel in pixels {
        for channel in 0..3 {
            sum[channel] += u32::from(pixel[channel]);
        }
    }
    [
        (sum[0] / pixels.len() as u32) as u8,
        (sum[1] / pixels.len() as u32) as u8,
        (sum[2] / pixels.len() as u32) as u8,
    ]
}

fn quadrant_glyph(mask: u8) -> char {
    [
        ' ', '▘', '▝', '▀', '▖', '▌', '▞', '▛', '▗', '▚', '▐', '▜', '▄', '▙', '▟', '█',
    ][mask as usize]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CellSize, PixelFormat, ResizeMode};

    #[test]
    fn renders_half_block_with_truecolor() {
        let frame = FrameView::new(&[255, 0, 0, 0, 0, 255], 1, 2, 3, PixelFormat::Rgb8).unwrap();
        let mut output = Vec::new();
        render_unicode(
            frame,
            &mut output,
            UnicodeOptions {
                render_options: RenderOptions {
                    width: 1,
                    height: 1,
                    resize: ResizeMode::None,
                    cell: CellSize {
                        width: 1,
                        height: 2,
                    },
                    background: [0, 0, 0],
                },
                hide_cursor: false,
            },
        )
        .unwrap();
        assert_eq!(
            String::from_utf8(output).unwrap(),
            "\x1b[38;2;255;0;0m\x1b[48;2;0;0;255m▀\x1b[0m"
        );
    }

    #[test]
    fn maps_quadrant_cells_to_unicode() {
        assert_eq!(quadrant_glyph(0b0011), '▀');
        assert_eq!(quadrant_glyph(0b1100), '▄');
        assert_eq!(quadrant_glyph(0b1111), '█');
    }
}