voxels: add engine Rust tests and fix durable-item stacking
- Commit
e0c053c580581221a9e1c632a0287718d7a641aa- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 21:55 UTC (18 days ago)
- Parents
d07735e
40 new tests (135 -> 175): block table, world generator structures, inventory/crafting, net DTOs, blessings, texture atlas, input. Fix found by the tests: Inventory::move_item merged any same-id pair up to the stack cap, but for tools/armor the count is durability, so dragging one pickaxe onto another fused and deleted a tool; durable gear now swaps instead of merging. Line coverage 56.0% -> 61.6%. cargo test -p voxels_engine green.
Diff
games/voxels/src/main/rust/src/blessing.rs
diff --git a/games/voxels/src/main/rust/src/blessing.rs b/games/voxels/src/main/rust/src/blessing.rsindex ef39ee19dd..622eed1857 100644--- a/games/voxels/src/main/rust/src/blessing.rs+++ b/games/voxels/src/main/rust/src/blessing.rs@@ -191,3 +191,7 @@ mod tests { assert!(!a.attune(1065)); // a pickaxe } }++#[cfg(test)]+#[path = "blessing_tests.rs"]+mod blessing_tests;
games/voxels/src/main/rust/src/blessing_tests.rs
diff --git a/games/voxels/src/main/rust/src/blessing_tests.rs b/games/voxels/src/main/rust/src/blessing_tests.rsnew file mode 100644index 0000000000..537ed9ec2c--- /dev/null+++ b/games/voxels/src/main/rust/src/blessing_tests.rs@@ -0,0 +1,51 @@+//! JSON-facing blessing behaviour: the attunement summary the HUD reads+//! and the catalog the blessing screen lists.++use super::*;++#[test]+fn attunement_json_describes_each_slot() {+ let empty: serde_json::Value = serde_json::from_str(&Attunement::default().to_json()).unwrap();+ let slots = empty["slots"].as_array().unwrap();+ assert_eq!(slots.len(), SLOTS);+ assert!(slots.iter().all(|s| s["id"] == 0 && s["name"] == "" && s["effect"] == ""));++ let mut a = Attunement::default();+ assert!(a.attune(1056));+ assert!(a.attune(1145));+ let v: serde_json::Value = serde_json::from_str(&a.to_json()).unwrap();+ assert_eq!(v["slots"][0]["name"], "Blessing of Clement");+ assert_eq!(v["slots"][1]["name"], "Blessing of Anubis");+ assert_eq!(v["slots"][1]["effect"], find(1145).unwrap().effect);+ assert_eq!(v["slots"][2]["id"], 0, "the unbound slot stays blank");+}++#[test]+fn catalog_json_lists_the_whole_pantheon() {+ let v: serde_json::Value = serde_json::from_str(&catalog_json()).unwrap();+ let list = v.as_array().unwrap();+ assert_eq!(list.len(), PANTHEON.len());+ for (entry, blessing) in list.iter().zip(PANTHEON.iter()) {+ assert_eq!(entry["id"], blessing.id);+ assert_eq!(entry["name"], blessing.name);+ assert_eq!(entry["effect"], blessing.effect);+ }+}++#[test]+fn attunement_edges_are_total() {+ let mut a = Attunement::default();+ assert_eq!(a.release(0), None, "releasing an empty slot gives nothing");+ assert_eq!(a.release(SLOTS), None, "releasing past the end gives nothing, not a panic");+ assert_eq!(a.release(usize::MAX), None);+ // A corrupt slot id (not a blessing) is inert: it grants no passive and+ // cannot block attuning, but releasing it still returns the raw id.+ let mut corrupt = Attunement { slots: [9999, 0, 0] };+ assert!(!corrupt.has(Passive::Traversal));+ assert!(corrupt.contains(9999) && !corrupt.contains(1056));+ assert!(find(9999).is_none());+ assert!(find(0).is_none());+ assert!(!is_blessing(0) && is_blessing(PANTHEON[0].id));+ assert_eq!(corrupt.release(0), Some(9999));+ assert!(corrupt.attune(1056), "the freed slot can be bound again");+}
games/voxels/src/main/rust/src/input.rs
diff --git a/games/voxels/src/main/rust/src/input.rs b/games/voxels/src/main/rust/src/input.rsindex 449aa8a80d..0a152c9067 100644--- a/games/voxels/src/main/rust/src/input.rs+++ b/games/voxels/src/main/rust/src/input.rs@@ -74,3 +74,7 @@ mod tests { assert_eq!((b.look_dyaw, b.look_dpitch), (0.0, 0.0)); } }++#[cfg(test)]+#[path = "input_tests.rs"]+mod input_tests;
games/voxels/src/main/rust/src/input_tests.rs
diff --git a/games/voxels/src/main/rust/src/input_tests.rs b/games/voxels/src/main/rust/src/input_tests.rsnew file mode 100644index 0000000000..fe4a84eb3c--- /dev/null+++ b/games/voxels/src/main/rust/src/input_tests.rs@@ -0,0 +1,39 @@+//! Held-control state: setters clamp, persistent axes survive a frame+//! snapshot, and `release_all` drops everything held. These mutate the+//! process-global input state, so they hold the engine test lock and+//! leave the state released behind them.++use super::*;++#[test]+fn held_controls_clamp_snapshot_and_release() {+ let _serial = crate::engine::GLOBAL_ENGINE_TEST.lock();+ release_all();+ set_move(2.5, -7.0);+ set_look_rate(-3.0, 0.5);+ set_jump(true);+ set_down(true);+ set_sneak(true);+ let s = snapshot_and_clear_look();+ assert_eq!((s.move_right, s.move_forward), (1.0, -1.0), "move axes clamp to -1..=1");+ assert_eq!((s.look_yaw_rate, s.look_pitch_rate), (-1.0, 0.5), "look rates clamp to -1..=1");+ assert!(s.jump_held && s.down_held && s.sneak);+ // Held axes are persistent: a second snapshot still reports them.+ let again = snapshot_and_clear_look();+ assert_eq!(again.move_right, 1.0);+ assert!(again.jump_held);+ // The fly toggle is edge-triggered: reported once, then consumed.+ request_toggle_fly();+ assert!(snapshot_and_clear_look().toggle_fly);+ assert!(!snapshot_and_clear_look().toggle_fly, "the fly toggle must not re-fire");+ // Non-finite look deltas are ignored rather than poisoning the camera.+ add_look_delta(f32::INFINITY, 0.25);+ add_look_delta(0.25, f32::NEG_INFINITY);+ let clean = snapshot_and_clear_look();+ assert_eq!((clean.look_dyaw, clean.look_dpitch), (0.0, 0.0));+ release_all();+ let dropped = snapshot_and_clear_look();+ assert_eq!((dropped.move_forward, dropped.move_right, dropped.look_yaw_rate, dropped.look_pitch_rate), (0.0, 0.0, 0.0, 0.0));+ assert!(!dropped.jump_held && !dropped.down_held && !dropped.toggle_fly);+ set_sneak(false); // leave no state behind for other suites+}
games/voxels/src/main/rust/src/inventory.rs
diff --git a/games/voxels/src/main/rust/src/inventory.rs b/games/voxels/src/main/rust/src/inventory.rsindex 4cd15e23f7..90440567ef 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -283,4 +283,7 @@ impl Default for Inventory { } include!("inventory_part1.rs");-include!("inventory_part2.rs");\ No newline at end of file+include!("inventory_part2.rs");+#[cfg(test)]+#[path = "inventory_tests.rs"]+mod inventory_tests;
games/voxels/src/main/rust/src/inventory_part1.rs
diff --git a/games/voxels/src/main/rust/src/inventory_part1.rs b/games/voxels/src/main/rust/src/inventory_part1.rsindex 7c01b51b6b..7b39c74ff5 100644--- a/games/voxels/src/main/rust/src/inventory_part1.rs+++ b/games/voxels/src/main/rust/src/inventory_part1.rs@@ -30,7 +30,11 @@ impl Inventory { if a.id == 0 { return; } if b.id == 0 { self.slots[to] = a; self.slots[from] = InvSlot::default();- } else if a.id == b.id {+ } else if a.id == b.id && !crate::item::has_durability(a.id) {+ // Only stackables merge. A durable item's count is its remaining+ // durability, so merging two of them would fuse two tools into+ // one slot with summed (possibly over-maximum) durability and+ // silently delete the other; those swap below instead. let space = STACK - b.count; let mv = a.count.min(space); self.slots[to].count += mv;
games/voxels/src/main/rust/src/inventory_tests.rs
diff --git a/games/voxels/src/main/rust/src/inventory_tests.rs b/games/voxels/src/main/rust/src/inventory_tests.rsnew file mode 100644index 0000000000..603f61e1de--- /dev/null+++ b/games/voxels/src/main/rust/src/inventory_tests.rs@@ -0,0 +1,190 @@+//! Crafting, smelting, trading and container-transfer rules driven+//! through the real recipe tables (looked up by output, never by a+//! hard-coded index, so a table reorder cannot silently retarget them).++use super::*;+use crate::item::{has_durability, max_durability};+use crate::villager::Offer;++fn recipe_for(out: Id) -> usize {+ RECIPES.iter().position(|r| r.out == out).expect("recipe exists")+}++fn unlocked_crafted() -> Vec<bool> {+ vec![true; RECIPES.len()]+}++#[test]+fn recipe_unlocking_follows_the_tech_tree() {+ assert!(!recipe_unlocked(RECIPES.len(), &[]), "no recipe lives past the table");+ assert!(!recipe_unlocked(usize::MAX, &[]));+ let gated = RECIPES.iter().position(|r| r.unlocked_by != 0).expect("the tree has gated recipes");+ let mut crafted = vec![false; RECIPES.len()];+ assert!(!recipe_unlocked(gated, &crafted), "a gated recipe starts locked");+ let parent = RECIPES.iter().position(|r| r.out == RECIPES[gated].unlocked_by).unwrap();+ crafted[parent] = true;+ assert!(recipe_unlocked(gated, &crafted), "crafting the prerequisite unlocks it");+ let free = RECIPES.iter().position(|r| r.unlocked_by == 0).expect("some recipes are free");+ assert!(recipe_unlocked(free, &[]), "prerequisite-free recipes are always open");+ // Categories are a pure function of the output id.+ assert_eq!(recipe_category(1026), "food"); // apple dishes classify as food+ assert_eq!(recipe_category(Block::Stone as Id), "block");+ assert_eq!(recipe_category(1056), "blessing");+}++#[test]+fn crafting_consumes_inputs_and_respects_locks() {+ // Flint & steel: 1 iron (1050) + 1 coal item (1053) -> 1082, gated on+ // having crafted whatever produces 1061. Use the table itself.+ let idx = recipe_for(1082);+ let recipe = &RECIPES[idx];+ let mut inv = Inventory::empty();+ for _ in 0..recipe.n1 { inv.add_block(recipe.in1); }+ if recipe.in2 != 0 { for _ in 0..recipe.n2 { inv.add_block(recipe.in2); } }+ assert!(!inv.craft(idx, &[]), "a locked recipe consumes nothing and fails");+ assert_eq!(inv.count_of(recipe.in1), recipe.n1, "the failed craft ate an input");+ assert!(inv.craft(idx, &unlocked_crafted()));+ assert_eq!(inv.count_of(recipe.in1), 0);+ if recipe.in2 != 0 { assert_eq!(inv.count_of(recipe.in2), 0); }+ assert_eq!(inv.count_of(1082), max_durability(1082), "tools arrive at full durability");+ assert!(!inv.craft(idx, &unlocked_crafted()), "without inputs a craft fails");+ assert!(!inv.craft(RECIPES.len(), &unlocked_crafted()), "past-the-table crafts fail");+}++#[test]+fn smelting_and_fuel_rules_hold() {+ let iron = SMELTING.iter().find(|s| s.out == 1050).expect("iron smelts");+ let mut inv = Inventory::empty();+ assert!(!inv.can_smelt(iron));+ inv.add_block(iron.in1);+ assert!(inv.can_smelt(iron));+ inv.take_smelt_inputs(iron);+ assert_eq!(inv.count_of(iron.in1), 0);+ inv.give_smelt_output(iron);+ assert_eq!(inv.count_of(1050), iron.out_n);+ // Fuel values: coal burns long, lava longest, stone never.+ assert_eq!(fuel_secs(1053), 80.0);+ assert_eq!(fuel_secs(84), 200.0);+ assert!(fuel_secs(Block::Stone as Id) == 0.0 && fuel_secs(0) == 0.0);+ // Dedicated fuel is burned before building wood, and spared ingredients+ // are never eaten (sulfur is both a fuel and the steel ingredient).+ let mut stove = Inventory::empty();+ stove.slots[0] = InvSlot { id: Block::Wood as Id, count: 2 }; // 4: a log+ stove.slots[1] = InvSlot { id: 1053, count: 1 }; // coal+ assert_eq!(stove.consume_fuel(&[]), Some(80.0), "coal is preferred over logs");+ assert_eq!(stove.slots[1].id, 0, "the coal is spent");+ let mut spared = Inventory::empty();+ spared.slots[0] = InvSlot { id: 1088, count: 1 }; // sulfur+ assert_eq!(spared.consume_fuel(&[1088]), None, "a spared ingredient is not fuel");+ assert_eq!(spared.consume_fuel(&[]), Some(60.0));+ assert_eq!(Inventory::empty().consume_fuel(&[]), None);+}++#[test]+fn stonecutting_and_trading_move_goods_atomically() {+ let cuts = cut_variants();+ assert!(cuts.len() >= 32, "8 materials x 4 conversions plus decor cuts");+ let slab_cut = cuts.iter().position(|c| c.input == Block::Stone as Id && c.output == Block::StoneSlab as Id)+ .expect("stone cuts into slabs");+ assert_eq!(cuts[slab_cut].count, 2, "one cube yields two slabs");+ let mut inv = Inventory::empty();+ assert!(!inv.cut(slab_cut), "cutting without the input fails");+ inv.add_block(Block::Stone as Id);+ assert!(inv.cut(slab_cut));+ assert_eq!(inv.count_of(Block::Stone as Id), 0);+ assert_eq!(inv.count_of(Block::StoneSlab as Id), 2);+ assert!(!inv.cut(cuts.len()), "past-the-table cuts fail");++ // A trade checks both costs before taking either.+ let offer = Offer { cost: 1052, cost_n: 2, cost2: 1050, cost2_n: 1, give: 1027, give_n: 1 };+ let mut trader = Inventory::empty();+ trader.add_block(1052); // one emerald, needs two+ trader.add_block(1050);+ assert!(!trader.trade_offer(&offer));+ assert_eq!(trader.count_of(1050), 1, "a half-affordable trade took the second cost");+ trader.add_block(1052);+ assert!(trader.trade_offer(&offer));+ assert_eq!(trader.count_of(1052), 0);+ assert_eq!(trader.count_of(1027), 1);+}++#[test]+fn container_transfers_and_gear_wear_are_lossless() {+ // take_from moves what fits and leaves the rest behind.+ let mut inv = Inventory::empty();+ let mut chest_slot = InvSlot { id: Block::Stone as Id, count: 70 };+ inv.take_from(&mut chest_slot);+ assert_eq!(inv.count_of(Block::Stone as Id), 64 + 6, "70 stones fill one stack and start another");+ assert_eq!(chest_slot.id, 0, "a fully moved stack empties the container slot");+ let mut full = Inventory::empty();+ for s in full.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as Id, count: STACK }; }+ let mut stuck = InvSlot { id: Block::Stone as Id, count: 3 };+ full.take_from(&mut stuck);+ assert_eq!(stuck.count, 3, "a full inventory must not void container contents");+ // A durable item moves whole (its count is durability, not a stack).+ let mut tool_inv = Inventory::empty();+ let mut tool = InvSlot { id: 1065, count: 250 };+ tool_inv.take_from(&mut tool);+ assert_eq!(tool.id, 0);+ assert_eq!(tool_inv.count_of(1065), 250);+ assert!(has_durability(1065));+ // Armor equips into its own slot and returns the displaced piece.+ let mut wearer = Inventory::empty();+ assert!(wearer.equip_armor(1067, 240).is_none());+ let displaced = wearer.equip_armor(1071, 528).expect("the iron helm is displaced");+ assert_eq!((displaced.id, displaced.count), (1067, 240));+ assert!((wearer.armor_defense() - crate::item::armor_defense(1071)).abs() < 1e-6);+ wearer.damage_armor();+ assert_eq!(wearer.armor[0].count, 527, "a hit wears every equipped piece by one");+ wearer.mend_one();+ assert_eq!(wearer.armor[0].count, 528, "mending restores the most worn piece first");+ // selected_count / take_selected guard the hotbar bounds.+ let mut held = Inventory::empty();+ held.slots[0] = InvSlot { id: 5, count: 2 };+ assert_eq!(held.selected_count(), 2);+ assert_eq!(held.take_selected(), Some((5, 2)));+ assert_eq!(held.take_selected(), None);+}++#[test]+fn dragging_stacks_merges_but_durable_gear_swaps() {+ // Stackables merge up to the stack cap and keep the remainder.+ let mut inv = Inventory::empty();+ inv.slots[0] = InvSlot { id: Block::Stone as Id, count: 60 };+ inv.slots[1] = InvSlot { id: Block::Stone as Id, count: 10 };+ inv.move_item(0, 1);+ assert_eq!((inv.slots[1].id, inv.slots[1].count), (Block::Stone as Id, STACK));+ assert_eq!((inv.slots[0].id, inv.slots[0].count), (Block::Stone as Id, 6));+ // A tool's count is its durability, not a stack size: dragging one+ // pickaxe onto another must swap them, never fuse two tools into a+ // single slot with summed (and over-maximum) durability.+ let mut gear = Inventory::empty();+ gear.slots[0] = InvSlot { id: 1065, count: 100 };+ gear.slots[1] = InvSlot { id: 1065, count: 200 };+ gear.move_item(0, 1);+ assert_eq!((gear.slots[0].id, gear.slots[0].count), (1065, 200), "the tools must swap");+ assert_eq!((gear.slots[1].id, gear.slots[1].count), (1065, 100));+ assert!(gear.slots.iter().all(|s| s.count <= max_durability(s.id) || s.id == 0));+ // Out-of-range and self moves are no-ops.+ gear.move_item(0, SLOTS);+ gear.move_item(1, 1);+ assert_eq!(gear.slots[1].count, 100);+}++#[test]+fn inventory_json_round_trips() {+ let mut inv = Inventory::empty();+ inv.slots[3] = InvSlot { id: 42, count: 7 };+ inv.armor[1] = InvSlot { id: 1068, count: 200 };+ inv.selected = 2;+ let back: Inventory = serde_json::from_str(&inv.to_json()).unwrap();+ assert_eq!((back.slots[3].id, back.slots[3].count), (42, 7));+ assert_eq!(back.armor[1].id, 1068);+ assert_eq!(back.selected, 2);+ assert_eq!(back.slots.len(), SLOTS);+ // The starter kit is exactly the documented grant.+ let starter = Inventory::default();+ assert_eq!(starter.count_of(Block::Grass as Id), 64);+ assert_eq!(starter.count_of(Block::Brick as Id), 16);+ assert_eq!(starter.placed, 0);+}
games/voxels/src/main/rust/src/net.rs
diff --git a/games/voxels/src/main/rust/src/net.rs b/games/voxels/src/main/rust/src/net.rsindex 24de195b52..3797b06f4f 100644--- a/games/voxels/src/main/rust/src/net.rs+++ b/games/voxels/src/main/rust/src/net.rs@@ -440,4 +440,7 @@ pub fn apply_inbound(state: &mut EngineState) { } } -include!("net_part1.rs");\ No newline at end of file+include!("net_part1.rs");+#[cfg(test)]+#[path = "net_tests.rs"]+mod net_tests;
games/voxels/src/main/rust/src/net_tests.rs
diff --git a/games/voxels/src/main/rust/src/net_tests.rs b/games/voxels/src/main/rust/src/net_tests.rsnew file mode 100644index 0000000000..f8c73e33fc--- /dev/null+++ b/games/voxels/src/main/rust/src/net_tests.rs@@ -0,0 +1,107 @@+//! Wire-format tests: DTO conversions and the serde shape of every+//! `NetMsg` variant. Global-queue tests live in one sequential test so+//! they cannot interleave with each other.++use super::*;++#[test]+fn projectile_cells_round_trip_and_unknown_is_fireball() {+ for kind in [ProjKind::Fireball, ProjKind::ShulkerBullet, ProjKind::Firework, ProjKind::Snowball, ProjKind::EnderPearl] {+ assert!(proj_from_cell(proj_cell(kind)) == kind);+ }+ assert!(proj_from_cell(99) == ProjKind::Fireball, "unknown cells fall back, never panic");+ assert!(proj_from_cell(u32::MAX) == ProjKind::Fireball);+}++#[test]+fn mob_and_player_dtos_preserve_their_fields() {+ let mob = Mob::new(MobKind::Zombie, Vec3::new(1.0, 64.0, -3.0), 7);+ let dto = MobDto::of(&mob);+ assert_eq!(dto.kind, MobKind::Zombie.cell());+ let back = dto.to_mob();+ assert_eq!(back.kind, MobKind::Zombie);+ assert_eq!(back.pos, mob.pos);+ assert_eq!(back.health, mob.health);+ assert_eq!(back.max_health, mob.max_health);+ // Every mob kind survives the cell round-trip.+ for kind in MobKind::ALL {+ let m = Mob::new(kind, Vec3::ZERO, 1);+ assert_eq!(MobDto::of(&m).to_mob().kind, kind, "{kind:?} lost in the DTO");+ }+ assert_eq!(MobKind::from_cell(999), MobKind::Pig, "corrupt cells degrade to a pig");++ let player = Player::new(2.0, 65.0, 4.0);+ let pdto = PlayerDto::of(&player);+ assert_eq!(pdto.pos, player.pos);+ assert_eq!(pdto.health, player.health);+ assert!(!pdto.on_ground && !pdto.sneaking && !pdto.gliding);+}++#[test]+fn every_netmsg_variant_survives_json() {+ let player = PlayerDto { pos: Vec3::new(1.0, 2.0, 3.0), vel: Vec3::ZERO, yaw: 0.5, pitch: -0.2, on_ground: true, sneaking: false, gliding: false, health: 20.0 };+ let msgs: Vec<NetMsg> = vec![+ NetMsg::Join { device: "d1".into(), name: "Bob".into() },+ NetMsg::WorldInit { seed: 42, name: "world".into(), player: player.clone() },+ NetMsg::ChunkData { dim: 1, cx: -2, cz: 3, data: vec![0, 1, 2, 255] },+ NetMsg::BlockEdit { dim: 0, x: 3, y: 64, z: -7, id: 12, meta: 5 },+ NetMsg::PlayerTransform { device: "d1".into(), player },+ NetMsg::MobSnapshot { mobs: vec![MobDto { kind: 5, pos: Vec3::ONE, vel: Vec3::ZERO, yaw: 1.0, health: 10.0, max_health: 20.0 }] },+ NetMsg::ProjSnapshot { projs: vec![ProjDto { kind: 3, pos: Vec3::ZERO, vel: Vec3::ONE, life: 2.5, from_player: true }] },+ NetMsg::InventorySync { inv: "{}".into() },+ NetMsg::ContainerSync { key: [0, 1, 2, 3], slots: vec![InvSlot { id: 5, count: 2 }] },+ NetMsg::WorldClock { world_secs: 123.5, weather: 1, weather_cd: 40.0, rain: 0.8 },+ NetMsg::EditIntent { device: "d1".into(), dim: 0, x: 1, y: 2, z: 3, id: 9, meta: 0, break_it: true },+ NetMsg::InvIntent { device: "d1".into(), from: 3, to: 9 },+ NetMsg::ContainerIntent { device: "d1".into(), key: [1, 4, 5, 6], take: false, idx: u32::MAX },+ ];+ for msg in &msgs {+ let s = serde_json::to_string(msg).unwrap();+ assert!(s.contains("\"type\":\""), "messages are internally tagged: {s}");+ let back: NetMsg = serde_json::from_str(&s).unwrap();+ // Re-serialising the parsed copy must reproduce the wire bytes.+ assert_eq!(serde_json::to_string(&back).unwrap(), s, "{msg:?} changed on the wire");+ }+ // Spot-check the fields that routing depends on.+ let edit: NetMsg = serde_json::from_str(r#"{"type":"BlockEdit","dim":0,"x":3,"y":64,"z":-7,"id":12,"meta":0}"#).unwrap();+ assert!(matches!(edit, NetMsg::BlockEdit { x: 3, z: -7, id: 12, .. }));+ let sync: NetMsg = serde_json::from_str(r#"{"type":"ContainerIntent","device":"d","key":[1,4,5,6],"take":true,"idx":4294967295}"#).unwrap();+ assert!(matches!(sync, NetMsg::ContainerIntent { idx: u32::MAX, take: true, .. }), "u32::MAX is the sync-me sentinel");+}++#[test]+fn inbound_json_rejects_garbage_without_panicking() {+ assert!(!push_inbound_json("not json"));+ assert!(!push_inbound_json(r#"{"type":"NoSuchVariant"}"#));+ assert!(!push_inbound_json(""));+ assert!(push_inbound_json("[]"), "an empty batch is well-formed");+}++#[test]+fn net_globals_move_messages_end_to_end() {+ // Sequential by construction: role, device, outbox and the remote+ // player table are process-global, so this is the only test here+ // that mutates them.+ let _ = drain_outbound_json(); // drop anything a parallel suite queued+ set_role(ROLE_HOST);+ assert!(is_networked() && is_host() && !is_client());+ set_local_device("net-test-device".to_string());+ client_inv_intent(3, 5);+ client_container_intent([0, 1, 2, 3], true, 7);+ let drained: Vec<NetMsg> = serde_json::from_str(&drain_outbound_json()).unwrap();+ assert!(drained.iter().any(|m| matches!(m, NetMsg::InvIntent { device, from: 3, to: 5 } if device == "net-test-device")),+ "the inv intent was not queued: {drained:?}");+ assert!(drained.iter().any(|m| matches!(m, NetMsg::ContainerIntent { take: true, idx: 7, .. })));+ assert_eq!(drain_outbound_json(), "[]", "draining empties the outbox");++ upsert_remote("peer-a".to_string(), Vec3::new(9.0, 64.0, 9.0), 1.25);+ upsert_remote(String::new(), Vec3::ZERO, 0.0); // anonymous poses are dropped+ upsert_remote("net-test-device".to_string(), Vec3::ZERO, 0.0); // and so are our own+ let poses = remote_player_poses();+ assert!(poses.iter().any(|(p, y)| *p == Vec3::new(9.0, 64.0, 9.0) && *y == 1.25));+ assert!(!poses.iter().any(|(p, _)| *p == Vec3::ZERO), "self/anonymous poses leaked in");+ let peers: Vec<serde_json::Value> = serde_json::from_str(&peers_json()).unwrap();+ assert!(peers.iter().any(|p| p["device"] == "peer-a" && p["x"] == 9.0));+ set_role(ROLE_OFFLINE);+ assert!(!is_networked());+}
games/voxels/src/main/rust/src/texture_atlas.rs
diff --git a/games/voxels/src/main/rust/src/texture_atlas.rs b/games/voxels/src/main/rust/src/texture_atlas.rsindex a8874e8018..02ff834c5e 100644--- a/games/voxels/src/main/rust/src/texture_atlas.rs+++ b/games/voxels/src/main/rust/src/texture_atlas.rs@@ -127,3 +127,7 @@ pub fn load_entity_atlas_bin() -> Vec<u8> { let expect = (ENTITY_ATLAS_W * ENTITY_ATLAS_H * 4) as usize; if maybe.len() == expect { maybe.to_vec() } else { vec![255u8; expect] } }++#[cfg(test)]+#[path = "texture_atlas_tests.rs"]+mod texture_atlas_tests;
games/voxels/src/main/rust/src/texture_atlas_tests.rs
diff --git a/games/voxels/src/main/rust/src/texture_atlas_tests.rs b/games/voxels/src/main/rust/src/texture_atlas_tests.rsnew file mode 100644index 0000000000..455bdd90cf--- /dev/null+++ b/games/voxels/src/main/rust/src/texture_atlas_tests.rs@@ -0,0 +1,28 @@+//! The CPU-side atlas contract: geometry constants and the bundled+//! pixel payloads. (The Vulkan upload itself needs a GPU and is not+//! exercised here.)++use super::*;++#[test]+fn atlas_geometry_is_consistent() {+ assert_eq!(ATLAS_W, ATLAS_TILES_PER_ROW * TILE_SIZE);+ assert_eq!(ATLAS_H, ATLAS_TILE_ROWS * TILE_SIZE);+ assert_eq!((ATLAS_W, ATLAS_H), (256, 256));+ assert_eq!(ENTITY_ATLAS_W % ENTITY_CELL, 0, "entity cells must tile the atlas exactly");+ assert_eq!(ENTITY_ATLAS_H % ENTITY_CELL, 0);+ assert_eq!(ENTITY_ATLAS_W / ENTITY_CELL, 4, "mob kinds index a 4-wide cell grid");+}++#[test]+fn bundled_atlases_are_full_frames() {+ let atlas = load_atlas_bin();+ assert_eq!(atlas.len(), (ATLAS_W * ATLAS_H * 4) as usize, "one RGBA byte set per pixel");+ assert_eq!(atlas, load_atlas_bin(), "the bundled atlas is deterministic");+ let entity = load_entity_atlas_bin();+ assert_eq!(entity.len(), (ENTITY_ATLAS_W * ENTITY_ATLAS_H * 4) as usize);+ // A real texture is not a flat fill: many distinct byte values appear.+ let mut seen = [false; 256];+ for &b in atlas.iter().step_by(997) { seen[b as usize] = true; }+ assert!(seen.iter().filter(|s| **s).count() > 8, "the block atlas looks like a flat fill");+}
games/voxels/src/main/rust/src/world/block.rs
diff --git a/games/voxels/src/main/rust/src/world/block.rs b/games/voxels/src/main/rust/src/world/block.rsindex d8f6beb858..0a425f63a9 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -198,4 +198,7 @@ impl Boxes { } include!("block_part1.rs");-include!("block_part2.rs");\ No newline at end of file+include!("block_part2.rs");+#[cfg(test)]+#[path = "block_tests.rs"]+mod block_tests;
games/voxels/src/main/rust/src/world/block_tests.rs
diff --git a/games/voxels/src/main/rust/src/world/block_tests.rs b/games/voxels/src/main/rust/src/world/block_tests.rsnew file mode 100644index 0000000000..df7d1e62c9--- /dev/null+++ b/games/voxels/src/main/rust/src/world/block_tests.rs@@ -0,0 +1,222 @@+//! Sweeps over the whole block table: id round-trips, shape families,+//! collision/occlusion geometry, atlas tiles and crop wiring. The tables in+//! `block_part1.rs` are hand-written per variant, so only a full-population+//! sweep catches a variant that was left behind in one of them.++use super::*;++fn all_blocks() -> impl Iterator<Item = Block> {+ (0..=MAX_BLOCK_ID).map(Block::from_id)+}++#[test]+fn every_block_id_round_trips_and_out_of_range_is_air() {+ for id in 0..=MAX_BLOCK_ID {+ assert_eq!(Block::from_id(id).id(), id, "id {id} did not round-trip");+ }+ assert_eq!(Block::from_id(MAX_BLOCK_ID + 1), Block::Air);+ assert_eq!(Block::from_id(u16::MAX), Block::Air);+ assert!(Block::Air.is_air());+ assert!(!Block::Stone.is_air());+}++#[test]+fn crop_meta_packs_and_clamps_the_stage() {+ for stage in 0..=CROP_RIPE {+ assert_eq!(crop_stage(crop_meta(stage)), stage);+ }+ assert_eq!(crop_meta(99), crop_meta(CROP_RIPE), "stages above ripe must clamp");+ assert_eq!(crop_meta(0), 0);+ // Facing/half bits (0..2) must survive a stage read untouched by the mask.+ assert_eq!(crop_stage(META_TOP | META_FACING), 0);+}++#[test]+fn crop_seed_and_yield_form_a_cycle() {+ for crop in [Block::WheatCrop, Block::CarrotCrop, Block::MelonCrop] {+ assert!(crop.is_crop());+ let seed = crop.crop_seed();+ assert_ne!(seed, 0, "{crop:?} has no seed");+ assert_eq!(Block::crop_from_seed(seed), Some(crop), "seed {seed} does not replant {crop:?}");+ assert_ne!(crop.crop_yield(), 0, "{crop:?} yields nothing");+ }+ assert_eq!(Block::Stone.crop_seed(), 0);+ assert_eq!(Block::Stone.crop_yield(), 0);+ assert_eq!(Block::crop_from_seed(0), None);+ assert_eq!(Block::crop_from_seed(1), None);+ assert!(!Block::Stone.is_crop());+}++#[test]+fn slab_and_stair_families_are_closed_under_parent() {+ let mut families = 0;+ for b in all_blocks() {+ if let Some(slab) = b.slab_of() {+ families += 1;+ assert_eq!(slab.shape(), Shape::Slab, "{slab:?} is not slab-shaped");+ assert_eq!(slab.parent(), b, "{slab:?} lost its parent material");+ let stairs = b.stairs_of().expect("a slab material must also have stairs");+ assert_eq!(stairs.shape(), Shape::Stairs);+ assert_eq!(stairs.parent(), b);+ // The shapes themselves have no further shapes.+ assert_eq!(slab.slab_of(), None);+ assert_eq!(stairs.stairs_of(), None);+ } else {+ assert_eq!(b.stairs_of(), None, "{b:?} has stairs but no slab");+ }+ // Every shaped block resolves back to a cube parent that names it.+ if b.shape() != Shape::Cube {+ assert_eq!(b.parent().shape(), Shape::Cube, "{b:?} parent is not a cube");+ let back = if b.shape() == Shape::Slab { b.parent().slab_of() } else { b.parent().stairs_of() };+ assert_eq!(back, Some(b), "{b:?} is not the shape its parent claims");+ } else {+ assert_eq!(b.parent(), b, "cube {b:?} changed under parent()");+ }+ }+ assert_eq!(families, 8, "expected the 8 slab/stair material families");+}++#[test]+fn collision_boxes_stay_inside_the_cell() {+ for b in all_blocks() {+ for meta in [0u8, META_TOP, 1, 2, 3, META_TOP | 3] {+ let boxes = b.collision_boxes(meta);+ if !b.is_solid() {+ assert!(boxes.as_slice().is_empty(), "non-solid {b:?} must not collide");+ continue;+ }+ assert!(!boxes.as_slice().is_empty(), "solid {b:?} must collide");+ for a in boxes.as_slice() {+ for i in 0..3 {+ assert!(a.min[i] >= 0.0 && a.max[i] <= 1.0 && a.min[i] < a.max[i],+ "{b:?} meta {meta} box {a:?} escapes its cell");+ }+ }+ }+ }+ // Exact shapes: full cube, bottom/top slab.+ assert_eq!(Block::Stone.collision_boxes(0).as_slice(), &[FULL_CUBE]);+ assert_eq!(Block::StoneSlab.collision_boxes(0).as_slice()[0], Aabb::new([0.0, 0.0, 0.0], [1.0, 0.5, 1.0]));+ assert_eq!(Block::StoneSlab.collision_boxes(META_TOP).as_slice()[0], Aabb::new([0.0, 0.5, 0.0], [1.0, 1.0, 1.0]));+ // Every stair, in every facing and half, spans the full cell height somewhere.+ for facing in 0..=3u8 {+ for meta in [facing, facing | META_TOP] {+ let boxes = Block::StoneStairs.collision_boxes(meta);+ assert_eq!(boxes.as_slice().len(), 2, "a stair is base + step");+ let (lo, hi) = boxes.as_slice().iter().fold((1.0f32, 0.0f32), |(lo, hi), a| (lo.min(a.min[1]), hi.max(a.max[1])));+ assert_eq!((lo, hi), (0.0, 1.0), "stair meta {meta} does not span the cell");+ }+ }+}++#[test]+fn occlusion_matches_the_filled_half() {+ let dirs = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)];+ for (dx, dy, dz) in dirs {+ assert!(Block::Stone.occludes_face(0, dx, dy, dz), "opaque stone must hide every face");+ assert!(!Block::Air.occludes_face(0, dx, dy, dz));+ assert!(!Block::Glass.occludes_face(0, dx, dy, dz), "glass hides no face");+ assert!(!Block::Water.occludes_face(0, dx, dy, dz));+ }+ // A bottom slab seals only its underside; a top slab only its top.+ assert!(Block::StoneSlab.occludes_face(0, 0, -1, 0));+ assert!(!Block::StoneSlab.occludes_face(0, 0, 1, 0));+ assert!(!Block::StoneSlab.occludes_face(0, 1, 0, 0));+ assert!(Block::StoneSlab.occludes_face(META_TOP, 0, 1, 0));+ assert!(!Block::StoneSlab.occludes_face(META_TOP, 0, -1, 0));+ // Stairs: the sealed horizontal side follows the half, the tall side is+ // opposite the facing (north-facing stairs are tall toward +Z).+ assert!(Block::StoneStairs.occludes_face(0, 0, -1, 0));+ assert!(Block::StoneStairs.occludes_face(0, 0, 0, 1), "north stair tall side is +Z");+ assert!(!Block::StoneStairs.occludes_face(0, 0, 0, -1));+ assert!(Block::StoneStairs.occludes_face(1, -1, 0, 0), "east stair tall side is -X");+ assert!(Block::StoneStairs.occludes_face(2, 0, 0, -1), "south stair tall side is -Z");+ assert!(Block::StoneStairs.occludes_face(3, 1, 0, 0), "west stair tall side is +X");+ assert!(Block::StoneStairs.occludes_face(META_TOP, 0, 1, 0));+}++#[test]+fn atlas_tiles_fit_the_atlas_and_follow_the_parent() {+ let max_tile = (ATLAS_COLS * ATLAS_ROWS) as u32;+ for b in all_blocks() {+ for tile in [b.tile_top(), b.tile_bottom(), b.tile_side()] {+ assert!(tile < max_tile, "{b:?} tile {tile} is outside the {ATLAS_COLS}x{ATLAS_ROWS} atlas");+ }+ assert_eq!(b.tile_for_dir(0, 1, 0), b.parent().tile_top());+ assert_eq!(b.tile_for_dir(0, -1, 0), b.parent().tile_bottom());+ assert_eq!(b.tile_for_dir(1, 0, 0), b.parent().tile_side());+ assert_eq!(b.tile_for_dir(0, 0, 1), b.parent().tile_side());+ for c in b.color() {+ assert!((0.0..=1.0).contains(&c), "{b:?} colour {c} out of range");+ }+ }+ // Faces that differ from the top are the exception, not the rule.+ assert_eq!(Block::Grass.tile_top(), 2);+ assert_eq!(Block::Grass.tile_bottom(), 1);+ assert_eq!(Block::Grass.tile_side(), 3);+ assert_eq!(Block::Stone.tile_bottom(), Block::Stone.tile_top());+}++#[test]+fn tile_uv_maps_corners_and_stays_in_unit_space() {+ assert_eq!(tile_uv(0), (0.0, 0.0, 0.0625, 0.0625));+ assert_eq!(tile_uv(17), (0.0625, 0.0625, 0.125, 0.125));+ let (x0, y0, x1, y1) = tile_uv(255);+ assert_eq!((x0, y0, x1, y1), (0.9375, 0.9375, 1.0, 1.0));+ for tile in [0u32, 1, 15, 16, 100, 254] {+ let (x0, y0, x1, y1) = tile_uv(tile);+ assert!(0.0 <= x0 && x0 < x1 && x1 <= 1.0 && 0.0 <= y0 && y0 < y1 && y1 <= 1.0);+ assert!((x1 - x0 - 0.0625).abs() < 1e-6 && (y1 - y0 - 0.0625).abs() < 1e-6);+ }+ assert_eq!(GRASS_SIDE_OVERLAY, 16);+ assert!(GRASS_SIDE_TILE >= 256, "the sentinel must never collide with a real tile");+}++#[test]+fn light_and_shadow_predicates_agree_with_material() {+ for (b, want) in [+ (Block::Glowstone, 15u8), (Block::SeaLantern, 15), (Block::Lava, 15), (Block::Beacon, 15),+ (Block::WardingStone, 13), (Block::NetherPortal, 12), (Block::EndPortal, 12),+ (Block::Magma, 11), (Block::Stone, 0), (Block::Air, 0),+ ] {+ assert_eq!(b.light_emission(), want, "{b:?} emits the wrong light");+ }+ for b in all_blocks() {+ assert!(b.light_emission() <= 15);+ assert_eq!(b.is_opaque(), !b.is_transparent(), "{b:?} opacity is inconsistent");+ }+ assert!(Block::Stone.blocks_light());+ assert!(!Block::Glass.blocks_light(), "glass fills its cell but passes light");+ assert!(!Block::Air.blocks_light());+ assert!(Block::StoneSlab.blocks_light(), "a stone slab is still stone for shadowing");+ assert!(!Block::Leaves.blocks_light() || Block::Leaves.is_opaque());+}++#[test]+fn menus_pickaxes_and_solidity_are_pinned() {+ assert_eq!(Block::CraftingTable.menu(), 1);+ assert_eq!(Block::Furnace.menu(), 2);+ assert_eq!(Block::Jukebox.menu(), 3);+ assert_eq!(Block::BlastFurnace.menu(), 4);+ assert_eq!(Block::Stonecutter.menu(), 5);+ assert_eq!(Block::Stone.menu(), 0);+ assert!(Block::Stone.needs_pickaxe() && Block::Obsidian.needs_pickaxe());+ assert!(!Block::Dirt.needs_pickaxe() && !Block::Planks.needs_pickaxe());+ for b in all_blocks() {+ if b.shape() != Shape::Cube {+ assert_eq!(b.needs_pickaxe(), b.parent().needs_pickaxe(),+ "{b:?} pickaxe rule differs from its parent material");+ }+ }+ assert!(Block::Stone.is_solid() && Block::Glass.is_solid() == false);+ assert!(!Block::Water.is_solid() && !Block::WheatCrop.is_solid());+}++#[test]+fn aabb_overlap_is_strict_on_touching_faces() {+ assert!(FULL_CUBE.overlaps_at([0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [2.0, 2.0, 2.0]));+ assert!(!FULL_CUBE.overlaps_at([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 1.0, 1.0]),+ "boxes that only share a face do not overlap");+ assert!(!FULL_CUBE.overlaps_at([3.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]));+ assert!(FULL_CUBE.overlaps_at([3.0, 0.0, 0.0], [3.25, 0.0, 0.0], [4.0, 1.0, 1.0]));+}
games/voxels/src/main/rust/src/world/generator.rs
diff --git a/games/voxels/src/main/rust/src/world/generator.rs b/games/voxels/src/main/rust/src/world/generator.rsindex b79c337ec6..9a1279455a 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -317,4 +317,7 @@ const NETHER_VEINS: [Vein; 2] = [ const DEEPSLATE_Y: i32 = 16; include!("generator_part1.rs");-include!("generator_part2.rs");\ No newline at end of file+include!("generator_part2.rs");+#[cfg(test)]+#[path = "generator_tests.rs"]+mod generator_tests;
games/voxels/src/main/rust/src/world/generator_tests.rs
diff --git a/games/voxels/src/main/rust/src/world/generator_tests.rs b/games/voxels/src/main/rust/src/world/generator_tests.rsnew file mode 100644index 0000000000..e8b8550cba--- /dev/null+++ b/games/voxels/src/main/rust/src/world/generator_tests.rs@@ -0,0 +1,309 @@+//! Structure builders and terrain classification with fixed seeds. The+//! builders write only columns inside the target chunk and must no-op+//! (never panic) when their footprint or height would leave the world.++use super::*;+use crate::world::chunk::ChunkPos;++fn empty_chunk(x: i32, z: i32) -> Chunk {+ Chunk::new(ChunkPos(x, z))+}++fn count_id(chunk: &Chunk, id: Id) -> usize {+ let mut n = 0;+ for y in 0..CHUNK_HEIGHT {+ for z in 0..16 {+ for x in 0..16 {+ if chunk.get_block(x, y, z) == id { n += 1; }+ }+ }+ }+ n+}++#[test]+fn in_chunk_and_hash3_are_exact() {+ assert!(in_chunk(0, 0, 0, 0) && in_chunk(15, 15, 0, 0));+ assert!(!in_chunk(16, 0, 0, 0) && !in_chunk(-1, 0, 0, 0) && !in_chunk(0, 16, 0, 0));+ assert!(in_chunk(-16, -1, -16, -16) && !in_chunk(-17, 0, -16, -16));+ assert_eq!(hash3(3, -7, 42), hash3(3, -7, 42), "the world hash must be deterministic");+ assert_ne!(hash3(3, -7, 42), hash3(3, -7, 43));+ assert_ne!(hash3(3, -7, 42), hash3(-7, 3, 42));+}++#[test]+fn level_column_lays_foundation_floor_and_clearing() {+ let mut c = empty_chunk(0, 0);+ for y in 7..=14 { c.set_block(4, y, 4, 1); }+ level_column(&mut c, 4, 4, 10, 3, 8);+ assert_eq!(c.get_block(4, 7, 4), 2, "foundation is dirt below the floor");+ assert_eq!(c.get_block(4, 9, 4), 2);+ assert_eq!(c.get_block(4, 10, 4), 8, "the floor itself is the given block");+ for y in 11..=13 { assert_eq!(c.get_block(4, y, 4), 0, "y={y} above the floor must be cleared"); }+ assert_eq!(c.get_block(4, 14, 4), 1, "clearing stops at clear_to");+ // At the very bottom the foundation must clamp instead of underflowing.+ let mut low = empty_chunk(0, 0);+ level_column(&mut low, 0, 0, 1, 2, 8);+ assert_eq!(low.get_block(0, 0, 0), 2);+ assert_eq!(low.get_block(0, 1, 0), 8);+}++#[test]+fn village_buildings_write_their_footprint() {+ // Well: water centre, cobble rim and corner posts.+ let mut well = empty_chunk(0, 0);+ render_building(&mut well, 0, 0, Building { bx: 2, bz: 2, w: 3, d: 3, base: 20, kind: B_WELL });+ assert_eq!(well.get_block(3, 20, 3), 12);+ assert_eq!(well.get_block(2, 20, 2), 8);+ assert_eq!(well.get_block(2, 22, 2), 8, "corner posts rise two above the rim");+ assert_eq!(well.get_block(3, 21, 2), 0, "non-corner rim stays low");+ // Lamp: a wood post topped with glowstone.+ let mut lamp = empty_chunk(0, 0);+ render_building(&mut lamp, 0, 0, Building { bx: 5, bz: 5, w: 1, d: 1, base: 20, kind: B_LAMP });+ assert_eq!(lamp.get_block(5, 21, 5), 4);+ assert_eq!(lamp.get_block(5, 23, 5), 4);+ assert_eq!(lamp.get_block(5, 24, 5), 77);+ // Farm: a central water channel, farmland elsewhere, crops on alternate plots.+ let mut farm = empty_chunk(0, 0);+ render_building(&mut farm, 0, 0, Building { bx: 1, bz: 1, w: 5, d: 3, base: 20, kind: B_FARM });+ assert_eq!(farm.get_block(3, 20, 2), 12, "middle row is the irrigation channel");+ assert_eq!(farm.get_block(1, 20, 1), 59);+ assert_eq!(farm.get_block(1, 21, 1), 58, "(0+0) is even, so a crop stands here");+ assert_eq!(farm.get_block(2, 21, 1), 0, "odd plots stay bare");+ // House: cobble floor, plank walls, a doorway gap, glass window, roof, lamp inside.+ let mut house = empty_chunk(0, 0);+ render_building(&mut house, 0, 0, Building { bx: 2, bz: 2, w: 4, d: 4, base: 20, kind: B_HOUSE });+ assert_eq!(house.get_block(3, 20, 3), 8);+ assert_eq!(house.get_block(2, 21, 3), 10, "edge columns are walls");+ assert_eq!(house.get_block(4, 21, 2), 0, "the doorway (front middle) stays open");+ assert_eq!(house.get_block(4, 23, 2), 10, "the wall resumes above the door");+ assert_eq!(house.get_block(2, 22, 4), 7, "side window at wall height 2");+ assert_eq!(house.get_block(3, 24, 3), 10, "roof caps the house");+ assert_eq!(house.get_block(4, 20, 4), 77, "a plain house is lit by glowstone");+ // Big house / church / blacksmith variants.+ let mut big = empty_chunk(0, 0);+ render_building(&mut big, 0, 0, Building { bx: 1, bz: 1, w: 5, d: 5, base: 20, kind: B_BIGHOUSE });+ assert_eq!(big.get_block(3, 20, 3), 81, "a big house centres on a warding stone");+ assert_eq!(big.get_block(3, 26, 3), 10, "big houses are six tall");+ let mut church = empty_chunk(0, 0);+ render_building(&mut church, 0, 0, Building { bx: 1, bz: 1, w: 5, d: 5, base: 20, kind: B_CHURCH });+ assert_eq!(church.get_block(3, 30, 3), 67, "the church beacon sits above its nine-tall roof");+ let mut smith = empty_chunk(0, 0);+ render_building(&mut smith, 0, 0, Building { bx: 1, bz: 1, w: 6, d: 6, base: 20, kind: B_BLACKSMITH });+ assert_eq!(smith.get_block(2, 21, 2), 35);+ assert_eq!(smith.get_block(3, 20, 2), 76);+ assert_eq!(smith.get_block(4, 21, 2), 23);+}++#[test]+fn buildings_clip_at_chunk_borders_and_the_sky() {+ // Only the columns inside this chunk may be written.+ let mut c = empty_chunk(0, 0);+ render_building(&mut c, 0, 0, Building { bx: 14, bz: 2, w: 4, d: 4, base: 20, kind: B_HOUSE });+ assert_eq!(c.get_block(14, 20, 2), 8);+ assert_eq!(c.get_block(15, 20, 2), 8);+ assert_eq!(c.get_block(14, 24, 2), 10, "the roof is written for in-chunk columns only");+ assert_eq!(c.get_block(15, 21, 3), 0, "the out-of-chunk half of the house is not built");+ // A building whose roof would leave the world builds nothing at all.+ let mut sky = empty_chunk(0, 0);+ render_building(&mut sky, 0, 0, Building { bx: 2, bz: 2, w: 4, d: 4, base: CHUNK_HEIGHT - 7, kind: B_HOUSE });+ assert_eq!(count_id(&sky, 10), 0);+ assert_eq!(count_id(&sky, 8), 0);+}++#[test]+fn ruined_portal_dungeon_and_temple_have_their_loot() {+ let mut portal = empty_chunk(0, 0);+ build_ruined_portal(&mut portal, 2, 5, 30);+ assert_eq!(portal.get_block(2, 30, 5), 76, "the broken frame corner is covered by magma rubble");+ assert_eq!(portal.get_block(3, 30, 5), 78);+ assert_eq!(portal.get_block(6, 31, 5), 83, "the loot chest stands beside the frame");+ let mut clipped = empty_chunk(0, 0);+ build_ruined_portal(&mut clipped, 13, 5, 30);+ assert_eq!(count_id(&clipped, 78), 0, "a portal that would leave the chunk is skipped");+ let mut dungeon = empty_chunk(0, 0);+ build_dungeon(&mut dungeon, 2, 2, 10, 7);+ assert_eq!(dungeon.get_block(2, 10, 2), 15, "(0+0+0)%3==0 is mossy cobble");+ assert_eq!(dungeon.get_block(3, 10, 2), 8);+ assert_eq!(dungeon.get_block(4, 13, 4), 77);+ assert_eq!(dungeon.get_block(3, 11, 3), 83);+ assert_eq!(dungeon.get_block(5, 11, 5), 83);+ assert_eq!(dungeon.get_block(4, 12, 4), 0, "the room interior is hollow");+ let mut temple = empty_chunk(0, 0);+ build_temple(&mut temple, 8, 8, 30);+ assert_eq!(temple.get_block(8, 30, 8), 38);+ assert_eq!(temple.get_block(4, 30, 8), 38, "the base layer spans the full 9x9");+ assert_eq!(temple.get_block(4, 31, 8), 0, "upper layers step inward");+ assert_eq!(temple.get_block(7, 27, 7), 83);+ assert_eq!(temple.get_block(9, 27, 9), 83);+ assert_eq!(temple.get_block(8, 29, 8), 77);+ let mut edge = empty_chunk(0, 0);+ build_temple(&mut edge, 2, 8, 30);+ assert_eq!(count_id(&edge, 38), 0, "a temple centred too near the edge is skipped");+}++#[test]+fn stronghold_fortress_and_end_city_are_built() {+ let mut hold = empty_chunk(0, 0);+ build_stronghold(&mut hold, 2, 2, 10);+ assert_eq!(hold.get_block(3, 11, 3), 83);+ assert_eq!(hold.get_block(5, 13, 5), 78, "the portal frame's top rail overwrites the light at its centre");+ assert_eq!(hold.get_block(4, 10, 4), 85, "end-stone rim under the portal");+ assert_eq!(hold.get_block(4, 11, 4), 87, "the End portal itself");+ assert_eq!(hold.get_block(5, 12, 5), 0, "interior stays hollow");+ let mut fort = empty_chunk(0, 0);+ build_nether_fortress(&mut fort, 3, 3, 40, 9);+ assert_eq!(fort.get_block(3, 40, 3), 55);+ assert_eq!(fort.get_block(7, 46, 7), 77, "central lamp under the beams");+ assert_eq!(fort.get_block(4, 41, 7), 83);+ assert_eq!(fort.get_block(7, 42, 7), 0, "the hall is hollowed out");+ let mut city = empty_chunk(0, 0);+ build_end_city(&mut city, 3, 3, 40, 0); // r % 6 == 0, so the tower is 12 tall+ assert_eq!(city.get_block(3, 40, 3), 89);+ assert_eq!(city.get_block(5, 42, 5), 0, "between floors the tower is hollow");+ assert_eq!(city.get_block(4, 48, 4), 83, "loot chest in the top room");+ assert_eq!(city.get_block(5, 51, 5), 77, "lantern at the top");+ // Out-of-world placements are skipped whole, never partially written.+ let mut clipped = empty_chunk(0, 0);+ build_stronghold(&mut clipped, 11, 2, 10);+ build_nether_fortress(&mut clipped, 9, 3, 40, 9);+ build_end_city(&mut clipped, 12, 3, 40, 0);+ build_dungeon(&mut clipped, 2, 2, 1, 7);+ assert_eq!(count_id(&clipped, 83), 0);+}++#[test]+fn mineshaft_corridors_have_floors_and_supports() {+ let mut c = empty_chunk(0, 0);+ carve_corridor(&mut c, 0, 0, Corridor { cx: 2, cz: 8, dirx: 1, dirz: 0, len: 7, fy: 20 });+ assert_eq!(c.get_block(2, 20, 8), 10, "plank floor along the arm");+ assert_eq!(c.get_block(8, 20, 8), 10);+ assert_eq!(c.get_block(5, 21, 8), 0, "the passage is carved open");+ assert_eq!(c.get_block(2, 21, 7), 4, "support posts flank the first frame");+ assert_eq!(c.get_block(2, 23, 8), 4, "and a beam crosses above it");+ assert_eq!(c.get_block(3, 21, 7), 0, "frames repeat only every six blocks");+ // A corridor running off the chunk edge writes only its in-chunk part.+ let mut off = empty_chunk(1, 0);+ carve_corridor(&mut off, 16, 0, Corridor { cx: 2, cz: 8, dirx: 1, dirz: 0, len: 7, fy: 20 });+ assert_eq!(count_id(&off, 10), 0);+}++#[test]+fn terrain_classification_is_deterministic_and_bounded() {+ let gen = TerrainGen::new(42);+ let twin = TerrainGen::new(42);+ for wx in -200..200 {+ for wz in [-137, 0, 91] {+ let (wx, wz) = (wx as f64, wz as f64);+ let h = gen.height_at(wx, wz);+ assert_eq!(h, twin.height_at(wx, wz), "same seed must give the same height");+ assert!((12..=128).contains(&h), "height {h} outside the clamped band");+ assert!(gen.biome_at(wx, wz, h) == twin.biome_at(wx, wz, h));+ }+ }+ // Elevation bands win over the lowland climate grid.+ assert!(matches!(gen.biome_at(0.0, 0.0, 200), Biome::FrozenPeaks | Biome::StonyPeaks | Biome::JaggedPeaks));+ assert!(matches!(gen.biome_at(0.0, 0.0, 110), Biome::SnowySlopes | Biome::Grove | Biome::WindsweptHills));+ assert!(!gen.cave_at(0.0, 0.0, 0.0) && !gen.cave_at(0.0, 200.0, 0.0), "caves stay inside 6..=112");+ assert_eq!(gen.cave_kind(0.0, 0.0, 10), 0, "the deep dark owns y<20");+ assert!(gen.cave_kind(0.0, 0.0, 60) <= 2 && gen.ocean_kind(0.0, 0.0) <= 3);+}++#[test]+fn surface_and_stone_selection_follow_the_tables() {+ let gen = TerrainGen::new(7);+ assert_eq!(gen.surface_blocks(Biome::Desert, 70, 0.0, 0.0), (6, 38));+ assert_eq!(gen.surface_blocks(Biome::Badlands, 70, 0.0, 0.0), (36, 37));+ assert_eq!(gen.surface_blocks(Biome::IceSpikes, 70, 0.0, 0.0), (11, 42));+ assert_eq!(gen.surface_blocks(Biome::FrozenPeaks, 130, 0.0, 0.0), (42, 42));+ assert_eq!(gen.surface_blocks(Biome::StonyPeaks, 130, 0.0, 0.0), (1, 1));+ assert_eq!(gen.surface_blocks(Biome::JaggedPeaks, 130, 0.0, 0.0), (11, 1), "high jagged peaks wear snow");+ assert_eq!(gen.surface_blocks(Biome::JaggedPeaks, 100, 0.0, 0.0), (1, 1));+ assert_eq!(gen.surface_blocks(Biome::MushroomFields, 70, 0.0, 0.0), (41, 2));+ assert_eq!(gen.surface_blocks(Biome::Swamp, 70, 0.0, 0.0), (45, 45));+ assert_eq!(gen.surface_blocks(Biome::Plains, 70, 0.0, 0.0), (3, 2));+ // A vein table whose threshold always passes must win inside its y-band+ // and fall back to the base stone outside it.+ let always: [Vein; 1] = [(20, 0.0, 0.1, -2.0, 5, 20)];+ assert_eq!(gen.stone_at(&always, 3.0, 10, 4.0, 1), 20);+ assert_eq!(gen.stone_at(&always, 3.0, 21, 4.0, 1), 1);+ assert_eq!(gen.stone_at(&always, 3.0, 4, 4.0, 1), 1);+ assert_eq!(gen.stone_at(&[], 3.0, 10, 4.0, 57), 57);+ // Richest-first: the first matching vein in the table wins.+ let two: [Vein; 2] = [(22, 0.0, 0.1, -2.0, 5, 20), (20, 0.0, 0.1, -2.0, 5, 20)];+ assert_eq!(gen.stone_at(&two, 3.0, 10, 4.0, 1), 22);+ assert_eq!(gen.deep_base(0.0, 0, 0.0), 57, "the world floor is deepslate");+ assert_eq!(gen.deep_base(0.0, 100, 0.0), 1, "the upper world is plain stone");+}++#[test]+fn dimension_fills_have_their_signatures() {+ // Nether: bedrock floor and roof, netherrack/lava between them.+ let nether = TerrainGen::new_dim(99, 1);+ let mut nc = empty_chunk(0, 0);+ nether.fill_chunk(&mut nc);+ assert!(nc.generated && nc.mesh_dirty);+ assert_eq!(nc.get_block(0, 0, 0), 13);+ assert_eq!(nc.get_block(0, 120, 0), 13);+ assert!(count_id(&nc, 32) + count_id(&nc, 84) > 1000, "the nether is netherrack and lava");+ // End: a guaranteed central island around y=62, void above it.+ let end = TerrainGen::new_dim(99, 2);+ let mut ec = empty_chunk(0, 0);+ end.fill_chunk(&mut ec);+ assert_eq!(ec.get_block(8, 62, 8), 85, "the central island is guaranteed");+ assert_eq!(ec.get_block(8, 100, 8), 0, "the End is void above its islands");+ assert_eq!(ec.get_block(2, 65, 2), 78, "obsidian pillars stand on the central island");+ // Overworld: bedrock at the very bottom, solid ground somewhere.+ let over = TerrainGen::new(42);+ let mut oc = empty_chunk(0, 0);+ over.fill_chunk(&mut oc);+ for x in 0..16 { assert_eq!(oc.get_block(x, 0, 0), 13); }+ assert!(count_id(&oc, 1) > 100, "the overworld has stone");+ // A different dimension value falls back to the overworld.+ let other = TerrainGen::new_dim(42, 9);+ let mut dc = empty_chunk(0, 0);+ other.fill_chunk(&mut dc);+ assert_eq!(dc.get_block(0, 0, 0), 13);+}++#[test]+fn grass_tint_and_ensure_water_behave() {+ let gen = TerrainGen::new(42);+ for wx in (-300..300).step_by(37) {+ for wz in (-300..300).step_by(41) {+ for c in gen.grass_tint(wx as f64, wz as f64) {+ assert!(c.is_finite() && (0.0..=1.0).contains(&c), "tint {c} out of range");+ }+ }+ }+ // Find a lowland column, then flooding it must reach sea level exactly.+ let mut flooded = None;+ 'scan: for cx in -4..4 {+ for cz in -4..4 {+ let mut c = empty_chunk(cx, cz);+ gen.ensure_water(&mut c);+ for dz in 0..16 {+ for dx in 0..16 {+ let wx = (cx * 16 + dx as i32) as f64;+ let wz = (cz * 16 + dz as i32) as f64;+ if gen.height_at(wx, wz) < TerrainGen::SEA_LEVEL as i32+ && matches!(c.get_block(dx, TerrainGen::SEA_LEVEL, dz), 12 | 43) {+ flooded = Some(c.get_block(dx, TerrainGen::SEA_LEVEL, dz));+ break 'scan;+ }+ }+ }+ }+ }+ assert!(flooded.is_some(), "some lowland column must flood to sea level");+ // Water is a no-op outside the overworld and idempotent inside it.+ let nether = TerrainGen::new_dim(42, 1);+ let mut nc = empty_chunk(0, 0);+ nether.ensure_water(&mut nc);+ assert_eq!(count_id(&nc, 12), 0);+ let mut once = empty_chunk(-1, -1);+ gen.ensure_water(&mut once);+ let before = count_id(&once, 12) + count_id(&once, 43);+ gen.ensure_water(&mut once);+ assert_eq!(count_id(&once, 12) + count_id(&once, 43), before, "flooding twice changes nothing");+}