Address PR59 review: axolotl timers, fluid and fire parity, persistence and Rust tests

This commit is contained in:
Cosmic
2026-10-14 10:05:41 -04:00
parent 726f88fcfc
commit f3dda9c412
22 changed files with 730 additions and 365 deletions
-93
View File
@@ -1,93 +0,0 @@
"""Compile the actual drop and ignition branches with world effects stubbed."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def block(source, start):
opening = source.index("{", start)
depth, end = 1, opening + 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
class ItemActionAnimationTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is required for action-policy tests")
def test_successful_drop_and_ignition_start_a_swing(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
drop = block(source, source.index("fn drop_held("))
ignition = block(source, source.index("if self.can_place_used_fire(target)"))
caller_start = source.index(" let swings = self.swings_started;", source.index("fn use_item_as_player("))
caller = source[caller_start:source.index(" if self.use_potion_item", caller_start)]
program = """
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
enum UseResult { Pass, Fail, Success { swing: bool } }
#[derive(Clone)] struct ItemStack { count: u32, item: String }
struct Hit { pos: [i32; 3], face: [i32; 3] }
struct Facts; impl Facts { fn is_air(&self, state:u8)->bool { state == 0 } }
struct Res { facts:Facts }
struct Random; impl Random { fn next_float(&mut self)->f32 { 0.5 } }
struct World { air:bool, path:bool, random:Random }
impl World { fn block(&self,_:i32,_:i32,_:i32)->u8 { if self.air {0} else {1} } }
struct Audio { sounds:u32 } impl Audio { fn play(&mut self,_:&str,_:Option<[f64;3]>,_:f32,_:f32) {self.sounds+=1;} }
struct Game { selected:usize, inventory:[Option<ItemStack>;1], alive:bool, swings:u32, drops:u32, res:Res, world:World, audio:Audio }
impl Game {
DROP
fn ignite(&mut self,item:&str)->Result<()> {
let stack=ItemStack {count:1,item:item.into()};
CALLER
Ok(())
}
fn use_tool(&mut self,stack:&ItemStack)->Result<UseResult> {
let item=stack.item.as_str();
let hit = Hit { pos:[0;3], face:[0,1,0] };
let at = |p:[i32;3]| p.map(f64::from);
let target = [0,1,0];
IGNITION
Ok(UseResult::Fail)
}
fn eye_position(&self)->Option<[f64;3]> { self.alive.then_some([0.0;3]) }
fn player_drop(&mut self,stack:ItemStack) { self.drops += stack.count; }
fn swing_arm(&mut self) { self.swings += 1; }
fn try_light_portal(&mut self,_:[i32;3])->Result<bool> {Ok(false)}
fn may_build(&self)->bool {true}
fn can_place_used_fire(&self,_:[i32;3])->bool {self.world.air&&!self.world.path}
fn place_used_fire(&mut self,_:[i32;3])->Result<()> {Ok(())}
fn consume_held(&mut self) {} fn damage_held(&mut self,_:u32) {}
}
fn game()->Game { Game { selected:0, inventory:[Some(ItemStack { count:4,item:"minecraft:stone".into() })], alive:true, swings:0, drops:0, res:Res {facts:Facts}, world:World {air:true,path:false,random:Random}, audio:Audio {sounds:0} } }
#[test] fn dropping_one_and_all_swings_only_on_success() {
let mut g=game();g.drop_held(false);assert_eq!((g.drops,g.swings),(1,1));
g.drop_held(true);assert_eq!((g.drops,g.swings),(4,2));
g.drop_held(false);assert_eq!(g.swings,2);
let mut g=game();g.alive=false;g.drop_held(false);assert_eq!(g.swings,0);
}
#[test] fn successful_ignition_swings_but_blocked_ignition_does_not() {
for item in ["flint_and_steel","fire_charge"] {
let mut g=game();g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(1,1));
let mut g=game();g.world.air=false;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0));
let mut g=game();g.world.path=true;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0));
}
}
""".replace("DROP", drop).replace("IGNITION", ignition).replace("CALLER", caller)
program = program.replace("self.swings_started", "self.swings")
with tempfile.TemporaryDirectory(prefix="horizon-item-action-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
compiled = subprocess.run(
["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
capture_output=True, text=True, check=False,
)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
tested = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr)
if __name__ == "__main__":
unittest.main()
-71
View File
@@ -1,71 +0,0 @@
"""Exercise the actual animation uploader with a recording queue, without a GPU/window."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from test_item_action_animation import block
ROOT = Path(__file__).resolve().parents[1]
class SpriteAnimationUploadTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is required")
def test_animation_updates_entire_layer_and_every_mip(self):
source = (ROOT / "crates/horizon-client/src/gfx.rs").read_text()
animate = block(source, source.index("fn animate(&mut self, tick: u64)"))
mips = block(source, source.index("fn mip_chain("))
program = r"""
use std::cell::RefCell;
mod wgpu {
pub struct Texture(pub u32);
impl Texture {pub fn width(&self)->u32 {self.0}}
pub struct Origin3d {pub x:u32,pub y:u32,pub z:u32}
pub enum TextureAspect {All}
pub struct TexelCopyTextureInfo<LIFETIME> {
pub texture:&LIFETIME Texture,pub mip_level:u32,pub origin:Origin3d,pub aspect:TextureAspect,
}
pub struct TexelCopyBufferLayout {pub offset:u64,pub bytes_per_row:Option<u32>,pub rows_per_image:Option<u32>}
pub struct Extent3d {pub width:u32,pub height:u32,pub depth_or_array_layers:u32}
}
struct Queue {writes:RefCell<Vec<Vec<u8>>>}
impl Queue {
fn write_texture(&self, info:wgpu::TexelCopyTextureInfo, pixels:&[u8], layout:wgpu::TexelCopyBufferLayout, extent:wgpu::Extent3d) {
let size=info.texture.width() >> info.mip_level;
assert_eq!((extent.width,extent.height,extent.depth_or_array_layers),(size,size,1),"animation must update the entire mip, not a quarter");
assert_eq!((layout.bytes_per_row,layout.rows_per_image,layout.offset),(Some(size*4),Some(size),0));
assert_eq!((info.origin.x,info.origin.y,info.origin.z),(0,0,7));
assert_eq!(pixels.len(),(size*size*4) as usize);
self.writes.borrow_mut().push(pixels.to_vec());
}
}
struct Animation {layer:u32,pixels:Vec<u8>}
impl Animation {fn frame(&self,tick:u64)->usize {if tick==0 {0} else {1}} fn pixels(&self,_:usize)->&[u8] {&self.pixels}}
struct Gfx {animations:Vec<(Animation,usize)>,mip_levels:u32,sprite_texture:wgpu::Texture,queue:Queue}
MIPS
impl Gfx {ANIMATE}
fn main() {
for size in [16u32,32] {
let pixels:Vec<u8>=(0..size*size).flat_map(|i|[(i%size) as u8,(i/size) as u8,99,255]).collect();
let (expected,levels)=mip_chain(&pixels,size,1);
let mut gfx=Gfx {animations:vec![(Animation {layer:7,pixels:pixels.clone()},0)],mip_levels:levels,sprite_texture:wgpu::Texture(size),queue:Queue {writes:RefCell::default()}};
gfx.animate(0);assert!(gfx.queue.writes.borrow().is_empty());
gfx.animate(1);
assert_eq!(gfx.queue.writes.borrow().len(),levels as usize);
assert_eq!(gfx.queue.writes.borrow()[0],pixels,"the bottom-right texel must animate too");
assert_eq!(gfx.queue.writes.borrow().concat(),expected);
gfx.animate(1);assert_eq!(gfx.queue.writes.borrow().len(),levels as usize);
}
}
""".replace("LIFETIME", chr(39)+"a").replace("MIPS", mips).replace("ANIMATE", animate)
with tempfile.TemporaryDirectory(prefix="horizon-animation-upload-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
subprocess.run(["rustc", "--edition=2024", "-Awarnings", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True)
result = subprocess.run([str(path / "probe")], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
"""The actual world-entry reset must invalidate previously loaded player progress."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def run_reset(source):
start = source.index(" self.persist = Default::default();", source.index(" fn open_world("))
reset = source[start:source.index(" // RandomSequences", start)]
program = """
#[derive(Default)] struct Game {persist:bool,score:bool,fns:bool,bosses:bool,adv:bool,stats:bool}
impl Game {fn enter_world(&mut self) {RESET}}
fn main() {
let mut game=Game {persist:true,score:true,fns:true,bosses:true,adv:true,stats:true};
game.enter_world();
assert!(!game.adv,"loaded advancement progress must not survive world entry");
assert!(!game.stats,"loaded statistics must not survive world entry");
}
""".replace("RESET", reset)
with tempfile.TemporaryDirectory(prefix="horizon-world-reset-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
subprocess.run(["rustc", "--edition=2024", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True)
return subprocess.run([str(path / "probe")], capture_output=True, text=True)
class WorldRuntimeResetTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is required")
def test_world_entry_invalidates_loaded_progress(self):
result = run_reset((ROOT / "crates/horizon-client/src/game.rs").read_text())
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()