voxels_engine: fix clippy warnings
- Commit
841d41bd97b6ba76e11e953d6072fee7f2c7aee6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 14:12 UTC (18 days ago)
- Parents
6d8662b
Fix every cargo check and clippy warning in the voxels_engine crate: range-contains and clamp idioms, collapsed conditionals, needless range loops rewritten over iterators in the mesher and terrain generator, and the unused-mut / dead-assignment / unnecessary-unsafe findings. Group wide argument lists into purpose-built structs (Burst, Tree, Building, Corridor, TextureUpload, PipelineDeps and UboFrame, plus grouped smelt inputs) instead of suppressing too_many_arguments, rename the Block variants that repeated the enum name (discriminants unchanged, so saved ids are stable), derive Default for InvSlot, annotate the block transmute, add ChunkMap::is_empty, take Attunement::to_json by value, and move the constant id-space assertions into const blocks. Document the Safety contract on every public unsafe Vulkan and atlas function that was missing one. No allow attributes were added and no files outside games/voxels/src/main/rust/ change. Verification: cargo check -p voxels_engine --all-targets, cargo clippy -p voxels_engine --all-targets and cargo test -p voxels_engine all pass with zero crate warnings (135 unit tests plus 5 integration tests). The pre-existing workspace warnings that profiles for non-root packages are ignored are untouched, as they come from the workspace root, not this crate.
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 83e331c957..ef39ee19dd 100644--- a/games/voxels/src/main/rust/src/blessing.rs+++ b/games/voxels/src/main/rust/src/blessing.rs@@ -119,7 +119,7 @@ impl Attunement { self.slots[slot] = 0; Some(id) }- pub fn to_json(&self) -> String {+ pub fn to_json(self) -> String { let list: Vec<_> = self.slots.iter().map(|&id| { match find(id) { Some(b) => serde_json::json!({"id": b.id, "name": b.name, "effect": b.effect}),
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 9d6fb33916..e862613844 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -108,7 +108,7 @@ const NOON_OFFSET: f32 = DAY_CYCLE * 0.5; pub fn day_t_at(elapsed: f32) -> f32 { ((NOON_OFFSET + elapsed) / DAY_CYCLE) % 1.0 } // The sun is below the horizon at both ends of the cycle (day_t = 0 is midnight). This band is not // arbitrary: renderer.rs derives sun height as -cos(day_t * TAU), which is negative exactly here.-pub fn is_night_at(day_t: f32) -> bool { day_t < 0.25 || day_t > 0.75 }+pub fn is_night_at(day_t: f32) -> bool { !(0.25..=0.75).contains(&day_t) } /// The world clock wraps after this many seconds: a whole number of days (96), so wrapping never /// shifts the time of day, while keeping f32 precision fine over endless sessions. pub const WORLD_SECS_WRAP: f32 = 86_400.0;@@ -188,8 +188,7 @@ pub fn new_state(files_dir: String, seed: u32, render_distance: i32) -> EngineSt let progress = player_save.as_ref().map(|ps| ps.progress.clone()).unwrap_or_default(); let (px, py, pz, yaw, pitch, inv) = if let Some(ps) = &player_save { let inv = {- let mut inv = Inventory::default();- inv.selected = ps.inventory.selected.min(8);+ let mut inv = Inventory { selected: ps.inventory.selected.min(8), ..Default::default() }; for (i, slot) in ps.inventory.slots.iter().enumerate().take(inv.slots.len()) { inv.slots[i].id = slot.id; inv.slots[i].count = slot.count;
games/voxels/src/main/rust/src/engine_part1.rs
diff --git a/games/voxels/src/main/rust/src/engine_part1.rs b/games/voxels/src/main/rust/src/engine_part1.rsindex 57737218df..1d17fd35a0 100644--- a/games/voxels/src/main/rust/src/engine_part1.rs+++ b/games/voxels/src/main/rust/src/engine_part1.rs@@ -151,7 +151,7 @@ fn simulate(state: &mut EngineState, dt: f32) { if tier == 0 { continue; } let d2 = dx * dx + dz * dz; let range = tier * 10 + 10;- if d2 <= range * range && best.map_or(true, |b| d2 < b.1) {+ if d2 <= range * range && best.is_none_or(|b| d2 < b.1) { best = Some((tier, d2)); } }@@ -231,12 +231,12 @@ fn simulate(state: &mut EngineState, dt: f32) { // Slain Ender Dragon: mark defeated + a victory burst of particles. if let Some(dpos) = state.mobs.iter().find(|m| m.kind == MobKind::Dragon && m.health <= 0.0).map(|m| m.pos) { state.end_dragon_dead = true;- spawn_particles(&mut state.spawn_rng, &mut state.particles, dpos, 60, [0.7, 0.3, 0.95], 8.0, 1.4, 0.4);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: dpos, n: 60, color: [0.7, 0.3, 0.95], speed: 8.0, life: 1.4, size: 0.4 }); } // Slain Wither: mark defeated + drop the Nether Star (via loot) + a dark burst. if let Some(wpos) = state.mobs.iter().find(|m| m.kind == MobKind::Wither && m.health <= 0.0).map(|m| m.pos) { state.nether_wither_dead = true;- spawn_particles(&mut state.spawn_rng, &mut state.particles, wpos, 60, [0.15, 0.15, 0.2], 8.0, 1.4, 0.4);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: wpos, n: 60, color: [0.15, 0.15, 0.2], speed: 8.0, life: 1.4, size: 0.4 }); } // Remove dead mobs and auto-collect their drops. Glaucus makes ordinary kills pay double, // but not bosses — a second Nether Star would hand out a free extra beacon.@@ -259,7 +259,7 @@ fn simulate(state: &mut EngineState, dt: f32) { if state.mobs.len() < 22 { use crate::world::chunk::CHUNK_HEIGHT; let mut rng = state.spawn_rng;- let mut rand = |r: &mut u32| { let mut x = *r; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *r = x; (x >> 8) as f32 / 16_777_216.0 };+ let rand = |r: &mut u32| { let mut x = *r; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *r = x; (x >> 8) as f32 / 16_777_216.0 }; let ang = rand(&mut rng) * std::f32::consts::TAU; let dist = 24.0 + rand(&mut rng) * 20.0; let sx = player_pos.x + ang.cos() * dist;@@ -380,7 +380,7 @@ fn render_frame(state: &mut EngineState) { let dim = state.dim; let rain = state.rain; unsafe {- renderer.update_ubo(view_proj, state.player.pos, time, underwater, nv, dim, rain);+ renderer.update_ubo(crate::vulkan::renderer::UboFrame { view_proj, player_pos: state.player.pos, time, underwater, night_vision: nv, dim, rain }); renderer.upload_entity_mesh(&entity_verts, &entity_indices); let _ = renderer.draw_frame(pcx, pcz, uploads); }
games/voxels/src/main/rust/src/engine_part2.rs
diff --git a/games/voxels/src/main/rust/src/engine_part2.rs b/games/voxels/src/main/rust/src/engine_part2.rsindex 5aeb732e48..a45648c5d6 100644--- a/games/voxels/src/main/rust/src/engine_part2.rs+++ b/games/voxels/src/main/rust/src/engine_part2.rs@@ -311,11 +311,11 @@ fn tick_projectiles(state: &mut EngineState, dt: f32) { state.player.vel = Vec3::ZERO; state.player.air_max_y = state.player.pos.y; // no fall damage from the teleport state.player.damage(2.0); // ender pearls jar you a little- spawn_particles(&mut state.spawn_rng, &mut state.particles, tp, 16, [0.25, 0.85, 0.7], 4.0, 0.6, 0.14);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: tp, n: 16, color: [0.25, 0.85, 0.7], speed: 4.0, life: 0.6, size: 0.14 }); } for (pos, color, big) in bursts { let n = if big { 24 } else { 10 };- spawn_particles(&mut state.spawn_rng, &mut state.particles, pos, n, color, if big { 5.0 } else { 3.0 }, 0.6, if big { 0.22 } else { 0.13 });+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: pos, n, color, speed: if big { 5.0 } else { 3.0 }, life: 0.6, size: if big { 0.22 } else { 0.13 } }); } } @@ -333,7 +333,7 @@ fn tick_fishing(state: &mut EngineState, dt: f32, player_pos: Vec3) { } if state.fishing.tick(dt) { // A bite: splash, so the player knows to strike without needing to watch a HUD element.- spawn_particles(&mut state.spawn_rng, &mut state.particles, bob, 10, [0.60, 0.80, 0.95], 3.0, 0.5, 0.09);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: bob, n: 10, color: [0.60, 0.80, 0.95], speed: 3.0, life: 0.5, size: 0.09 }); } // The float itself, redrawn each frame as a short-lived particle. if state.particles.len() < 480 {
games/voxels/src/main/rust/src/engine_part3.rs
diff --git a/games/voxels/src/main/rust/src/engine_part3.rs b/games/voxels/src/main/rust/src/engine_part3.rsindex 8136cc2575..633a7c3612 100644--- a/games/voxels/src/main/rust/src/engine_part3.rs+++ b/games/voxels/src/main/rust/src/engine_part3.rs@@ -1,6 +1,9 @@ // Spawn a small burst of particles (capped so the buffer never overflows).-fn spawn_particles(rng: &mut u32, out: &mut Vec<Particle>, center: Vec3, n: usize, color: [f32; 3], speed: f32, life: f32, size: f32) {- let mut r = |s: &mut u32| { let mut x = *s; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *s = x; (x >> 8) as f32 / 16_777_216.0 * 2.0 - 1.0 };+/// What one particle burst looks like: where, how many, and how they fly.+struct Burst { center: Vec3, n: usize, color: [f32; 3], speed: f32, life: f32, size: f32 }+fn spawn_particles(rng: &mut u32, out: &mut Vec<Particle>, burst: Burst) {+ let Burst { center, n, color, speed, life, size } = burst;+ let r = |s: &mut u32| { let mut x = *s; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *s = x; (x >> 8) as f32 / 16_777_216.0 * 2.0 - 1.0 }; for _ in 0..n { if out.len() > 500 { break; } let v = vec3(r(rng) * speed, r(rng).abs() * speed + 1.0, r(rng) * speed);@@ -59,8 +62,8 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { } } // Firework rocket: consume one to launch a burst; boosts the player forward while gliding.- if item::is_firework(sel) && state.player.eat_cd <= 0.0 {- if state.inventory.consume_selected().is_some() {+ if item::is_firework(sel) && state.player.eat_cd <= 0.0+ && state.inventory.consume_selected().is_some() { state.player.firework_boost(); let f = state.player.forward(); let origin = state.player.eye_pos() + f * 0.5;@@ -68,7 +71,6 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { state.player.eat_cd = 0.4; return true; }- } // Brushing: sweep suspicious sand for whatever was buried in it. The sand stays behind either // way, so a dig site can't be turned into a hole by accident. if sel == crate::item::BRUSH {@@ -86,7 +88,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { mark_neighbors_dirty(state, x, z); damage_tool(state); let c = vec3(x as f32 + 0.5, y as f32 + 1.0, z as f32 + 0.5);- spawn_particles(&mut state.spawn_rng, &mut state.particles, c, 12, [0.86, 0.78, 0.58], 2.5, 0.6, 0.1);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: c, n: 12, color: [0.86, 0.78, 0.58], speed: 2.5, life: 0.6, size: 0.1 }); return true; } }@@ -158,7 +160,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { if p.from_player || p.kind != ProjKind::Fireball { continue; } let to = p.pos - eye_pos; let d = to.length();- if d < 4.5 && to.normalize_or_zero().dot(f) > 0.5 && best.map_or(true, |b| d < b.1) { best = Some((i, d)); }+ if d < 4.5 && to.normalize_or_zero().dot(f) > 0.5 && best.is_none_or(|b| d < b.1) { best = Some((i, d)); } } if let Some((i, _)) = best { let p = &mut state.projectiles[i];@@ -184,14 +186,13 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { state.player.eat_cd = 0.8; return true; }- } else if item::is_heart_container(sel) && state.player.max_health < crate::player::CAP_MAX_HEALTH {- if state.inventory.consume_selected().is_some() {+ } else if item::is_heart_container(sel) && state.player.max_health < crate::player::CAP_MAX_HEALTH+ && state.inventory.consume_selected().is_some() { state.player.max_health = (state.player.max_health + 2.0).min(crate::player::CAP_MAX_HEALTH); state.player.heal(2.0); state.player.eat_cd = 0.8; return true; }- } } // Attack a mob if one is under the cursor within reach and nearer than any block. let reach = player_reach(state);@@ -216,7 +217,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { } state.player.lifesteal(dmg); state.player.wind_burst();- spawn_particles(&mut state.spawn_rng, &mut state.particles, mpos, 6, [0.85, 0.12, 0.12], 3.0, 0.4, 0.09);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: mpos, n: 6, color: [0.85, 0.12, 0.12], speed: 3.0, life: 0.4, size: 0.09 }); return true; } }@@ -228,10 +229,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { let key = ensure_chest(state, x, y, z); // Only break the chest once everything actually fit — otherwise the leftovers would be // dropped on the floor, which this game has no representation for.- let mut left = match state.containers.remove(key) {- Some(slots) => slots,- None => Vec::new(),- };+ let mut left = state.containers.remove(key).unwrap_or_default(); for s in left.iter_mut() { state.inventory.take_from(s); } if left.iter().any(|s| s.id != 0) { state.containers.insert(key, left);@@ -268,7 +266,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { damage_tool(state); mark_neighbors_dirty(state, x, z); let c = vec3(x as f32 + 0.5, y as f32 + 0.5, z as f32 + 0.5);- spawn_particles(&mut state.spawn_rng, &mut state.particles, c, 7, [0.55, 0.45, 0.35], 2.6, 0.5, 0.11);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: c, n: 7, color: [0.55, 0.45, 0.35], speed: 2.6, life: 0.5, size: 0.11 }); return true; } }
games/voxels/src/main/rust/src/engine_part4.rs
diff --git a/games/voxels/src/main/rust/src/engine_part4.rs b/games/voxels/src/main/rust/src/engine_part4.rsindex f00b99d7d9..57ae217bf6 100644--- a/games/voxels/src/main/rust/src/engine_part4.rs+++ b/games/voxels/src/main/rust/src/engine_part4.rs@@ -47,7 +47,7 @@ fn tick_farmland(state: &mut EngineState, dt: f32, player_pos: Vec3) { let (px, py, pz) = (player_pos.x.floor() as i32, player_pos.y.floor() as i32, player_pos.z.floor() as i32); let mut r = state.spawn_rng;- let mut next = |s: &mut u32| { *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5; *s };+ let next = |s: &mut u32| { *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5; *s }; let mut grown: Vec<(i32, i32)> = Vec::new(); for _ in 0..FARM_SAMPLES { let a = next(&mut r);@@ -157,8 +157,8 @@ fn explode(state: &mut EngineState, center: Vec3, radius: f32) { for (x, z) in cols { mark_neighbors_dirty(state, x, z); } let pd = (state.player.pos - center).length(); if pd < radius * 2.0 { hurt_player(state, (1.0 - pd / (radius * 2.0)).max(0.0) * 22.0); }- spawn_particles(&mut state.spawn_rng, &mut state.particles, center, 30, [0.28, 0.25, 0.22], 6.0, 0.9, 0.3);- spawn_particles(&mut state.spawn_rng, &mut state.particles, center, 12, [1.0, 0.55, 0.15], 5.0, 0.5, 0.22);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center, n: 30, color: [0.28, 0.25, 0.22], speed: 6.0, life: 0.9, size: 0.3 });+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center, n: 12, color: [1.0, 0.55, 0.15], speed: 5.0, life: 0.5, size: 0.22 }); } /// Which way a stair placed now should face. Its low side looks back at the player so that walking@@ -226,13 +226,12 @@ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { if state.chunks.get_block_world(tx, ty, tz) == sel { let existing_top = state.chunks.get_meta_world(tx, ty, tz) & crate::world::block::META_TOP != 0; // Only the face on the cell's empty side can complete it.- if (existing_top && hit.normal.1 == -1) || (!existing_top && hit.normal.1 == 1) {- if state.inventory.consume_selected().is_some() {+ if ((existing_top && hit.normal.1 == -1) || (!existing_top && hit.normal.1 == 1))+ && state.inventory.consume_selected().is_some() { state.chunks.set_block_world(tx, ty, tz, block.parent() as Id); mark_neighbors_dirty(state, tx, tz); return true; }- } } } @@ -308,7 +307,7 @@ fn place_at(state: &mut EngineState, px: f32, py: f32) -> i32 { state.weather = WEATHER_CLEAR; state.weather_cd = weather_duration(0.4); let c = vec3(x as f32 + 0.5, y as f32 + 1.2, z as f32 + 0.5);- spawn_particles(&mut state.spawn_rng, &mut state.particles, c, 20, [1.0, 0.82, 0.42], 2.0, 1.0, 0.12);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, Burst { center: c, n: 20, color: [1.0, 0.82, 0.42], speed: 2.0, life: 1.0, size: 0.12 }); return 1; } if id == 83 { // chest: open its container@@ -317,9 +316,8 @@ fn place_at(state: &mut EngineState, px: f32, py: f32) -> i32 { return 30; } // Tap an obsidian frame with flint & steel to ignite a nether portal.- if id == 78 && state.dim != 2 && crate::item::is_flint_steel(state.inventory.selected_block()) {- if light_portal(state, x, y, z) { state.inventory.damage_selected(); return 41; }- }+ if id == 78 && state.dim != 2 && crate::item::is_flint_steel(state.inventory.selected_block())+ && light_portal(state, x, y, z) { state.inventory.damage_selected(); return 41; } let m = crate::world::block::Block::from_id(id).menu(); if m != 0 { return 10 + m; } }
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 6bf75c00c3..4cd15e23f7 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -6,8 +6,8 @@ pub const HOTBAR: usize = 9; pub const STACK: i32 = 64; #[derive(Debug, Clone, Copy, Serialize, Deserialize)]+#[derive(Default)] pub struct InvSlot { pub id: Id, pub count: i32 }-impl Default for InvSlot { fn default() -> Self { Self { id: 0, count: 0 } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Inventory {@@ -46,7 +46,7 @@ pub const RECIPES: [Recipe; 96] = [ r(1055, 3, 1033, 2, 1149, 1, 1055), // sticks + leather -> fishing rod r(1055, 1, 1132, 1, 1151, 1, 1055), // stick + copper -> archaeologist's brush r(1147, 3, 0, 0, 1027, 1, 1146), // wheat -> bread- r(Block::HayBlock as Id, 1, 0, 0, 1146, 4, 0), // hay bale -> wheat seeds+ r(Block::Hay as Id, 1, 0, 0, 1146, 4, 0), // hay bale -> wheat seeds r(1083, 1, Block::Glass as Id, 5, Block::Beacon as Id, 1, 1065), // nether star + glass -> beacon r(1034, 2, 0, 0, 1085, 3, 0), // gunpowder -> firework rockets r(Block::Snow as Id, 1, 0, 0, 1086, 4, 0), // snow -> snowballs@@ -58,9 +58,9 @@ pub const RECIPES: [Recipe; 96] = [ r(Block::Diorite as Id, 4, 0, 0, Block::PolishedDiorite as Id, 4, 0), r(Block::Planks as Id, 2, 0, 0, 1055 /*Stick*/, 4, 0), // Material -> block.- r(1050, 9, 0, 0, Block::IronBlock as Id, 1, 1061),- r(1051, 9, 0, 0, Block::DiamondBlock as Id, 1, 1063),- r(1052, 9, 0, 0, Block::EmeraldBlock as Id, 1, 1063),+ r(1050, 9, 0, 0, Block::Iron as Id, 1, 1061),+ r(1051, 9, 0, 0, Block::Diamond as Id, 1, 1063),+ r(1052, 9, 0, 0, Block::Emerald as Id, 1, 1063), // Tools: material + stick(1055). r(Block::Planks as Id, 3, 1055, 2, 1059, 1, 0), // wood pickaxe r(Block::Planks as Id, 2, 1055, 1, 1060, 1, 0), // wood sword@@ -79,9 +79,9 @@ pub const RECIPES: [Recipe; 96] = [ r(1092, 2, 1055, 1, 1094, 1, 1093), // adamant sword r(1092, 5, 0, 0, 1095, 1, 1093), r(1092, 8, 0, 0, 1096, 1, 1093), r(1092, 7, 0, 0, 1097, 1, 1093), r(1092, 4, 0, 0, 1098, 1, 1093), // Metal storage blocks (silver/steel/adamant also power beacons).- r(1089, 9, 0, 0, Block::SilverBlock as Id, 1, Block::BlastFurnace as Id),- r(1091, 9, 0, 0, Block::SteelBlock as Id, 1, Block::BlastFurnace as Id),- r(1092, 9, 0, 0, Block::AdamantBlock as Id, 1, Block::BlastFurnace as Id),+ r(1089, 9, 0, 0, Block::Silver as Id, 1, Block::BlastFurnace as Id),+ r(1091, 9, 0, 0, Block::Steel as Id, 1, Block::BlastFurnace as Id),+ r(1092, 9, 0, 0, Block::Adamant as Id, 1, Block::BlastFurnace as Id), // A steel-lined furnace: the only place the alloy recipes will smelt. r(Block::Furnace as Id, 1, 1091, 5, Block::BlastFurnace as Id, 1, Block::Furnace as Id), // Blessings: quicksilver charms bound to a thematic offering. Attuning one grants a permanent@@ -97,7 +97,7 @@ pub const RECIPES: [Recipe; 96] = [ r(1090, 2, 1034, 8, 1104, 1, Block::BlastFurnace as Id), // gunpowder -> Arachnae, bane of horrors r(1090, 2, 1092, 2, 1105, 1, Block::BlastFurnace as Id), // adamant -> Prometheus, armor never wears r(1090, 2, 1051, 3, 1106, 1, Block::BlastFurnace as Id), // diamond -> Lu Ban, mending- r(1090, 2, Block::EmeraldBlock as Id, 1, 1107, 1, Block::BlastFurnace as Id), // Eros, fortune+ r(1090, 2, Block::Emerald as Id, 1, 1107, 1, Block::BlastFurnace as Id), // Eros, fortune r(1090, 2, 1087, 3, 1108, 1, Block::BlastFurnace as Id), // ender pearls -> Will, reach r(1090, 2, Block::Glowstone as Id, 4, 1109, 1, Block::BlastFurnace as Id), // Hyacinthus, second jump r(1090, 2, Block::Purpur as Id, 6, 1110, 1, Block::BlastFurnace as Id), // Aeolus, wind burst@@ -107,9 +107,9 @@ pub const RECIPES: [Recipe; 96] = [ r(1090, 2, Block::Amethyst as Id, 6, 1114, 1, Block::BlastFurnace as Id), // Apollo, marksman r(1090, 2, 1086, 16, 1115, 1, Block::BlastFurnace as Id), // snowballs -> Artemis, multishot r(1090, 2, Block::WardingStone as Id, 2, 1116, 1, Block::BlastFurnace as Id), // Warding, thorns- r(1090, 2, Block::DiamondBlock as Id, 1, 1117, 1, Block::BlastFurnace as Id), // Paris, infinity+ r(1090, 2, Block::Diamond as Id, 1, 1117, 1, Block::BlastFurnace as Id), // Paris, infinity // The five late additions cost the alloy tier, so they arrive after the Blast Furnace does.- r(1090, 2, Block::IronBlock as Id, 2, 1141, 1, Block::BlastFurnace as Id), // Athena, absorption shield+ r(1090, 2, Block::Iron as Id, 2, 1141, 1, Block::BlastFurnace as Id), // Athena, absorption shield r(1090, 2, Block::Magma as Id, 4, 1142, 1, Block::BlastFurnace as Id), // Sekhmet, bloodrage r(1090, 2, 1118, 12, 1143, 1, Block::BlastFurnace as Id), // raw meat -> Camazotz, lifesteal r(1090, 2, Block::Prismarine as Id, 8, 1144, 1, Block::BlastFurnace as Id), // Tangaroa, conduit@@ -134,9 +134,9 @@ pub const RECIPES: [Recipe; 96] = [ r(1134, 3, 1055, 2, 1135, 1, 1063), // bronze pickaxe r(1134, 2, 1055, 1, 1136, 1, 1135), // bronze sword r(1134, 5, 0, 0, 1137, 1, 1135), r(1134, 8, 0, 0, 1138, 1, 1135), r(1134, 7, 0, 0, 1139, 1, 1135), r(1134, 4, 0, 0, 1140, 1, 1135),- r(1132, 9, 0, 0, Block::CopperBlock as Id, 1, 1063),- r(1133, 9, 0, 0, Block::GoldBlock as Id, 1, 1063),- r(1134, 9, 0, 0, Block::BronzeBlock as Id, 1, 1063),+ r(1132, 9, 0, 0, Block::Copper as Id, 1, 1063),+ r(1133, 9, 0, 0, Block::Gold as Id, 1, 1063),+ r(1134, 9, 0, 0, Block::Bronze as Id, 1, 1063), // The stonecutter itself: an iron blade on a stone bed. r(Block::Stone as Id, 3, 1050, 1, Block::Stonecutter as Id, 1, 1061), ];@@ -151,30 +151,30 @@ pub struct Smelt { pub secs: f32, pub blast: bool, }-const fn smelt(in1: Id, n1: i32, in2: Id, n2: i32, out: Id, out_n: i32, secs: f32, blast: bool) -> Smelt {- Smelt { in1, n1, in2, n2, out, out_n, secs, blast }+const fn smelt(first: (Id, i32), second: (Id, i32), output: (Id, i32), secs: f32, blast: bool) -> Smelt {+ Smelt { in1: first.0, n1: first.1, in2: second.0, n2: second.1, out: output.0, out_n: output.1, secs, blast } } pub const SMELTING: [Smelt; 19] = [- smelt(1150, 1, 0, 0, 1028, 1, 6.0, false), // raw fish -> cooked fish- smelt(Block::CoalOre as Id, 1, 0, 0, 1053, 1, 6.0, false), // coal- smelt(Block::IronOre as Id, 1, 0, 0, 1050, 1, 8.0, false), // iron ingot- smelt(Block::DiamondOre as Id, 1, 0, 0, 1051, 1, 10.0, false),- smelt(Block::EmeraldOre as Id, 1, 0, 0, 1052, 1, 10.0, false),- smelt(Block::RedstoneOre as Id, 1, 0, 0, 1054, 1, 6.0, false),- smelt(Block::SilverOre as Id, 1, 0, 0, 1089, 1, 9.0, false), // silver ingot- smelt(Block::Sand as Id, 2, 0, 0, Block::Glass as Id, 1, 5.0, false),- smelt(Block::Cobble as Id, 4, 0, 0, Block::Stone as Id, 1, 5.0, false),- smelt(Block::Clay as Id, 4, 0, 0, Block::Brick as Id, 1, 6.0, false),- smelt(1118, 1, 0, 0, 1119, 1, 6.0, false), // raw meat -> cooked meat- smelt(1027, 1, 0, 0, 1043, 3, 5.0, false), // bread -> cookies (baking)- smelt(Block::CopperOre as Id, 1, 0, 0, 1132, 1, 6.0, false), // copper ingot- smelt(Block::GoldOre as Id, 1, 0, 0, 1133, 1, 8.0, false), // gold ingot- smelt(1132, 6, 1133, 1, 1134, 1, 14.0, true), // copper + gold -> bronze+ smelt((1150, 1), (0, 0), (1028, 1), 6.0, false), // raw fish -> cooked fish+ smelt((Block::CoalOre as Id, 1), (0, 0), (1053, 1), 6.0, false), // coal+ smelt((Block::IronOre as Id, 1), (0, 0), (1050, 1), 8.0, false), // iron ingot+ smelt((Block::DiamondOre as Id, 1), (0, 0), (1051, 1), 10.0, false),+ smelt((Block::EmeraldOre as Id, 1), (0, 0), (1052, 1), 10.0, false),+ smelt((Block::RedstoneOre as Id, 1), (0, 0), (1054, 1), 6.0, false),+ smelt((Block::SilverOre as Id, 1), (0, 0), (1089, 1), 9.0, false), // silver ingot+ smelt((Block::Sand as Id, 2), (0, 0), (Block::Glass as Id, 1), 5.0, false),+ smelt((Block::Cobble as Id, 4), (0, 0), (Block::Stone as Id, 1), 5.0, false),+ smelt((Block::Clay as Id, 4), (0, 0), (Block::Brick as Id, 1), 6.0, false),+ smelt((1118, 1), (0, 0), (1119, 1), 6.0, false), // raw meat -> cooked meat+ smelt((1027, 1), (0, 0), (1043, 3), 5.0, false), // bread -> cookies (baking)+ smelt((Block::CopperOre as Id, 1), (0, 0), (1132, 1), 6.0, false), // copper ingot+ smelt((Block::GoldOre as Id, 1), (0, 0), (1133, 1), 8.0, false), // gold ingot+ smelt((1132, 6), (1133, 1), (1134, 1), 14.0, true), // copper + gold -> bronze // Blast furnace only: the alloy line.- smelt(Block::SulfurOre as Id, 1, 0, 0, 1088, 2, 5.0, true), // sulfur- smelt(Block::CinnabarOre as Id, 1, 0, 0, 1090, 1, 7.0, true), // quicksilver- smelt(1050, 1, 1088, 1, 1091, 1, 12.0, true), // iron + sulfur -> steel- smelt(1091, 4, 1090, 2, 1092, 1, 20.0, true), // steel + quicksilver -> adamant+ smelt((Block::SulfurOre as Id, 1), (0, 0), (1088, 2), 5.0, true), // sulfur+ smelt((Block::CinnabarOre as Id, 1), (0, 0), (1090, 1), 7.0, true), // quicksilver+ smelt((1050, 1), (1088, 1), (1091, 1), 12.0, true), // iron + sulfur -> steel+ smelt((1091, 4), (1090, 2), (1092, 1), 20.0, true), // steel + quicksilver -> adamant ]; // Seconds of furnace burn a stack item is worth. Anything not listed can't be used as fuel.
games/voxels/src/main/rust/src/item.rs
diff --git a/games/voxels/src/main/rust/src/item.rs b/games/voxels/src/main/rust/src/item.rsindex df93c3f6ba..ae140e8edc 100644--- a/games/voxels/src/main/rust/src/item.rs+++ b/games/voxels/src/main/rust/src/item.rs@@ -144,7 +144,7 @@ mod tests { // line it would silently become unplaceable, so pin the invariant down. #[test] fn block_ids_stay_below_the_item_base() {- assert!(crate::world::block::MAX_BLOCK_ID < ITEM_BASE);+ const { assert!(crate::world::block::MAX_BLOCK_ID < ITEM_BASE) }; assert!(!is_item(crate::world::block::MAX_BLOCK_ID)); assert!(is_item(ITEM_BASE), "the boundary itself belongs to items"); }
games/voxels/src/main/rust/src/lib_jni_inventory.rs
diff --git a/games/voxels/src/main/rust/src/lib_jni_inventory.rs b/games/voxels/src/main/rust/src/lib_jni_inventory.rsindex 1ac0fb1e1e..3753b8d68e 100644--- a/games/voxels/src/main/rust/src/lib_jni_inventory.rs+++ b/games/voxels/src/main/rust/src/lib_jni_inventory.rs@@ -7,7 +7,7 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_selec slot: jint, ) { engine::with_engine(|s| {- s.inventory.select(slot.max(0).min(8) as usize);+ s.inventory.select(slot.clamp(0, 8) as usize); }); }
games/voxels/src/main/rust/src/player_part1.rs
diff --git a/games/voxels/src/main/rust/src/player_part1.rs b/games/voxels/src/main/rust/src/player_part1.rsindex caad137b68..fac0d6d0bd 100644--- a/games/voxels/src/main/rust/src/player_part1.rs+++ b/games/voxels/src/main/rust/src/player_part1.rs@@ -17,7 +17,7 @@ mod tests { plain.damage(plain.air_max_y - plain.pos.y - 3.5); assert!(plain.health < 20.0, "an unblessed fall should hurt"); - let mut blessed = blessed_player(&[1100]);+ let blessed = blessed_player(&[1100]); assert!(blessed.blessed(Passive::FeatherFall)); // The tick applies the same drop with the blessing attuned. assert_eq!(blessed.health, 20.0);
games/voxels/src/main/rust/src/raycast.rs
diff --git a/games/voxels/src/main/rust/src/raycast.rs b/games/voxels/src/main/rust/src/raycast.rsindex b77be4d6ad..c930fc486b 100644--- a/games/voxels/src/main/rust/src/raycast.rs+++ b/games/voxels/src/main/rust/src/raycast.rs@@ -82,7 +82,7 @@ pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Opt let border = if step_z > 0 { z as f32 + 1.0 } else { z as f32 }; (border - origin.z) / dir.z } else { f32::INFINITY };- let mut prev = (x,y,z);+ let mut prev; let mut dist = 0.0; // Which axis the DDA last crossed, so a cube hit reports the face it entered through without // relying on float equality between accumulated t values.
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 fc1e959699..a8874e8018 100644--- a/games/voxels/src/main/rust/src/texture_atlas.rs+++ b/games/voxels/src/main/rust/src/texture_atlas.rs@@ -7,6 +7,16 @@ pub const TILE_SIZE: u32 = 16; pub const ATLAS_W: u32 = ATLAS_TILES_PER_ROW * TILE_SIZE; // 256 pub const ATLAS_H: u32 = ATLAS_TILE_ROWS * TILE_SIZE; // 256 +/// The Vulkan objects an atlas upload runs on, grouped so texture creation+/// does not take them as five separate arguments.+pub struct TextureUpload<'a> {+ pub instance: &'a ash::Instance,+ pub device: &'a ash::Device,+ pub phys: vk::PhysicalDevice,+ pub command_pool: vk::CommandPool,+ pub queue: vk::Queue,+}+ pub struct TextureAtlas { pub image: vk::Image, pub memory: vk::DeviceMemory,@@ -15,6 +25,10 @@ pub struct TextureAtlas { } impl TextureAtlas {+ /// Creates the block atlas texture.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. `atlas_pixels` must hold the atlas image data. pub unsafe fn new( instance: &ash::Instance, device: &ash::Device,@@ -23,19 +37,20 @@ impl TextureAtlas { queue: vk::Queue, atlas_pixels: &[u8], ) -> Result<Self, String> {- Self::new_sized(instance, device, phys, command_pool, queue, ATLAS_W, ATLAS_H, atlas_pixels)+ Self::new_sized(TextureUpload { instance, device, phys, command_pool, queue }, ATLAS_W, ATLAS_H, atlas_pixels) } // Generic RGBA sampled texture of arbitrary size (used for the block atlas and the entity atlas).+ /// Creates a sized RGBA texture.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. `atlas_pixels` must be `atlas_w * atlas_h * 4` bytes. pub unsafe fn new_sized(- instance: &ash::Instance,- device: &ash::Device,- phys: vk::PhysicalDevice,- command_pool: vk::CommandPool,- queue: vk::Queue,+ upload: TextureUpload<'_>, atlas_w: u32, atlas_h: u32, atlas_pixels: &[u8], ) -> Result<Self, String> {+ let TextureUpload { instance, device, phys, command_pool, queue } = upload; let img_info = vk::ImageCreateInfo::default() .image_type(vk::ImageType::TYPE_2D) .format(vk::Format::R8G8B8A8_SRGB)@@ -80,6 +95,10 @@ impl TextureAtlas { let sampler = device.create_sampler(&sampler_info, None).map_err(|e| format!("sampler failed: {e:?}"))?; Ok(Self { image, memory, view, sampler }) }+ /// Destroys the atlas handles.+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. pub unsafe fn destroy(&mut self, device: &ash::Device) { device.destroy_sampler(self.sampler, None); device.destroy_image_view(self.view, None);
games/voxels/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/buffers.rs b/games/voxels/src/main/rust/src/vulkan/buffers.rsindex 7d11435567..ab3998b0cb 100644--- a/games/voxels/src/main/rust/src/vulkan/buffers.rs+++ b/games/voxels/src/main/rust/src/vulkan/buffers.rs@@ -68,6 +68,10 @@ pub struct AllocatedBuffer { } impl AllocatedBuffer {+ /// Allocates a Vulkan buffer.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. pub unsafe fn new(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, size: vk::DeviceSize, usage: vk::BufferUsageFlags, properties: vk::MemoryPropertyFlags) -> Result<Self, String> { let info = vk::BufferCreateInfo::default().size(size.max(1)).usage(usage).sharing_mode(vk::SharingMode::EXCLUSIVE); let buffer = device.create_buffer(&info, None).map_err(|e| format!("create buffer {e:?}"))?;@@ -79,16 +83,28 @@ impl AllocatedBuffer { device.bind_buffer_memory(buffer, memory, 0).map_err(|e| format!("bind {e:?}"))?; Ok(Self { buffer, memory, size }) }+ /// Copies `data` into the mapped buffer memory.+ ///+ /// # Safety+ /// `device` must be the device this buffer was created on, `data` must fit in the allocation, and the memory must not be in use by the GPU. pub unsafe fn upload(&self, device: &ash::Device, data: &[u8]) { if data.is_empty() { return; } let ptr = device.map_memory(self.memory, 0, data.len() as u64, vk::MemoryMapFlags::empty()).unwrap() as *mut u8; ptr.copy_from_nonoverlapping(data.as_ptr(), data.len()); device.unmap_memory(self.memory); }+ /// Destroys the buffer and frees its memory.+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. pub unsafe fn destroy(&mut self, device: &ash::Device) { device.destroy_buffer(self.buffer, None); device.free_memory(self.memory, None); }+ /// Destroys the buffer and frees its memory (shared-reference form).+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. The caller must guarantee no other reference will use or destroy them again. pub unsafe fn destroy_inner(&self, device: &ash::Device) { device.destroy_buffer(self.buffer, None); device.free_memory(self.memory, None);
games/voxels/src/main/rust/src/vulkan/context.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/context.rs b/games/voxels/src/main/rust/src/vulkan/context.rsindex d6e37d2c51..9f3d09884c 100644--- a/games/voxels/src/main/rust/src/vulkan/context.rs+++ b/games/voxels/src/main/rust/src/vulkan/context.rs@@ -18,14 +18,26 @@ extern "C" { #[cfg(not(target_os = "android"))] #[allow(non_snake_case)]+/// Non-Android stub; always returns null.+///+/// # Safety+/// No pointers are dereferenced on this platform, so no requirements are imposed on the arguments. pub unsafe fn ANativeWindow_fromSurface(_env: *mut c_void, _surface: *mut c_void) -> *mut ANativeWindow { std::ptr::null_mut() } #[cfg(not(target_os = "android"))] #[allow(non_snake_case)]+/// Non-Android stub; does nothing.+///+/// # Safety+/// The argument is never dereferenced on this platform. pub unsafe fn ANativeWindow_acquire(_window: *mut ANativeWindow) {} #[cfg(not(target_os = "android"))] #[allow(non_snake_case)]+/// Non-Android stub; does nothing.+///+/// # Safety+/// The argument is never dereferenced on this platform. pub unsafe fn ANativeWindow_release(_window: *mut ANativeWindow) {} pub struct VulkanContext {@@ -42,6 +54,10 @@ pub struct VulkanContext { } impl VulkanContext {+ /// Creates the instance, surface, device and queue.+ ///+ /// # Safety+ /// `window` must be a live, acquired `ANativeWindow` that stays alive until the surface is destroyed. pub unsafe fn new(window: *mut ANativeWindow, _width: i32, _height: i32) -> Result<Self, String> { let entry = unsafe { Entry::load().map_err(|e| format!("Entry::load failed: {e:?}"))? }; let app_name = CString::new("Voxels").unwrap();
games/voxels/src/main/rust/src/vulkan/pipeline.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/pipeline.rs b/games/voxels/src/main/rust/src/vulkan/pipeline.rsindex 9593d23351..fed2076448 100644--- a/games/voxels/src/main/rust/src/vulkan/pipeline.rs+++ b/games/voxels/src/main/rust/src/vulkan/pipeline.rs@@ -30,9 +30,32 @@ pub struct Pipelines { pub descriptor_pool: vk::DescriptorPool, pub descriptor_set: vk::DescriptorSet, }+/// Everything `Pipelines::new` needs besides the device: the render passes it+/// renders into and the images it samples, grouped as one argument.+pub struct PipelineDeps {+ pub render_pass: vk::RenderPass,+ pub shadow_render_pass: vk::RenderPass,+ pub composite_rp: vk::RenderPass,+ pub post_rp: vk::RenderPass,+ pub post_desc_layout: vk::DescriptorSetLayout,+ pub ubo_buffer: vk::Buffer,+ pub ubo_size: u64,+ pub atlas_view: vk::ImageView,+ pub atlas_sampler: vk::Sampler,+ pub shadow_view: vk::ImageView,+ pub shadow_sampler: vk::Sampler,+ pub entity_view: vk::ImageView,+ pub entity_sampler: vk::Sampler,+}+ impl Pipelines { // Classic Vulkan 1.0 RenderPass path - no KHR_dynamic_rendering, avoids Unable to load cmd_begin_rendering- pub unsafe fn new(device: &ash::Device, render_pass: vk::RenderPass, shadow_render_pass: vk::RenderPass, composite_rp: vk::RenderPass, post_rp: vk::RenderPass, post_desc_layout: vk::DescriptorSetLayout, ubo_buffer: vk::Buffer, ubo_size: u64, atlas_view: vk::ImageView, atlas_sampler: vk::Sampler, shadow_view: vk::ImageView, shadow_sampler: vk::Sampler, entity_view: vk::ImageView, entity_sampler: vk::Sampler) -> Result<Self, String> {+ /// Creates layouts, descriptor set and all pipelines.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. All render passes, views, samplers and the UBO buffer must outlive the pipelines built from them.+ pub unsafe fn new(device: &ash::Device, deps: PipelineDeps) -> Result<Self, String> {+ let PipelineDeps { render_pass, shadow_render_pass, composite_rp, post_rp, post_desc_layout, ubo_buffer, ubo_size, atlas_view, atlas_sampler, shadow_view, shadow_sampler, entity_view, entity_sampler } = deps; let bindings = [ vk::DescriptorSetLayoutBinding::default().binding(0).descriptor_type(vk::DescriptorType::UNIFORM_BUFFER).descriptor_count(1).stage_flags(vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT), vk::DescriptorSetLayoutBinding::default().binding(1).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).descriptor_count(1).stage_flags(vk::ShaderStageFlags::FRAGMENT),@@ -201,6 +224,10 @@ impl Pipelines { let code = unsafe { std::slice::from_raw_parts(spv.as_ptr() as *const u32, spv.len()/4) }; device.create_shader_module(&vk::ShaderModuleCreateInfo::default().code(code), None).map_err(|e| format!("mod {e:?}")) }+ /// Destroys all pipelines, layouts and descriptor objects.+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. pub unsafe fn destroy(&mut self, device: &ash::Device) { device.destroy_pipeline(self.pipeline, None); device.destroy_pipeline(self.sky_pipeline, None);
games/voxels/src/main/rust/src/vulkan/postfx.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/postfx.rs b/games/voxels/src/main/rust/src/vulkan/postfx.rsindex cd69b99be5..41f4d87563 100644--- a/games/voxels/src/main/rust/src/vulkan/postfx.rs+++ b/games/voxels/src/main/rust/src/vulkan/postfx.rs@@ -32,7 +32,8 @@ unsafe fn mem_type(instance: &ash::Instance, phys: vk::PhysicalDevice, bits: u32 (0..mp.memory_type_count).find(|&i| (bits & (1<<i))!=0 && mp.memory_types[i as usize].property_flags.contains(props)).ok_or("no mem type".into()) } -unsafe fn make_image(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, w: u32, h: u32, format: vk::Format, usage: vk::ImageUsageFlags, aspect: vk::ImageAspectFlags) -> Result<(vk::Image, vk::DeviceMemory, vk::ImageView), String> {+unsafe fn make_image(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, extent: vk::Extent2D, format: vk::Format, usage: vk::ImageUsageFlags, aspect: vk::ImageAspectFlags) -> Result<(vk::Image, vk::DeviceMemory, vk::ImageView), String> {+ let (w, h) = (extent.width, extent.height); let ci = vk::ImageCreateInfo::default().image_type(vk::ImageType::TYPE_2D).format(format) .extent(vk::Extent3D{width:w.max(1),height:h.max(1),depth:1}).mip_levels(1).array_layers(1) .samples(vk::SampleCountFlags::TYPE_1).tiling(vk::ImageTiling::OPTIMAL).usage(usage).initial_layout(vk::ImageLayout::UNDEFINED);@@ -72,6 +73,10 @@ fn color_rp(device: &ash::Device, format: vk::Format, with_depth: Option<vk::For } impl PostFx {+ /// Creates the post-processing render passes and targets.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. `swapchain` must be live and its depth view valid. pub unsafe fn new(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, swapchain: &Swapchain, depth_format: vk::Format) -> Result<Self, String> { let main_rp = color_rp(device, HDR_FORMAT, Some(depth_format))?; let post_rp = color_rp(device, HDR_FORMAT, None)?;@@ -103,9 +108,9 @@ impl PostFx { let ext = swapchain.extent; self.extent = ext; self.bloom_extent = vk::Extent2D { width: (ext.width/2).max(1), height: (ext.height/2).max(1) };- let (hi, hm, hv) = make_image(instance, device, phys, ext.width, ext.height, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?;- let (ai, am, av) = make_image(instance, device, phys, self.bloom_extent.width, self.bloom_extent.height, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?;- let (bi, bm, bv) = make_image(instance, device, phys, self.bloom_extent.width, self.bloom_extent.height, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?;+ let (hi, hm, hv) = make_image(instance, device, phys, ext, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?;+ let (ai, am, av) = make_image(instance, device, phys, self.bloom_extent, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?;+ let (bi, bm, bv) = make_image(instance, device, phys, self.bloom_extent, HDR_FORMAT, vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED, vk::ImageAspectFlags::COLOR)?; self.hdr_img=hi; self.hdr_mem=hm; self.hdr_view=hv; self.ba_img=ai; self.ba_mem=am; self.bloom_a_view=av; self.bb_img=bi; self.bb_mem=bm; self.bloom_b_view=bv;@@ -141,11 +146,19 @@ impl PostFx { for m in [self.hdr_mem, self.ba_mem, self.bb_mem] { if m != vk::DeviceMemory::null() { device.free_memory(m, None); } } } + /// Recreates the sized targets for a new swapchain extent.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. pub unsafe fn resize(&mut self, instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, swapchain: &Swapchain) -> Result<(), String> { self.destroy_targets(device); self.create_targets(instance, device, phys, swapchain) } + /// Destroys the render passes, descriptor objects and targets.+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. pub unsafe fn destroy(&mut self, device: &ash::Device) { self.destroy_targets(device); device.destroy_descriptor_pool(self.desc_pool, None);
games/voxels/src/main/rust/src/vulkan/renderer.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/renderer.rs b/games/voxels/src/main/rust/src/vulkan/renderer.rsindex 8fd429d460..3375db6a25 100644--- a/games/voxels/src/main/rust/src/vulkan/renderer.rs+++ b/games/voxels/src/main/rust/src/vulkan/renderer.rs@@ -38,6 +38,17 @@ fn aabb_in_frustum(planes: &[glam::Vec4; 6], min: Vec3, max: Vec3) -> bool { true } +/// Per-frame inputs to `VulkanRenderer::update_ubo`, grouped as one argument.+pub struct UboFrame {+ pub view_proj: Mat4,+ pub player_pos: Vec3,+ pub time: f32,+ pub underwater: f32,+ pub night_vision: f32,+ pub dim: u8,+ pub rain: f32,+}+ pub struct VulkanRenderer { pub ctx: VulkanContext, pub swapchain: Swapchain,@@ -75,6 +86,10 @@ pub struct VulkanRenderer { } impl VulkanRenderer {+ /// Builds the renderer on an existing Vulkan context.+ ///+ /// # Safety+ /// `ctx` must own live Vulkan handles, and this must run on the thread that will own the renderer. pub unsafe fn new(ctx: VulkanContext, width: u32, height: u32) -> Result<Self, String> { let swapchain = Swapchain::new(&ctx, width.max(1), height.max(1))?; let ubo_size = std::mem::size_of::<UboData>() as u64;@@ -86,14 +101,14 @@ impl VulkanRenderer { let atlas_pixels = crate::texture_atlas::load_atlas_bin(); let atlas = unsafe { TextureAtlas::new(&instance, &device, phys, command_pool, ctx.queue, &atlas_pixels)? }; let entity_pixels = crate::texture_atlas::load_entity_atlas_bin();- let entity_atlas = unsafe { TextureAtlas::new_sized(&instance, &device, phys, command_pool, ctx.queue, crate::texture_atlas::ENTITY_ATLAS_W, crate::texture_atlas::ENTITY_ATLAS_H, &entity_pixels)? };+ let entity_atlas = unsafe { TextureAtlas::new_sized(crate::texture_atlas::TextureUpload { instance: &instance, device: &device, phys, command_pool, queue: ctx.queue }, crate::texture_atlas::ENTITY_ATLAS_W, crate::texture_atlas::ENTITY_ATLAS_H, &entity_pixels)? }; // Dynamic host-visible buffers for the per-frame mob mesh. let entity_vbuf = unsafe { AllocatedBuffer::new(&instance, &device, phys, (MAX_ENTITY_VERTS * std::mem::size_of::<VulkanVertex>()) as u64, vk::BufferUsageFlags::VERTEX_BUFFER, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT)? }; let entity_ibuf = unsafe { AllocatedBuffer::new(&instance, &device, phys, (MAX_ENTITY_INDICES * 4) as u64, vk::BufferUsageFlags::INDEX_BUFFER, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT)? }; let shadow = unsafe { crate::vulkan::shadow::ShadowMap::new(&instance, &device, phys)? }; let postfx = unsafe { crate::vulkan::postfx::PostFx::new(&instance, &device, phys, &swapchain, vk::Format::D32_SFLOAT)? }; let ubo_buffer = unsafe { AllocatedBuffer::new(&instance, &device, phys, ubo_size, vk::BufferUsageFlags::UNIFORM_BUFFER, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT)? };- let pipelines = unsafe { Pipelines::new(&device, postfx.main_rp, shadow.render_pass, swapchain.render_pass, postfx.post_rp, postfx.desc_layout, ubo_buffer.buffer, ubo_size, atlas.view, atlas.sampler, shadow.view, shadow.sampler, entity_atlas.view, entity_atlas.sampler)? };+ let pipelines = unsafe { Pipelines::new(&device, crate::vulkan::pipeline::PipelineDeps { render_pass: postfx.main_rp, shadow_render_pass: shadow.render_pass, composite_rp: swapchain.render_pass, post_rp: postfx.post_rp, post_desc_layout: postfx.desc_layout, ubo_buffer: ubo_buffer.buffer, ubo_size, atlas_view: atlas.view, atlas_sampler: atlas.sampler, shadow_view: shadow.view, shadow_sampler: shadow.sampler, entity_view: entity_atlas.view, entity_sampler: entity_atlas.sampler })? }; let alloc_info = vk::CommandBufferAllocateInfo::default().command_pool(command_pool).level(vk::CommandBufferLevel::PRIMARY).command_buffer_count(swapchain.images.len() as u32); let command_buffers = device.allocate_command_buffers(&alloc_info).map_err(|e| format!("alloc cmd {e:?}"))?; let sem_info = vk::SemaphoreCreateInfo::default();@@ -111,6 +126,10 @@ impl VulkanRenderer { let ts_period = ctx.device_properties.limits.timestamp_period; Ok(Self { ctx, swapchain, atlas, entity_atlas, entity_vbuf, entity_ibuf, entity_index_count: 0, shadow, postfx, pipelines, command_pool, command_buffers, image_available, render_finished, in_flight_fences, ubo_buffer, ubo_data: UboData::default(), queued_meshes: HashMap::new(), gpu_meshes: HashMap::new(), current_frame: 0, frame_count: 0, width, height, query_pool, ts_period, ts_written: vec![false; img_count], pass_ms: [0.0;4], drawn_sections: 0, dim: 0, suspended: false }) }+ /// Rebuilds the swapchain at a new size.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer, with no frames in flight beyond what the call itself synchronises. pub unsafe fn resize(&mut self, width: u32, height: u32) -> Result<(), String> { if width==0 || height==0 || self.suspended { return Ok(()); } self.ctx.device.device_wait_idle().map_err(|e| format!("wait {e:?}"))?;@@ -154,10 +173,18 @@ impl VulkanRenderer { self.suspended = false; Ok(()) }+ /// Queues a meshed section for upload.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer. pub unsafe fn enqueue_mesh(&mut self, chunk_x: i32, sec_y: i32, chunk_z: i32, mesh: Option<MeshData>) { self.queued_meshes.insert((chunk_x, sec_y, chunk_z), mesh); } // Destroy all chunk meshes (used when switching dimensions — mesh keys are per chunk coord).+ /// Destroys every uploaded chunk mesh.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer, and the device must be idle or made idle by this call before handles are destroyed. pub unsafe fn clear_meshes(&mut self) { self.ctx.device.device_wait_idle().ok(); for (_, mut m) in self.gpu_meshes.drain() {@@ -169,6 +196,10 @@ impl VulkanRenderer { self.queued_meshes.clear(); } // Replace the mob mesh for this frame (host-visible buffers, clamped to capacity).+ /// Copies the entity mesh into the host-visible buffers.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer, and the buffers must not be in use by an in-flight frame. pub unsafe fn upload_entity_mesh(&mut self, verts: &[VulkanVertex], indices: &[u32]) { let nv = verts.len().min(MAX_ENTITY_VERTS); let ni = indices.len().min(MAX_ENTITY_INDICES);@@ -181,6 +212,9 @@ impl VulkanRenderer { } /// Uploads up to `budget` queued section meshes, nearest to chunk (`cx`, `cz`) first so the /// ground around the player fills in before the horizon.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer; all Vulkan handles in `self` must be valid. pub unsafe fn process_pending_uploads(&mut self, cx: i32, cz: i32, budget: usize) -> Result<(), String> { let mut processed=0; let mut keys: Vec<_> = self.queued_meshes.keys().copied().collect();@@ -222,7 +256,12 @@ impl VulkanRenderer { } Ok(()) }- pub unsafe fn update_ubo(&mut self, view_proj: Mat4, player_pos: Vec3, time: f32, underwater: f32, night_vision: f32, dim: u8, rain: f32) {+ /// Recomputes and uploads the per-frame uniform block.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer, and the UBO buffer must not be read by an in-flight frame while it is rewritten.+ pub unsafe fn update_ubo(&mut self, frame: UboFrame) {+ let UboFrame { view_proj, player_pos, time, underwater, night_vision, dim, rain } = frame; self.dim = dim; let day_cycle=crate::engine::DAY_CYCLE; let day_t=(time/day_cycle)%1.0; let sun_angle=day_t*std::f32::consts::TAU - std::f32::consts::FRAC_PI_2;@@ -281,6 +320,10 @@ impl VulkanRenderer { pub fn queued_near(&self, cx: i32, cz: i32, r: i32) -> usize { self.queued_meshes.keys().filter(|k| (k.0 - cx).abs() <= r && (k.2 - cz).abs() <= r).count() }+ /// Records and submits one frame.+ ///+ /// # Safety+ /// Must be called from the thread that owns the renderer; all Vulkan handles in `self` must be valid and the surface must be live unless suspended. pub unsafe fn draw_frame(&mut self, cx: i32, cz: i32, upload_budget: usize) -> Result<bool, String> { if self.suspended { return Ok(false); } let device=self.ctx.device.clone();@@ -401,18 +444,16 @@ impl VulkanRenderer { let post_layout = self.pipelines.post_layout; let post_rp = self.postfx.post_rp; let post_pass = |fb: vk::Framebuffer, pipe: vk::Pipeline, dset: vk::DescriptorSet, pc: [f32;4]| {- unsafe {- let bg = vk::RenderPassBeginInfo::default().render_pass(post_rp).framebuffer(fb).render_area(vk::Rect2D{offset:vk::Offset2D{x:0,y:0},extent:bext}).clear_values(std::slice::from_ref(&zero_clear));- device.cmd_begin_render_pass(cmd, &bg, vk::SubpassContents::INLINE);- device.cmd_set_viewport(cmd, 0, std::slice::from_ref(&bvp));- device.cmd_set_scissor(cmd, 0, std::slice::from_ref(&bsc));- device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipe);- device.cmd_bind_descriptor_sets(cmd, vk::PipelineBindPoint::GRAPHICS, post_layout, 0, std::slice::from_ref(&dset), &[]);- let bytes = std::slice::from_raw_parts(pc.as_ptr() as *const u8, 16);- device.cmd_push_constants(cmd, post_layout, vk::ShaderStageFlags::FRAGMENT, 0, bytes);- device.cmd_draw(cmd, 3, 1, 0, 0);- device.cmd_end_render_pass(cmd);- }+ let bg = vk::RenderPassBeginInfo::default().render_pass(post_rp).framebuffer(fb).render_area(vk::Rect2D{offset:vk::Offset2D{x:0,y:0},extent:bext}).clear_values(std::slice::from_ref(&zero_clear));+ device.cmd_begin_render_pass(cmd, &bg, vk::SubpassContents::INLINE);+ device.cmd_set_viewport(cmd, 0, std::slice::from_ref(&bvp));+ device.cmd_set_scissor(cmd, 0, std::slice::from_ref(&bsc));+ device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipe);+ device.cmd_bind_descriptor_sets(cmd, vk::PipelineBindPoint::GRAPHICS, post_layout, 0, std::slice::from_ref(&dset), &[]);+ let bytes = std::slice::from_raw_parts(pc.as_ptr() as *const u8, 16);+ device.cmd_push_constants(cmd, post_layout, vk::ShaderStageFlags::FRAGMENT, 0, bytes);+ device.cmd_draw(cmd, 3, 1, 0, 0);+ device.cmd_end_render_pass(cmd); }; let (bw, bh) = (bext.width as f32, bext.height as f32); post_pass(self.postfx.bloom_a_fb, self.pipelines.bright_pipeline, self.postfx.bright_set, [0.0,0.0,0.0,0.0]);@@ -454,6 +495,10 @@ impl VulkanRenderer { self.frame_count+=1; Ok(true) }+ /// Destroys the renderer and every Vulkan object it owns.+ ///+ /// # Safety+ /// Must be called once, from the thread that owns the renderer, after the device is idle; `self` must not be used afterwards. pub unsafe fn destroy(&mut self) { self.ctx.device.device_wait_idle().ok(); for (_, mut mesh) in self.gpu_meshes.drain() {
games/voxels/src/main/rust/src/vulkan/shadow.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/shadow.rs b/games/voxels/src/main/rust/src/vulkan/shadow.rsindex e0dbe38c23..382e72ec38 100644--- a/games/voxels/src/main/rust/src/vulkan/shadow.rs+++ b/games/voxels/src/main/rust/src/vulkan/shadow.rs@@ -15,6 +15,10 @@ pub struct ShadowMap { } impl ShadowMap {+ /// Creates the shadow map target.+ ///+ /// # Safety+ /// The Vulkan handles passed in must be valid, created from the same instance/device, and must not be destroyed or used concurrently while this call runs. pub unsafe fn new(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice) -> Result<Self, String> { let img_ci = vk::ImageCreateInfo::default() .image_type(vk::ImageType::TYPE_2D)@@ -69,6 +73,10 @@ impl ShadowMap { Ok(Self { image, memory, view, sampler, render_pass, framebuffer }) } + /// Destroys the shadow map handles.+ ///+ /// # Safety+ /// The handles owned by `self` must have been created on `device`, must not already have been destroyed, and no in-flight GPU work may still use them. pub unsafe fn destroy(&mut self, device: &ash::Device) { device.destroy_framebuffer(self.framebuffer, None); device.destroy_render_pass(self.render_pass, None);
games/voxels/src/main/rust/src/vulkan/swapchain.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/swapchain.rs b/games/voxels/src/main/rust/src/vulkan/swapchain.rsindex d17078737d..708423fb67 100644--- a/games/voxels/src/main/rust/src/vulkan/swapchain.rs+++ b/games/voxels/src/main/rust/src/vulkan/swapchain.rs@@ -37,7 +37,7 @@ impl Swapchain { let formats = ctx.surface_loader.get_physical_device_surface_formats(ctx.physical_device, ctx.surface).map_err(|e| format!("formats {e:?}"))?; let present_modes = ctx.surface_loader.get_physical_device_surface_present_modes(ctx.physical_device, ctx.surface).map_err(|e| format!("present_modes {e:?}"))?; // Fix black screen: Pixel gralloc rejects SRGB 0x3b, prefer B8G8R8A8_UNORM- let mut chosen_format = formats.get(0).copied().ok_or("no surface formats")?;+ let mut chosen_format = formats.first().copied().ok_or("no surface formats")?; for fmt in &formats { if fmt.format == vk::Format::B8G8R8A8_UNORM { chosen_format = *fmt; break; } } if chosen_format.format == vk::Format::B8G8R8A8_SRGB { if let Some(&f) = formats.iter().find(|f| f.format == vk::Format::B8G8R8A8_UNORM || f.format == vk::Format::R8G8B8A8_UNORM) { chosen_format = f; }
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 3579cff0b3..d8f6beb858 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -30,9 +30,9 @@ pub enum Block { DiamondOre = 20, RedstoneOre = 21, EmeraldOre = 22,- IronBlock = 23,- DiamondBlock = 24,- EmeraldBlock = 25,+ Iron = 23,+ Diamond = 24,+ Emerald = 25, BirchLog = 26, BirchPlanks = 27, BirchLeaves = 28,@@ -65,7 +65,7 @@ pub enum Block { NetherBricks = 55, EndStoneBricks = 56, CobbledDeepslate = 57,- HayBlock = 58,+ Hay = 58, Farmland = 59, PackedDirt = 60, TubeCoral = 61,@@ -78,7 +78,7 @@ pub enum Block { Prismarine = 68, DarkPrismarine = 69, Dripstone = 70,- MossBlock = 71,+ Moss = 71, Sculk = 72, Amethyst = 73, Calcite = 74,@@ -102,16 +102,16 @@ pub enum Block { SilverOre = 90, SulfurOre = 91, CinnabarOre = 92,- SilverBlock = 93,- SteelBlock = 94,- AdamantBlock = 95,+ Silver = 93,+ Steel = 94,+ Adamant = 95, BlastFurnace = 96, // Copper and gold round out Matcha's metals, feeding the bronze alloy. CopperOre = 97, GoldOre = 98,- CopperBlock = 99,- GoldBlock = 100,- BronzeBlock = 101,+ Copper = 99,+ Gold = 100,+ Bronze = 101, // Matcha's building set. Each slab/stair pair borrows its parent material's atlas tiles; the // top/bottom half and the stair's facing live in the per-voxel meta byte, not in the id. StoneSlab = 102,
games/voxels/src/main/rust/src/world/block_part1.rs
diff --git a/games/voxels/src/main/rust/src/world/block_part1.rs b/games/voxels/src/main/rust/src/world/block_part1.rsindex 338cd06891..1648c998fb 100644--- a/games/voxels/src/main/rust/src/world/block_part1.rs+++ b/games/voxels/src/main/rust/src/world/block_part1.rs@@ -1,6 +1,6 @@ impl Block { pub fn from_id(id: Id) -> Self {- if id <= MAX_BLOCK_ID { unsafe { std::mem::transmute(id) } } else { Self::Air }+ if id <= MAX_BLOCK_ID { unsafe { std::mem::transmute::<Id, Self>(id) } } else { Self::Air } } pub fn id(self) -> Id { self as Id } pub fn is_air(self) -> bool { matches!(self, Self::Air) }@@ -176,9 +176,9 @@ impl Block { Self::DiamondOre => 23, Self::RedstoneOre => 24, Self::EmeraldOre => 25,- Self::IronBlock => 26,- Self::DiamondBlock => 27,- Self::EmeraldBlock => 28,+ Self::Iron => 26,+ Self::Diamond => 27,+ Self::Emerald => 28, Self::BirchLog => 30, Self::BirchPlanks => 31, Self::BirchLeaves => 32,@@ -211,7 +211,7 @@ impl Block { Self::NetherBricks => 90, Self::EndStoneBricks => 91, Self::CobbledDeepslate => 92,- Self::HayBlock => 94,+ Self::Hay => 94, Self::Farmland => 95, Self::PackedDirt => 96, Self::TubeCoral => 97,@@ -224,7 +224,7 @@ impl Block { Self::Prismarine => 104, Self::DarkPrismarine => 105, Self::Dripstone => 106,- Self::MossBlock => 107,+ Self::Moss => 107, Self::Sculk => 108, Self::Amethyst => 109, Self::Calcite => 110,@@ -246,15 +246,15 @@ impl Block { Self::SilverOre => 128, Self::SulfurOre => 129, Self::CinnabarOre => 130,- Self::SilverBlock => 131,- Self::SteelBlock => 132,- Self::AdamantBlock => 133,+ Self::Silver => 131,+ Self::Steel => 132,+ Self::Adamant => 133, Self::BlastFurnace => 134, Self::CopperOre => 136, Self::GoldOre => 137,- Self::CopperBlock => 138,- Self::GoldBlock => 139,- Self::BronzeBlock => 140,+ Self::Copper => 138,+ Self::Gold => 139,+ Self::Bronze => 140, Self::Stonecutter => 141, Self::Wool => 143, Self::SuspiciousSand => 144,@@ -304,7 +304,7 @@ impl Block { Self::DarkOakLog => 79, Self::AcaciaLog => 83, Self::JungleLog => 85,- Self::HayBlock => 93,+ Self::Hay => 93, Self::Farmland => 1, Self::BlastFurnace => 135, Self::Stonecutter => 142,@@ -332,12 +332,12 @@ impl Block { matches!(self, Self::Stone | Self::Cobble | Self::Brick | Self::MossyCobble | Self::Diorite | Self::PolishedDiorite | Self::CoalOre | Self::IronOre | Self::DiamondOre | Self::RedstoneOre | Self::EmeraldOre- | Self::IronBlock | Self::DiamondBlock | Self::EmeraldBlock | Self::Netherrack | Self::Furnace+ | Self::Iron | Self::Diamond | Self::Emerald | Self::Netherrack | Self::Furnace | Self::RedSandstone | Self::Sandstone | Self::GraniteBricks | Self::DeepslateBricks | Self::NetherBricks | Self::EndStoneBricks | Self::CobbledDeepslate | Self::Prismarine | Self::DarkPrismarine | Self::Dripstone | Self::Amethyst | Self::Calcite | Self::Tuff | Self::Magma | Self::Obsidian | Self::PackedIce | Self::BlueIce | Self::Purpur- | Self::SilverOre | Self::SulfurOre | Self::CinnabarOre | Self::SilverBlock | Self::SteelBlock | Self::AdamantBlock | Self::BlastFurnace- | Self::CopperOre | Self::GoldOre | Self::CopperBlock | Self::GoldBlock | Self::BronzeBlock+ | Self::SilverOre | Self::SulfurOre | Self::CinnabarOre | Self::Silver | Self::Steel | Self::Adamant | Self::BlastFurnace+ | Self::CopperOre | Self::GoldOre | Self::Copper | Self::Gold | Self::Bronze | Self::Stonecutter | Self::StoneSlab | Self::StoneStairs | Self::CobbleSlab | Self::CobbleStairs | Self::BrickSlab | Self::BrickStairs | Self::SandstoneSlab | Self::SandstoneStairs
games/voxels/src/main/rust/src/world/block_part2.rs
diff --git a/games/voxels/src/main/rust/src/world/block_part2.rs b/games/voxels/src/main/rust/src/world/block_part2.rsindex d6ff4e8c22..a4314b598b 100644--- a/games/voxels/src/main/rust/src/world/block_part2.rs+++ b/games/voxels/src/main/rust/src/world/block_part2.rs@@ -16,7 +16,7 @@ mod tests { // One boundary, and blocks have to stay on their side of it. #[test] fn blocks_and_items_never_share_an_id() {- assert!(MAX_BLOCK_ID < crate::item::ITEM_BASE);+ const { assert!(MAX_BLOCK_ID < crate::item::ITEM_BASE) }; for id in 0..=MAX_BLOCK_ID { assert!(!crate::item::is_item(id), "block {id} reads as an item"); } assert!(crate::item::is_item(crate::item::ITEM_BASE)); // Every item id decodes to air, so a stray one in a chunk is a hole rather than a wrong block.
games/voxels/src/main/rust/src/world/chunk_map.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk_map.rs b/games/voxels/src/main/rust/src/world/chunk_map.rsindex 56ea632b40..ed1aecb18e 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -184,5 +184,6 @@ impl ChunkMap { /// Edited chunks waiting for the next save after leaving range. pub fn pending_len(&self) -> usize { self.pending.len() } pub fn len(&self) -> usize { self.chunks.len() }+ pub fn is_empty(&self) -> bool { self.chunks.is_empty() } pub fn grass_tint(&self, wx: i32, wz: i32) -> [f32; 3] { self.gen.grass_tint(wx as f64, wz as f64) } }
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 a489b6d802..b79c337ec6 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -43,9 +43,14 @@ fn hash3(a: i32, b: i32, c: u32) -> u64 { } fn in_chunk(wx: i32, wz: i32, ox: i32, oz: i32) -> bool { wx >= ox && wx < ox + 16 && wz >= oz && wz < oz + 16 } +/// One tree to plant: its cell, surface height, wood and canopy.+struct Tree { dx: usize, dz: usize, h: usize, log: Id, leaf: Id, trunk_h: usize }+/// One village building: its world corner, footprint, surface base and kind.+struct Building { bx: i32, bz: i32, w: i32, d: i32, base: usize, kind: u8 } // Render a single village building, writing only the columns that fall inside this chunk (so a // building straddling a chunk border is completed by whichever chunks overlap it).-fn render_building(chunk: &mut Chunk, ox: i32, oz: i32, bx: i32, bz: i32, w: i32, d: i32, base: usize, kind: u8) {+fn render_building(chunk: &mut Chunk, ox: i32, oz: i32, building: Building) {+ let Building { bx, bz, w, d, base, kind } = building; if base + 7 >= CHUNK_HEIGHT { return; } match kind { B_WELL => {@@ -128,7 +133,7 @@ fn build_ruined_portal(chunk: &mut Chunk, cx: usize, cz: usize, base: usize) { // A little rubble at the base, with scattered magma and glowstone. for gx in -1i32..=4 { let x = cx as i32 + gx;- if x >= 0 && x < 16 {+ if (0..16).contains(&x) { let rub = match (gx.rem_euclid(3), gx.rem_euclid(5)) { (0, _) => 76, (_, 0) => 77, _ => 78 }; // magma/glowstone/obsidian chunk.set_block(x as usize, base, cz, rub); }@@ -139,7 +144,10 @@ fn build_ruined_portal(chunk: &mut Chunk, cx: usize, cz: usize, base: usize) { // Carve one 3-wide mineshaft corridor arm from a centre along (dirx,dirz), with a plank floor, // periodic wood support frames, and only the columns inside this chunk written.-fn carve_corridor(chunk: &mut Chunk, ox: i32, oz: i32, cx: i32, cz: i32, dirx: i32, dirz: i32, len: i32, fy: usize) {+/// One mineshaft corridor arm: centre, direction, length and floor height.+struct Corridor { cx: i32, cz: i32, dirx: i32, dirz: i32, len: i32, fy: usize }+fn carve_corridor(chunk: &mut Chunk, ox: i32, oz: i32, corridor: Corridor) {+ let Corridor { cx, cz, dirx, dirz, len, fy } = corridor; for i in 0..len { let (ax, az) = (cx + dirx * i, cz + dirz * i); for p in -1..=1 {
games/voxels/src/main/rust/src/world/generator_part1.rs
diff --git a/games/voxels/src/main/rust/src/world/generator_part1.rs b/games/voxels/src/main/rust/src/world/generator_part1.rsindex 2d9aa27ec7..0dd6b91488 100644--- a/games/voxels/src/main/rust/src/world/generator_part1.rs+++ b/games/voxels/src/main/rust/src/world/generator_part1.rs@@ -58,11 +58,11 @@ impl TerrainGen { if temp < 0.28 { if variant > 0.86 { return Biome::IceSpikes; } if humid > 0.55 { return Biome::SnowyTaiga; }- return Biome::SnowyPlains;+ Biome::SnowyPlains } else if temp > 0.72 { if humid < 0.28 { return if variant > 0.72 { Biome::Badlands } else { Biome::Desert }; } if humid > 0.60 { return if variant > 0.5 { Biome::Jungle } else { Biome::SparseJungle }; }- return Biome::Savanna;+ Biome::Savanna } else { if humid < 0.30 { return Biome::Savanna; } if humid > 0.78 { return if variant > 0.7 { Biome::MushroomFields } else if temp > 0.5 { Biome::MangroveSwamp } else { Biome::Swamp }; }@@ -72,7 +72,7 @@ impl TerrainGen { if variant > 0.72 { return Biome::FlowerForest; } if variant < 0.14 { return Biome::BirchForest; } if variant < 0.30 { return Biome::Meadow; }- return Biome::Plains;+ Biome::Plains } } // Surface + subsurface block for a biome at surface height `h` (before the sea/beach override).@@ -99,7 +99,8 @@ impl TerrainGen { } } // Plant a simple tree: a trunk of `log` topped with a `leaf` canopy. Shared by all wooded biomes.- fn plant_tree(&self, chunk: &mut Chunk, dx: usize, dz: usize, h: usize, log: Id, leaf: Id, trunk_h: usize) {+ fn plant_tree(&self, chunk: &mut Chunk, tree: Tree) {+ let Tree { dx, dz, h, log, leaf, trunk_h } = tree; for ty in 1..=trunk_h { let y = h + ty; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, log); }@@ -112,7 +113,7 @@ impl TerrainGen { if lx.abs() == 2 && lz.abs() == 2 { continue; } let x = dx as i32 + lx; let z = dz as i32 + lz;- if x < 0 || x >= 16 || z < 0 || z >= 16 { continue; }+ if !(0..16).contains(&x) || !(0..16).contains(&z) { continue; } if ly == 0 && lx == 0 && lz == 0 { continue; } if chunk.get_block(x as usize, y, z as usize) == 0 { chunk.set_block(x as usize, y, z as usize, leaf);@@ -132,7 +133,7 @@ impl TerrainGen { base.clamp(12.0, 128.0) as i32 } pub fn cave_at(&self, x: f64, y: f64, z: f64) -> bool {- if y < 6.0 || y > 112.0 { return false; }+ if !(6.0..=112.0).contains(&y) { return false; } // Spaghetti tunnels: two independent noise fields both near zero carve winding 1D tubes // (Perlin-worm approximation), giving long connected passages instead of isolated blobs. let n1 = self.perlin_cave.get([x * 0.021 + 11.0, y * 0.030, z * 0.021]).abs();@@ -141,7 +142,7 @@ impl TerrainGen { if n1 < width && n2 < width { return true; } // Cheese caverns: larger open rooms, concentrated in the lower half of the world. let cheese = self.perlin_cave.get([x * 0.045, y * 0.055, z * 0.045]);- let depth_bias = ((60.0 - y) / 55.0).clamp(0.0, 1.0) as f64; // more/bigger caverns deeper+ let depth_bias = ((60.0 - y) / 55.0).clamp(0.0, 1.0); // more/bigger caverns deeper cheese > (0.70 - 0.16 * depth_bias) } // The block that fills a solid underground cell: an ore/variant vein if one passes here,@@ -237,7 +238,7 @@ impl TerrainGen { // Obsidian pillars on the central island. if ox.abs() < 16 && oz.abs() < 16 { for &(px, pz) in &[(2i32, 2i32), (12, 3), (4, 12), (11, 11)] {- if px >= 0 && px < 16 && pz >= 0 && pz < 16 {+ if (0..16).contains(&px) && (0..16).contains(&pz) { for y in 63..70 { chunk.set_block(px as usize, y, pz as usize, 78); } } }
games/voxels/src/main/rust/src/world/generator_part2.rs
diff --git a/games/voxels/src/main/rust/src/world/generator_part2.rs b/games/voxels/src/main/rust/src/world/generator_part2.rsindex 1f12b6e26c..7aa3913039 100644--- a/games/voxels/src/main/rust/src/world/generator_part2.rs+++ b/games/voxels/src/main/rust/src/world/generator_part2.rs@@ -2,14 +2,14 @@ impl TerrainGen { fn fill_overworld(&self, chunk: &mut Chunk) { let (ox, oz) = chunk.pos.world_origin(); let mut heightmap = [[0i32; CHUNK_SIZE]; CHUNK_SIZE];- for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {- heightmap[dz][dx] = self.height_at((ox + dx as i32) as f64, (oz + dz as i32) as f64);+ for (dz, row) in heightmap.iter_mut().enumerate() { for (dx, cell) in row.iter_mut().enumerate() {+ *cell = self.height_at((ox + dx as i32) as f64, (oz + dz as i32) as f64); }}- for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {+ for (dz, row) in heightmap.iter().enumerate() { for (dx, &cell) in row.iter().enumerate() { let wx = (ox + dx as i32) as f64; let wz = (oz + dz as i32) as f64;- let h = (heightmap[dz][dx] as usize).min(CHUNK_HEIGHT - 2);- let biome = self.biome_at(wx, wz, heightmap[dz][dx]);+ let h = (cell as usize).min(CHUNK_HEIGHT - 2);+ let biome = self.biome_at(wx, wz, cell); for y in 0..5 { let id = if y == 0 { 13 } else if y < 3 && self.perlin_detail.get([wx * 0.1, y as f64 * 0.2, wz *0.1]) > 0.2 { 0 } else { 1 }; if id != 0 { chunk.set_block(dx, y, dz, id); }@@ -42,13 +42,13 @@ impl TerrainGen { } }} // Vegetation / surface decoration, per biome.- for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {- let h = heightmap[dz][dx] as usize;- if h < 63 || h > 122 { continue; }+ for (dz, row) in heightmap.iter().enumerate() { for (dx, &cell) in row.iter().enumerate() {+ let h = cell as usize;+ if !(63..=122).contains(&h) { continue; } let wx = (ox + dx as i32) as f64; let wz = (oz + dz as i32) as f64; let surf = chunk.get_block(dx, h, dz);- let biome = self.biome_at(wx, wz, heightmap[dz][dx]);+ let biome = self.biome_at(wx, wz, cell); let mut hasher = DefaultHasher::new(); (ox+dx as i32, oz+dz as i32, self.seed).hash(&mut hasher); let r = hasher.finish() % 1000;@@ -59,8 +59,8 @@ impl TerrainGen { match biome { Desert => { if surf == 6 && r < 4 { let y = h + 1; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, 8); } } } Badlands => { /* barren red terrain */ }- SnowyPlains => { if surf == 11 && r < 4 { self.plant_tree(chunk, dx, dz, h, 29, 31, th); } }- SnowyTaiga => { if surf == 11 && r < 40 { self.plant_tree(chunk, dx, dz, h, 29, 31, th + 1); } }+ SnowyPlains => { if surf == 11 && r < 4 { self.plant_tree(chunk, Tree { dx, dz, h, log: 29, leaf: 31, trunk_h: th }); } }+ SnowyTaiga => { if surf == 11 && r < 40 { self.plant_tree(chunk, Tree { dx, dz, h, log: 29, leaf: 31, trunk_h: th + 1 }); } } IceSpikes => { // Tall spikes of packed ice. if surf == 11 && r < 12 {@@ -68,34 +68,34 @@ impl TerrainGen { for ty in 1..=sh { let y = h + ty; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, 42); } } } }- Taiga => { if (surf == 3 || surf == 39 || surf == 40) && r < 55 { self.plant_tree(chunk, dx, dz, h, 29, 31, th + 1); } }- Forest => { if grassy && r < 65 { if alt { self.plant_tree(chunk, dx, dz, h, 26, 28, th); } else { self.plant_tree(chunk, dx, dz, h, 4, 5, th); } } }- BirchForest => { if grassy && r < 70 { self.plant_tree(chunk, dx, dz, h, 26, 28, th + 1); } }- DarkForest => { if grassy && r < 90 { self.plant_tree(chunk, dx, dz, h, 47, 48, th); } } // dense dark oak- FlowerForest => { if grassy && r < 18 { self.plant_tree(chunk, dx, dz, h, 4, 5, th); } }- Savanna => { if grassy && r < 12 { self.plant_tree(chunk, dx, dz, h, 50, 5, th.min(5)); } } // acacia (oak leaves)- Jungle => { if grassy && r < 85 { self.plant_tree(chunk, dx, dz, h, 51, 5, th + 3); } } // tall jungle- SparseJungle => { if grassy && r < 22 { self.plant_tree(chunk, dx, dz, h, 51, 5, th + 2); } }- Swamp => { if grassy && r < 8 { self.plant_tree(chunk, dx, dz, h, 4, 5, th); } }- MangroveSwamp => { if surf == 45 && r < 20 { self.plant_tree(chunk, dx, dz, h, 51, 5, th); } }+ Taiga => { if (surf == 3 || surf == 39 || surf == 40) && r < 55 { self.plant_tree(chunk, Tree { dx, dz, h, log: 29, leaf: 31, trunk_h: th + 1 }); } }+ Forest => { if grassy && r < 65 { if alt { self.plant_tree(chunk, Tree { dx, dz, h, log: 26, leaf: 28, trunk_h: th }); } else { self.plant_tree(chunk, Tree { dx, dz, h, log: 4, leaf: 5, trunk_h: th }); } } }+ BirchForest => { if grassy && r < 70 { self.plant_tree(chunk, Tree { dx, dz, h, log: 26, leaf: 28, trunk_h: th + 1 }); } }+ DarkForest => { if grassy && r < 90 { self.plant_tree(chunk, Tree { dx, dz, h, log: 47, leaf: 48, trunk_h: th }); } } // dense dark oak+ FlowerForest => { if grassy && r < 18 { self.plant_tree(chunk, Tree { dx, dz, h, log: 4, leaf: 5, trunk_h: th }); } }+ Savanna => { if grassy && r < 12 { self.plant_tree(chunk, Tree { dx, dz, h, log: 50, leaf: 5, trunk_h: th.min(5) }); } } // acacia (oak leaves)+ Jungle => { if grassy && r < 85 { self.plant_tree(chunk, Tree { dx, dz, h, log: 51, leaf: 5, trunk_h: th + 3 }); } } // tall jungle+ SparseJungle => { if grassy && r < 22 { self.plant_tree(chunk, Tree { dx, dz, h, log: 51, leaf: 5, trunk_h: th + 2 }); } }+ Swamp => { if grassy && r < 8 { self.plant_tree(chunk, Tree { dx, dz, h, log: 4, leaf: 5, trunk_h: th }); } }+ MangroveSwamp => { if surf == 45 && r < 20 { self.plant_tree(chunk, Tree { dx, dz, h, log: 51, leaf: 5, trunk_h: th }); } } MushroomFields => { if surf == 41 && r < 3 { let y = h + 1; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, 5); } } }- Meadow => { if grassy && r == 3 { self.plant_tree(chunk, dx, dz, h, 4, 5, th); } }- Grove => { if surf == 11 && r < 30 { self.plant_tree(chunk, dx, dz, h, 29, 31, th); } }- WindsweptHills => { if grassy && r < 6 { self.plant_tree(chunk, dx, dz, h, 29, 31, th); } }+ Meadow => { if grassy && r == 3 { self.plant_tree(chunk, Tree { dx, dz, h, log: 4, leaf: 5, trunk_h: th }); } }+ Grove => { if surf == 11 && r < 30 { self.plant_tree(chunk, Tree { dx, dz, h, log: 29, leaf: 31, trunk_h: th }); } }+ WindsweptHills => { if grassy && r < 6 { self.plant_tree(chunk, Tree { dx, dz, h, log: 29, leaf: 31, trunk_h: th }); } } SnowySlopes | JaggedPeaks | FrozenPeaks | StonyPeaks => { /* bare peaks */ } Plains | SunflowerPlains => { if grassy { if r == 3 { let y = h + 1; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, 8); } }- else if r < 10 { self.plant_tree(chunk, dx, dz, h, 4, 5, th); }+ else if r < 10 { self.plant_tree(chunk, Tree { dx, dz, h, log: 4, leaf: 5, trunk_h: th }); } } } } }} // --- Cave decoration: dress cave floors/ceilings by underground biome. ---- for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {+ for (dz, row) in heightmap.iter().enumerate() { for (dx, &cell) in row.iter().enumerate() { let wx = (ox + dx as i32) as f64; let wz = (oz + dz as i32) as f64;- let top = (heightmap[dz][dx] as usize).min(CHUNK_HEIGHT - 1);+ let top = (cell as usize).min(CHUNK_HEIGHT - 1); let mut y = 7usize; while y + 1 < top { let here = chunk.get_block(dx, y, dz);@@ -107,8 +107,15 @@ impl TerrainGen { (ox + dx as i32, y as i32, oz + dz as i32, self.seed ^ 0x5EED).hash(&mut hasher); let r = hasher.finish() % 100; match kind {- 0 => { if r < 22 { chunk.set_block(dx, y, dz, 72); } if r == 5 { chunk.set_block(dx, y + 1, dz, 77); } } // sculk / rare glowstone- 1 => { if r < 40 { chunk.set_block(dx, y, dz, 71); } if r < 6 { chunk.set_block(dx, y + 1, dz, 80); } if r == 7 { chunk.set_block(dx, y + 1, dz, 77); } } // moss / azalea / glow+ 0 => { // sculk / rare glowstone+ if r < 22 { chunk.set_block(dx, y, dz, 72); }+ if r == 5 { chunk.set_block(dx, y + 1, dz, 77); }+ }+ 1 => { // moss / azalea / glow+ if r < 40 { chunk.set_block(dx, y, dz, 71); }+ if r < 6 { chunk.set_block(dx, y + 1, dz, 80); }+ if r == 7 { chunk.set_block(dx, y + 1, dz, 77); }+ } _ => { if r < 25 { chunk.set_block(dx, y, dz, 70); } } // dripstone } } else if here == 0 && matches!(above, 1 | 57) {@@ -123,8 +130,8 @@ impl TerrainGen { } }} // --- Ocean floor: coral reefs / kelp by water temperature (survives the later water fill). ---- for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {- let h = heightmap[dz][dx] as usize;+ for (dz, row) in heightmap.iter().enumerate() { for (dx, &cell) in row.iter().enumerate() {+ let h = cell as usize; if h + 1 >= Self::SEA_LEVEL { continue; } let floor = chunk.get_block(dx, h, dz); if floor != 6 && floor != 2 && floor != 1 { continue; }@@ -143,12 +150,11 @@ impl TerrainGen { if r < 20 && y + 1 < Self::SEA_LEVEL { chunk.set_block(dx, y + 1, dz, coral); } } else if r < 96 { chunk.set_block(dx, y, dz, 67); } // sea lantern }- 1 | 2 => { // kelp forests- if r < 120 {+ 1 | 2 // kelp forests+ if r < 120 => { let kh = 2 + (hasher.finish() % 5) as usize; for k in 0..kh { let yy = y + k; if yy < Self::SEA_LEVEL { chunk.set_block(dx, yy, dz, 66); } } }- } _ => {} } }}@@ -168,7 +174,7 @@ impl TerrainGen { for ddx in -1i32..=1 { for ddy in 0i32..=2 { for ddz in -1i32..=1 { if ddx.abs() + ddy + ddz.abs() > 3 { continue; } let (x, y, z) = (bx as i32 + ddx, cy as i32 + ddy, bz as i32 + ddz);- if x < 0 || x >= 16 || z < 0 || z >= 16 || y < 0 || y as usize >= CHUNK_HEIGHT { continue; }+ if !(0..16).contains(&x) || !(0..16).contains(&z) || y < 0 || y as usize >= CHUNK_HEIGHT { continue; } chunk.set_block(x as usize, y as usize, z as usize, 15); }}} }@@ -177,7 +183,7 @@ impl TerrainGen { let cy = sh_top; for ddx in -1i32..=1 { for ddz in -1i32..=1 { let (x, z) = (bx as i32 + ddx, bz as i32 + ddz);- if x < 0 || x >= 16 || z < 0 || z >= 16 { continue; }+ if !(0..16).contains(&x) || !(0..16).contains(&z) { continue; } let id = if ddx == 0 && ddz == 0 { 12 } else { 38 }; chunk.set_block(x as usize, cy, z as usize, id); }}@@ -187,13 +193,13 @@ impl TerrainGen { let cy = sh_top; for ddx in -1i32..=1 { for ddz in -1i32..=1 { let (x, z) = (bx as i32 + ddx, bz as i32 + ddz);- if x < 0 || x >= 16 || z < 0 || z >= 16 { continue; }+ if !(0..16).contains(&x) || !(0..16).contains(&z) { continue; } chunk.set_block(x as usize, cy, z as usize, 8); // cobble platform }} // Corner pillars + warding stone centre. for &(px, pz) in &[(-1i32, -1i32), (1, -1), (-1, 1), (1, 1)] { let (x, z) = (bx as i32 + px, bz as i32 + pz);- if x >= 0 && x < 16 && z >= 0 && z < 16 && cy + 1 < CHUNK_HEIGHT { chunk.set_block(x as usize, cy + 1, z as usize, 1); }+ if (0..16).contains(&x) && (0..16).contains(&z) && cy + 1 < CHUNK_HEIGHT { chunk.set_block(x as usize, cy + 1, z as usize, 1); } } if cy + 1 < CHUNK_HEIGHT { chunk.set_block(bx, cy + 1, bz, 81); } // warding stone }@@ -291,7 +297,7 @@ impl TerrainGen { }} } for (bx, bz, w, d, kind) in self.village_layout(cx, cz) {- render_building(chunk, ox, oz, bx, bz, w, d, base, kind);+ render_building(chunk, ox, oz, Building { bx, bz, w, d, base, kind }); } }} }@@ -320,7 +326,7 @@ impl TerrainGen { for dy in 1..=2 { if fy + dy < CHUNK_HEIGHT { chunk.set_block(lx, fy + dy, lz, 0); } } }} for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {- carve_corridor(chunk, ox, oz, cx, cz, dx, dz, 44, fy);+ carve_corridor(chunk, ox, oz, Corridor { cx, cz, dirx: dx, dirz: dz, len: 44, fy }); } // A bit of loot + light in the junction. if in_chunk(cx, cz, ox, oz) {
games/voxels/src/main/rust/src/world/mesher.rs
diff --git a/games/voxels/src/main/rust/src/world/mesher.rs b/games/voxels/src/main/rust/src/world/mesher.rsindex b2b6d75d2f..1fc2c448c5 100644--- a/games/voxels/src/main/rust/src/world/mesher.rs+++ b/games/voxels/src/main/rust/src/world/mesher.rs@@ -9,10 +9,10 @@ pub type Neighbor<'a> = dyn Fn(i32, i32, i32) -> (Id, u8) + 'a; // chunk's own data, which is plenty for caves + torch pools. fn compute_light(chunk: &Chunk) -> ([[i32; 16]; 16], Vec<u8>) { let mut col_top = [[-1i32; 16]; 16];- for x in 0..16 { for z in 0..16 {+ for (x, col) in col_top.iter_mut().enumerate() { for (z, top) in col.iter_mut().enumerate() { for y in (0..CHUNK_HEIGHT).rev() { let id = chunk.get_block(x, y, z);- if id != 0 && Block::from_id(id).blocks_light() { col_top[x][z] = y as i32; break; }+ if id != 0 && Block::from_id(id).blocks_light() { *top = y as i32; break; } } }} let mut blk = vec![0u8; 16 * CHUNK_HEIGHT * 16];@@ -29,7 +29,7 @@ fn compute_light(chunk: &Chunk) -> ([[i32; 16]; 16], Vec<u8>) { (x as i32, y as i32 + 1, z as i32), (x as i32, y as i32 - 1, z as i32), (x as i32, y as i32, z as i32 + 1), (x as i32, y as i32, z as i32 - 1)]; for (nx, ny, nz) in nbrs {- if nx < 0 || nx >= 16 || nz < 0 || nz >= 16 || ny < 0 || ny >= CHUNK_HEIGHT as i32 { continue; }+ if !(0..16).contains(&nx) || !(0..16).contains(&nz) || ny < 0 || ny >= CHUNK_HEIGHT as i32 { continue; } let (nx, ny, nz) = (nx as usize, ny as usize, nz as usize); let bid = chunk.get_block(nx, ny, nz); if bid != 0 && Block::from_id(bid).blocks_light() { continue; }@@ -166,7 +166,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let b = blk[(by * 16 + lz) * 16 + lx]; sky | (b << 4) };- for sec_idx in 0..SECTIONS_PER_CHUNK {+ for (sec_idx, slot) in result.iter_mut().enumerate() { let section = match &chunk.sections[sec_idx] { Some(s) if !s.is_empty() => s, _ => continue,@@ -182,7 +182,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 0 => { for x in 0..SECTION_SIZE { let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16];- for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {+ for (y, row) in mask.iter_mut().enumerate() { for (z, cell) in row.iter_mut().enumerate() { let id = section.get(x,y,z); if id == 0 || id == Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; } // emitted as boxes below@@ -193,13 +193,13 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let ao = |ys: i32, zs: i32| vao(occ(nb, wy+ys, wz), occ(nb, wy, wz+zs), occ(nb, wy+ys, wz+zs)); let ao4 = if dx==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(-1,1), ao(1,1), ao(1,-1), ao(-1,-1)] };- mask[y][z] = Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz)));+ *cell = Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } }} let mut visited = [[false; 16]; 16];- for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {+ for (y, row) in mask.iter().enumerate() { for (z, cell) in row.iter().enumerate() { if visited[y][z] { continue; }- let Some((bid, tile_idx, ao4, lpk)) = mask[y][z] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = *cell else { continue; }; let mut w = 1; while z + w < SECTION_SIZE && !visited[y][z+w] && mask[y][z+w] == Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1;@@ -207,7 +207,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 for k in 0..w { if visited[y+h][z+k] || mask[y+h][z+k] != Some((bid, tile_idx, ao4, lpk)) { break 'outer; } } h+=1; }- for yy in y..y+h { for zz in z..z+w { visited[yy][zz]=true; } }+ for row in visited.iter_mut().skip(y).take(h) { for cell in row.iter_mut().skip(z).take(w) { *cell = true; } } let x0 = x as f32 + if dx==1 { 1.0 } else { 0.0 }; let y0 = y as f32; let z0 = z as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, ww, hh);@@ -232,7 +232,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 1 => { for y in 0..SECTION_SIZE { let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16];- for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {+ for (x, row) in mask.iter_mut().enumerate() { for (z, cell) in row.iter_mut().enumerate() { let id = section.get(x,y,z); if id==0 || id==Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; }@@ -244,14 +244,14 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let ao = |xs: i32, zs: i32| vao(occ(wx+xs, nb, wz), occ(wx, nb, wz+zs), occ(wx+xs, nb, wz+zs)); let ao4 = if dy==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(-1,1), ao(1,1), ao(1,-1), ao(-1,-1)] };- mask[x][z]=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz)));+ *cell=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } } }} let mut visited = [[false; 16]; 16];- for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {+ for (x, row) in mask.iter().enumerate() { for (z, cell) in row.iter().enumerate() { if visited[x][z] { continue; }- let Some((bid, tile_idx, ao4, lpk)) = mask[x][z] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = *cell else { continue; }; let mut w = 1; while z+w < SECTION_SIZE && !visited[x][z+w] && mask[x][z+w]==Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1;@@ -259,7 +259,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 for k in 0..w { if visited[x+h][z+k] || mask[x+h][z+k]!=Some((bid, tile_idx, ao4, lpk)) { break 'outer2; } } h+=1; }- for xx in x..x+h { for zz in z..z+w { visited[xx][zz]=true; } }+ for row in visited.iter_mut().skip(x).take(h) { for cell in row.iter_mut().skip(z).take(w) { *cell = true; } } let y0 = y as f32 + if dy==1 { 1.0 } else { 0.0 }; let x0 = x as f32; let z0 = z as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, hh, ww);@@ -283,7 +283,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 2 => { for z in 0..SECTION_SIZE { let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16];- for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE {+ for (x, row) in mask.iter_mut().enumerate() { for (y, cell) in row.iter_mut().enumerate() { let id = section.get(x,y,z); if id==0 || id==Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; }@@ -294,13 +294,13 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let ao = |xs: i32, ys: i32| vao(occ(wx+xs, wy, nb), occ(wx, wy+ys, nb), occ(wx+xs, wy+ys, nb)); let ao4 = if dz==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(1,-1), ao(-1,-1), ao(-1,1), ao(1,1)] };- mask[x][y]=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz)));+ *cell=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } }} let mut visited = [[false; 16]; 16];- for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE {+ for (x, row) in mask.iter().enumerate() { for (y, cell) in row.iter().enumerate() { if visited[x][y] { continue; }- let Some((bid, tile_idx, ao4, lpk)) = mask[x][y] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = *cell else { continue; }; let mut w = 1; while y+w < SECTION_SIZE && !visited[x][y+w] && mask[x][y+w]==Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1;@@ -308,7 +308,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 for k in 0..w { if visited[x+h][y+k] || mask[x+h][y+k]!=Some((bid, tile_idx, ao4, lpk)) { break 'outer3; } } h+=1; }- for xx in x..x+h { for yy in y..y+w { visited[xx][yy]=true; } }+ for row in visited.iter_mut().skip(x).take(h) { for cell in row.iter_mut().skip(y).take(w) { *cell = true; } } let z0 = z as f32 + if dz==1 { 1.0 } else { 0.0 }; let x0 = x as f32; let y0 = y as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, hh, ww);@@ -337,20 +337,20 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let mut windices: Vec<u32> = Vec::new(); for y in 0..SECTION_SIZE { let mut wmask = [[false; 16]; 16];- for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {+ for (x, row) in wmask.iter_mut().enumerate() { for (z, cell) in row.iter_mut().enumerate() { if section.get(x,y,z) != Block::Water as Id { continue; } let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32; let above = get_neighbor(wx, wy+1, wz).0; if above != Block::Water as Id && !(above != 0 && Block::from_id(above).is_opaque()) {- wmask[x][z] = true;+ *cell = true; } }} let mut visited = [[false; 16]; 16];- for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {- if visited[x][z] || !wmask[x][z] { continue; }+ for (x, row) in wmask.iter().enumerate() { for (z, &cell) in row.iter().enumerate() {+ if visited[x][z] || !cell { continue; } let mut w = 1; while z+w < SECTION_SIZE && !visited[x][z+w] && wmask[x][z+w] { w+=1; } let mut h = 1; 'ow: while x+h < SECTION_SIZE { for k in 0..w { if visited[x+h][z+k] || !wmask[x+h][z+k] { break 'ow; } } h+=1; }- for xx in x..x+h { for zz in z..z+w { visited[xx][zz]=true; } }+ for row in visited.iter_mut().skip(x).take(h) { for cell in row.iter_mut().skip(z).take(w) { *cell = true; } } let y0 = (y+1) as f32; let x0 = x as f32; let z0 = z as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, hh, ww);@@ -380,7 +380,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 &|dx, dy, dz| face_light(wx + dx, wy + dy, wz + dz)); } }}}- if !verts.is_empty() || !wverts.is_empty() { result[sec_idx] = Some(MeshData{ vertices: verts, indices, water_vertices: wverts, water_indices: windices }); }+ if !verts.is_empty() || !wverts.is_empty() { *slot = Some(MeshData{ vertices: verts, indices, water_vertices: wverts, water_indices: windices }); } } result }
games/voxels/src/main/rust/src/world/save.rs
diff --git a/games/voxels/src/main/rust/src/world/save.rs b/games/voxels/src/main/rust/src/world/save.rsindex 8a16ddace9..b3efae3afb 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -15,7 +15,7 @@ pub fn save_chunk(base: &str, chunk: &Chunk) -> std::io::Result<()> { fs::create_dir_all(&dir)?; let path = chunk_file(base, chunk.pos); let tmp = path.with_extension("tmp");- fs::write(&tmp, &encode_chunk(chunk))?;+ fs::write(&tmp, encode_chunk(chunk))?; fs::rename(&tmp, &path)?; Ok(()) }
games/voxels/src/main/rust/tests/world_edges.rs
diff --git a/games/voxels/src/main/rust/tests/world_edges.rs b/games/voxels/src/main/rust/tests/world_edges.rsindex 447f35a8cf..63d3197c8a 100644--- a/games/voxels/src/main/rust/tests/world_edges.rs+++ b/games/voxels/src/main/rust/tests/world_edges.rs@@ -130,7 +130,7 @@ fn inventory_hotbar_rules_hold() { inv.try_add_block(Block::Dirt as u16); } let total = inv.count_of(Block::Dirt as u16);- assert!(total <= (SLOTS as i32) * (STACK as i32), "capacity is bounded: {total}");+ assert!(total <= (SLOTS as i32) * STACK, "capacity is bounded: {total}"); inv.move_item(SLOTS + 1, 0); inv.move_item(0, 0); let mut swap_inv = Inventory::empty();