Modern Apps git

← Modern-Apps.git

voxels: add slabs, stairs and a stonecutter with a VOX2 chunk format

Commit
34416fb934c5180cc199fd6c7148d2c38f8cf8dc
Author
Vayun Mathur <[email protected]>
When
2026-08-05 16:03 UTC (4 months ago)
Parents
747ea85

Diff

games/voxels/src/main/assets/block/stonecutter.png
diff --git a/games/voxels/src/main/assets/block/stonecutter.png b/games/voxels/src/main/assets/block/stonecutter.pngnew file mode 100644index 0000000000..02844f7d87Binary files /dev/null and b/games/voxels/src/main/assets/block/stonecutter.png differ
games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex 75e69cc469..f3a15382e5 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -61,9 +61,11 @@ class MainActivity : ComponentActivity() {                 var furnaceOpen by remember { mutableStateOf(false) }                 var furnaceIsBlast by remember { mutableStateOf(false) }                 var chestOpen by remember { mutableStateOf(false) }+                var cutsJson by remember { mutableStateOf("[]") }+                var stonecutterOpen by remember { mutableStateOf(false) }                 var tradesJson by remember { mutableStateOf("[]") }                 var tradeOpen by remember { mutableStateOf(false) }-                LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); tradesJson = VoxelsNative.getTradesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson() } catch (_: Exception) {} }+                LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); tradesJson = VoxelsNative.getTradesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson(); cutsJson = VoxelsNative.getCutsJson() } catch (_: Exception) {} }                 var achievementsManager by remember { mutableStateOf<VoxelsAchievementsManager?>(null) }                 val newAchievement by (achievementsManager?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -166,6 +168,7 @@ class MainActivity : ComponentActivity() {                                         val held = inv?.slots?.getOrNull(inv.selected)?.id ?: 0                                         com.vayunmathur.games.voxels.util.MusicFx.toggle(this@MainActivity, com.vayunmathur.games.voxels.ui.discTrack[held])                                     }+                                    15 -> stonecutterOpen = true // stonecutter                                     20 -> tradeOpen = true // villager                                     30 -> { // chest                                         containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }@@ -286,6 +289,11 @@ class MainActivity : ComponentActivity() {                         })                     } +                    if (stonecutterOpen && VoxelsNative.isAvailable) {+                        StonecutterOverlay(cutsJson = cutsJson, inventoryJson = inventoryJson,+                            onClose = { stonecutterOpen = false })+                    }+                     if (paused) {                         Box(                             Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.ktindex dd19275a89..3a429d91a5 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt@@ -114,7 +114,14 @@ val blockNames = mapOf(     93 to "Silver Block", 94 to "Steel Block", 95 to "Adamant Block", 96 to "Blast Furnace",     192 to "Sulfur", 193 to "Silver Ingot", 194 to "Quicksilver", 195 to "Steel Ingot", 196 to "Adamant Ingot",     197 to "Adamant Pickaxe", 198 to "Adamant Sword",-    199 to "Adamant Helmet", 200 to "Adamant Chestplate", 201 to "Adamant Leggings", 202 to "Adamant Boots"+    199 to "Adamant Helmet", 200 to "Adamant Chestplate", 201 to "Adamant Leggings", 202 to "Adamant Boots",+    // Matcha's building set: slabs and stairs, cut on a stonecutter.+    102 to "Stone Slab", 103 to "Stone Stairs", 104 to "Cobble Slab", 105 to "Cobble Stairs",+    106 to "Plank Slab", 107 to "Plank Stairs", 108 to "Brick Slab", 109 to "Brick Stairs",+    110 to "Sandstone Slab", 111 to "Sandstone Stairs",+    112 to "Deepslate Brick Slab", 113 to "Deepslate Brick Stairs",+    114 to "Nether Brick Slab", 115 to "Nether Brick Stairs",+    116 to "Purpur Slab", 117 to "Purpur Stairs", 118 to "Stonecutter" )  // Music disc item id -> track asset in assets/music/.@@ -178,7 +185,17 @@ val blockIconFile = mapOf(     93 to "silver_block.png", 94 to "steel_block.png", 95 to "adamant_block.png", 96 to "blast_furnace.png",     192 to "sulfur.png", 193 to "silver_ingot.png", 194 to "quicksilver.png", 195 to "steel_ingot.png",     196 to "adamant_ingot.png", 197 to "adamant_pickaxe.png", 198 to "adamant_sword.png",-    199 to "adamant_helmet.png", 200 to "adamant_chestplate.png", 201 to "adamant_leggings.png", 202 to "adamant_boots.png"+    199 to "adamant_helmet.png", 200 to "adamant_chestplate.png", 201 to "adamant_leggings.png", 202 to "adamant_boots.png",+    // Slabs and stairs reuse their parent material's icon; the name tells them apart.+    102 to "deepslate.png", 103 to "deepslate.png",+    104 to "cobblestone.png", 105 to "cobblestone.png",+    106 to "oak_planks.png", 107 to "oak_planks.png",+    108 to "bricks.png", 109 to "bricks.png",+    110 to "sandstone.png", 111 to "sandstone.png",+    112 to "deepslate_bricks.png", 113 to "deepslate_bricks.png",+    114 to "nether_bricks.png", 115 to "nether_bricks.png",+    116 to "purpur_block.png", 117 to "purpur_block.png",+    118 to "stonecutter.png" )  // Creative catalog, split into tabs.@@ -199,7 +216,8 @@ val catalogGear = listOf(163, 164, 165, 166, 167, 168, 169, 170,     239, 240, 241, 242, 243, 244,     197, 198, 199, 200, 201, 202) val catalogMusic = listOf(82, 179, 180, 181, 182, 183, 184, 185)-val catalogBuilding = listOf(10, 27, 30, 49, 52, 8, 57, 9, 53, 54, 55, 56, 58, 59, 72, 74, 76, 77, 78, 81, 7, 33, 34, 35, 96, 88, 89)+val catalogBuilding = listOf(10, 27, 30, 49, 52, 8, 57, 9, 53, 54, 55, 56, 58, 59, 72, 74, 76, 77, 78, 81, 7, 33, 34, 35, 96, 118, 88, 89,+    102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117)  @Composable fun rememberBlockIcon(id: Int): androidx.compose.ui.graphics.ImageBitmap? {
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.ktnew file mode 100644index 0000000000..08063e678c--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/StonecutterScreen.kt@@ -0,0 +1,134 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.voxels.R+import com.vayunmathur.games.voxels.util.VoxelsNative+import com.vayunmathur.library.ui.Text++/** One stonecutter conversion, addressed by its index in the engine's table. */+data class CutRecipe(val index: Int, val inId: Int, val outId: Int, val outN: Int)++fun parseCuts(json: String): List<CutRecipe> = try {+    val arr = org.json.JSONArray(json)+    (0 until arr.length()).map { i ->+        val o = arr.getJSONObject(i)+        CutRecipe(i, o.getInt("in"), o.getInt("out"), o.optInt("outN", 1))+    }+} catch (_: Exception) { emptyList() }++/**+ * Stonecutter: pick a block you are carrying on the left, then a shape to cut it into on the right.+ * Unlike the furnace this is instant and costs no fuel — it only reshapes.+ */+@Composable+fun StonecutterOverlay(cutsJson: String, inventoryJson: String, onClose: () -> Unit) {+    val cuts = remember(cutsJson) { parseCuts(cutsJson) }+    val inv = remember(inventoryJson) {+        try {+            kotlinx.serialization.json.Json { ignoreUnknownKeys = true }+                .decodeFromString<InventoryState>(inventoryJson)+        } catch (_: Exception) { InventoryState() }+    }+    // Only offer materials the player actually has, so the list stays short and honest.+    val held = remember(inv, cuts) {+        cuts.map { it.inId }.distinct().filter { id -> inv.slots.any { it.id == id && it.count > 0 } }+    }+    var material by remember(held) { mutableStateOf(held.firstOrNull() ?: 0) }+    val options = remember(material, cuts) { cuts.filter { it.inId == material } }++    Box(+        Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))+            .pointerInput(Unit) { detectTapGestures { onClose() } }+    ) {+        Column(+            Modifier.align(Alignment.Center).fillMaxWidth(0.9f).fillMaxHeight(0.84f)+                .clip(RoundedCornerShape(14.dp)).background(Color(0xF01A1E1A))+                .pointerInput(Unit) { detectTapGestures { } }+                .padding(14.dp),+            verticalArrangement = Arrangement.spacedBy(10.dp)+        ) {+            Row(verticalAlignment = Alignment.CenterVertically) {+                Text(stringResource(R.string.stonecutter), color = Color.White, fontWeight = FontWeight.SemiBold, fontSize = 17.sp)+                Spacer(Modifier.weight(1f))+                Box(+                    Modifier.clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.10f))+                        .clickable { onClose() }.padding(horizontal = 18.dp, vertical = 8.dp)+                ) { Text(stringResource(R.string.close), color = Color.White, fontSize = 14.sp) }+            }++            if (held.isEmpty()) {+                Text(stringResource(R.string.stonecutter_empty), color = Color.White.copy(0.55f), fontSize = 12.sp)+                return@Column+            }++            Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) {+                // Materials on hand.+                Column(+                    Modifier.width(180.dp).fillMaxHeight().verticalScroll(rememberScrollState()),+                    verticalArrangement = Arrangement.spacedBy(4.dp)+                ) {+                    Text(stringResource(R.string.material), color = Color.White.copy(0.6f), fontSize = 12.sp)+                    held.forEach { id ->+                        val icon = rememberBlockIcon(id)+                        Row(+                            Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))+                                .background(if (id == material) Color(0xFF3A6B3A) else Color.White.copy(alpha = 0.08f))+                                .clickable { material = id }.padding(6.dp),+                            verticalAlignment = Alignment.CenterVertically,+                            horizontalArrangement = Arrangement.spacedBy(6.dp)+                        ) {+                            if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(26.dp), filterQuality = FilterQuality.None)+                            Text(blockNames[id] ?: "", color = Color.White.copy(0.95f), fontSize = 12.sp)+                        }+                    }+                }++                // Shapes that material can become.+                Column(+                    Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()),+                    verticalArrangement = Arrangement.spacedBy(4.dp)+                ) {+                    Text(stringResource(R.string.cut_into), color = Color.White.copy(0.6f), fontSize = 12.sp)+                    options.forEach { c ->+                        val icon = rememberBlockIcon(c.outId)+                        Row(+                            Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))+                                .background(Color.White.copy(alpha = 0.08f))+                                .clickable { try { VoxelsNative.cut(c.index) } catch (_: Exception) {} }+                                .padding(8.dp),+                            verticalAlignment = Alignment.CenterVertically,+                            horizontalArrangement = Arrangement.spacedBy(8.dp)+                        ) {+                            Box(Modifier.size(30.dp), contentAlignment = Alignment.Center) {+                                if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(28.dp), filterQuality = FilterQuality.None)+                            }+                            Text(blockNames[c.outId] ?: "", color = Color.White.copy(0.95f), fontSize = 13.sp)+                            Spacer(Modifier.weight(1f))+                            Text("×${c.outN}", color = Color.White.copy(0.7f), fontSize = 12.sp)+                        }+                    }+                }+            }+            Text(stringResource(R.string.stonecutter_hint), color = Color.White.copy(0.5f), fontSize = 11.sp)+        }+    }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.ktindex a739c78255..dc9a439ae0 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt@@ -31,6 +31,9 @@ object VoxelsNative {     external fun moveItem(from: Int, to: Int)     external fun giveBlock(id: Int)     external fun craft(recipe: Int): Boolean+    // Stonecutter: one block in, one shape out.+    external fun cut(idx: Int): Boolean+    external fun getCutsJson(): String     external fun trade(index: Int): Boolean     external fun getRecipesJson(): String     external fun getTradesJson(): String
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex f1ea16dd7a..334486b9ad 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -37,6 +37,11 @@     <string name="fuel">Fuel</string>     <string name="furnace_fuel_hint">Burns coal, logs, planks or sulfur from your inventory.</string>     <string name="furnace_busy">Already smelting something else — stop it first.</string>+    <string name="stonecutter">Stonecutter</string>+    <string name="material">Material</string>+    <string name="cut_into">Cut into</string>+    <string name="stonecutter_empty">Carry a stone or wood block to cut it into slabs and stairs.</string>+    <string name="stonecutter_hint">Cutting is instant and needs no fuel — slabs and stairs only.</string>     <string name="busy">Busy</string>     <string name="chest_tap_hint">Tap a chest slot to take it, an inventory slot to store it.</string>     <string name="blessings">Blessings</string>
games/voxels/src/main/rust/shaders/atlas.bin
diff --git a/games/voxels/src/main/rust/shaders/atlas.bin b/games/voxels/src/main/rust/shaders/atlas.binindex 6c6121aeeb..f2da2b78fe 100644Binary files a/games/voxels/src/main/rust/shaders/atlas.bin and b/games/voxels/src/main/rust/shaders/atlas.bin differ
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 1cc7680186..002a5faa43 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -1,4 +1,4 @@-use crate::world::{ChunkMap, block::Block};+use crate::world::{ChunkMap, block::{Block, Shape}}; use crate::player::Player; use crate::inventory::Inventory; use crate::entity::{Mob, MobKind, Particle, Projectile, ProjKind, build_entity_mesh, tick_particles, append_particles, append_projectiles};@@ -289,8 +289,8 @@ pub fn rebuild_chunk_meshes(state: &mut EngineState, chunk_pos: crate::world::ch     let meshes = {         let chunk = state.chunks.get(chunk_pos).unwrap();         let map_ptr = &state.chunks as *const ChunkMap;-        let closure = move |wx: i32, wy: i32, wz: i32| -> u8 {-            unsafe { (*map_ptr).get_block_world(wx, wy, wz) }+        let closure = move |wx: i32, wy: i32, wz: i32| -> (u8, u8) {+            unsafe { ((*map_ptr).get_block_world(wx, wy, wz), (*map_ptr).get_meta_world(wx, wy, wz)) }         };         let tint = move |wx: i32, wz: i32| -> [f32;3] {             unsafe { (*map_ptr).grass_tint(wx, wz) }@@ -727,6 +727,15 @@ pub fn get_trades_json() -> String {         .collect();     serde_json::json!(items).to_string() }++// The stonecutter's whole catalog; the UI filters it down to what the player is carrying.+pub fn get_cuts_json() -> String {+    let items: Vec<_> = crate::inventory::cut_variants().iter()+        .map(|c| serde_json::json!({ "in": c.input, "out": c.output, "outN": c.count }))+        .collect();+    serde_json::json!(items).to_string()+}+pub fn do_cut(idx: usize) -> bool { with_engine(|s| s.inventory.cut(idx)).unwrap_or(false) } pub fn get_recipes_json() -> String {     let items: Vec<_> = crate::inventory::RECIPES.iter()         .map(|(i1, c1, i2, c2, oid, oc)| serde_json::json!({@@ -1400,27 +1409,78 @@ fn explode(state: &mut EngineState, center: Vec3, radius: f32) {     spawn_particles(&mut state.spawn_rng, &mut state.particles, center, 12, [1.0, 0.55, 0.15], 5.0, 0.5, 0.22); } +/// Which way a stair placed now should face. Its low side looks back at the player so that walking+/// forward climbs it. Yaw 0 looks north (-Z).+fn stair_facing(yaw: f32) -> u8 {+    use crate::world::block::{FACE_EAST, FACE_NORTH, FACE_SOUTH, FACE_WEST};+    let turns = (yaw / std::f32::consts::FRAC_PI_2).round() as i32;+    match turns.rem_euclid(4) {+        0 => FACE_SOUTH, // looking north, so approach from the south+        1 => FACE_EAST,+        2 => FACE_NORTH,+        _ => FACE_WEST,+    }+}++/// The meta byte for placing `block` against `hit`. Cubes get 0; slabs and stairs pick their half+/// from the face that was clicked, falling back to which half of a side face was hit.+fn placement_meta(block: Block, hit: &crate::raycast::HitResult, origin: Vec3, dir: Vec3, yaw: f32) -> u8 {+    use crate::world::block::META_TOP;+    if block.shape() == Shape::Cube { return 0; }+    let top = match hit.normal.1 {+        1 => false,  // placed on a surface: rests on the floor of its cell+        -1 => true,  // placed under a ceiling: hangs from the top+        _ => {+            // A side face: the half of the face that was clicked decides.+            let point = origin + dir.normalize_or_zero() * hit.dist;+            point.y - point.y.floor() > 0.5+        }+    };+    let mut meta = if top { META_TOP } else { 0 };+    if block.shape() == Shape::Stairs { meta |= stair_facing(yaw); }+    meta+}+ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {     // Items (food, estus, materials) are never placeable as blocks.     let sel = state.inventory.selected_block();     if sel == 0 || crate::item::is_item(sel) { return false; }-    if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) {-        let (px,py,pz) = hit.prev;-        if state.chunks.get_block_world(px,py,pz) != 0 { return false; }-        let min_check = vec3(state.player.pos.x - 0.3, state.player.pos.y, state.player.pos.z - 0.3);-        let max_check = vec3(state.player.pos.x + 0.3, state.player.pos.y + 1.8, state.player.pos.z + 0.3);-        let inside_x = (px as f32 + 1.0) > min_check.x && (px as f32) < max_check.x;-        let inside_y = (py as f32 + 1.0) > min_check.y && (py as f32) < max_check.y;-        let inside_z = (pz as f32 + 1.0) > min_check.z && (pz as f32) < max_check.z;-        if inside_x && inside_y && inside_z { return false; }-        if let Some(id) = state.inventory.consume_selected() {-            state.chunks.set_block_world(px,py,pz, id);-            // A chest the player places starts empty; only chests already in the world roll loot.-            if id == 83 { state.containers.insert_empty((state.dim, px, py, pz)); }-            mark_neighbors_dirty(state, px, pz);-            return true;+    let block = Block::from_id(sel);+    let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) else { return false; };++    // Two matching slabs in one cell make the full block again.+    if block.shape() == Shape::Slab {+        let (tx, ty, tz) = hit.pos;+        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() {+                    state.chunks.set_block_world(tx, ty, tz, block.parent() as u8);+                    mark_neighbors_dirty(state, tx, tz);+                    return true;+                }+            }         }     }++    let (px, py, pz) = hit.prev;+    if state.chunks.get_block_world(px, py, pz) != 0 { return false; }+    let meta = placement_meta(block, &hit, origin, dir, state.player.yaw);+    // Refuse only if the block's actual geometry would intersect the player — a slab at their feet+    // is fine even though a full cube there would not be.+    let pmin = [state.player.pos.x - 0.3, state.player.pos.y, state.player.pos.z - 0.3];+    let pmax = [state.player.pos.x + 0.3, state.player.pos.y + 1.8, state.player.pos.z + 0.3];+    let cell = [px as f32, py as f32, pz as f32];+    if block.collision_boxes(meta).as_slice().iter().any(|b| b.overlaps_at(cell, pmin, pmax)) { return false; }++    if let Some(id) = state.inventory.consume_selected() {+        state.chunks.set_block_meta_world(px, py, pz, id, meta);+        // A chest the player places starts empty; only chests already in the world roll loot.+        if id == 83 { state.containers.insert_empty((state.dim, px, py, pz)); }+        mark_neighbors_dirty(state, px, pz);+        return true;+    }     false } @@ -1463,3 +1523,24 @@ pub fn place_block_at(px: f32, py: f32) -> i32 {         if do_place(state, o, d) { 1 } else { 0 }     }).unwrap_or(0) }++#[cfg(test)]+mod tests {+    use super::*;+    use crate::world::block::{FACE_EAST, FACE_NORTH, FACE_SOUTH, FACE_WEST};++    // Yaw 0 looks north, and yaw grows counter-clockwise (see Player::forward). A stair's low side+    // must end up facing the player so that walking forward climbs it.+    #[test]+    fn stairs_face_back_toward_the_player() {+        use std::f32::consts::FRAC_PI_2;+        assert_eq!(stair_facing(0.0), FACE_SOUTH, "looking north, approach from the south");+        assert_eq!(stair_facing(FRAC_PI_2), FACE_EAST, "looking west, approach from the east");+        assert_eq!(stair_facing(FRAC_PI_2 * 2.0), FACE_NORTH);+        assert_eq!(stair_facing(FRAC_PI_2 * 3.0), FACE_WEST);+        // Wraps cleanly, and snaps from in-between angles.+        assert_eq!(stair_facing(FRAC_PI_2 * 4.0), FACE_SOUTH);+        assert_eq!(stair_facing(-FRAC_PI_2), FACE_WEST);+        assert_eq!(stair_facing(0.3), FACE_SOUTH, "a small tilt still reads as north");+    }+}
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 5356d828e1..e301c010e9 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -24,7 +24,7 @@ pub struct Inventory { // (in1_id, in1_count, in2_id, in2_count, out_id, out_count). in2_id == 0 means a single ingredient. // Item ids 154+ are materials/tools (see item.rs). Ore -> material conversions live in SMELTING // instead, since those need a furnace, fuel and time.-pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 85] = [+pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 86] = [     (154, 1, 157, 1, 186, 1), // iron + coal -> flint & steel     (187, 1, Block::Glass as u8, 5, Block::Beacon as u8, 1), // nether star + glass -> beacon     (138, 2, 0, 0, 189, 3), // gunpowder -> firework rockets@@ -110,6 +110,8 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 85] = [     (236, 9, 0, 0, Block::CopperBlock as u8, 1),     (237, 9, 0, 0, Block::GoldBlock as u8,   1),     (238, 9, 0, 0, Block::BronzeBlock as u8, 1),+    // The stonecutter itself: an iron blade on a stone bed.+    (Block::Stone as u8, 3, 154, 1, Block::Stonecutter as u8, 1), ];  // Furnace recipes. Unlike crafting these cost fuel and take `secs` of real time, and the ones marked@@ -194,6 +196,47 @@ pub fn recipe_category(out: u8) -> &'static str {     "block" } +// The stonecutter: one block in, one shape out, no fuel and no waiting. This is Matcha's stonecutting+// book condensed — the pack's hundreds of recipes are almost all "material -> slab/stairs/variant",+// which is exactly what `cut_variants` enumerates.+pub struct Cut { pub input: u8, pub output: u8, pub count: i32 }++/// Every stonecutter conversion, derived from the block table so a new slab family is picked up for+/// free. A cube yields two slabs or one stair, and either shape converts back to the other.+pub fn cut_variants() -> Vec<Cut> {+    let mut out = Vec::new();+    for material in CUTTABLE {+        let (Some(slab), Some(stairs)) = (material.slab_of(), material.stairs_of()) else { continue; };+        let (m, s, st) = (material as u8, slab as u8, stairs as u8);+        out.push(Cut { input: m, output: s, count: 2 });+        out.push(Cut { input: m, output: st, count: 1 });+        out.push(Cut { input: s, output: st, count: 1 });+        out.push(Cut { input: st, output: s, count: 1 });+    }+    // Decorative conversions between whole blocks of the same family.+    for &(input, output) in DECOR_CUTS {+        out.push(Cut { input: input as u8, output: output as u8, count: 1 });+    }+    out+}++// Materials that have a slab and a stair shape.+const CUTTABLE: [Block; 8] = [+    Block::Stone, Block::Cobble, Block::Planks, Block::Brick,+    Block::Sandstone, Block::DeepslateBricks, Block::NetherBricks, Block::Purpur,+];+// Whole-block decorative swaps the stonecutter also offers.+const DECOR_CUTS: &[(Block, Block)] = &[+    (Block::Stone, Block::Cobble),+    (Block::Stone, Block::Brick),+    (Block::Cobble, Block::MossyCobble),+    (Block::Diorite, Block::PolishedDiorite),+    (Block::CobbledDeepslate, Block::DeepslateBricks),+    (Block::Sandstone, Block::RedSandstone),+    (Block::EndStone, Block::EndStoneBricks),+    (Block::Netherrack, Block::NetherBricks),+];+ impl Default for Inventory {     fn default() -> Self {         let mut slots = [InvSlot::default(); SLOTS];@@ -312,6 +355,16 @@ impl Inventory {         else { for _ in 0..gn { self.add_block(g); } }         true     }+    // Execute a stonecutter conversion if the player has the input and room for the output.+    pub fn cut(&mut self, idx: usize) -> bool {+        let cuts = cut_variants();+        let Some(c) = cuts.get(idx) else { return false; };+        if self.count_of(c.input) < 1 { return false; }+        if !self.has_room_for(c.output, c.count) { return false; }+        self.remove_count(c.input, 1);+        for _ in 0..c.count { self.add_block(c.output); }+        true+    }     pub fn armor_defense(&self) -> f32 { self.armor.iter().map(|s| if s.id != 0 { crate::item::armor_defense(s.id) } else { 0.0 }).sum() }      // ---- Smelting ----@@ -521,6 +574,57 @@ mod tests {         assert!(inv.has_room_for(169, 1), "an empty slot can hold a tool");     } +    // The stonecutter is the only route to slabs and stairs, so every shape must be reachable and+    // no cut may create something from nothing.+    #[test]+    fn the_stonecutter_reaches_every_shape() {+        let cuts = cut_variants();+        for m in CUTTABLE {+            let slab = m.slab_of().unwrap() as u8;+            let stairs = m.stairs_of().unwrap() as u8;+            assert!(cuts.iter().any(|c| c.input == m as u8 && c.output == slab), "{m:?} -> slab missing");+            assert!(cuts.iter().any(|c| c.input == m as u8 && c.output == stairs), "{m:?} -> stairs missing");+            assert!(cuts.iter().any(|c| c.input == slab && c.output == stairs), "slab -> stairs missing");+            assert!(cuts.iter().any(|c| c.input == stairs && c.output == slab), "stairs -> slab missing");+        }+        for c in &cuts {+            assert!(c.input != 0 && c.output != 0, "a cut with no input or output");+            assert_ne!(c.input, c.output, "a cut must actually change the block");+            assert!(c.count >= 1 && c.count <= 2, "cut yields should stay modest, got {}", c.count);+        }+    }++    #[test]+    fn cutting_consumes_one_block_and_yields_the_shape() {+        let cuts = cut_variants();+        let idx = cuts.iter().position(|c| c.input == Block::Stone as u8 && c.output == Block::StoneSlab as u8).unwrap();+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot::default(); }+        inv.slots[0] = InvSlot { id: Block::Stone as u8, count: 3 };++        assert!(inv.cut(idx));+        assert_eq!(inv.count_of(Block::Stone as u8), 2, "one stone consumed");+        assert_eq!(inv.count_of(Block::StoneSlab as u8), 2, "a stone block yields two slabs");++        // With no input left the cut must refuse rather than conjure slabs.+        inv.remove_count(Block::Stone as u8, 99);+        assert!(!inv.cut(idx));+        assert_eq!(inv.count_of(Block::StoneSlab as u8), 2);+    }++    // A full inventory must not let the stonecutter eat the input and drop the result.+    #[test]+    fn cutting_into_a_full_inventory_is_refused() {+        let cuts = cut_variants();+        let idx = cuts.iter().position(|c| c.input == Block::Stone as u8 && c.output == Block::StoneSlab as u8).unwrap();+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as u8, count: STACK }; }+        inv.slots[0] = InvSlot { id: Block::Stone as u8, count: STACK };++        assert!(!inv.cut(idx), "nowhere to put the slabs");+        assert_eq!(inv.count_of(Block::Stone as u8), STACK, "the input must survive a refused cut");+    }+     #[test]     fn only_listed_items_burn() {         assert!(fuel_secs(157) > 0.0);   // coal
games/voxels/src/main/rust/src/lib.rs
diff --git a/games/voxels/src/main/rust/src/lib.rs b/games/voxels/src/main/rust/src/lib.rsindex 13502f8d35..a36339d2e1 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -375,6 +375,21 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_relea     engine::release_blessing(slot.max(0) as usize) as jboolean } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getCutsJson<'l>(+    mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+    let null = std::ptr::null_mut();+    match env.new_string(engine::get_cuts_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_cut<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>, idx: jint,+) -> jboolean {+    if idx >= 0 && engine::do_cut(idx as usize) { 1 } else { 0 }+}+ #[cfg(test)] mod tests {     use crate::world::chunk::{Chunk, ChunkPos};@@ -388,7 +403,7 @@ mod tests {         let mut c = Chunk::new(ChunkPos(0, 0));         gen.fill_chunk(&mut c);         assert!(c.generated);-        let mesh = mesh_chunk(&c, &|_, _, _| 0, &|_, _| [0.4, 0.7, 0.3]);+        let mesh = mesh_chunk(&c, &|_, _, _| (0, 0), &|_, _| [0.4, 0.7, 0.3]);         let total: usize = mesh.iter().filter_map(|o| o.as_ref()).map(|m| m.vertices.len()).sum();         assert!(total > 0 || c.sections.iter().all(|s| s.is_none() || s.as_ref().unwrap().is_empty()));     }
games/voxels/src/main/rust/src/player.rs
diff --git a/games/voxels/src/main/rust/src/player.rs b/games/voxels/src/main/rust/src/player.rsindex 49a9dda4b0..a37786ce27 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -252,17 +252,27 @@ impl Player {         feet == 12 || chest == 12     } -    // True if there is a solid block just under the player's footprint at `pos` (used so a sneaking-    // player won't walk off ledges).+    // True if there is something solid to stand on just under the player's footprint at `pos` (used+    // so a sneaking player won't walk off ledges). A slab counts only where its solid half reaches.     fn supported_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {         let hw = 0.3;-        let y = (pos.y - 0.05).floor() as i32;+        let foot = pos.y - 0.05;+        let y = foot.floor() as i32;         for &dx in &[-hw, hw] {             for &dz in &[-hw, hw] {                 let x = (pos.x + dx).floor() as i32;                 let z = (pos.z + dz).floor() as i32;                 let id = chunks.get_block_world(x, y, z);-                if id != 0 && Block::from_id(id).is_solid() { return true; }+                if id == 0 { continue; }+                let meta = chunks.get_meta_world(x, y, z);+                // The probe point sits `foot` above the cell floor; something must fill it.+                let local = foot - y as f32;+                let (lx, lz) = (pos.x + dx - x as f32, pos.z + dz - z as f32);+                for b in Block::from_id(id).collision_boxes(meta).as_slice() {+                    if local >= b.min[1] && local <= b.max[1]+                        && lx >= b.min[0] && lx <= b.max[0]+                        && lz >= b.min[2] && lz <= b.max[2] { return true; }+                }             }         }         false@@ -270,16 +280,17 @@ impl Player {      fn collides_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {         let hw = 0.3;-        let min = vec3(pos.x - hw, pos.y, pos.z - hw);-        let max = vec3(pos.x + hw, pos.y + 1.8, pos.z + hw);-        let x0 = min.x.floor() as i32; let y0 = min.y.floor() as i32; let z0 = min.z.floor() as i32;-        let x1 = max.x.ceil() as i32; let y1 = max.y.ceil() as i32; let z1 = max.z.ceil() as i32;+        let min = [pos.x - hw, pos.y, pos.z - hw];+        let max = [pos.x + hw, pos.y + 1.8, pos.z + hw];+        let x0 = min[0].floor() as i32; let y0 = min[1].floor() as i32; let z0 = min[2].floor() as i32;+        let x1 = max[0].ceil() as i32; let y1 = max[1].ceil() as i32; let z1 = max[2].ceil() as i32;         for x in x0..=x1 { for y in y0..=y1 { for z in z0..=z1 {             let id = chunks.get_block_world(x, y, z);-            if id != 0 && Block::from_id(id).is_solid() {-                if (x as f32 + 1.0) > min.x && (x as f32) < max.x && (y as f32 + 1.0) > min.y && (y as f32) < max.y && (z as f32 + 1.0) > min.z && (z as f32) < max.z {-                    return true;-                }+            if id == 0 || !Block::from_id(id).is_solid() { continue; }+            let meta = chunks.get_meta_world(x, y, z);+            let cell = [x as f32, y as f32, z as f32];+            for b in Block::from_id(id).collision_boxes(meta).as_slice() {+                if b.overlaps_at(cell, min, max) { return true; }             }         }}}         false@@ -351,6 +362,52 @@ mod tests {         assert_eq!(landing_damage(66.0, 64.0, false), 0.0);     } +    // Terrain never reaches this high, so surrounding cells are guaranteed air.+    const SKY: i32 = 200;+    fn world() -> ChunkMap {+        let dir = std::env::temp_dir().join("voxels_collide_test").to_string_lossy().into_owned();+        ChunkMap::new(2, dir)+    }++    // You stand on a bottom slab half a block up, not a whole one.+    #[test]+    fn a_bottom_slab_only_fills_the_lower_half() {+        let mut w = world();+        w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+        let p = Player::new(0.5, 0.0, 0.5);++        assert!(!p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.5), &w), "resting on the slab's surface is clear");+        assert!(p.collides_at(vec3(0.5, SKY as f32 + 0.4, 0.5), &w), "any lower and you are inside it");+        assert!(p.supported_at(vec3(0.5, SKY as f32 + 0.5, 0.5), &w), "the slab holds you up");+    }++    // The empty half of a top slab is real headroom — a full cube in the same cell would not fit.+    #[test]+    fn you_can_walk_under_a_top_slab() {+        let feet = vec3(0.5, SKY as f32 - 0.3, 0.5); // head lands exactly at the slab's underside++        let mut with_slab = world();+        with_slab.set_block_meta_world(0, SKY + 1, 0, Block::StoneSlab as u8, crate::world::block::META_TOP);+        let p = Player::new(0.5, 0.0, 0.5);+        assert!(!p.collides_at(feet, &with_slab), "a top slab leaves its lower half open");++        let mut with_cube = world();+        with_cube.set_block_world(0, SKY + 1, 0, Block::Stone as u8);+        assert!(p.collides_at(feet, &with_cube), "a full cube in the same cell would block");+    }++    // Stairs are open above their low half, which is what makes them climbable.+    #[test]+    fn stairs_are_open_over_their_low_half() {+        let mut w = world();+        w.set_block_meta_world(0, SKY, 0, Block::StoneStairs as u8, crate::world::block::FACE_NORTH);+        let p = Player::new(0.0, 0.0, 0.0);+        // The low half is -Z. The player is 0.6 wide, so their box has to sit well into it.+        assert!(!p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.2), &w), "standing on the tread is clear");+        // The tall half is +Z and reaches the cell ceiling.+        assert!(p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.75), &w), "the step fills the far half");+    }+     #[test]     fn attunements_are_independent() {         let p = blessed_player(&[205, 211]);
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 06f7c5cfcd..6ef2c35349 100644--- a/games/voxels/src/main/rust/src/raycast.rs+++ b/games/voxels/src/main/rust/src/raycast.rs@@ -1,9 +1,63 @@ use glam::Vec3;-use crate::world::{ChunkMap, block::Block};+use crate::world::{ChunkMap, block::{Aabb, Block, Shape}};  #[derive(Debug, Clone, Copy)] pub struct HitResult { pub pos: (i32,i32,i32), pub prev: (i32,i32,i32), pub normal: (i32,i32,i32), pub dist: f32 } +/// Slab in `t` for a ray against one box, in world space. Returns the entry distance and the axis+/// that was crossed on entry, or None if the ray misses.+fn ray_box(origin: Vec3, dir: Vec3, min: [f32; 3], max: [f32; 3]) -> Option<(f32, usize, bool)> {+    let o = [origin.x, origin.y, origin.z];+    let d = [dir.x, dir.y, dir.z];+    let (mut t_near, mut t_far) = (f32::NEG_INFINITY, f32::INFINITY);+    let (mut axis, mut positive) = (0usize, false);+    for i in 0..3 {+        if d[i].abs() < 1e-8 {+            // Parallel to this slab: a miss unless the origin already lies inside it.+            if o[i] < min[i] || o[i] > max[i] { return None; }+            continue;+        }+        let inv = 1.0 / d[i];+        let mut t0 = (min[i] - o[i]) * inv;+        let mut t1 = (max[i] - o[i]) * inv;+        let mut enter_positive = false; // the ray enters through this axis' max face+        if t0 > t1 { std::mem::swap(&mut t0, &mut t1); enter_positive = true; }+        if t0 > t_near { t_near = t0; axis = i; positive = enter_positive; }+        if t1 < t_far { t_far = t1; }+        if t_near > t_far { return None; }+    }+    if t_far < 0.0 { return None; }+    Some((t_near.max(0.0), axis, positive))+}++/// The nearest surface of a block within its cell, and the outward normal of the face hit. Cubes+/// short-circuit; slabs and stairs are tested box by box so you can look through their empty half.+fn hit_in_cell(chunks: &ChunkMap, cell: (i32, i32, i32), origin: Vec3, dir: Vec3) -> Option<(f32, (i32, i32, i32))> {+    let (x, y, z) = cell;+    let id = chunks.get_block_world(x, y, z);+    if id == 0 { return None; }+    let block = Block::from_id(id);+    if !block.is_solid() { return None; }+    let meta = chunks.get_meta_world(x, y, z);+    let base = [x as f32, y as f32, z as f32];+    let mut best: Option<(f32, (i32, i32, i32))> = None;+    for b in block.collision_boxes(meta).as_slice() {+        let min = [base[0] + b.min[0], base[1] + b.min[1], base[2] + b.min[2]];+        let max = [base[0] + b.max[0], base[1] + b.max[1], base[2] + b.max[2]];+        let Some((t, axis, positive)) = ray_box(origin, dir, min, max) else { continue; };+        if best.is_some_and(|(bt, _)| bt <= t) { continue; }+        let mut n = [0i32; 3];+        n[axis] = if positive { 1 } else { -1 };+        best = Some((t, (n[0], n[1], n[2])));+    }+    best+}++/// The cell a face normal points into — where a block placed against this hit would go.+fn step_out(cell: (i32, i32, i32), normal: (i32, i32, i32)) -> (i32, i32, i32) {+    (cell.0 + normal.0, cell.1 + normal.1, cell.2 + normal.2)+}+ pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Option<HitResult> {     let dir = dir.normalize_or_zero();     if dir.length_squared() < 1e-6 { return None; }@@ -30,25 +84,120 @@ pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Opt     } else { f32::INFINITY };     let mut prev = (x,y,z);     let mut dist = 0.0;-    let id_start = chunks.get_block_world(x,y,z);-    if id_start != 0 && Block::from_id(id_start).is_solid() {-        return Some(HitResult{ pos: (x,y,z), prev: (x - step_x, y - step_y, z - step_z), normal: (-step_x, -step_y, -step_z), 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.+    let mut step_axis;+    // Starting inside a block still counts, but only if the ray actually meets its geometry — the+    // eye can sit in the empty half of a slab's cell.+    if let Some((t, normal)) = hit_in_cell(chunks, (x,y,z), origin, dir) {+        return Some(HitResult{ pos: (x,y,z), prev: step_out((x,y,z), normal), normal, dist: t });     }     loop {         if dist > max_dist { return None; }         if t_max_x < t_max_y && t_max_x < t_max_z {-            prev = (x,y,z); x += step_x; dist = t_max_x; t_max_x += t_delta_x;-            let nid = chunks.get_block_world(x,y,z);-            if nid !=0 && Block::from_id(nid).is_solid() { return Some(HitResult{ pos: (x,y,z), prev, normal: (-step_x,0,0), dist }); }+            prev = (x,y,z); x += step_x; dist = t_max_x; t_max_x += t_delta_x; step_axis = 0;         } else if t_max_y < t_max_z {-            prev = (x,y,z); y += step_y; dist = t_max_y; t_max_y += t_delta_y;-            let nid = chunks.get_block_world(x,y,z);-            if nid !=0 && Block::from_id(nid).is_solid() { return Some(HitResult{ pos: (x,y,z), prev, normal: (0,-step_y,0), dist }); }+            prev = (x,y,z); y += step_y; dist = t_max_y; t_max_y += t_delta_y; step_axis = 1;         } else {-            prev = (x,y,z); z += step_z; dist = t_max_z; t_max_z += t_delta_z;-            let nid = chunks.get_block_world(x,y,z);-            if nid !=0 && Block::from_id(nid).is_solid() { return Some(HitResult{ pos: (x,y,z), prev, normal: (0,0,-step_z), dist }); }+            prev = (x,y,z); z += step_z; dist = t_max_z; t_max_z += t_delta_z; step_axis = 2;+        }+        if dist > max_dist { return None; }+        let id = chunks.get_block_world(x, y, z);+        if id != 0 && Block::from_id(id).is_solid() {+            if Block::from_id(id).shape() == Shape::Cube {+                // A full cube is entered exactly at the DDA boundary we just crossed.+                let normal = match step_axis {+                    0 => (-step_x, 0, 0),+                    1 => (0, -step_y, 0),+                    _ => (0, 0, -step_z),+                };+                return Some(HitResult{ pos: (x,y,z), prev, normal, dist });+            }+            // Partial block: keep going unless the ray really meets one of its boxes.+            if let Some((t, normal)) = hit_in_cell(chunks, (x,y,z), origin, dir) {+                if t <= max_dist {+                    return Some(HitResult{ pos: (x,y,z), prev: step_out((x,y,z), normal), normal, dist: t });+                }+                return None;+            }         }         if x.abs() > 10000 || y.abs() > 10000 || z.abs() > 10000 { return None; }     } }++#[cfg(test)]+mod tests {+    use super::*;+    use crate::world::block::{Block, FACE_NORTH, META_TOP};+    use glam::vec3;++    // Terrain never reaches this high, so the test cells around it are guaranteed empty air.+    const SKY: i32 = 200;++    fn world() -> ChunkMap {+        let dir = std::env::temp_dir().join("voxels_raycast_test").to_string_lossy().into_owned();+        ChunkMap::new(1, dir)+    }++    // A bottom slab leaves the top half of its cell empty; a ray through that half must pass by.+    #[test]+    fn a_ray_passes_through_a_slabs_empty_half() {+        let mut w = world();+        w.set_block_meta_world(4, SKY, 0, Block::StoneSlab as u8, 0);++        // Aim along +X at 0.75 up the cell, above the slab's solid half.+        let high = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.5), vec3(1.0, 0.0, 0.0), 20.0);+        assert!(high.is_none(), "the upper half of a bottom slab's cell is empty");++        // The same ray at 0.25 up must strike it.+        let low = raycast(&w, vec3(0.0, SKY as f32 + 0.25, 0.5), vec3(1.0, 0.0, 0.0), 20.0).expect("must hit the slab");+        assert_eq!(low.pos, (4, SKY, 0));+        assert_eq!(low.normal, (-1, 0, 0), "entered through the slab's west face");+        assert_eq!(low.prev, (3, SKY, 0), "a block placed here goes in front of the slab");+    }++    // Looking straight down onto a bottom slab must report the top surface, not the cell's ceiling.+    #[test]+    fn looking_down_hits_the_slabs_top_surface() {+        let mut w = world();+        w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+        let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit");+        assert_eq!(hit.pos, (0, SKY, 0));+        assert_eq!(hit.normal, (0, 1, 0));+        assert!((hit.dist - 4.5).abs() < 1e-3, "the surface is half a block up, got dist {}", hit.dist);+        assert_eq!(hit.prev, (0, SKY + 1, 0), "placing against the top goes in the cell above");+    }++    #[test]+    fn a_top_slab_is_hit_from_above_at_the_cell_ceiling() {+        let mut w = world();+        w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, META_TOP);+        let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit");+        assert!((hit.dist - 4.0).abs() < 1e-3, "a top slab's surface is the cell ceiling");+    }++    // Cubes must behave exactly as before the sub-voxel test was added.+    #[test]+    fn cubes_still_hit_at_the_cell_boundary() {+        let mut w = world();+        w.set_block_world(4, SKY, 0, Block::Stone as u8);+        let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.5, 0.5), vec3(1.0, 0.0, 0.0), 20.0).expect("must hit");+        assert_eq!(hit.pos, (4, SKY, 0));+        assert_eq!(hit.normal, (-1, 0, 0));+        assert_eq!(hit.prev, (3, SKY, 0));+        assert!((hit.dist - 4.0).abs() < 1e-3);+    }++    // Stairs facing north keep their tall half on the +Z side; a ray into the low half at head+    // height should sail over the tread.+    #[test]+    fn stairs_are_open_above_their_low_half() {+        let mut w = world();+        w.set_block_meta_world(4, SKY, 0, Block::StoneStairs as u8, FACE_NORTH);+        // z = 0.25 is the low (north) half, 0.75 up the cell is above the tread.+        assert!(raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.25), vec3(1.0, 0.0, 0.0), 20.0).is_none());+        // z = 0.75 is under the tall step, so the same height is solid.+        let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.75), vec3(1.0, 0.0, 0.0), 20.0);+        assert!(hit.is_some(), "the stair's tall half must block the ray");+    }+}
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 564d598a17..0349edf3a4 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -110,9 +110,65 @@ pub enum Block {     CopperBlock = 99,     GoldBlock = 100,     BronzeBlock = 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,+    StoneStairs = 103,+    CobbleSlab = 104,+    CobbleStairs = 105,+    PlankSlab = 106,+    PlankStairs = 107,+    BrickSlab = 108,+    BrickStairs = 109,+    SandstoneSlab = 110,+    SandstoneStairs = 111,+    DeepslateBrickSlab = 112,+    DeepslateBrickStairs = 113,+    NetherBrickSlab = 114,+    NetherBrickStairs = 115,+    PurpurSlab = 116,+    PurpurStairs = 117,+    Stonecutter = 118, } -pub const MAX_BLOCK_ID: u8 = 101;+pub const MAX_BLOCK_ID: u8 = 118;++/// The geometry a block occupies within its cell.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Shape { Cube, Slab, Stairs }++/// Meta bit layout for non-cube blocks: bits 0-1 facing, bit 2 half. Four bits are spare for+/// future shapes (corner stairs).+pub const META_FACING: u8 = 0b11;+pub const META_TOP: u8 = 0b100;+/// Facing values, named for the direction the stair's *low* side looks toward.+pub const FACE_NORTH: u8 = 0; // -Z+pub const FACE_EAST: u8 = 1;  // +X+pub const FACE_SOUTH: u8 = 2; // +Z+pub const FACE_WEST: u8 = 3;  // -X++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Aabb { pub min: [f32; 3], pub max: [f32; 3] }++impl Aabb {+    pub const fn new(min: [f32; 3], max: [f32; 3]) -> Self { Self { min, max } }+    /// Does this box, placed in the cell at `cell`, overlap the world-space box `min`..`max`?+    pub fn overlaps_at(&self, cell: [f32; 3], min: [f32; 3], max: [f32; 3]) -> bool {+        (0..3).all(|i| cell[i] + self.max[i] > min[i] && cell[i] + self.min[i] < max[i])+    }+}++pub const FULL_CUBE: Aabb = Aabb::new([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);++/// The one or two boxes a block occupies. Returned by value to keep collision allocation-free.+#[derive(Clone, Copy, Debug)]+pub struct Boxes { len: usize, boxes: [Aabb; 2] }+impl Boxes {+    const fn one(a: Aabb) -> Self { Self { len: 1, boxes: [a, a] } }+    const fn two(a: Aabb, b: Aabb) -> Self { Self { len: 2, boxes: [a, b] } }+    const fn none() -> Self { Self { len: 0, boxes: [FULL_CUBE, FULL_CUBE] } }+    pub fn as_slice(&self) -> &[Aabb] { &self.boxes[..self.len] }+}  impl Block {     pub fn from_id(id: u8) -> Self {@@ -122,13 +178,123 @@ impl Block {     pub fn is_air(self) -> bool { matches!(self, Self::Air) }     pub fn is_solid(self) -> bool { !matches!(self, Self::Air | Self::Water | Self::Glass | Self::Lava | Self::NetherPortal | Self::EndPortal) }     pub fn is_transparent(self) -> bool {-        matches!(self, Self::Air | Self::Glass | Self::Leaves | Self::Water | Self::BirchLeaves | Self::SpruceLeaves | Self::DarkOakLeaves | Self::AzaleaLeaves | Self::Lava | Self::NetherPortal | Self::EndPortal)+        // Slabs and stairs leave part of their cell empty, so they can never hide a neighbour's+        // face wholesale. `occludes_face` decides the per-direction cases.+        self.shape() != Shape::Cube+            || matches!(self, Self::Air | Self::Glass | Self::Leaves | Self::Water | Self::BirchLeaves | Self::SpruceLeaves | Self::DarkOakLeaves | Self::AzaleaLeaves | Self::Lava | Self::NetherPortal | Self::EndPortal)     }     pub fn is_opaque(self) -> bool { !self.is_transparent() } -    // Interactive block menu: 0 = none, 1 = crafting, 2 = furnace, 3 = jukebox, 4 = blast furnace.+    pub fn shape(self) -> Shape {+        match self {+            Self::StoneSlab | Self::CobbleSlab | Self::PlankSlab | Self::BrickSlab+            | Self::SandstoneSlab | Self::DeepslateBrickSlab | Self::NetherBrickSlab | Self::PurpurSlab => Shape::Slab,+            Self::StoneStairs | Self::CobbleStairs | Self::PlankStairs | Self::BrickStairs+            | Self::SandstoneStairs | Self::DeepslateBrickStairs | Self::NetherBrickStairs | Self::PurpurStairs => Shape::Stairs,+            _ => Shape::Cube,+        }+    }++    /// The full-cube material a slab or stair is cut from; its textures are reused verbatim.+    pub fn parent(self) -> Self {+        match self {+            Self::StoneSlab | Self::StoneStairs => Self::Stone,+            Self::CobbleSlab | Self::CobbleStairs => Self::Cobble,+            Self::PlankSlab | Self::PlankStairs => Self::Planks,+            Self::BrickSlab | Self::BrickStairs => Self::Brick,+            Self::SandstoneSlab | Self::SandstoneStairs => Self::Sandstone,+            Self::DeepslateBrickSlab | Self::DeepslateBrickStairs => Self::DeepslateBricks,+            Self::NetherBrickSlab | Self::NetherBrickStairs => Self::NetherBricks,+            Self::PurpurSlab | Self::PurpurStairs => Self::Purpur,+            other => other,+        }+    }++    /// The slab shape for a material, and the stair shape. Used by the stonecutter and by the+    /// "two slabs make a cube" merge at placement.+    pub fn slab_of(self) -> Option<Self> {+        Some(match self {+            Self::Stone => Self::StoneSlab,+            Self::Cobble => Self::CobbleSlab,+            Self::Planks => Self::PlankSlab,+            Self::Brick => Self::BrickSlab,+            Self::Sandstone => Self::SandstoneSlab,+            Self::DeepslateBricks => Self::DeepslateBrickSlab,+            Self::NetherBricks => Self::NetherBrickSlab,+            Self::Purpur => Self::PurpurSlab,+            _ => return None,+        })+    }+    pub fn stairs_of(self) -> Option<Self> {+        Some(match self {+            Self::Stone => Self::StoneStairs,+            Self::Cobble => Self::CobbleStairs,+            Self::Planks => Self::PlankStairs,+            Self::Brick => Self::BrickStairs,+            Self::Sandstone => Self::SandstoneStairs,+            Self::DeepslateBricks => Self::DeepslateBrickStairs,+            Self::NetherBricks => Self::NetherBrickStairs,+            Self::Purpur => Self::PurpurStairs,+            _ => return None,+        })+    }++    /// The boxes this block fills, in cell-local 0..1 coordinates.+    pub fn collision_boxes(self, meta: u8) -> Boxes {+        if !self.is_solid() { return Boxes::none(); }+        let top = meta & META_TOP != 0;+        match self.shape() {+            Shape::Cube => Boxes::one(FULL_CUBE),+            Shape::Slab => Boxes::one(if top {+                Aabb::new([0.0, 0.5, 0.0], [1.0, 1.0, 1.0])+            } else {+                Aabb::new([0.0, 0.0, 0.0], [1.0, 0.5, 1.0])+            }),+            Shape::Stairs => {+                // A stair is a half-height slab plus a quarter block on the side opposite `facing`,+                // so you climb it walking against the way it faces.+                let (base, step_y) = if top {+                    (Aabb::new([0.0, 0.5, 0.0], [1.0, 1.0, 1.0]), [0.0, 0.5])+                } else {+                    (Aabb::new([0.0, 0.0, 0.0], [1.0, 0.5, 1.0]), [0.5, 1.0])+                };+                let step = match meta & META_FACING {+                    FACE_NORTH => Aabb::new([0.0, step_y[0], 0.5], [1.0, step_y[1], 1.0]),+                    FACE_EAST => Aabb::new([0.0, step_y[0], 0.0], [0.5, step_y[1], 1.0]),+                    FACE_SOUTH => Aabb::new([0.0, step_y[0], 0.0], [1.0, step_y[1], 0.5]),+                    _ => Aabb::new([0.5, step_y[0], 0.0], [1.0, step_y[1], 1.0]),+                };+                Boxes::two(base, step)+            }+        }+    }++    /// Whether this block completely hides a neighbour's face in direction (dx, dy, dz), pointing+    /// out of this block. Only a fully covered face may be culled; a half-covered one would leave+    /// a hole in the world.+    pub fn occludes_face(self, meta: u8, dx: i32, dy: i32, dz: i32) -> bool {+        let top = meta & META_TOP != 0;+        match self.shape() {+            Shape::Cube => self.is_opaque(),+            // A slab seals only the face its solid half rests against.+            Shape::Slab => if top { dy == 1 } else { dy == -1 },+            Shape::Stairs => {+                if if top { dy == 1 } else { dy == -1 } { return true; }+                // The tall side is opposite `facing`, and there the block spans the full face.+                match meta & META_FACING {+                    FACE_NORTH => dz == 1,+                    FACE_EAST => dx == -1,+                    FACE_SOUTH => dz == -1,+                    _ => dx == 1,+                }+            }+        }+    }++    // Interactive block menu: 0 = none, 1 = crafting, 2 = furnace, 3 = jukebox, 4 = blast furnace,+    // 5 = stonecutter.     pub fn menu(self) -> i32 {-        match self { Self::CraftingTable => 1, Self::Furnace => 2, Self::Jukebox => 3, Self::BlastFurnace => 4, _ => 0 }+        match self { Self::CraftingTable => 1, Self::Furnace => 2, Self::Jukebox => 3, Self::BlastFurnace => 4, Self::Stonecutter => 5, _ => 0 }     }      // Atlas tile indices (8x8 atlas). See the atlas generator's TILES order.@@ -236,6 +402,16 @@ impl Block {             Self::CopperBlock => 138,             Self::GoldBlock => 139,             Self::BronzeBlock => 140,+            Self::Stonecutter => 141,+            // Slabs and stairs are textured entirely from their parent material.+            Self::StoneSlab | Self::StoneStairs => Self::Stone.tile_top(),+            Self::CobbleSlab | Self::CobbleStairs => Self::Cobble.tile_top(),+            Self::PlankSlab | Self::PlankStairs => Self::Planks.tile_top(),+            Self::BrickSlab | Self::BrickStairs => Self::Brick.tile_top(),+            Self::SandstoneSlab | Self::SandstoneStairs => Self::Sandstone.tile_top(),+            Self::DeepslateBrickSlab | Self::DeepslateBrickStairs => Self::DeepslateBricks.tile_top(),+            Self::NetherBrickSlab | Self::NetherBrickStairs => Self::NetherBricks.tile_top(),+            Self::PurpurSlab | Self::PurpurStairs => Self::Purpur.tile_top(),         }     }     pub fn tile_bottom(self) -> u32 {@@ -273,9 +449,16 @@ impl Block {             Self::HayBlock => 93,             Self::Farmland => 1,             Self::BlastFurnace => 135,+            Self::Stonecutter => 142,             _ => self.tile_top(),         }     }+    // Slabs and stairs draw with their parent's faces; the geometry, not the texture, is what makes+    // them a different block.+    pub fn tile_for_dir(self, _dx: i32, dy: i32, _dz: i32) -> u32 {+        let m = self.parent();+        if dy == 1 { m.tile_top() } else if dy == -1 { m.tile_bottom() } else { m.tile_side() }+    }     pub fn color(self) -> [f32; 3] {         match self {             Self::Leaves => [0.42, 0.72, 0.33],@@ -296,7 +479,12 @@ impl Block {             | 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::CopperOre | Self::GoldOre | Self::CopperBlock | Self::GoldBlock | Self::BronzeBlock+            | Self::Stonecutter+            | Self::StoneSlab | Self::StoneStairs | Self::CobbleSlab | Self::CobbleStairs+            | Self::BrickSlab | Self::BrickStairs | Self::SandstoneSlab | Self::SandstoneStairs+            | Self::DeepslateBrickSlab | Self::DeepslateBrickStairs+            | Self::NetherBrickSlab | Self::NetherBrickStairs | Self::PurpurSlab | Self::PurpurStairs)     }     // Block light emitted (0..15) for dynamic lighting.     pub fn light_emission(self) -> u8 {@@ -308,9 +496,6 @@ impl Block {             _ => 0,         }     }-    pub fn tile_for_dir(self, _dx: i32, dy: i32, _dz: i32) -> u32 {-        if dy == 1 { self.tile_top() } else if dy == -1 { self.tile_bottom() } else { self.tile_side() }-    } }  // Atlas is 16 tiles wide x 16 tall (256x256). Tiles 0..15 = base blocks, 16 = grass side overlay,@@ -329,3 +514,99 @@ pub fn tile_uv(tile_index: u32) -> (f32,f32,f32,f32) {     let sy = 1.0 / ATLAS_ROWS;     (tx*sx, ty*sy, (tx+1.0)*sx, (ty+1.0)*sy) }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn every_id_up_to_the_max_maps_to_a_distinct_block() {+        for id in 0..=MAX_BLOCK_ID {+            assert_eq!(Block::from_id(id).id(), id, "id {id} did not round-trip");+        }+        // Ids above the max must not be mistaken for real blocks.+        assert_eq!(Block::from_id(MAX_BLOCK_ID + 1), Block::Air);+        // Blocks and items share one u8 space; crossing ITEM_BASE would make a block unplaceable.+        assert!(MAX_BLOCK_ID < crate::item::ITEM_BASE);+    }++    #[test]+    fn slabs_and_stairs_know_their_material() {+        for m in [Block::Stone, Block::Cobble, Block::Planks, Block::Brick,+                  Block::Sandstone, Block::DeepslateBricks, Block::NetherBricks, Block::Purpur] {+            let slab = m.slab_of().unwrap_or_else(|| panic!("{m:?} needs a slab"));+            let stairs = m.stairs_of().unwrap_or_else(|| panic!("{m:?} needs stairs"));+            assert_eq!(slab.shape(), Shape::Slab);+            assert_eq!(stairs.shape(), Shape::Stairs);+            assert_eq!(slab.parent(), m);+            assert_eq!(stairs.parent(), m);+            // They borrow the parent's faces, so no new atlas art is needed.+            for (dx, dy, dz) in [(1, 0, 0), (0, 1, 0), (0, -1, 0)] {+                assert_eq!(slab.tile_for_dir(dx, dy, dz), m.tile_for_dir(dx, dy, dz));+                assert_eq!(stairs.tile_for_dir(dx, dy, dz), m.tile_for_dir(dx, dy, dz));+            }+            // A partial block can never be treated as a solid occluder wholesale.+            assert!(!slab.is_opaque());+            assert!(!stairs.is_opaque());+            assert!(slab.is_solid() && stairs.is_solid());+        }+        assert_eq!(Block::Stone.shape(), Shape::Cube);+        assert_eq!(Block::Stone.parent(), Block::Stone);+        assert_eq!(Block::Dirt.slab_of(), None);+    }++    #[test]+    fn a_slab_fills_the_half_its_meta_says() {+        let bottom = Block::StoneSlab.collision_boxes(0);+        assert_eq!(bottom.as_slice(), &[Aabb::new([0.0, 0.0, 0.0], [1.0, 0.5, 1.0])]);+        let top = Block::StoneSlab.collision_boxes(META_TOP);+        assert_eq!(top.as_slice(), &[Aabb::new([0.0, 0.5, 0.0], [1.0, 1.0, 1.0])]);++        // A bottom slab seals only the floor; a top slab only the ceiling.+        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));+    }++    #[test]+    fn a_stair_is_a_slab_plus_a_step_opposite_its_facing() {+        let boxes = Block::StoneStairs.collision_boxes(FACE_NORTH);+        let s = boxes.as_slice();+        assert_eq!(s.len(), 2);+        assert_eq!(s[0], Aabb::new([0.0, 0.0, 0.0], [1.0, 0.5, 1.0]), "base half-slab");+        assert_eq!(s[1], Aabb::new([0.0, 0.5, 0.5], [1.0, 1.0, 1.0]), "step on the far side of north");++        // The tall side is fully covered, so it may hide a neighbour; the low side may not.+        assert!(Block::StoneStairs.occludes_face(FACE_NORTH, 0, 0, 1), "tall side seals");+        assert!(!Block::StoneStairs.occludes_face(FACE_NORTH, 0, 0, -1), "low side is only half filled");+        assert!(Block::StoneStairs.occludes_face(FACE_NORTH, 0, -1, 0), "the base covers the floor");+        assert!(!Block::StoneStairs.occludes_face(FACE_NORTH, 0, 1, 0));++        // Flipping to the top half mirrors the geometry vertically.+        let flipped = Block::StoneStairs.collision_boxes(FACE_NORTH | META_TOP);+        let f = flipped.as_slice();+        assert_eq!(f[0], Aabb::new([0.0, 0.5, 0.0], [1.0, 1.0, 1.0]));+        assert_eq!(f[1], Aabb::new([0.0, 0.0, 0.5], [1.0, 0.5, 1.0]));+        assert!(Block::StoneStairs.occludes_face(FACE_NORTH | META_TOP, 0, 1, 0));+    }++    #[test]+    fn each_facing_puts_the_step_on_the_opposite_side() {+        let step = |facing: u8| Block::StoneStairs.collision_boxes(facing).as_slice()[1];+        assert_eq!(step(FACE_NORTH).min[2], 0.5, "north-facing steps sit on +Z");+        assert_eq!(step(FACE_SOUTH).max[2], 0.5, "south-facing steps sit on -Z");+        assert_eq!(step(FACE_EAST).max[0], 0.5, "east-facing steps sit on -X");+        assert_eq!(step(FACE_WEST).min[0], 0.5, "west-facing steps sit on +X");+    }++    #[test]+    fn cubes_are_unchanged() {+        assert_eq!(Block::Stone.collision_boxes(0).as_slice(), &[FULL_CUBE]);+        assert!(Block::Stone.occludes_face(0, 1, 0, 0));+        assert!(!Block::Glass.occludes_face(0, 1, 0, 0), "glass never hid faces");+        assert!(Block::Air.collision_boxes(0).as_slice().is_empty(), "air has no collision");+        assert!(Block::Water.collision_boxes(0).as_slice().is_empty());+    }+}
games/voxels/src/main/rust/src/world/chunk.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk.rs b/games/voxels/src/main/rust/src/world/chunk.rsindex 5c93cfd73b..b7930067c1 100644--- a/games/voxels/src/main/rust/src/world/chunk.rs+++ b/games/voxels/src/main/rust/src/world/chunk.rs@@ -8,16 +8,28 @@ impl ChunkPos {     pub fn from_world(x: i32, z: i32) -> Self { Self(x.div_euclid(CHUNK_SIZE as i32), z.div_euclid(CHUNK_SIZE as i32)) }     pub fn world_origin(self) -> (i32, i32) { (self.0 * CHUNK_SIZE as i32, self.1 * CHUNK_SIZE as i32) } }+// `meta` carries the per-voxel state that doesn't fit in the block id (slab half, stair facing). It+// is allocated only once a section actually stores a non-zero value: generated terrain is all plain+// cubes, so the vast majority of resident sections stay at 8 bytes instead of 4 KB. #[derive(Clone)]-pub struct BlockSection { pub blocks: [u8; 4096], pub non_air: usize, }+pub struct BlockSection { pub blocks: [u8; 4096], pub meta: Option<Box<[u8; 4096]>>, pub non_air: usize, } impl BlockSection {-    pub fn empty() -> Self { Self { blocks: [0;4096], non_air:0 } }+    pub fn empty() -> Self { Self { blocks: [0;4096], meta: None, non_air:0 } }     fn idx(x: usize, y: usize, z: usize) -> usize { y*256+z*16+x }     pub fn get(&self, x: usize, y: usize, z: usize) -> u8 { self.blocks[Self::idx(x,y,z)] }     pub fn set(&mut self, x: usize, y: usize, z: usize, id: u8) {         let i=Self::idx(x,y,z); let prev=self.blocks[i];         if prev!=0 && id==0 { self.non_air=self.non_air.saturating_sub(1); } else if prev==0 && id!=0 { self.non_air+=1; }         self.blocks[i]=id;+        if let Some(m) = self.meta.as_mut() { m[i] = 0; }+    }+    pub fn get_meta(&self, x: usize, y: usize, z: usize) -> u8 {+        match &self.meta { Some(m) => m[Self::idx(x,y,z)], None => 0 }+    }+    pub fn set_meta(&mut self, x: usize, y: usize, z: usize, meta: u8) {+        if meta == 0 && self.meta.is_none() { return; }+        let m = self.meta.get_or_insert_with(|| Box::new([0u8; 4096]));+        m[Self::idx(x,y,z)] = meta;     }     pub fn is_empty(&self) -> bool { self.non_air==0 } }@@ -32,10 +44,19 @@ impl Chunk {         if y>=CHUNK_HEIGHT { return 0; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE;         if let Some(s)=&self.sections[sec] { s.get(x,ly,z) } else { 0 }     }-    pub fn set_block(&mut self, x: usize, y: usize, z: usize, id: u8) {+    pub fn get_meta(&self, x: usize, y: usize, z: usize) -> u8 {+        if y>=CHUNK_HEIGHT { return 0; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE;+        if let Some(s)=&self.sections[sec] { s.get_meta(x,ly,z) } else { 0 }+    }+    pub fn set_block(&mut self, x: usize, y: usize, z: usize, id: u8) { self.set_block_meta(x, y, z, id, 0); }+    pub fn set_block_meta(&mut self, x: usize, y: usize, z: usize, id: u8, meta: u8) {         if y>=CHUNK_HEIGHT { return; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE;         if self.sections[sec].is_none() { if id==0 { return; } self.sections[sec]=Some(BlockSection::empty()); }-        if let Some(s)=self.sections[sec].as_mut() { s.set(x,ly,z,id); if s.is_empty() { self.sections[sec]=None; } }+        if let Some(s)=self.sections[sec].as_mut() {+            s.set(x,ly,z,id);+            s.set_meta(x,ly,z,meta);+            if s.is_empty() { self.sections[sec]=None; }+        }         self.dirty=true; self.mesh_dirty=true;     } }
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 aae6a84d63..4e3d02b866 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -25,14 +25,26 @@ impl ChunkMap {             chunk.get_block(lx, wy as usize, lz)         } else { 0 }     }+    pub fn get_meta_world(&self, wx: i32, wy: i32, wz: i32) -> u8 {+        if wy < 0 || wy >= CHUNK_HEIGHT as i32 { return 0; }+        let cp = ChunkPos::from_world(wx, wz);+        if let Some(chunk) = self.chunks.get(&cp) {+            let lx = wx.rem_euclid(CHUNK_SIZE as i32) as usize;+            let lz = wz.rem_euclid(CHUNK_SIZE as i32) as usize;+            chunk.get_meta(lx, wy as usize, lz)+        } else { 0 }+    }     pub fn set_block_world(&mut self, wx: i32, wy: i32, wz: i32, id: u8) -> bool {+        self.set_block_meta_world(wx, wy, wz, id, 0)+    }+    pub fn set_block_meta_world(&mut self, wx: i32, wy: i32, wz: i32, id: u8, meta: u8) -> bool {         if wy < 0 || wy >= CHUNK_HEIGHT as i32 { return false; }         let cp = ChunkPos::from_world(wx, wz);         if !self.chunks.contains_key(&cp) { self.load_or_gen(cp); }         if let Some(chunk) = self.chunks.get_mut(&cp) {             let lx = wx.rem_euclid(CHUNK_SIZE as i32) as usize;             let lz = wz.rem_euclid(CHUNK_SIZE as i32) as usize;-            chunk.set_block(lx, wy as usize, lz, id);+            chunk.set_block_meta(lx, wy as usize, lz, id, meta);             true         } else { false }     }
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 1bccc93089..4c9f0d18bd 100644--- a/games/voxels/src/main/rust/src/world/mesher.rs+++ b/games/voxels/src/main/rust/src/world/mesher.rs@@ -1,6 +1,9 @@-use super::block::{Block, GRASS_SIDE_TILE};+use super::block::{Aabb, Block, Shape, GRASS_SIDE_TILE}; use super::chunk::{Chunk, SECTION_SIZE, SECTIONS_PER_CHUNK, CHUNK_HEIGHT}; +/// A neighbour lookup: block id plus its meta byte, since occlusion now depends on both.+pub type Neighbor<'a> = dyn Fn(i32, i32, i32) -> (u8, u8) + 'a;+ // Per-chunk lighting: skylight column tops (highest opaque block per column) and a block-light grid // (BFS flood from emitters, decreasing by 1 per open cell). Cross-chunk bleed is limited to this // chunk's own data, which is plenty for caves + torch pools.@@ -68,8 +71,87 @@ impl MeshData { pub fn is_empty(&self) -> bool { self.vertices.is_empty() && sel fn vao(s1: bool, s2: bool, c: bool) -> u8 { if s1 && s2 { 0 } else { 3 - (s1 as u8 + s2 as u8 + c as u8) } } fn aof(level: u8) -> f32 { level as f32 / 3.0 } -pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_tint: &dyn Fn(i32,i32)->[f32;3]) -> Vec<Option<MeshData>> {-    let occ = |ax: i32, ay: i32, az: i32| -> bool { let id = get_neighbor(ax, ay, az); id != 0 && Block::from_id(id).is_opaque() };+const FACE_DIRS: [(i32, i32, i32); 6] = [(1,0,0), (-1,0,0), (0,1,0), (0,-1,0), (0,0,1), (0,0,-1)];++/// Is this face of `b` sealed against another box of the same block? Emitting both sides of a shared+/// plane would z-fight, so the fully covered one is dropped.+fn face_covered_by_sibling(b: &Aabb, siblings: &[Aabb], axis: usize, positive: bool) -> bool {+    let plane = if positive { b.max[axis] } else { b.min[axis] };+    let (u, v) = ((axis + 1) % 3, (axis + 2) % 3);+    siblings.iter().any(|s| {+        if std::ptr::eq(s, b) { return false; }+        // The sibling must start exactly where this face ends, on the far side.+        let touches = if positive { s.min[axis] == plane } else { s.max[axis] == plane };+        touches && s.min[u] <= b.min[u] && s.max[u] >= b.max[u]+               && s.min[v] <= b.min[v] && s.max[v] >= b.max[v]+    })+}++/// Emit the six faces of one sub-block box. `cell` is the box's cell in section-local coordinates and+/// `origin` the section's world corner. Faces flush with the cell boundary are culled against the+/// neighbouring block; faces sealed against a sibling box are dropped.+#[allow(clippy::too_many_arguments)]+fn append_box(+    verts: &mut Vec<Vertex>, indices: &mut Vec<u32>,+    block: Block, b: Aabb, siblings: &[Aabb],+    cell: [f32; 3], origin: [f32; 3],+    hidden: &dyn Fn(i32, i32, i32) -> bool,+    light: &dyn Fn(i32, i32, i32) -> u8,+) {+    let color = block.color();+    for (dx, dy, dz) in FACE_DIRS {+        let axis = if dx != 0 { 0 } else if dy != 0 { 1 } else { 2 };+        let positive = dx + dy + dz > 0;+        let plane = if positive { b.max[axis] } else { b.min[axis] };+        // Only a face sitting exactly on the cell wall can be hidden by the neighbouring block.+        let flush = if positive { plane >= 1.0 } else { plane <= 0.0 };+        if flush && hidden(dx, dy, dz) { continue; }+        if face_covered_by_sibling(&b, siblings, axis, positive) { continue; }++        let (x0, y0, z0) = (b.min[0], b.min[1], b.min[2]);+        let (x1, y1, z1) = (b.max[0], b.max[1], b.max[2]);+        // Texture coordinates follow the block's own 0..1 cell, so a half-height side samples the+        // matching half of the tile rather than squashing the whole thing into it. v grows downward.+        let corners: [([f32; 3], [f32; 2]); 4] = match (dx, dy, dz) {+            (1, 0, 0) => [([x1,y0,z0],[z0,1.0-y0]), ([x1,y1,z0],[z0,1.0-y1]), ([x1,y1,z1],[z1,1.0-y1]), ([x1,y0,z1],[z1,1.0-y0])],+            (-1, 0, 0) => [([x0,y0,z1],[1.0-z1,1.0-y0]), ([x0,y1,z1],[1.0-z1,1.0-y1]), ([x0,y1,z0],[1.0-z0,1.0-y1]), ([x0,y0,z0],[1.0-z0,1.0-y0])],+            (0, 1, 0) => [([x0,y1,z0],[x0,z0]), ([x1,y1,z0],[x1,z0]), ([x1,y1,z1],[x1,z1]), ([x0,y1,z1],[x0,z1])],+            (0, -1, 0) => [([x0,y0,z1],[x0,1.0-z1]), ([x1,y0,z1],[x1,1.0-z1]), ([x1,y0,z0],[x1,1.0-z0]), ([x0,y0,z0],[x0,1.0-z0])],+            (0, 0, 1) => [([x0,y0,z1],[x0,1.0-y0]), ([x1,y0,z1],[x1,1.0-y0]), ([x1,y1,z1],[x1,1.0-y1]), ([x0,y1,z1],[x0,1.0-y1])],+            _ => [([x1,y0,z0],[1.0-x1,1.0-y0]), ([x0,y0,z0],[1.0-x0,1.0-y0]), ([x0,y1,z0],[1.0-x0,1.0-y1]), ([x1,y1,z0],[1.0-x1,1.0-y1])],+        };+        let tile = block.tile_for_dir(dx, dy, dz) as f32;+        let lpk = light(dx, dy, dz);+        let start = verts.len() as u32;+        for (pos, uv) in corners {+            verts.push(Vertex {+                pos: [origin[0] + cell[0] + pos[0], origin[1] + cell[1] + pos[1], origin[2] + cell[2] + pos[2]],+                uv,+                color,+                // Partial faces get flat lighting: the corner AO sampler only understands whole cells.+                ao: 1.0,+                tile_idx: tile,+                normal: [dx as f32, dy as f32, dz as f32],+                light: light_to_f32(lpk),+            });+        }+        indices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]);+    }+}++pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i32,i32)->[f32;3]) -> Vec<Option<MeshData>> {+    // AO only samples whole cells, so a partial block never darkens its neighbours.+    let occ = |ax: i32, ay: i32, az: i32| -> bool {+        let (id, _) = get_neighbor(ax, ay, az);+        id != 0 && Block::from_id(id).is_opaque()+    };+    // Whether the neighbour in direction (dx,dy,dz) fully covers the face we are about to emit.+    let hidden = |wx: i32, wy: i32, wz: i32, dx: i32, dy: i32, dz: i32| -> bool {+        let (nid, nmeta) = get_neighbor(wx + dx, wy + dy, wz + dz);+        if nid == 0 { return false; }+        // The neighbour's own face points back at us.+        Block::from_id(nid).occludes_face(nmeta, -dx, -dy, -dz)+    };     let mut result: Vec<Option<MeshData>> = (0..SECTIONS_PER_CHUNK).map(|_| None).collect();     let ox = chunk.pos.world_origin().0;     let oz = chunk.pos.world_origin().1;@@ -103,10 +185,9 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t                         for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {                             let id = section.get(x,y,z);                             if id == 0 || id == Block::Water as u8 { continue; }+                            if Block::from_id(id).shape() != Shape::Cube { continue; } // emitted as boxes below                             let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32;-                            let nid = get_neighbor(wx+dx, wy+dy, wz+dz);-                            let need = if nid != 0 { !Block::from_id(nid).is_opaque() } else { true };-                            if need {+                            if !hidden(wx, wy, wz, dx, dy, dz) {                                 let tile = Block::from_id(id).tile_for_dir(dx,dy,dz);                                 let nb = wx + dx;                                 let ao = |ys: i32, zs: i32| vao(occ(nb, wy+ys, wz), occ(nb, wy, wz+zs), occ(nb, wy+ys, wz+zs));@@ -154,10 +235,10 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t                         for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {                             let id = section.get(x,y,z);                             if id==0 || id==Block::Water as u8 { continue; }+                            if Block::from_id(id).shape() != Shape::Cube { continue; }                             let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32;-                            let nid = get_neighbor(wx+dx, wy+dy, wz+dz);-                            if nid==0 || !Block::from_id(nid).is_opaque() {-                                if !(nid==id && Block::from_id(nid).is_opaque()) {+                            if !hidden(wx, wy, wz, dx, dy, dz) {+                                {                                     let tile = Block::from_id(id).tile_for_dir(dx,dy,dz);                                     let nb = wy + dy;                                     let ao = |xs: i32, zs: i32| vao(occ(wx+xs, nb, wz), occ(wx, nb, wz+zs), occ(wx+xs, nb, wz+zs));@@ -205,9 +286,9 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t                         for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE {                             let id = section.get(x,y,z);                             if id==0 || id==Block::Water as u8 { continue; }+                            if Block::from_id(id).shape() != Shape::Cube { continue; }                             let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32;-                            let nid = get_neighbor(wx+dx, wy+dy, wz+dz);-                            if nid==0 || !Block::from_id(nid).is_opaque() {+                            if !hidden(wx, wy, wz, dx, dy, dz) {                                 let tile = Block::from_id(id).tile_for_dir(dx,dy,dz);                                 let nb = wz + dz;                                 let ao = |xs: i32, ys: i32| vao(occ(wx+xs, wy, nb), occ(wx, wy+ys, nb), occ(wx+xs, wy+ys, nb));@@ -259,7 +340,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t             for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {                 if section.get(x,y,z) != Block::Water as u8 { 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);+                let above = get_neighbor(wx, wy+1, wz).0;                 if above != Block::Water as u8 && !(above != 0 && Block::from_id(above).is_opaque()) {                     wmask[x][z] = true;                 }@@ -282,6 +363,23 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t                 windices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]);             }}         }+        // --- Slabs and stairs: emitted box by box, since they never merge with anything. ---+        for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { for x in 0..SECTION_SIZE {+            let id = section.get(x, y, z);+            if id == 0 { continue; }+            let block = Block::from_id(id);+            if block.shape() == Shape::Cube { continue; }+            let meta = section.get_meta(x, y, z);+            let (wx, wy, wz) = (ox + x as i32, base_y + y as i32, oz + z as i32);+            let cell = [x as f32, y as f32, z as f32];+            let origin = [ox as f32, base_y as f32, oz as f32];+            let boxes = block.collision_boxes(meta);+            for bx in boxes.as_slice() {+                append_box(&mut verts, &mut indices, block, *bx, boxes.as_slice(), cell, origin,+                           &|dx, dy, dz| hidden(wx, wy, wz, dx, dy, dz),+                           &|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 }); }     }     result@@ -291,18 +389,95 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t mod tests {     use super::*;     use crate::world::chunk::{Chunk, ChunkPos};++    /// Mesh a chunk at the origin, resolving neighbours from the chunk itself so in-chunk occlusion+    /// is exercised. Anything outside the chunk reads as air.+    fn mesh_alone(c: &Chunk) -> Vec<Option<MeshData>> {+        mesh_chunk(c, &|x, y, z| {+            if !(0..16).contains(&x) || !(0..16).contains(&z) || y < 0 || y >= CHUNK_HEIGHT as i32 { return (0, 0); }+            let (x, y, z) = (x as usize, y as usize, z as usize);+            (c.get_block(x, y, z), c.get_meta(x, y, z))+        }, &|_, _| [0.4, 0.7, 0.3])+    }+    fn vert_count(m: &[Option<MeshData>]) -> usize {+        m.iter().filter_map(|o| o.as_ref()).map(|md| md.vertices.len()).sum()+    }+     #[test]     fn empty_chunk_no_mesh() {         let c = Chunk::new(ChunkPos(0,0));-        let m = mesh_chunk(&c, &|_,_,_| 0, &|_,_| [0.4,0.7,0.3]);+        let m = mesh_alone(&c);         assert!(m.iter().all(|o| o.is_none()));     }     #[test]     fn single_block_has_faces() {         let mut c = Chunk::new(ChunkPos(0,0));         c.set_block(1, 10, 1, 1);-        let m = mesh_chunk(&c, &|x,y,z| if x==1 && y==10 && z==1 { 1 } else { 0 }, &|_,_| [0.4,0.7,0.3]);-        let total: usize = m.iter().filter_map(|o| o.as_ref()).map(|md| md.vertices.len()).sum();-        assert!(total >= 24);+        let m = mesh_chunk(&c, &|x,y,z| if x==1 && y==10 && z==1 { (1, 0) } else { (0, 0) }, &|_,_| [0.4,0.7,0.3]);+        assert!(vert_count(&m) >= 24);+    }++    #[test]+    fn a_lone_slab_is_meshed() {+        let mut c = Chunk::new(ChunkPos(0,0));+        c.set_block_meta(2, 10, 2, Block::StoneSlab as u8, 0);+        let m = mesh_alone(&c);+        assert_eq!(vert_count(&m), 24, "a free-standing slab shows all six faces");++        // Its side faces must span only the lower half of the cell.+        let md = m.iter().flatten().next().unwrap();+        let ys: Vec<f32> = md.vertices.iter().map(|v| v.pos[1]).collect();+        assert!(ys.iter().any(|&y| (y - 10.0).abs() < 1e-5), "bottom sits on the cell floor");+        assert!(ys.iter().any(|&y| (y - 10.5).abs() < 1e-5), "top sits at mid-cell");+        assert!(!ys.iter().any(|&y| y > 10.5 + 1e-5), "a bottom slab never reaches the cell ceiling");+    }++    // The regression the directional occlusion test exists for: a cube beside a slab must still draw+    // the half of its face the slab doesn't cover, or the world gets holes.+    #[test]+    fn a_cube_next_to_a_slab_keeps_its_face() {+        let mut with_slab = Chunk::new(ChunkPos(0,0));+        with_slab.set_block(5, 10, 5, Block::Stone as u8);+        with_slab.set_block_meta(6, 10, 5, Block::StoneSlab as u8, 0);++        let mut with_cube = Chunk::new(ChunkPos(0,0));+        with_cube.set_block(5, 10, 5, Block::Stone as u8);+        with_cube.set_block(6, 10, 5, Block::Stone as u8);++        let slab_faces = count_faces_at(&mesh_alone(&with_slab), 6.0, [1.0, 0.0, 0.0]);+        let cube_faces = count_faces_at(&mesh_alone(&with_cube), 6.0, [1.0, 0.0, 0.0]);+        assert_eq!(cube_faces, 0, "two touching cubes hide the shared face");+        assert_eq!(slab_faces, 1, "the slab only covers half, so the cube must still draw its +X face");+    }++    // Count faces on the plane x == `x_plane` with the given normal.+    fn count_faces_at(m: &[Option<MeshData>], x_plane: f32, normal: [f32; 3]) -> usize {+        m.iter().flatten()+            .flat_map(|md| md.indices.chunks(6).map(move |c| &md.vertices[c[0] as usize]))+            .filter(|v| v.normal == normal && (v.pos[0] - x_plane).abs() < 1e-5)+            .count()+    }++    // Two boxes of one stair share a plane. Emitting both sides would z-fight, so the sealed one is+    // dropped — but the visible tread must survive.+    #[test]+    fn stairs_drop_only_the_sealed_internal_face() {+        let mut c = Chunk::new(ChunkPos(0,0));+        c.set_block_meta(3, 10, 3, Block::StoneStairs as u8, crate::world::block::FACE_NORTH);+        let m = mesh_alone(&c);+        let md = m.iter().flatten().next().expect("stairs must mesh");++        let up: Vec<_> = md.indices.chunks(6)+            .map(|ci| &md.vertices[ci[0] as usize])+            .filter(|v| v.normal == [0.0, 1.0, 0.0])+            .collect();+        let down: Vec<_> = md.indices.chunks(6)+            .map(|ci| &md.vertices[ci[0] as usize])+            .filter(|v| v.normal == [0.0, -1.0, 0.0])+            .collect();+        // The tread (base top) and the step top face up; only the base bottom faces down, because+        // the step's underside is sealed against the base.+        assert_eq!(up.len(), 2, "the tread and the step's top both face up");+        assert_eq!(down.len(), 1, "the step's underside is sealed against the base and must be dropped");     } }
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 b2ac61a51d..2ec1a10d07 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -13,37 +13,66 @@ 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::rename(&tmp, &path)?;+    Ok(())+}+// VOX2: "VOX2", section count, then per section: present u8; if 1 { 4096 block bytes; has_meta u8;+// if 1 { 4096 meta bytes } }. The meta flag keeps cube-only sections exactly the size VOX1 wrote.+fn encode_chunk(chunk: &Chunk) -> Vec<u8> {     let mut data = Vec::with_capacity(16*1024);-    data.extend_from_slice(b"VOX1");+    data.extend_from_slice(b"VOX2");     data.push(SECTIONS_PER_CHUNK as u8);     for sec_opt in chunk.sections.iter() {-        if let Some(sec) = sec_opt {-            data.push(1);-            data.extend_from_slice(&sec.blocks);-        } else { data.push(0); }+        let Some(sec) = sec_opt else { data.push(0); continue; };+        data.push(1);+        data.extend_from_slice(&sec.blocks);+        match sec.meta.as_ref().filter(|m| m.iter().any(|&v| v != 0)) {+            Some(meta) => { data.push(1); data.extend_from_slice(&meta[..]); }+            None => data.push(0),+        }     }-    fs::write(&tmp, &data)?;-    fs::rename(&tmp, &path)?;-    Ok(())+    data } pub fn load_chunk(base: &str, _pos: ChunkPos, chunk: &mut Chunk) -> std::io::Result<()> {     let path = chunk_file(base, chunk.pos);-    let bytes = fs::read(&path)?;-    if bytes.len() < 5 { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "too small")); }-    if &bytes[0..4] != b"VOX1" { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad magic")); }+    decode_chunk(&fs::read(&path)?, chunk)+}+// Reads VOX1 and VOX2. A VOX1 chunk upgrades losslessly: every block it can contain is a full cube,+// which is exactly what meta 0 means. Rejecting it instead would make `load_or_gen` treat the chunk+// as ungenerated and regenerate it from the seed, erasing the player's build.+fn decode_chunk(bytes: &[u8], chunk: &mut Chunk) -> std::io::Result<()> {+    let bad = |m: &'static str| std::io::Error::new(std::io::ErrorKind::InvalidData, m);+    if bytes.len() < 5 { return Err(bad("too small")); }+    let has_meta_flags = match &bytes[0..4] {+        b"VOX1" => false,+        b"VOX2" => true,+        _ => return Err(bad("bad magic")),+    };     let sec_count = bytes[4] as usize;     let mut off = 5usize;     for sec_idx in 0..sec_count.min(SECTIONS_PER_CHUNK) {         if off >= bytes.len() { break; }         let flag = bytes[off]; off+=1;-        if flag==1 {-            if off + 4096 > bytes.len() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "section overflow")); }-            let mut blocks = [0u8; 4096];-            blocks.copy_from_slice(&bytes[off..off+4096]);-            off+=4096;-            let non_air = blocks.iter().filter(|&&b| b!=0).count();-            if non_air>0 { chunk.sections[sec_idx] = Some(super::chunk::BlockSection{ blocks, non_air }); }+        if flag != 1 { continue; }+        if off + 4096 > bytes.len() { return Err(bad("section overflow")); }+        let mut blocks = [0u8; 4096];+        blocks.copy_from_slice(&bytes[off..off+4096]);+        off+=4096;+        let mut meta = None;+        if has_meta_flags {+            if off >= bytes.len() { return Err(bad("missing meta flag")); }+            let has_meta = bytes[off]; off+=1;+            if has_meta == 1 {+                if off + 4096 > bytes.len() { return Err(bad("meta overflow")); }+                let mut m = Box::new([0u8; 4096]);+                m.copy_from_slice(&bytes[off..off+4096]);+                off+=4096;+                meta = Some(m);+            }         }+        let non_air = blocks.iter().filter(|&&b| b!=0).count();+        if non_air>0 { chunk.sections[sec_idx] = Some(super::chunk::BlockSection{ blocks, meta, non_air }); }     }     chunk.generated = true; chunk.dirty = false; chunk.mesh_dirty = true;     Ok(())@@ -114,6 +143,98 @@ pub fn load_player(base: &str) -> Option<PlayerSave> { #[cfg(test)] mod tests {     use super::*;+    use super::super::chunk::{BlockSection, SECTIONS_PER_CHUNK};++    // Build a chunk file in the retired VOX1 layout: magic, section count, then per section a+    // present-flag followed by 4096 raw block bytes and nothing else.+    fn encode_vox1(chunk: &Chunk) -> Vec<u8> {+        let mut data = vec![];+        data.extend_from_slice(b"VOX1");+        data.push(SECTIONS_PER_CHUNK as u8);+        for sec in chunk.sections.iter() {+            match sec {+                Some(s) => { data.push(1); data.extend_from_slice(&s.blocks); }+                None => data.push(0),+            }+        }+        data+    }++    // The load path treats a decode failure as "not generated", which makes ChunkMap regenerate the+    // chunk from the seed and silently destroy whatever the player built there. A VOX1 file must+    // therefore keep loading, byte-for-byte, with meta defaulting to plain cubes.+    #[test]+    fn legacy_vox1_chunks_still_load() {+        let mut original = Chunk::new(ChunkPos(3, -4));+        original.set_block(1, 5, 2, 42);+        original.set_block(15, 200, 15, 7);+        let bytes = encode_vox1(&original);++        let mut loaded = Chunk::new(ChunkPos(3, -4));+        decode_chunk(&bytes, &mut loaded).expect("a VOX1 chunk must still decode");++        assert!(loaded.generated, "a decoded chunk must count as generated or it gets regenerated");+        assert_eq!(loaded.get_block(1, 5, 2), 42);+        assert_eq!(loaded.get_block(15, 200, 15), 7);+        assert_eq!(loaded.get_meta(1, 5, 2), 0, "legacy blocks are all full cubes");+        for (a, b) in original.sections.iter().zip(loaded.sections.iter()) {+            match (a, b) {+                (Some(a), Some(b)) => assert_eq!(a.blocks, b.blocks, "block bytes must survive verbatim"),+                (None, None) => {}+                _ => panic!("section presence changed across a VOX1 load"),+            }+        }+    }++    #[test]+    fn slabs_and_stairs_survive_a_round_trip() {+        let mut original = Chunk::new(ChunkPos(0, 0));+        // A slab, and stairs facing each of the four compass directions.+        original.set_block_meta(0, 64, 0, 102, 0b100);       // top-half slab+        original.set_block_meta(1, 64, 0, 103, 0);           // stairs facing north, bottom+        original.set_block_meta(2, 64, 0, 103, 1);           // east+        original.set_block_meta(3, 64, 0, 103, 0b110);       // south, top-half+        original.set_block_meta(4, 64, 0, 103, 3);           // west+        original.set_block(5, 64, 0, 1);                     // a plain cube alongside++        let mut loaded = Chunk::new(ChunkPos(0, 0));+        decode_chunk(&encode_chunk(&original), &mut loaded).expect("VOX2 must decode");++        assert_eq!(loaded.get_meta(0, 64, 0), 0b100);+        assert_eq!(loaded.get_meta(1, 64, 0), 0);+        assert_eq!(loaded.get_meta(2, 64, 0), 1);+        assert_eq!(loaded.get_meta(3, 64, 0), 0b110);+        assert_eq!(loaded.get_meta(4, 64, 0), 3);+        assert_eq!(loaded.get_block(3, 64, 0), 103);+        assert_eq!(loaded.get_block(5, 64, 0), 1);+        assert_eq!(loaded.get_meta(5, 64, 0), 0);+    }++    // Terrain is all cubes, so a chunk that never stored a meta value must not pay for one — on+    // disk or in memory.+    #[test]+    fn cube_only_chunks_carry_no_meta() {+        let mut chunk = Chunk::new(ChunkPos(0, 0));+        for x in 0..16 { for z in 0..16 { chunk.set_block(x, 10, z, 1); } }+        let sec = chunk.sections[0].as_ref().expect("section 0 holds the stone");+        assert!(sec.meta.is_none(), "a cube-only section must not allocate a meta array");++        let encoded = encode_chunk(&chunk);+        let one_section = 1 + 4096 + 1; // present flag, blocks, has-meta flag+        assert_eq!(encoded.len(), 5 + one_section + (SECTIONS_PER_CHUNK - 1), "no meta bytes should be written");+    }++    // Clearing a block must clear its meta too, or a later slab placed in the same cell would+    // inherit a stale facing.+    #[test]+    fn replacing_a_block_clears_its_meta() {+        let mut s = BlockSection::empty();+        s.set(1, 2, 3, 103);+        s.set_meta(1, 2, 3, 0b110);+        assert_eq!(s.get_meta(1, 2, 3), 0b110);+        s.set(1, 2, 3, 1);+        assert_eq!(s.get_meta(1, 2, 3), 0, "a fresh block starts with default meta");+    }      // A player.json written before ProgressSave existed must still load, defaulting to a fresh     // progression rather than failing and wiping the world.
scripts/voxels/build_atlas.py
diff --git a/scripts/voxels/build_atlas.py b/scripts/voxels/build_atlas.pyindex cae912e4e2..646b9967de 100644--- a/scripts/voxels/build_atlas.py+++ b/scripts/voxels/build_atlas.py@@ -107,6 +107,8 @@ PROC_TILES = {     138: (204, 118, 66),   # copper block     139: (246, 208, 62),   # gold block     140: (176, 141, 87),   # bronze block+    141: (188, 192, 198),  # stonecutter top (saw blade steel)+    142: (112, 110, 106),  # stonecutter side (stone body) }  # Ore tiles: a stone/netherrack base with deterministic mineral blobs speckled over it, so new ores@@ -173,6 +175,7 @@ PROC_ICON = {     131: "silver_block.png", 132: "steel_block.png", 134: "blast_furnace.png",     136: "copper_ore.png", 137: "gold_ore.png",     138: "copper_block.png", 139: "gold_block.png", 140: "bronze_block.png",+    141: "stonecutter.png", }