use std::{ops::Range, time::Duration};
use super::render::{apply_opacity, mirror_frame};
use crate::{Animation, Bounds, Error, PlaybackMode, RenderMapping, RenderOptions, RgbaFrame};
#[derive(Clone, Debug)]
pub struct SpriteClip {
pub name: String,
pub frames: Range<usize>,
pub frame_duration: Duration,
}
#[derive(Debug)]
pub struct SpriteAnimation {
frames: Vec<RgbaFrame>,
clips: Vec<(SpriteClip, Duration)>,
selected: usize,
playback_mode: PlaybackMode,
output: Option<RgbaFrame>,
}
impl SpriteAnimation {
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)
}
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(())
}
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;
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));
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) {
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);
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],
];
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);
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 {
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);
}
}
}