anitty 0.1.0

Anime character animation rendering for terminals
Documentation
use std::error::Error;

use anitty::{Bounds, RenderOptions};

pub const HELP: &str = "Shared rendering options:
  --flip-x          Mirror horizontally
  --flip-y          Mirror vertically
  --scale X,Y       Scale relative to fitted size (default: 1,1)
  --rotate DEGREES  Rotate clockwise about the pivot
  --translate X,Y   Translate in canvas pixels after scaling/rotation
  --pivot X,Y       Pivot in canvas pixels (default: canvas center)
  --view X,Y,W,H    Fixed source rectangle, X right / Y down; no auto padding
  --opacity N       Overall opacity, 0 through 1 (default: 1)";

pub fn parse_option(
    arg: &str,
    args: &mut impl Iterator<Item = String>,
    options: &mut RenderOptions,
) -> Result<bool, Box<dyn Error>> {
    match arg {
        "--flip-x" => options.transform.scale[0] = -options.transform.scale[0].abs(),
        "--flip-y" => options.transform.scale[1] = -options.transform.scale[1].abs(),
        "--scale" => options.transform.scale = numbers(arg, args)?,
        "--rotate" => options.transform.rotation = numbers::<1>(arg, args)?[0].to_radians(),
        "--translate" => options.transform.translation = numbers(arg, args)?,
        "--pivot" => options.transform.pivot = Some(numbers(arg, args)?),
        "--view" => {
            let [x, y, width, height] = numbers(arg, args)?;
            options.view = Some(Bounds {
                x,
                y,
                width,
                height,
            });
        }
        "--opacity" => options.opacity = numbers::<1>(arg, args)?[0],
        _ => return Ok(false),
    }
    Ok(true)
}

fn numbers<const N: usize>(
    arg: &str,
    args: &mut impl Iterator<Item = String>,
) -> Result<[f64; N], Box<dyn Error>> {
    let value = args
        .next()
        .ok_or_else(|| format!("{arg} requires a value"))?;
    let values: Vec<f64> = value.split(',').map(str::parse).collect::<Result<_, _>>()?;
    values
        .try_into()
        .map_err(|_| format!("{arg} requires {N} comma-separated number(s)").into())
}