anitty 0.1.0

Anime character animation rendering for terminals
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::{ops::Range, time::Duration};

use super::render::{apply_opacity, mirror_frame};
use crate::{Animation, Bounds, Error, PlaybackMode, RenderMapping, RenderOptions, RgbaFrame};

/// A named, contiguous range of source frames with a fixed duration per frame.
/// Ranges are zero-based and end-exclusive; clips may overlap. Definitions are
/// validated by [`SpriteAnimation::set_clips`], and do not own pixel data.
#[derive(Clone, Debug)]
pub struct SpriteClip {
    pub name: String,
    pub frames: Range<usize>,
    pub frame_duration: Duration,
}

/// Equally sized source frames with selectable named clips.
/// Native-sized rendering borrows the original frame. Other sizes use centered,
/// proportional bilinear resampling in premultiplied alpha, with transparent padding.
#[derive(Debug)]
pub struct SpriteAnimation {
    frames: Vec<RgbaFrame>,
    clips: Vec<(SpriteClip, Duration)>,
    selected: usize,
    playback_mode: PlaybackMode,
    output: Option<RgbaFrame>,
}

impl SpriteAnimation {
    /// Create a single clip named `default` containing all decoded frames.
    /// Use [`Self::set_clips`] to define multiple clips over the same frames.
    pub fn new(frames: Vec<RgbaFrame>, frame_duration: Duration) -> Result<Self, Error> {
        let first = frames.first().ok_or(Error::InvalidSprite("no frames"))?;
        if frames
            .iter()
            .any(|frame| frame.width() != first.width() || frame.height() != first.height())
        {
            return Err(Error::InvalidSprite(
                "all frames must have the same dimensions",
            ));
        }
        let count = frames.len();
        let mut source = Self {
            frames,
            clips: Vec::new(),
            selected: 0,
            playback_mode: PlaybackMode::Loop,
            output: None,
        };
        source.set_clips(vec![SpriteClip {
            name: "default".into(),
            frames: 0..count,
            frame_duration,
        }])?;
        Ok(source)
    }

    /// Replace all clip definitions and select the first one. Does not copy or
    /// reload source pixels or change playback mode. Names must be nonempty and
    /// unique; ranges must be nonempty and within the source frames; durations
    /// must be nonzero and fit in [`Duration`]. On error, definitions and selection
    /// remain unchanged.
    pub fn set_clips(&mut self, clips: Vec<SpriteClip>) -> Result<(), Error> {
        if clips.is_empty() {
            return Err(Error::InvalidSprite("no clips"));
        }
        let mut validated: Vec<(SpriteClip, Duration)> = Vec::with_capacity(clips.len());
        for clip in clips {
            if clip.name.is_empty() || validated.iter().any(|(c, _)| c.name == clip.name) {
                return Err(Error::InvalidSprite(
                    "clip names must be nonempty and unique",
                ));
            }
            if clip.frames.is_empty() || clip.frames.end > self.frames.len() {
                return Err(Error::InvalidSprite(
                    "clip range must be nonempty and within source frames",
                ));
            }
            if clip.frame_duration.is_zero() {
                return Err(Error::InvalidSprite("frame duration must be nonzero"));
            }
            let count = u32::try_from(clip.frames.len())
                .map_err(|_| Error::InvalidSprite("too many frames"))?;
            let duration = clip
                .frame_duration
                .checked_mul(count)
                .ok_or(Error::InvalidSprite("animation duration is too large"))?;
            validated.push((clip, duration));
        }
        self.clips = validated;
        self.selected = 0;
        Ok(())
    }

    /// Slice a regular grid left-to-right, then top-to-bottom.
    ///
    /// The sheet must be an exact multiple of the frame dimensions, with no
    /// margins or padding. Every grid cell becomes one frame.
    pub fn from_sheet(
        sheet: RgbaFrame,
        frame_width: u32,
        frame_height: u32,
        frame_duration: Duration,
    ) -> Result<Self, Error> {
        if frame_width == 0 || frame_height == 0 {
            return Err(Error::InvalidSprite("frame dimensions must be nonzero"));
        }
        if sheet.width() % frame_width != 0 || sheet.height() % frame_height != 0 {
            return Err(Error::InvalidSprite(
                "sheet dimensions must be multiples of frame dimensions",
            ));
        }
        if frame_duration.is_zero() {
            return Err(Error::InvalidSprite("frame duration must be nonzero"));
        }
        let mut frames = Vec::new();
        let sheet_stride = sheet.width() as usize * 4;
        let frame_stride = frame_width as usize * 4;
        for row in 0..sheet.height() / frame_height {
            for column in 0..sheet.width() / frame_width {
                let mut pixels = Vec::with_capacity(frame_stride * frame_height as usize);
                for y in row * frame_height..(row + 1) * frame_height {
                    let start = y as usize * sheet_stride + column as usize * frame_stride;
                    pixels.extend_from_slice(&sheet.pixels()[start..start + frame_stride]);
                }
                frames.push(RgbaFrame::new(frame_width, frame_height, pixels)?);
            }
        }
        Self::new(frames, frame_duration)
    }
}

impl Animation for SpriteAnimation {
    fn animations(&self) -> Box<dyn Iterator<Item = (&str, Duration)> + '_> {
        Box::new(
            self.clips
                .iter()
                .map(|(clip, duration)| (clip.name.as_str(), *duration)),
        )
    }

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

    fn set_animation(&mut self, name: &str) -> Result<(), Error> {
        let index = self
            .clips
            .iter()
            .position(|(clip, _)| clip.name == name)
            .ok_or_else(|| Error::AnimationNotFound(name.into()))?;
        self.selected = index;
        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 {
        self.clips[self.selected].1
    }

    fn bounds(&self) -> Bounds {
        Bounds {
            x: 0.0,
            y: 0.0,
            width: self.frames[0].width() as f64,
            height: self.frames[0].height() 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 Bounds {
            width: sw,
            height: sh,
            ..
        } = self.bounds();
        let scale = (width as f64 / sw).min(height as f64 / sh);
        let fw = (sw * scale).round().max(1.0) as u32;
        let fh = (sh * scale).round().max(1.0) as u32;
        // Validate before integer subtraction for zero-sized canvases.
        RgbaFrame::byte_len(width, height)?;
        RenderMapping::new(
            [fw as f64 / sw, fh as f64 / sh],
            [((width - fw) / 2) as f64, ((height - fh) / 2) as f64],
            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 clip = &self.clips[self.selected].0;
        let index = elapsed.as_nanos() / clip.frame_duration.as_nanos();
        let index = match self.playback_mode {
            PlaybackMode::Loop => index % clip.frames.len() as u128,
            PlaybackMode::Once => index.min(clip.frames.len() as u128 - 1),
        };
        let transformed = options.view.is_some() || !base_options.transform.is_identity();
        let mapping = if transformed {
            Some(self.mapping(width, height, &base_options)?)
        } else {
            None
        };
        let source = &self.frames[clip.frames.start + index as usize];
        let native_size = width == source.width() && height == source.height();
        if !transformed && native_size && options.opacity == 1.0 && mirror == Some([false; 2]) {
            return Ok(source);
        }
        let output = RgbaFrame::prepare_buffer(&mut self.output, width, height)?;
        if options.opacity == 0.0 {
            output.pixels_mut().fill(0);
            return Ok(output);
        }
        if let Some(mapping) = mapping {
            transform_frame(source, output, mapping);
        } else if native_size {
            output.pixels_mut().copy_from_slice(source.pixels());
        } else {
            scale_frame(source, output);
        }
        if let Some(axes) = mirror {
            mirror_frame(output, axes);
        }
        apply_opacity(output, options.opacity);
        Ok(output)
    }
}

fn transform_frame(source: &RgbaFrame, target: &mut RgbaFrame, mapping: RenderMapping) {
    let (sw, sh) = (source.width() as usize, source.height() as usize);
    let (width, height) = (target.width() as usize, target.height() as usize);
    target.pixels_mut().fill(0);
    let corners = [
        [0.0, 0.0],
        [sw as f64, 0.0],
        [0.0, sh as f64],
        [sw as f64, sh as f64],
    ]
    .map(|point| mapping.map_point(point));
    let min: [usize; 2] = std::array::from_fn(|axis| {
        corners
            .iter()
            .map(|p| p[axis])
            .fold(f64::INFINITY, f64::min)
            .floor()
            .max(0.0) as usize
    });
    let max: [usize; 2] = std::array::from_fn(|axis| {
        corners
            .iter()
            .map(|p| p[axis])
            .fold(f64::NEG_INFINITY, f64::max)
            .ceil()
            .clamp(0.0, [width, height][axis] as f64) as usize
    });
    for y in min[1]..max[1] {
        for x in min[0]..max[0] {
            let [sx, sy] = mapping.unmap_point([x as f64 + 0.5, y as f64 + 0.5]);
            if sx < 0.0 || sy < 0.0 || sx >= sw as f64 || sy >= sh as f64 {
                continue;
            }
            let sx = (sx - 0.5).clamp(0.0, (sw - 1) as f64);
            let sy = (sy - 0.5).clamp(0.0, (sh - 1) as f64);
            let (x0, y0) = (sx as usize, sy as usize);
            let (x1, y1) = ((x0 + 1).min(sw - 1), (y0 + 1).min(sh - 1));
            let texel =
                |x: usize, y: usize| &source.pixels()[(y * sw + x) * 4..(y * sw + x + 1) * 4];
            let pixel = &mut target.pixels_mut()[(y * width + x) * 4..(y * width + x + 1) * 4];
            let (fx, fy) = (sx - x0 as f64, sy - y0 as f64);
            if fx == 0.0 && fy == 0.0 {
                pixel.copy_from_slice(texel(x0, y0));
                continue;
            }
            interpolate(
                [texel(x0, y0), texel(x1, y0), texel(x0, y1), texel(x1, y1)],
                fx,
                fy,
                pixel,
            );
        }
    }
}

#[inline]
fn interpolate(texels: [&[u8]; 4], fx: f64, fy: f64, pixel: &mut [u8]) {
    if texels.iter().all(|texel| texel[3] == 0) {
        return;
    }
    let samples = [
        (texels[0], (1.0 - fx) * (1.0 - fy)),
        (texels[1], fx * (1.0 - fy)),
        (texels[2], (1.0 - fx) * fy),
        (texels[3], fx * fy),
    ];
    let samples = samples.map(|(texel, weight)| (texel, texel[3] as f64 * weight));
    // Interpolate premultiplied color, then return straight RGBA8. Keep each
    // sum's order consistent with the default fit path.
    let alpha = samples
        .iter()
        .fold(0.0, |sum, (_, weighted_alpha)| sum + weighted_alpha);
    if alpha > 0.0 {
        for c in 0..3 {
            let color = samples.iter().fold(0.0, |sum, (texel, weighted_alpha)| {
                sum + texel[c] as f64 * weighted_alpha
            });
            pixel[c] = rounded_byte(color / alpha);
        }
        pixel[3] = rounded_byte(alpha);
    }
}

fn scale_frame(source: &RgbaFrame, target: &mut RgbaFrame) {
    // Keep the measured default hot loop intact. The general transform path
    // uses interpolate separately so extra controls do not slow this loop down.
    let (sw, sh) = (source.width() as usize, source.height() as usize);
    let (width, height) = (target.width() as usize, target.height() as usize);
    let scale = (width as f64 / sw as f64).min(height as f64 / sh as f64);
    let fitted_width = ((sw as f64 * scale).round() as usize).max(1);
    let fitted_height = ((sh as f64 * scale).round() as usize).max(1);
    let left = (width - fitted_width) / 2;
    let top = (height - fitted_height) / 2;
    target.pixels_mut().fill(0);
    // At this size, (x + 0.5) * sw and (y + 0.5) * sh are exact in f64,
    // so identity resampling selects only the original texel.
    if fitted_width == sw && fitted_height == sh && sw.max(sh) <= 1 << 26 {
        for (source_row, target_row) in source
            .pixels()
            .chunks_exact(sw * 4)
            .zip(target.pixels_mut().chunks_exact_mut(width * 4).skip(top))
        {
            for (texel, pixel) in source_row
                .chunks_exact(4)
                .zip(target_row[left * 4..(left + sw) * 4].chunks_exact_mut(4))
            {
                if texel[3] != 0 {
                    pixel.copy_from_slice(texel);
                }
            }
        }
        return;
    }
    for (y, row) in target
        .pixels_mut()
        .chunks_exact_mut(width * 4)
        .skip(top)
        .take(fitted_height)
        .enumerate()
    {
        let sy =
            ((y as f64 + 0.5) * sh as f64 / fitted_height as f64 - 0.5).clamp(0.0, (sh - 1) as f64);
        let y0 = sy as usize;
        let y1 = (y0 + 1).min(sh - 1);
        let fy = sy - y0 as f64;
        let row0 = &source.pixels()[y0 * sw * 4..(y0 + 1) * sw * 4];
        let row1 = &source.pixels()[y1 * sw * 4..(y1 + 1) * sw * 4];
        for (x, pixel) in row[left * 4..(left + fitted_width) * 4]
            .chunks_exact_mut(4)
            .enumerate()
        {
            let sx = ((x as f64 + 0.5) * sw as f64 / fitted_width as f64 - 0.5)
                .clamp(0.0, (sw - 1) as f64);
            let x0 = sx as usize;
            let x1 = (x0 + 1).min(sw - 1);
            let texels = [
                &row0[x0 * 4..x0 * 4 + 4],
                &row0[x1 * 4..x1 * 4 + 4],
                &row1[x0 * 4..x0 * 4 + 4],
                &row1[x1 * 4..x1 * 4 + 4],
            ];
            // Invisible RGB contributes nothing when all four alphas are zero.
            if texels.iter().all(|texel| texel[3] == 0) {
                continue;
            }
            let fx = sx - x0 as f64;
            let samples = [
                (texels[0], (1.0 - fx) * (1.0 - fy)),
                (texels[1], fx * (1.0 - fy)),
                (texels[2], (1.0 - fx) * fy),
                (texels[3], fx * fy),
            ];
            let samples = samples.map(|(texel, weight)| (texel, texel[3] as f64 * weight));
            let alpha = samples
                .iter()
                .fold(0.0, |sum, (_, weighted_alpha)| sum + weighted_alpha);
            // Interpolate premultiplied color, then return straight RGBA8.
            // Preserve each sum's order; zero alpha needs no RGB calculation.
            if alpha > 0.0 {
                for c in 0..3 {
                    let color = samples.iter().fold(0.0, |sum, (texel, weighted_alpha)| {
                        sum + texel[c] as f64 * weighted_alpha
                    });
                    pixel[c] = rounded_byte(color / alpha);
                }
                pixel[3] = rounded_byte(alpha);
            }
        }
    }
}

fn rounded_byte(value: f64) -> u8 {
    // Subtracting the truncated byte is exact within [0, 255]. Adding 0.5
    // instead could round a value just below a half integer up to the boundary.
    let integer = value as u8;
    integer.saturating_add(u8::from(value - f64::from(integer) >= 0.5))
}

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

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