Interpolate animated textures like vanilla (prismarine, magma, stems, lit furnaces)
SpriteContents.AnimationState.drawToAtlas mixes an animation with "interpolate": true towards its next frame every tick (animate_sprite_interpolate.fsh: mix(current, next, subFrame / time), per mip level, into the 8-bit atlas). Horizon stepped the frames: the sprite upload now mixes the two frames' mip chains the same way and re-uploads every tick while the mix changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2749,7 +2749,8 @@ const ANIMATION_MIP_ENTRIES: usize = 4096;
|
||||
/// renderer on resource reload drops this entire snapshot, including its cache:
|
||||
/// frame indices can never alias another resource's pixels, size or settings.
|
||||
struct AnimatedSprites {
|
||||
animations: Vec<(SpriteAnimation, usize)>,
|
||||
/// Each animated sprite and what its layer holds (`None`: not uploaded yet).
|
||||
animations: Vec<(SpriteAnimation, Option<crate::sprites::FrameBlend>)>,
|
||||
size: u32,
|
||||
settings: Vec<crate::mipmap::Settings>,
|
||||
// Cache bookkeeping must not consume randomness or affect other maps' seeding.
|
||||
@@ -2765,11 +2766,7 @@ impl AnimatedSprites {
|
||||
settings: &[crate::mipmap::Settings],
|
||||
) -> Self {
|
||||
Self {
|
||||
animations: animations
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|a| (a, usize::MAX))
|
||||
.collect(),
|
||||
animations: animations.iter().cloned().map(|a| (a, None)).collect(),
|
||||
size,
|
||||
settings: settings.to_vec(),
|
||||
cache: Default::default(),
|
||||
@@ -2786,35 +2783,53 @@ fn animate_sprites(
|
||||
) {
|
||||
let size = state.size;
|
||||
let levels = size.trailing_zeros() + 1;
|
||||
for (index, (animation, previous)) in state.animations.iter_mut().enumerate() {
|
||||
let frame = animation.frame(tick);
|
||||
if frame == *previous {
|
||||
let AnimatedSprites {
|
||||
animations,
|
||||
settings,
|
||||
cache,
|
||||
cache_bytes,
|
||||
budget,
|
||||
..
|
||||
} = state;
|
||||
for (index, (animation, previous)) in animations.iter_mut().enumerate() {
|
||||
let blend = animation.blend(tick);
|
||||
if *previous == Some(blend) {
|
||||
continue;
|
||||
}
|
||||
*previous = frame;
|
||||
let room = state.cache.len() < ANIMATION_MIP_ENTRIES;
|
||||
let uncached;
|
||||
let mips: &[u8] = match state.cache.entry((index, frame)) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
let (pixels, _) = mip_chain(
|
||||
animation.pixels(frame),
|
||||
size,
|
||||
&state.settings,
|
||||
animation.layer,
|
||||
1,
|
||||
);
|
||||
// Bound both pixel storage and map metadata. Keep admitted
|
||||
// frames rather than churning them on large/unique workloads;
|
||||
// frames that do not fit still use the same generation path.
|
||||
if room && pixels.capacity() <= state.budget - state.cache_bytes {
|
||||
state.cache_bytes += pixels.capacity();
|
||||
entry.insert(pixels)
|
||||
} else {
|
||||
uncached = pixels;
|
||||
&uncached
|
||||
}
|
||||
}
|
||||
*previous = Some(blend);
|
||||
let (animation, settings) = (&*animation, &**settings);
|
||||
let chain = |frame: usize| {
|
||||
move || mip_chain(animation.pixels(frame), size, settings, animation.layer, 1).0
|
||||
};
|
||||
let (current, mixed);
|
||||
let mips: &[u8] = if blend.millis > 0 {
|
||||
let mut mix = frame_mips(
|
||||
cache,
|
||||
cache_bytes,
|
||||
*budget,
|
||||
(index, blend.frame),
|
||||
chain(blend.frame),
|
||||
)
|
||||
.into_owned();
|
||||
let next = frame_mips(
|
||||
cache,
|
||||
cache_bytes,
|
||||
*budget,
|
||||
(index, blend.next),
|
||||
chain(blend.next),
|
||||
);
|
||||
mix_frames(&mut mix, &next, blend.millis);
|
||||
mixed = mix;
|
||||
&mixed
|
||||
} else {
|
||||
current = frame_mips(
|
||||
cache,
|
||||
cache_bytes,
|
||||
*budget,
|
||||
(index, blend.frame),
|
||||
chain(blend.frame),
|
||||
);
|
||||
¤t
|
||||
};
|
||||
let mut offset = 0;
|
||||
for level in 0..levels.min(max_levels) {
|
||||
@@ -2825,6 +2840,40 @@ fn animate_sprites(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `animate_sprite_interpolate.fsh`: `mix(current, next, millis / 1000)` per
|
||||
/// channel of every mipmap level, stored as 8-bit unorm.
|
||||
/// One frame's mip chain: from the cache, or generated and kept while the budget has room.
|
||||
/// Frames that do not fit still go through the same generation path.
|
||||
fn frame_mips<'a>(
|
||||
cache: &'a mut crate::fast_hash::FxHashMap<(usize, usize), Vec<u8>>,
|
||||
cache_bytes: &mut usize,
|
||||
budget: usize,
|
||||
key: (usize, usize),
|
||||
generate: impl FnOnce() -> Vec<u8>,
|
||||
) -> std::borrow::Cow<'a, [u8]> {
|
||||
let room = cache.len() < ANIMATION_MIP_ENTRIES;
|
||||
match cache.entry(key) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut().as_slice().into(),
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
let pixels = generate();
|
||||
// Bound both pixel storage and map metadata. Keep admitted frames
|
||||
// rather than churning them on large/unique workloads.
|
||||
if room && pixels.capacity() <= budget - *cache_bytes {
|
||||
*cache_bytes += pixels.capacity();
|
||||
entry.insert(pixels).as_slice().into()
|
||||
} else {
|
||||
pixels.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) {
|
||||
let t = millis as f32 / 1000.0;
|
||||
for (c, n) in current.iter_mut().zip(next) {
|
||||
let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0);
|
||||
*c = ((a * (1.0 - t) + b * t) * 255.0).round() as u8;
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod sprite_upload_tests {
|
||||
use super::*;
|
||||
@@ -2843,7 +2892,7 @@ mod sprite_upload_tests {
|
||||
let settings = [];
|
||||
let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1);
|
||||
let mut animations = AnimatedSprites::new(&[animation], size, &settings);
|
||||
animations.animations[0].1 = 0;
|
||||
animations.animations[0].1 = Some(animations.animations[0].0.blend(0));
|
||||
let mut writes = Vec::new();
|
||||
let mut record = |layer, level, edge, data: &[u8]| {
|
||||
assert_eq!(layer, 7);
|
||||
@@ -2949,4 +2998,35 @@ mod sprite_upload_tests {
|
||||
});
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolated_animation_uploads_the_mix_every_tick() {
|
||||
let animation = crate::sprites::test_clip(16, 3, r#"{"frametime":4,"interpolate":true}"#);
|
||||
let settings = [];
|
||||
let (_, levels) = mip_chain(animation.pixels(0), 16, &settings, 3, 1);
|
||||
let mut cached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings);
|
||||
let mut uncached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings);
|
||||
uncached.budget = 0;
|
||||
for state in [&mut cached, &mut uncached] {
|
||||
state.animations[0].1 = Some(animation.blend(0));
|
||||
}
|
||||
let mut blues = Vec::new();
|
||||
let mut uncached_blues = Vec::new();
|
||||
let mut record = |_, level, _, data: &[u8]| {
|
||||
if level == 0 {
|
||||
blues.push(data[2]);
|
||||
}
|
||||
};
|
||||
for tick in [0, 1, 1, 2, 4] {
|
||||
animate_sprites(&mut cached, tick, levels, &mut record);
|
||||
animate_sprites(&mut uncached, tick, levels, |_, level, _, data: &[u8]| {
|
||||
if level == 0 {
|
||||
uncached_blues.push(data[2]);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Frame 0 is blue 0, frame 1 blue 99: a quarter, a half, then frame 1.
|
||||
assert_eq!(blues, [25, 50, 99]);
|
||||
assert_eq!(uncached_blues, blues);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,39 @@ pub struct SpriteAnimation {
|
||||
frames: Arc<Vec<Vec<u8>>>,
|
||||
clip: Arc<AnimationClip>,
|
||||
}
|
||||
/// What an animated sprite shows: `frame`, mixed `millis` thousandths of the
|
||||
/// way towards `next` (0 for a single frame).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FrameBlend {
|
||||
pub frame: usize,
|
||||
pub next: usize,
|
||||
pub millis: u32,
|
||||
}
|
||||
impl SpriteAnimation {
|
||||
pub fn frame(&self, tick: u64) -> usize {
|
||||
self.clip.sample(tick).frame as usize
|
||||
}
|
||||
/// `SpriteContents.AnimationState.drawToAtlas`: an animation with
|
||||
/// `interpolate` mixes the frame with the next one by
|
||||
/// `(int)(subFrame / time * 1000)` thousandths; others show the frame.
|
||||
pub fn blend(&self, tick: u64) -> FrameBlend {
|
||||
let sample = self.clip.sample(tick);
|
||||
let frame = sample.frame as usize;
|
||||
let next = sample.next_frame as usize;
|
||||
if self.clip.interpolates() && sample.interpolation_millis > 0 && next != frame {
|
||||
FrameBlend {
|
||||
frame,
|
||||
next,
|
||||
millis: sample.interpolation_millis,
|
||||
}
|
||||
} else {
|
||||
FrameBlend {
|
||||
frame,
|
||||
next: frame,
|
||||
millis: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn resized_pixels(&self, frame: usize, width: u32, height: u32) -> Vec<u8> {
|
||||
let source = self.pixels(frame);
|
||||
let side = (source.len() / 4).isqrt() as u32;
|
||||
@@ -254,12 +283,16 @@ impl Sprites {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation {
|
||||
test_clip(size, layer, r#"{"frametime":1,"frames":[0,1]}"#)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_clip(size: u32, layer: u32, metadata: &str) -> SpriteAnimation {
|
||||
let frame = |blue: u8| {
|
||||
(0..size * size)
|
||||
.flat_map(|i| [(i % size) as u8, (i / size) as u8, blue, 255])
|
||||
.collect()
|
||||
};
|
||||
let metadata = AnimationMetadata::from_json(r#"{"frametime":1,"frames":[0,1]}"#).unwrap();
|
||||
let metadata = AnimationMetadata::from_json(metadata).unwrap();
|
||||
SpriteAnimation {
|
||||
layer,
|
||||
frames: Arc::new(vec![frame(0), frame(99)]),
|
||||
@@ -408,4 +441,27 @@ mod tests {
|
||||
assert_eq!(animation.frame(tick), frame);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolated_animations_blend_towards_the_next_frame() {
|
||||
let animation = test_clip(16, 0, r#"{"frametime":4,"interpolate":true}"#);
|
||||
let blend = |frame, next, millis| FrameBlend {
|
||||
frame,
|
||||
next,
|
||||
millis,
|
||||
};
|
||||
for (tick, expected) in [
|
||||
(0, blend(0, 0, 0)),
|
||||
(1, blend(0, 1, 250)),
|
||||
(3, blend(0, 1, 750)),
|
||||
(4, blend(1, 1, 0)),
|
||||
(5, blend(1, 0, 250)),
|
||||
(8, blend(0, 0, 0)),
|
||||
] {
|
||||
assert_eq!(animation.blend(tick), expected, "tick {tick}");
|
||||
}
|
||||
let stepped = test_clip(16, 0, r#"{"frametime":4}"#);
|
||||
assert_eq!(stepped.blend(1), blend(0, 0, 0));
|
||||
assert_eq!(stepped.blend(5), blend(1, 1, 0));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user