anitty 0.1.0

Anime character animation rendering for terminals
Documentation
//! Spine 3.8 binary skeletons rendered on the CPU.

mod raster;
mod v38;

use std::{fs, path::Path, time::Duration};

use super::render::{apply_opacity, mirror_frame};
use crate::{Animation, Bounds, Error, PlaybackMode, RenderMapping, RenderOptions, RgbaFrame};
use raster::{Texture, View};
use v38::Runtime;

/// The atlas texture's alpha encoding. Canvas dimensions are passed to `render`.
#[derive(Clone, Copy, Debug, Default)]
pub struct SpineOptions {
    /// Whether RGB in the atlas images is already multiplied by alpha.
    /// Spine 3.8 atlases do not record this; use the exporter's setting.
    pub premultiplied_alpha: bool,
}

/// One selected Spine animation, fitted to the requested transparent canvas.
///
/// Supports trusted Spine 3.8 `.skel` exports and their matching `.atlas` files.
/// Parsing uses the original C runtime; this is not a validator for untrusted or
/// corrupt binary assets. Other Spine versions and JSON exports are unsupported.
/// The default skin is used. No mixing, event callbacks or playback thread.
pub struct SpineAnimation {
    runtime: Runtime,
    textures: Vec<Texture>,
    animations: Vec<(String, Duration)>,
    selected: usize,
    playback_mode: PlaybackMode,
    // Minimum and maximum animation-space coordinates across the selected clip.
    bounds: [[f32; 2]; 2],
    pixels: Vec<[f32; 4]>,
    frame: Option<RgbaFrame>,
}

impl SpineAnimation {
    /// Load a skeleton and atlas, selecting the first animation.
    /// Texture paths are relative to the atlas file.
    pub fn load(
        skeleton: impl AsRef<Path>,
        atlas: impl AsRef<Path>,
        options: SpineOptions,
    ) -> Result<Self, Error> {
        let data = fs::read(skeleton)?;
        let atlas = atlas.as_ref();
        let runtime = Runtime::load(&fs::read(atlas)?, &data)?;
        let directory = atlas.parent().unwrap_or_else(|| Path::new("."));
        let textures = runtime
            .pages()
            .into_iter()
            .map(|name| {
                Ok(Texture::new(
                    image::open(directory.join(name))?.into_rgba8(),
                    options.premultiplied_alpha,
                ))
            })
            .collect::<Result<Vec<_>, Error>>()?;
        let animations = runtime.animations()?;
        if animations.is_empty() {
            return Err(Error::Spine("skeleton has no animations".into()));
        }
        let mut source = Self {
            runtime,
            textures,
            animations,
            selected: 0,
            playback_mode: PlaybackMode::Loop,
            bounds: [[0.0; 2]; 2],
            pixels: Vec::new(),
            frame: None,
        };
        source.bounds = source.measure(0)?;
        Ok(source)
    }

    fn measure(&mut self, index: usize) -> Result<[[f32; 2]; 2], Error> {
        let mut min = [f32::INFINITY; 2];
        let mut max = [f32::NEG_INFINITY; 2];
        let duration = self.animations[index].1.as_secs_f32();
        for sample in 0..=120 {
            self.runtime.pose(index, duration * (sample as f32 / 120.0));
            self.runtime.meshes(|mesh| {
                for vertex in mesh.vertices.chunks_exact(2) {
                    for axis in 0..2 {
                        min[axis] = min[axis].min(vertex[axis]);
                        max[axis] = max[axis].max(vertex[axis]);
                    }
                }
            });
        }
        let (width, height) = (max[0] - min[0], max[1] - min[1]);
        if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
            return Err(Error::Spine(
                "animation has no visible region or mesh in the default skin".into(),
            ));
        }
        Ok([min, max])
    }

    fn automatic_view(&self, width: u32, height: u32) -> View {
        let [min, max] = self.bounds;
        let scale = (width as f32 / (max[0] - min[0])).min(height as f32 / (max[1] - min[1])) * 0.9;
        View {
            scale,
            offset: [
                width as f32 * 0.5 - (min[0] + max[0]) * 0.5 * scale,
                height as f32 * 0.5 + (min[1] + max[1]) * 0.5 * scale,
            ],
        }
    }
}

impl Animation for SpineAnimation {
    /// Exported names and durations. A zero-duration clip is a static pose.
    fn animations(&self) -> Box<dyn Iterator<Item = (&str, Duration)> + '_> {
        Box::new(
            self.animations
                .iter()
                .map(|(name, duration)| (name.as_str(), *duration)),
        )
    }

    fn animation_name(&self) -> &str {
        &self.animations[self.selected].0
    }

    /// Select a clip by name and measure its full motion at 121 points.
    /// Rendering fits these bounds to the requested canvas with 5% padding.
    /// Very brief excursions between samples can extend beyond that estimate.
    fn set_animation(&mut self, name: &str) -> Result<(), Error> {
        let index = self
            .animations
            .iter()
            .position(|(n, _)| n == name)
            .ok_or_else(|| Error::AnimationNotFound(name.into()))?;
        if index == self.selected {
            return Ok(());
        }
        let bounds = self.measure(index)?;
        self.selected = index;
        self.bounds = bounds;
        Ok(())
    }

    fn playback_mode(&self) -> PlaybackMode {
        self.playback_mode
    }

    fn set_playback_mode(&mut self, mode: PlaybackMode) {
        self.playback_mode = mode;
    }

    fn duration(&self) -> Duration {
        let duration = self.animations[self.selected].1;
        // Static poses still fulfill Animation's nonzero-cycle contract.
        if duration.is_zero() {
            Duration::from_secs(1)
        } else {
            duration
        }
    }

    fn clip_duration(&self) -> Duration {
        self.animations[self.selected].1
    }

    fn bounds(&self) -> Bounds {
        let [min, max] = self.bounds;
        Bounds {
            x: min[0] as f64,
            y: -max[1] as f64,
            width: max[0] as f64 - min[0] as f64,
            height: max[1] as f64 - min[1] as f64,
        }
    }

    fn mapping(
        &self,
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<RenderMapping, Error> {
        if options.view.is_some() {
            return RenderMapping::fit(self.bounds(), width, height, options);
        }
        let view = self.automatic_view(width, height);
        RenderMapping::new(
            [view.scale as f64; 2],
            view.offset.map(f64::from),
            width,
            height,
            options,
        )
    }

    fn render_with_options(
        &mut self,
        elapsed: Duration,
        width: u32,
        height: u32,
        options: &RenderOptions,
    ) -> Result<&RgbaFrame, Error> {
        options.validate()?;
        let mirror = options.transform.canvas_mirror(width, height);
        let base_options = RenderOptions {
            transform: if mirror.is_some() {
                Default::default()
            } else {
                options.transform
            },
            ..*options
        };
        let pixels_len = RgbaFrame::byte_len(width, height)? / 4;
        if pixels_len > isize::MAX as usize / std::mem::size_of::<[f32; 4]>() {
            return Err(Error::InvalidFrame("dimensions exceed addressable memory"));
        }
        let nanos = self
            .playback_mode
            .sample_time(elapsed, self.clip_duration())
            .as_nanos();
        let time = nanos as f64 / 1_000_000_000.0;
        let view = self.automatic_view(width, height);
        let mapping = if options.view.is_some() || !base_options.transform.is_identity() {
            Some(self.mapping(width, height, &base_options)?)
        } else {
            None
        };
        let frame = RgbaFrame::prepare_buffer(&mut self.frame, width, height)?;
        if options.opacity == 0.0 {
            // All inputs are validated; absolute sampling has no pose history.
            frame.pixels_mut().fill(0);
            return Ok(frame);
        }
        self.pixels.resize(pixels_len, [0.0; 4]);
        self.runtime.pose(self.selected, time as f32);
        self.pixels.fill([0.0; 4]);
        let width = width as usize;
        let height = height as usize;
        if let Some(mapping) = mapping {
            self.runtime.meshes(|mesh| {
                raster::draw_transformed(
                    &mut self.pixels,
                    width,
                    height,
                    &self.textures[mesh.page],
                    mesh,
                    mapping,
                );
            });
        } else {
            self.runtime.meshes(|mesh| {
                raster::draw(
                    &mut self.pixels,
                    width,
                    height,
                    &self.textures[mesh.page],
                    mesh,
                    view,
                );
            });
        }
        for (source, target) in self
            .pixels
            .iter()
            .zip(frame.pixels_mut().chunks_exact_mut(4))
        {
            let alpha = source[3];
            if alpha > 0.0 {
                for c in 0..3 {
                    target[c] = rounded_byte(source[c] / alpha * 255.0);
                }
                target[3] = rounded_byte(alpha * 255.0);
            } else {
                target.fill(0);
            }
        }
        if let Some(axes) = mirror {
            mirror_frame(frame, axes);
        }
        apply_opacity(frame, options.opacity);
        Ok(frame)
    }
}

fn rounded_byte(value: f32) -> u8 {
    // Widen before adding: f32 addition could round a value just below a
    // half integer up to the next integer. The cast saturates to 0..=255.
    (value as f64 + 0.5) as u8
}

#[cfg(test)]
mod tests {
    use super::rounded_byte;

    #[test]
    fn rgba_channels_round_at_half_integers_and_saturate() {
        for lower in 0..=254u8 {
            let half = lower as f32 + 0.5;
            assert_eq!(rounded_byte(f32::from_bits(half.to_bits() - 1)), lower);
            assert_eq!(rounded_byte(half), lower + 1);
            assert_eq!(rounded_byte(f32::from_bits(half.to_bits() + 1)), lower + 1);
        }
        for (value, expected) in [
            (f32::NEG_INFINITY, 0),
            (f32::MIN, 0),
            (-0.5, 0),
            (-0.0, 0),
            (0.0, 0),
            (255.0, 255),
            (255.5, 255),
            (f32::MAX, 255),
            (f32::INFINITY, 255),
            (f32::NAN, 0),
        ] {
            assert_eq!(rounded_byte(value), expected);
        }
    }
}