Modern Apps git

← Modern-Apps.git

voxels: add chest containers, furnace smelting with fuel, and 13 more achievements

Commit
e9e799a227ae911592f1b58ebb0003d9a48840b7
Author
Vayun Mathur <[email protected]>
When
2026-08-05 04:37 UTC (4 months ago)
Parents
4f7238f

Diff

games/voxels/src/main/assets/achievements.json
diff --git a/games/voxels/src/main/assets/achievements.json b/games/voxels/src/main/assets/achievements.jsonindex 97a4a0cfa7..3d468c452b 100644--- a/games/voxels/src/main/assets/achievements.json+++ b/games/voxels/src/main/assets/achievements.json@@ -1 +1,21 @@-[{"id":"first_block","name":"Groundbreaker","description":"Break your first block"},{"id":"first_place","name":"Builder","description":"Place your first block"},{"id":"explorer_100","name":"Explorer","description":"Walk 100 blocks","targetProgress":100},{"id":"builder_100","name":"Architect","description":"Place 100 blocks","targetProgress":100},{"id":"miner_100","name":"Miner","description":"Break 100 blocks","targetProgress":100},{"id":"night_survivor","name":"Night Owl","description":"Survive your first night cycle"}]\ No newline at end of file+[+  {"id":"first_block","name":"Groundbreaker","description":"Break your first block"},+  {"id":"first_place","name":"Builder","description":"Place your first block"},+  {"id":"explorer_100","name":"Explorer","description":"Walk 100 blocks","targetProgress":100},+  {"id":"builder_100","name":"Architect","description":"Place 100 blocks","targetProgress":100},+  {"id":"miner_100","name":"Miner","description":"Break 100 blocks","targetProgress":100},+  {"id":"night_survivor","name":"Night Owl","description":"Survive your first night"},+  {"id":"deep_diver","name":"Deep Diver","description":"Mine down to bedrock depth"},+  {"id":"silver_tongue","name":"Silver Tongue","description":"Smelt your first silver ingot"},+  {"id":"steelworker","name":"Steelworker","description":"Forge steel in a blast furnace"},+  {"id":"alchemist","name":"Alchemist","description":"Amalgamate an adamant ingot"},+  {"id":"blessed","name":"Blessed","description":"Craft a quicksilver blessing"},+  {"id":"fully_armed","name":"Fully Armed","description":"Wear a complete set of diamond or adamant armor"},+  {"id":"nether_bound","name":"Nether Bound","description":"Step through a nether portal"},+  {"id":"the_end","name":"The End","description":"Reach the End"},+  {"id":"dragonslayer","name":"Dragonslayer","description":"Defeat the Ender Dragon"},+  {"id":"withering","name":"Withering","description":"Defeat the Wither"},+  {"id":"beacon_master","name":"Beacon Master","description":"Power a full four-tier beacon"},+  {"id":"sky_bound","name":"Sky Bound","description":"Equip an elytra"},+  {"id":"heart_of_gold","name":"Heart of Gold","description":"Reach the maximum heart count"}+]
games/voxels/src/main/assets/block/netherite_block.png
diff --git a/games/voxels/src/main/assets/block/netherite_block.png b/games/voxels/src/main/assets/block/netherite_block.pngdeleted file mode 100644index 6fb6c9861e..0000000000Binary files a/games/voxels/src/main/assets/block/netherite_block.png and /dev/null 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 79c53085c0..a955529b6c 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@@ -53,9 +53,15 @@ class MainActivity : ComponentActivity() {                 val activity = LocalContext.current as? android.app.Activity                 var invStartTab by remember { mutableStateOf(0) }                 var recipesJson by remember { mutableStateOf("[]") }+                var smeltingJson by remember { mutableStateOf("[]") }+                var smeltJson by remember { mutableStateOf("{}") }+                var containerJson by remember { mutableStateOf("""{"slots":[]}""") }+                var furnaceOpen by remember { mutableStateOf(false) }+                var furnaceIsBlast by remember { mutableStateOf(false) }+                var chestOpen 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() } catch (_: Exception) {} }+                LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); tradesJson = VoxelsNative.getTradesJson(); smeltingJson = VoxelsNative.getSmeltingJson() } catch (_: Exception) {} }                 var achievementsManager by remember { mutableStateOf<VoxelsAchievementsManager?>(null) }                 val newAchievement by (achievementsManager?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -73,6 +79,8 @@ class MainActivity : ComponentActivity() {                             try {                                 inventoryJson = VoxelsNative.getInventoryJson()                                 debugJson = VoxelsNative.getDebugJson()+                                if (furnaceOpen) smeltJson = VoxelsNative.getSmeltJson()+                                if (chestOpen) containerJson = VoxelsNative.getContainerJson()                                 try {                                     healthJson = VoxelsNative.getHealthJson()                                     val hp = org.json.JSONObject(healthJson).optDouble("hp", prevHp.toDouble()).toFloat()@@ -96,6 +104,19 @@ class MainActivity : ComponentActivity() {                                         mgr.onProgressUpdated("miner_100", broken)                                         mgr.onProgressUpdated("explorer_100", walked)                                         if (obj.optBoolean("night", false)) mgr.onAchievementUnlocked("night_survivor")+                                        if (obj.optInt("depth", 128) <= 8) mgr.onAchievementUnlocked("deep_diver")+                                        if (obj.optBoolean("silver", false)) mgr.onAchievementUnlocked("silver_tongue")+                                        if (obj.optBoolean("steel", false)) mgr.onAchievementUnlocked("steelworker")+                                        if (obj.optBoolean("adamant", false)) mgr.onAchievementUnlocked("alchemist")+                                        if (obj.optBoolean("blessing", false)) mgr.onAchievementUnlocked("blessed")+                                        if (obj.optBoolean("fullArmor", false)) mgr.onAchievementUnlocked("fully_armed")+                                        if (obj.optBoolean("nether", false)) mgr.onAchievementUnlocked("nether_bound")+                                        if (obj.optBoolean("end", false)) mgr.onAchievementUnlocked("the_end")+                                        if (obj.optBoolean("dragon", false)) mgr.onAchievementUnlocked("dragonslayer")+                                        if (obj.optBoolean("wither", false)) mgr.onAchievementUnlocked("withering")+                                        if (obj.optInt("beacon", 0) >= 4) mgr.onAchievementUnlocked("beacon_master")+                                        if (obj.optBoolean("elytra", false)) mgr.onAchievementUnlocked("sky_bound")+                                        if (obj.optBoolean("maxHearts", false)) mgr.onAchievementUnlocked("heart_of_gold")                                     }                                 } catch (_: Exception) {}                             } catch (_: Exception) {}@@ -126,16 +147,26 @@ class MainActivity : ComponentActivity() {                             modifier = Modifier.fillMaxSize(),                             onLookRate = { ry, rp -> try { VoxelsNative.onLookInput(ry, rp) } catch (_: Exception) {} },                             onPlace = { off -> try {-                                when (VoxelsNative.placeBlockAt(off.x, off.y)) {+                                val code = VoxelsNative.placeBlockAt(off.x, off.y)+                                when (code) {                                     1 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace()-                                    11, 12, 14 -> { invStartTab = 2; inventoryOpen = true } // crafting table / furnace / blast furnace+                                    11 -> { invStartTab = 2; inventoryOpen = true } // crafting table+                                    12, 14 -> { // furnace / blast furnace+                                        furnaceIsBlast = code == 14+                                        smeltJson = try { VoxelsNative.getSmeltJson() } catch (_: Exception) { "{}" }+                                        furnaceOpen = true+                                    }                                     13 -> { // jukebox: play the held disc (or stop)                                         val inv = try { kotlinx.serialization.json.Json { ignoreUnknownKeys = true }.decodeFromString<com.vayunmathur.games.voxels.ui.InventoryState>(inventoryJson) } catch (_: Exception) { null }                                         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])                                     }                                     20 -> tradeOpen = true // villager-                                    30 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace() // looted a chest+                                    30 -> { // chest+                                        containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }+                                        chestOpen = true+                                        com.vayunmathur.games.voxels.util.SoundFx.playPlace()+                                    }                                     41 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace() // ignited a portal                                 }                             } catch (_: Exception) {} },@@ -232,6 +263,20 @@ class MainActivity : ComponentActivity() {                         TradeOverlay(tradesJson = tradesJson, onClose = { tradeOpen = false })                     } +                    if (furnaceOpen && VoxelsNative.isAvailable) {+                        FurnaceOverlay(+                            smeltingJson = smeltingJson, smeltJson = smeltJson,+                            isBlast = furnaceIsBlast, onClose = { furnaceOpen = false }+                        )+                    }++                    if (chestOpen && VoxelsNative.isAvailable) {+                        ChestOverlay(containerJson = containerJson, inventoryJson = inventoryJson, onClose = {+                            chestOpen = false+                            try { VoxelsNative.closeContainer() } catch (_: Exception) {}+                        })+                    }+                     if (paused) {                         Box(                             Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.ktnew file mode 100644index 0000000000..c59f6e7556--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FurnaceScreen.kt@@ -0,0 +1,285 @@+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++data class SmeltRecipe(+    val inId: Int, val inN: Int, val in2Id: Int, val in2N: Int,+    val outId: Int, val outN: Int, val secs: Float, val blast: Boolean+)++data class SmeltState(val active: Boolean, val recipe: Int, val progress: Float, val fuel: Float)++fun parseSmeltRecipes(json: String): List<SmeltRecipe> = try {+    val arr = org.json.JSONArray(json)+    (0 until arr.length()).map { i ->+        val o = arr.getJSONObject(i)+        SmeltRecipe(+            o.getInt("in"), o.getInt("inN"), o.optInt("in2", 0), o.optInt("in2N", 0),+            o.getInt("out"), o.getInt("outN"), o.getDouble("secs").toFloat(), o.optBoolean("blast", false)+        )+    }+} catch (_: Exception) { emptyList() }++fun parseSmeltState(json: String): SmeltState = try {+    val o = org.json.JSONObject(json)+    SmeltState(+        o.optBoolean("active", false), o.optInt("recipe", 0),+        o.optDouble("progress", 0.0).toFloat(), o.optDouble("fuel", 0.0).toFloat()+    )+} catch (_: Exception) { SmeltState(false, 0, 0f, 0f) }++/**+ * Furnace screen. A Blast Furnace additionally unlocks the alloy recipes, which are hidden on a+ * plain furnace so the upgrade is visible rather than just implied.+ */+@Composable+fun FurnaceOverlay(smeltingJson: String, smeltJson: String, isBlast: Boolean, onClose: () -> Unit) {+    val all = remember(smeltingJson) { parseSmeltRecipes(smeltingJson) }+    // Keep the original indices: startSmelt() addresses recipes by their position in the table.+    val visible = remember(all, isBlast) { all.withIndex().filter { isBlast || !it.value.blast } }+    val state = parseSmeltState(smeltJson)+    var sel by remember { mutableStateOf(visible.firstOrNull()?.index ?: 0) }+    val recipe = all.getOrNull(sel)++    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(if (isBlast) R.string.blast_furnace else R.string.furnace),+                    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) }+            }++            Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) {+                Column(+                    Modifier.width(190.dp).fillMaxHeight().verticalScroll(rememberScrollState()),+                    verticalArrangement = Arrangement.spacedBy(4.dp)+                ) {+                    visible.forEach { (idx, rec) ->+                        val icon = rememberBlockIcon(rec.outId)+                        Row(+                            Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))+                                .background(if (idx == sel) Color(0xFF6B4A2A) else Color.White.copy(alpha = 0.08f))+                                .clickable { sel = idx }.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[rec.outId] ?: "", color = Color.White.copy(0.95f), fontSize = 12.sp)+                        }+                    }+                }++                Column(+                    Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally,+                    verticalArrangement = Arrangement.spacedBy(14.dp)+                ) {+                    Spacer(Modifier.height(6.dp))+                    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+                        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+                            SmeltCell(recipe?.inId ?: 0, recipe?.inN ?: 0)+                            if (recipe != null && recipe.in2Id != 0) SmeltCell(recipe.in2Id, recipe.in2N)+                        }+                        Text("→", color = Color.White.copy(0.8f), fontSize = 24.sp)+                        SmeltCell(recipe?.outId ?: 0, recipe?.outN ?: 0)+                    }++                    val running = state.active && state.recipe == sel+                    // The engine refuses to switch a job mid-burn, so say so rather than offering a+                    // button that would do nothing.+                    val busyElsewhere = state.active && state.recipe != sel+                    MeterBar(stringResource(R.string.smelting_progress), if (running) state.progress else 0f, Color(0xFFE08A3C))+                    MeterBar(stringResource(R.string.fuel), if (state.active) state.fuel else 0f, Color(0xFF3C9AE0))+                    Text(+                        stringResource(if (busyElsewhere) R.string.furnace_busy else R.string.furnace_fuel_hint),+                        color = Color.White.copy(0.55f), fontSize = 11.sp+                    )++                    Box(+                        Modifier.clip(RoundedCornerShape(8.dp))+                            .background(+                                when {+                                    running -> Color(0xFF7A3A3A)+                                    busyElsewhere -> Color.White.copy(0.10f)+                                    else -> Color(0xFF3A6B3A)+                                }+                            )+                            .clickable(enabled = !busyElsewhere) {+                                try {+                                    if (running) VoxelsNative.stopSmelt() else VoxelsNative.startSmelt(sel, isBlast)+                                } catch (_: Exception) {}+                            }+                            .padding(horizontal = 26.dp, vertical = 9.dp)+                    ) {+                        Text(+                            stringResource(+                                when {+                                    running -> R.string.stop+                                    busyElsewhere -> R.string.busy+                                    else -> R.string.smelt+                                }+                            ),+                            color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.SemiBold+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun SmeltCell(id: Int, count: Int) {+    val icon = if (id != 0) rememberBlockIcon(id) else null+    Box(+        Modifier.size(50.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.4f))+            .border(1.dp, Color.White.copy(alpha = 0.15f), RoundedCornerShape(6.dp)),+        contentAlignment = Alignment.Center+    ) {+        if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(34.dp), filterQuality = FilterQuality.None)+        if (count > 1) Box(Modifier.align(Alignment.BottomEnd).padding(1.dp)) { Text("$count", color = Color.White, fontSize = 11.sp) }+    }+}++@Composable+private fun MeterBar(label: String, frac: Float, color: Color) {+    Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {+        Text(label, color = Color.White.copy(0.6f), fontSize = 11.sp)+        Box(Modifier.width(190.dp).height(8.dp).clip(RoundedCornerShape(4.dp)).background(Color.Black.copy(0.55f))) {+            Box(Modifier.fillMaxWidth(frac.coerceIn(0f, 1f)).fillMaxHeight().background(color))+        }+    }+}++/**+ * Chest screen: tap a chest slot to take the stack, tap an inventory slot to store it.+ */+@Composable+fun ChestOverlay(containerJson: String, inventoryJson: String, onClose: () -> Unit) {+    val chest = remember(containerJson) {+        try {+            val arr = org.json.JSONObject(containerJson).getJSONArray("slots")+            (0 until arr.length()).map { i ->+                val o = arr.getJSONObject(i)+                InvSlot(o.getInt("id"), o.getInt("count"))+            }+        } catch (_: Exception) { emptyList() }+    }+    val inv = remember(inventoryJson) {+        try {+            kotlinx.serialization.json.Json { ignoreUnknownKeys = true }+                .decodeFromString<InventoryState>(inventoryJson)+        } catch (_: Exception) { InventoryState() }+    }++    Box(+        Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))+            .pointerInput(Unit) { detectTapGestures { onClose() } }+    ) {+        Column(+            Modifier.align(Alignment.Center).fillMaxWidth(0.88f)+                .clip(RoundedCornerShape(14.dp)).background(Color(0xF01A1E1A))+                .pointerInput(Unit) { detectTapGestures { } }+                .padding(14.dp),+            verticalArrangement = Arrangement.spacedBy(8.dp),+            horizontalAlignment = Alignment.CenterHorizontally+        ) {+            Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                Text(stringResource(R.string.chest), 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) }+            }+            Text(stringResource(R.string.chest_tap_hint), color = Color.White.copy(0.55f), fontSize = 11.sp)++            for (row in 0 until 3) {+                Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+                    for (col in 0 until 9) {+                        val i = row * 9 + col+                        TapSlot(chest.getOrNull(i) ?: InvSlot(0, 0)) {+                            try { VoxelsNative.containerTake(i) } catch (_: Exception) {}+                        }+                    }+                }+            }+            Spacer(Modifier.height(8.dp))+            Text(stringResource(R.string.inventory), color = Color.White.copy(0.6f), fontSize = 12.sp)+            for (row in 0 until 3) {+                Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+                    for (col in 0 until 9) {+                        val i = 9 + row * 9 + col+                        TapSlot(inv.slots.getOrNull(i) ?: InvSlot(0, 0)) {+                            try { VoxelsNative.containerPut(i) } catch (_: Exception) {}+                        }+                    }+                }+            }+            Spacer(Modifier.height(6.dp))+            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+                for (col in 0 until 9) {+                    TapSlot(inv.slots.getOrNull(col) ?: InvSlot(0, 0)) {+                        try { VoxelsNative.containerPut(col) } catch (_: Exception) {}+                    }+                }+            }+        }+    }+}++@Composable+private fun TapSlot(slot: InvSlot, onTap: () -> Unit) {+    val icon = rememberBlockIcon(slot.id)+    Box(+        Modifier.size(42.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.45f))+            .border(1.dp, Color.White.copy(alpha = 0.12f), RoundedCornerShape(6.dp))+            .clickable(enabled = slot.id != 0) { onTap() },+        contentAlignment = Alignment.Center+    ) {+        if (slot.id != 0) {+            if (icon != null) Image(bitmap = icon, contentDescription = blockNames[slot.id], modifier = Modifier.size(28.dp), filterQuality = FilterQuality.None)+            else Text(blockNames[slot.id]?.take(2) ?: "", color = Color.White, fontSize = 10.sp)+            if (slot.count > 1 && !isDurabilityItem(slot.id)) {+                Box(Modifier.align(Alignment.BottomEnd)) { Text("${slot.count}", color = Color.White, fontSize = 10.sp) }+            }+            if (isDurabilityItem(slot.id)) DurabilityBar(slot.id, slot.count, Modifier.align(Alignment.BottomCenter).padding(bottom = 2.dp))+        }+    }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.ktindex 85f587e623..66ff2123a0 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt@@ -60,11 +60,11 @@ fun InventoryOverlay(inventoryJson: String, recipesJson: String, onClose: () ->         ) {             // Left tabs (top→bottom: Crafting, Outfit, Inventory).             Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {-                TabButton("Crafting", leftTab == 2) { leftTab = 2 }-                TabButton("Outfit", leftTab == 1) { leftTab = 1 }-                TabButton("Inventory", leftTab == 0) { leftTab = 0 }+                TabButton(stringResource(R.string.crafting), leftTab == 2) { leftTab = 2 }+                TabButton(stringResource(R.string.outfit), leftTab == 1) { leftTab = 1 }+                TabButton(stringResource(R.string.inventory), leftTab == 0) { leftTab = 0 }                 Spacer(Modifier.weight(1f))-                TabButton("Close", false) { onClose() }+                TabButton(stringResource(R.string.close), false) { onClose() }             }              // Center content.
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 8103e2b08e..a1a8d09dca 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@@ -24,7 +24,8 @@ object VoxelsNative {     external fun setSneak(on: Boolean)     external fun toggleFly()     external fun breakBlockAt(x: Float, y: Float): Boolean-    // 0 = nothing, 1 = placed, 11 = open crafting, 12 = open furnace+    // 0 = nothing, 1 = placed, 11 crafting table, 12 furnace, 13 jukebox, 14 blast furnace,+    // 20 villager trade, 30 chest opened, 41 portal lit.     external fun placeBlockAt(x: Float, y: Float): Int     external fun selectSlot(slot: Int)     external fun moveItem(from: Int, to: Int)@@ -37,4 +38,14 @@ object VoxelsNative {     external fun getDebugJson(): String     external fun getStatsJson(): String     external fun getHealthJson(): String+    // Furnace: recipe catalog, live job state, and start/stop.+    external fun getSmeltingJson(): String+    external fun getSmeltJson(): String+    external fun startSmelt(recipe: Int, blast: Boolean): Boolean+    external fun stopSmelt()+    // Chest containers, keyed by the block the player last opened.+    external fun getContainerJson(): String+    external fun containerTake(idx: Int): Boolean+    external fun containerPut(idx: Int): Boolean+    external fun closeContainer() }
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 a30351a141..a24b507677 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -24,4 +24,19 @@     <string name="seed_2">Seed: %1$s  •  %2$s</string>     <string name="estus">Estus ×%1$s</string>     <string name="down">Down</string>+    <string name="furnace">Furnace</string>+    <string name="blast_furnace">Blast Furnace</string>+    <string name="smelt">Smelt</string>+    <string name="stop">Stop</string>+    <string name="close">Close</string>+    <string name="inventory">Inventory</string>+    <string name="crafting">Crafting</string>+    <string name="outfit">Outfit</string>+    <string name="chest">Chest</string>+    <string name="smelting_progress">Smelting</string>+    <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="busy">Busy</string>+    <string name="chest_tap_hint">Tap a chest slot to take it, an inventory slot to store it.</string> </resources>
games/voxels/src/main/rust/src/container.rs
diff --git a/games/voxels/src/main/rust/src/container.rs b/games/voxels/src/main/rust/src/container.rsnew file mode 100644index 0000000000..8416503ed2--- /dev/null+++ b/games/voxels/src/main/rust/src/container.rs@@ -0,0 +1,206 @@+// Block-position-keyed storage for chests. Terrain-generated chests fill themselves with loot the+// first time they're opened; chests the player places start empty (they're registered at place time+// so the two cases stay distinguishable). Contents live outside the chunk format — chunks store a+// flat byte per block — so they get their own JSON file next to player.json.++use crate::inventory::InvSlot;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};++pub const CONTAINER_SLOTS: usize = 27;++// (dimension, x, y, z)+pub type ContainerKey = (u8, i32, i32, i32);++#[derive(Default)]+pub struct Containers {+    map: HashMap<ContainerKey, Vec<InvSlot>>,+}++#[derive(Serialize, Deserialize)]+struct ContainerEntry { dim: u8, x: i32, y: i32, z: i32, slots: Vec<InvSlot> }++impl Containers {+    pub fn get(&self, key: ContainerKey) -> Option<&Vec<InvSlot>> { self.map.get(&key) }+    pub fn contains(&self, key: ContainerKey) -> bool { self.map.contains_key(&key) }+    // A freshly placed chest is empty by definition: overwrite rather than inherit any entry that+    // outlived the block that owned it.+    pub fn insert_empty(&mut self, key: ContainerKey) {+        self.map.insert(key, vec![InvSlot::default(); CONTAINER_SLOTS]);+    }+    pub fn insert(&mut self, key: ContainerKey, slots: Vec<InvSlot>) { self.map.insert(key, slots); }+    pub fn remove(&mut self, key: ContainerKey) -> Option<Vec<InvSlot>> { self.map.remove(&key) }+    pub fn slot_mut(&mut self, key: ContainerKey, idx: usize) -> Option<&mut InvSlot> {+        self.map.get_mut(&key)?.get_mut(idx)+    }+    // Merge a stack into the container, returning what wouldn't fit.+    pub fn add(&mut self, key: ContainerKey, id: u8, mut count: i32) -> i32 {+        let Some(slots) = self.map.get_mut(&key) else { return count; };+        if crate::item::has_durability(id) {+            // Tools and armor never stack: they need a slot of their own to keep their durability.+            if let Some(s) = slots.iter_mut().find(|s| s.id == 0) { *s = InvSlot { id, count }; return 0; }+            return count;+        }+        for s in slots.iter_mut() {+            if count <= 0 { break; }+            if s.id == id && s.count < crate::inventory::STACK {+                let mv = count.min(crate::inventory::STACK - s.count);+                s.count += mv; count -= mv;+            }+        }+        for s in slots.iter_mut() {+            if count <= 0 { break; }+            if s.id == 0 {+                let mv = count.min(crate::inventory::STACK);+                *s = InvSlot { id, count: mv }; count -= mv;+            }+        }+        count+    }++    pub fn to_json(&self, key: ContainerKey) -> String {+        let empty = vec![InvSlot::default(); CONTAINER_SLOTS];+        let slots = self.map.get(&key).unwrap_or(&empty);+        serde_json::json!({ "slots": slots }).to_string()+    }++    pub fn save(&self, base: &str) -> std::io::Result<()> {+        let entries: Vec<ContainerEntry> = self.map.iter()+            .map(|(&(dim, x, y, z), slots)| ContainerEntry { dim, x, y, z, slots: slots.clone() })+            .collect();+        // Bail out rather than renaming an empty file over a good save and wiping every chest.+        let json = serde_json::to_string(&entries)+            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;+        let path = container_file(base);+        if let Some(p) = path.parent() { fs::create_dir_all(p)?; }+        let tmp = path.with_extension("tmp");+        fs::write(&tmp, json)?;+        fs::rename(tmp, path)?;+        Ok(())+    }++    pub fn load(base: &str) -> Self {+        let Ok(s) = fs::read_to_string(container_file(base)) else { return Self::default(); };+        let Ok(entries): Result<Vec<ContainerEntry>, _> = serde_json::from_str(&s) else { return Self::default(); };+        let mut map = HashMap::new();+        for mut e in entries {+            e.slots.resize(CONTAINER_SLOTS, InvSlot::default());+            map.insert((e.dim, e.x, e.y, e.z), e.slots);+        }+        Self { map }+    }+}++fn container_file(base: &str) -> PathBuf {+    Path::new(base).join("voxels").join("worlds").join("default").join("containers.json")+}++// Deterministic loot for a world-generated chest, from its position. The End's chests hold the+// endgame reward pool; everywhere else draws from the general pool.+pub fn roll_loot(x: i32, y: i32, z: i32, dim: u8) -> Vec<InvSlot> {+    let mut r = ((x as u64).wrapping_mul(73856093) ^ (y as u64).wrapping_mul(19349663) ^ (z as u64).wrapping_mul(83492791)) | 1;+    let next = |r: &mut u64| { *r ^= *r << 13; *r ^= *r >> 7; *r ^= *r << 17; *r };+    // (item id, max stack from this chest).+    let end_pool: [(u8, i32); 9] = [(188, 1), (176, 1), (175, 1), (170, 1), (129, 1), (155, 3), (156, 4), (133, 2), (24, 2)];+    let nether_pool: [(u8, i32); 7] = [(192, 6), (194, 2), (195, 2), (157, 8), (154, 4), (133, 1), (138, 3)];+    let over_pool: [(u8, i32); 11] = [(157, 8), (154, 4), (155, 1), (156, 2), (131, 4), (133, 1), (168, 1), (128, 1), (138, 3), (137, 2), (193, 2)];+    let pool: &[(u8, i32)] = match dim { 2 => &end_pool, 1 => &nether_pool, _ => &over_pool };++    let mut slots = vec![InvSlot::default(); CONTAINER_SLOTS];+    let n = 3 + (next(&mut r) % 4) as usize; // 3..6 stacks+    for _ in 0..n {+        let (id, maxc) = pool[(next(&mut r) as usize) % pool.len()];+        let count = if crate::item::has_durability(id) {+            crate::item::max_durability(id)+        } else {+            1 + (next(&mut r) % maxc as u64) as i32+        };+        // Scatter the stacks over the grid rather than packing them into the first rows.+        let mut idx = (next(&mut r) as usize) % CONTAINER_SLOTS;+        for _ in 0..CONTAINER_SLOTS {+            if slots[idx].id == 0 { break; }+            idx = (idx + 1) % CONTAINER_SLOTS;+        }+        if slots[idx].id == 0 { slots[idx] = InvSlot { id, count }; }+    }+    slots+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::inventory::{Inventory, InvSlot, STACK};++    #[test]+    fn generated_chests_have_loot_and_player_chests_do_not() {+        let mut c = Containers::default();+        let key = (0u8, 12, 40, -7);+        c.insert(key, roll_loot(12, 40, -7, 0));+        let filled = c.get(key).unwrap().iter().filter(|s| s.id != 0).count();+        assert!((3..=6).contains(&filled), "expected 3..6 loot stacks, got {filled}");++        let placed = (0u8, 1, 2, 3);+        c.insert_empty(placed);+        assert!(c.get(placed).unwrap().iter().all(|s| s.id == 0));+    }++    // If a chest is destroyed without its entry being cleaned up, placing a new chest on the same+    // block must not inherit the old loot — that would be a repeatable duplication.+    #[test]+    fn a_placed_chest_never_inherits_a_stale_entry() {+        let mut c = Containers::default();+        let key = (0u8, 4, 61, 4);+        c.insert(key, roll_loot(4, 61, 4, 0));+        assert!(c.get(key).unwrap().iter().any(|s| s.id != 0));++        c.insert_empty(key);+        assert!(c.get(key).unwrap().iter().all(|s| s.id == 0), "a new chest must start empty");+    }++    #[test]+    fn loot_is_deterministic_per_position() {+        let a = roll_loot(5, 30, 9, 0);+        let b = roll_loot(5, 30, 9, 0);+        let other = roll_loot(6, 30, 9, 0);+        assert_eq!(a.iter().map(|s| (s.id, s.count)).collect::<Vec<_>>(),+                   b.iter().map(|s| (s.id, s.count)).collect::<Vec<_>>());+        assert_ne!(a.iter().map(|s| s.id).collect::<Vec<_>>(),+                   other.iter().map(|s| s.id).collect::<Vec<_>>());+    }++    #[test]+    fn add_returns_the_overflow_when_full() {+        let mut c = Containers::default();+        let key = (0u8, 0, 0, 0);+        c.insert_empty(key);+        // Fill every slot with stone, then try to add one more.+        let left = c.add(key, 1, STACK * CONTAINER_SLOTS as i32);+        assert_eq!(left, 0);+        assert_eq!(c.add(key, 1, 5), 5, "a full chest must reject the whole stack");+    }++    // Taking from a chest into a full inventory must leave the remainder in the chest rather than+    // deleting it.+    #[test]+    fn take_from_leaves_the_remainder_when_inventory_is_full() {+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot { id: 2, count: STACK }; } // all dirt, no room+        let mut slot = InvSlot { id: 155, count: 7 }; // 7 diamonds in the chest+        inv.take_from(&mut slot);+        assert_eq!(slot.count, 7, "nothing fit, so nothing should have left the chest");+        assert_eq!(slot.id, 155);+    }++    #[test]+    fn take_from_moves_what_fits() {+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot { id: 2, count: STACK }; }+        inv.slots[5] = InvSlot { id: 155, count: STACK - 3 }; // room for exactly 3 diamonds+        let mut slot = InvSlot { id: 155, count: 10 };+        inv.take_from(&mut slot);+        assert_eq!(slot.count, 7, "only 3 of 10 should have moved");+        assert_eq!(inv.slots[5].count, STACK);+    }+}
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 5ad295e386..c860efd143 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -45,6 +45,25 @@ pub struct EngineState {     // after the player has actually lived through a full night.     pub was_night: bool,     pub night_survived: bool,+    pub containers: crate::container::Containers,+    pub open_chest: Option<crate::container::ContainerKey>,+    pub smelter: Smelter,+    // Milestone tracking for achievements.+    pub best_beacon: i32,+    pub deepest_y: i32,+}++// One furnace job at a time, owned by the world rather than by a specific furnace block: the player+// lights a recipe and it keeps burning while they walk away or close the menu.+#[derive(Default)]+pub struct Smelter {+    pub recipe: usize,+    pub active: bool,+    pub progress: f32,+    pub fuel_left: f32,+    pub fuel_max: f32,+    // Whether the furnace the player last opened was a Blast Furnace (gates the alloy recipes).+    pub blast: bool, }  // The world clock is offset by 60s so a fresh world opens at midday (day_t = 0.5 -> sun overhead).@@ -155,6 +174,11 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool {         nether_wither_dead: progress.nether_wither_dead,         was_night: false,         night_survived: player_save.as_ref().map(|ps| ps.stats.night_seen).unwrap_or(false),+        containers: crate::container::Containers::load(&files_dir),+        open_chest: None,+        smelter: Smelter::default(),+        best_beacon: progress.best_beacon,+        deepest_y: if had_save { progress.deepest_y } else { py as i32 },     });     INIT_DONE.store(true, Ordering::SeqCst);     true@@ -207,9 +231,12 @@ pub fn destroy_engine() {                 end_dragon_dead: state.end_dragon_dead,                 nether_wither_dead: state.nether_wither_dead,                 world_secs: state.start_time.elapsed().as_secs_f32(),+                best_beacon: state.best_beacon,+                deepest_y: state.deepest_y,             },         };         let _ = crate::world::save::save_player(&state.save_dir, &ps);+        let _ = state.containers.save(&state.save_dir);         state.chunks.save_all();         // Persist the stashed dimensions too (each writes to its own save subdir).         for m in state.stored.iter().flatten() { m.save_all(); }@@ -321,6 +348,10 @@ pub fn tick_and_render() {         if state.was_night && !night_now && !state.player.dead && state.dim == 0 { state.night_survived = true; }         state.was_night = night_now; +        tick_smelter(state, dt);+        // Overworld-only depth record, so the Nether's low ceiling doesn't hand out the mining badge.+        if state.dim == 0 { state.deepest_y = state.deepest_y.min(state.player.pos.y as i32); }+         // Elytra equipped in the chest slot enables gliding.         state.player.elytra = state.inventory.armor[1].id == 188;         state.player.tick(dt, &input_mut, &state.chunks);@@ -395,6 +426,7 @@ pub fn tick_and_render() {             }}}             if let Some((tier, _)) = best {                 use crate::item::Effect::*;+                state.best_beacon = state.best_beacon.max(tier);                 let e = &mut state.player;                 e.add_effect(Speed, 6.0, 0);                 if tier >= 2 { e.add_effect(Haste, 6.0, 0); }@@ -592,6 +624,7 @@ static DEBUG_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static INV_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static STATS_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static HEALTH_CACHE: OnceLock<Mutex<String>> = OnceLock::new();+static SMELT_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); fn cref(c: &'static OnceLock<Mutex<String>>, default: &str) -> &'static Mutex<String> { c.get_or_init(|| Mutex::new(default.to_string())) }  // Called from the render tick (holds the engine lock) to refresh the UI caches.@@ -616,9 +649,21 @@ fn publish_ui(state: &EngineState) {             format!("sh{:.1} main{:.1} bloom{:.1} comp{:.1}", p[0], p[1], p[2], p[3])         }).unwrap_or_default(),     }).to_string();+    let has = |id: u8| state.inventory.slots.iter().any(|s| s.id == id && s.count > 0);+    let armor_at_least = |lo: u8, hi: u8| state.inventory.armor.iter().all(|s| s.id >= lo && s.id <= hi);     let stats = serde_json::json!({         "placed": state.inventory.placed, "broken": state.inventory.broken,         "walked": state.player.walk_dist as i32, "night": state.night_survived,+        "nether": state.dim_visited[1], "end": state.dim_visited[2],+        "dragon": state.end_dragon_dead, "wither": state.nether_wither_dead,+        "beacon": state.best_beacon,+        "elytra": state.player.elytra,+        "maxHearts": state.player.max_health >= crate::player::CAP_MAX_HEALTH,+        // Full diamond (175..178) or full adamant (199..202) counts as end-tier armor.+        "fullArmor": armor_at_least(175, 178) || armor_at_least(199, 202),+        "silver": has(193), "steel": has(195), "adamant": has(196),+        "blessing": has(160) || has(161) || has(162),+        "depth": state.deepest_y,     }).to_string();     let inv = state.inventory.to_json();     let effects: Vec<_> = state.player.effects.iter().map(|e| serde_json::json!({"k": e.kind.key(), "amp": e.amp, "t": e.secs.ceil() as i32})).collect();@@ -635,12 +680,22 @@ fn publish_ui(state: &EngineState) {     if let Ok(mut c) = cref(&STATS_CACHE, "{}").lock() { *c = stats; }     if let Ok(mut c) = cref(&INV_CACHE, r#"{"selected":0,"slots":[]}"#).lock() { *c = inv; }     if let Ok(mut c) = cref(&HEALTH_CACHE, "{}").lock() { *c = health; }+    let sm = &state.smelter;+    let secs = crate::inventory::SMELTING.get(sm.recipe).map(|r| r.secs).unwrap_or(1.0);+    let smelt = serde_json::json!({+        "active": sm.active, "recipe": sm.recipe,+        "progress": (sm.progress / secs.max(0.001)).clamp(0.0, 1.0),+        "fuel": if sm.fuel_max > 0.0 { (sm.fuel_left / sm.fuel_max).clamp(0.0, 1.0) } else { 0.0 },+        "blast": sm.blast,+    }).to_string();+    if let Ok(mut c) = cref(&SMELT_CACHE, "{}").lock() { *c = smelt; } }  pub fn get_debug_json() -> String { cref(&DEBUG_CACHE, r#"{"error":"no engine"}"#).lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn get_inventory_json() -> String { cref(&INV_CACHE, r#"{"selected":0,"slots":[]}"#).lock().map(|c| c.clone()).unwrap_or_else(|_| r#"{"selected":0,"slots":[]}"#.into()) } pub fn get_stats_json() -> String { cref(&STATS_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn get_health_json() -> String { cref(&HEALTH_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) }+pub fn get_smelt_json() -> String { cref(&SMELT_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) }  pub fn inventory_move(from: usize, to: usize) { with_engine(|s| s.inventory.move_item(from, to)); } pub fn inventory_give(id: u8) { with_engine(|s| s.inventory.give(id)); }@@ -808,25 +863,14 @@ fn light_portal(state: &mut EngineState, x: i32, y: i32, z: i32) -> bool {     false } -// Loot a chest deterministically from its position (each chest is consumed after one open).-fn loot_chest(state: &mut EngineState, x: i32, y: i32, z: i32) {-    let mut r = ((x as u64).wrapping_mul(73856093) ^ (y as u64).wrapping_mul(19349663) ^ (z as u64).wrapping_mul(83492791)) | 1;-    let mut next = |r: &mut u64| { *r ^= *r << 13; *r ^= *r >> 7; *r ^= *r << 17; *r };-    // (item id, max stack from this chest). The End's chests (dim 2) hold the endgame reward pool:-    // an elytra, diamond gear, a heart container and gems.-    let end_pool: [(u8, i32); 9] = [(188, 1), (176, 1), (175, 1), (170, 1), (129, 1), (155, 3), (156, 4), (133, 2), (24, 2)];-    let over_pool: [(u8, i32); 10] = [(157, 8), (154, 4), (155, 1), (156, 2), (131, 4), (133, 1), (168, 1), (128, 1), (138, 3), (137, 2)];-    let pool: &[(u8, i32)] = if state.dim == 2 { &end_pool } else { &over_pool };-    let n = 2 + (next(&mut r) % 3) as usize; // 2..4 stacks-    for _ in 0..n {-        let (id, maxc) = pool[(next(&mut r) as usize) % pool.len()];-        if crate::item::has_durability(id) {-            state.inventory.add_item_with_count(id, crate::item::max_durability(id));-        } else {-            let c = 1 + (next(&mut r) % maxc as u64) as i32;-            for _ in 0..c { state.inventory.add_block(id); }-        }+// Make sure a chest at this position has a container, rolling world loot the first time a chest the+// player never placed is opened.+fn ensure_chest(state: &mut EngineState, x: i32, y: i32, z: i32) -> crate::container::ContainerKey {+    let key = (state.dim, x, y, z);+    if !state.containers.contains(key) {+        state.containers.insert(key, crate::container::roll_loot(x, y, z, state.dim));     }+    key }  // Apply damage to the player through equipped armor (each defense point cuts ~4%, capped), wearing@@ -1054,8 +1098,21 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {     if let Some(hit) = block_hit {         let (x, y, z) = hit.pos;         let id = state.chunks.get_block_world(x, y, z);-        if id == 83 { // chest: breaking it loots it (never yields a placeable chest item)-            loot_chest(state, x, y, z);+        if id == 83 { // chest: breaking it spills its contents and returns the chest itself+            let key = ensure_chest(state, x, y, z);+            // Only break the chest once everything actually fit — otherwise the leftovers would be+            // dropped on the floor, which this game has no representation for.+            let mut left = match state.containers.remove(key) {+                Some(slots) => slots,+                None => Vec::new(),+            };+            for s in left.iter_mut() { state.inventory.take_from(s); }+            if left.iter().any(|s| s.id != 0) {+                state.containers.insert(key, left);+                return false;+            }+            state.inventory.add_block(83);+            if state.open_chest == Some(key) { state.open_chest = None; }             state.chunks.set_block_world(x, y, z, 0);             mark_neighbors_dirty(state, x, z);             return true;@@ -1075,6 +1132,101 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {     false } +// Advance the active furnace job: burn fuel, accumulate progress and bank finished batches. Stops+// itself when it runs out of inputs or fuel so the player never silently loses items.+fn tick_smelter(state: &mut EngineState, dt: f32) {+    if !state.smelter.active { return; }+    let Some(recipe) = crate::inventory::SMELTING.get(state.smelter.recipe) else {+        state.smelter.active = false;+        return;+    };+    let stop = |s: &mut Smelter| { s.active = false; s.progress = 0.0; };+    if recipe.blast && !state.smelter.blast { stop(&mut state.smelter); return; }+    if !state.inventory.can_smelt(recipe) { stop(&mut state.smelter); return; }+    // Pause instead of burning fuel when the result would have nowhere to go.+    if !state.inventory.has_room_for(recipe.out, recipe.out_n) { return; }+    if state.smelter.fuel_left <= 0.0 {+        let spare = [recipe.in1, recipe.in2];+        match state.inventory.consume_fuel(&spare) {+            Some(secs) => { state.smelter.fuel_left = secs; state.smelter.fuel_max = secs; }+            None => { stop(&mut state.smelter); return; }+        }+    }+    state.smelter.fuel_left -= dt;+    state.smelter.progress += dt;+    if state.smelter.progress >= recipe.secs {+        state.smelter.progress -= recipe.secs;+        state.inventory.take_smelt_inputs(recipe);+        state.inventory.give_smelt_output(recipe);+        if !state.inventory.can_smelt(recipe) { stop(&mut state.smelter); }+    }+}++// Light a furnace recipe. `blast` reports which kind of furnace the player tapped. A job already in+// flight is left alone: switching would throw away its progress and the fuel already spent on it.+pub fn start_smelt(recipe: usize, blast: bool) -> bool {+    with_engine(|state| {+        let Some(r) = crate::inventory::SMELTING.get(recipe) else { return false; };+        if r.blast && !blast { return false; }+        if state.smelter.active && state.smelter.recipe != recipe { return false; }+        if !state.inventory.can_smelt(r) { return false; }+        state.smelter.blast = blast;+        if state.smelter.recipe != recipe { state.smelter.progress = 0.0; }+        state.smelter.recipe = recipe;+        state.smelter.active = true;+        true+    }).unwrap_or(false)+}+pub fn stop_smelt() { with_engine(|s| { s.smelter.active = false; s.smelter.progress = 0.0; }); }+pub fn get_smelting_json() -> String {+    let items: Vec<_> = crate::inventory::SMELTING.iter()+        .map(|s| serde_json::json!({+            "in": s.in1, "inN": s.n1, "in2": s.in2, "in2N": s.n2,+            "out": s.out, "outN": s.out_n, "secs": s.secs, "blast": s.blast,+        }))+        .collect();+    serde_json::json!(items).to_string()+}++// ---- Chest containers ----+pub fn get_container_json() -> String {+    with_engine_try(|state| match state.open_chest {+        Some(key) => state.containers.to_json(key),+        None => r#"{"slots":[]}"#.to_string(),+    }).unwrap_or_else(|| r#"{"slots":[]}"#.to_string())+}+// Move a chest stack into the player's inventory, leaving behind whatever didn't fit.+pub fn container_take(idx: usize) -> bool {+    with_engine(|state| {+        let Some(key) = state.open_chest else { return false; };+        let Some(slot) = state.containers.slot_mut(key, idx) else { return false; };+        if slot.id == 0 { return false; }+        let mut held = *slot;+        state.inventory.take_from(&mut held);+        let moved = held.count < slot.count || held.id == 0;+        if let Some(slot) = state.containers.slot_mut(key, idx) { *slot = held; }+        moved+    }).unwrap_or(false)+}+// Move a whole player stack into the chest, putting back anything that didn't fit.+pub fn container_put(inv_idx: usize) -> bool {+    with_engine(|state| {+        let Some(key) = state.open_chest else { return false; };+        if inv_idx >= crate::inventory::SLOTS { return false; }+        let s = state.inventory.slots[inv_idx];+        if s.id == 0 { return false; }+        let left = state.containers.add(key, s.id, s.count);+        if left >= s.count { return false; } // chest full, nothing moved+        state.inventory.slots[inv_idx] = if left > 0 {+            crate::inventory::InvSlot { id: s.id, count: left }+        } else {+            crate::inventory::InvSlot::default()+        };+        true+    }).unwrap_or(false)+}+pub fn close_container() { with_engine(|s| s.open_chest = None); }+ // Destroy blocks in a sphere and hurt the player — creeper explosions. fn explode(state: &mut EngineState, center: Vec3, radius: f32) {     let r = radius.ceil() as i32;@@ -1085,6 +1237,15 @@ fn explode(state: &mut EngineState, center: Vec3, radius: f32) {         let (x, y, z) = (cx + dx, cy + dy, cz + dz);         let id = state.chunks.get_block_world(x, y, z);         if id != 0 && id != 13 && Block::from_id(id).is_solid() {+            // A blown-up chest hands what it can to the player; the rest goes with the blast. Leaving+            // the entry behind would let a chest placed here later inherit the old loot.+            if id == 83 {+                let key = (state.dim, x, y, z);+                if let Some(mut slots) = state.containers.remove(key) {+                    for s in slots.iter_mut() { state.inventory.take_from(s); }+                }+                if state.open_chest == Some(key) { state.open_chest = None; }+            }             state.chunks.set_block_world(x, y, z, 0);             cols.push((x, z));         }@@ -1111,6 +1272,8 @@ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {         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;         }@@ -1140,10 +1303,9 @@ pub fn place_block_at(px: f32, py: f32) -> i32 {             if let Some(hit) = block_hit {                 let (x, y, z) = hit.pos;                 let id = state.chunks.get_block_world(x, y, z);-                if id == 83 { // chest: one-time loot, then it's consumed-                    loot_chest(state, x, y, z);-                    state.chunks.set_block_world(x, y, z, 0);-                    mark_neighbors_dirty(state, x, z);+                if id == 83 { // chest: open its container+                    let key = ensure_chest(state, x, y, z);+                    state.open_chest = Some(key);                     return 30;                 }                 // Tap an obsidian frame with flint & steel to ignite a nether portal.
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 41e23bb771..564bc0044a 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -22,9 +22,9 @@ 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). Crafting and smelting both flow through this table-// (the Furnace menu opens the same crafting UI).-pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 56] = [+// 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); 43] = [     (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@@ -34,17 +34,8 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 56] = [     (Block::SpruceLog as u8, 1, 0, 0, Block::SprucePlanks as u8,4),     (Block::Planks as u8,    4, 0, 0, Block::CraftingTable as u8, 1),     (Block::Cobble as u8,    8, 0, 0, Block::Furnace as u8,     1),-    (Block::Sand as u8,      2, 0, 0, Block::Glass as u8,       1),-    (Block::Cobble as u8,    4, 0, 0, Block::Stone as u8,       1),     (Block::Diorite as u8,   4, 0, 0, Block::PolishedDiorite as u8, 4),     (Block::Planks as u8,    2, 0, 0, 159 /*Stick*/,            4),-    (Block::Clay as u8,      4, 0, 0, Block::Brick as u8,       1),-    // Smelting: ore -> material.-    (Block::CoalOre as u8,   1, 0, 0, 157 /*Coal*/,             1),-    (Block::IronOre as u8,   1, 0, 0, 154 /*Iron Ingot*/,       1),-    (Block::DiamondOre as u8,1, 0, 0, 155 /*Diamond*/,          1),-    (Block::EmeraldOre as u8,1, 0, 0, 156 /*Emerald*/,          1),-    (Block::RedstoneOre as u8,1,0, 0, 158 /*Redstone*/,         1),     // Material -> block.     (154, 9, 0, 0, Block::IronBlock as u8,    1),     (155, 9, 0, 0, Block::DiamondBlock as u8, 1),@@ -62,13 +53,6 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 56] = [     (154, 5, 0, 0, 171, 1), (154, 8, 0, 0, 172, 1), (154, 7, 0, 0, 173, 1), (154, 4, 0, 0, 174, 1), // iron     (155, 5, 0, 0, 175, 1), (155, 8, 0, 0, 176, 1), (155, 7, 0, 0, 177, 1), (155, 4, 0, 0, 178, 1), // diamond     // --- Matcha alloy tier ----    // Smelt the three new ores into their raw materials.-    (Block::SilverOre as u8,   1, 0, 0, 193 /*Silver Ingot*/, 1),-    (Block::SulfurOre as u8,   1, 0, 0, 192 /*Sulfur*/,       2),-    (Block::CinnabarOre as u8, 1, 0, 0, 194 /*Quicksilver*/,  1),-    // Iron quenched in sulfur makes steel; steel amalgamated with quicksilver makes adamant.-    (154, 1, 192, 1, 195, 1), // iron ingot + sulfur -> steel ingot-    (195, 4, 194, 2, 196, 1), // steel + quicksilver -> adamant ingot     // Adamant gear: the tier above diamond.     (196, 3, 159, 2, 197, 1), // adamant pickaxe     (196, 2, 159, 1, 198, 1), // adamant sword@@ -85,6 +69,51 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 56] = [     (194, 2, 156, 2, 162, 1), // quicksilver + emerald-> Blessing of the Deep ]; +// Furnace recipes. Unlike crafting these cost fuel and take `secs` of real time, and the ones marked+// `blast` only run in a Blast Furnace — that gate is what makes the steel/adamant line an unlock+// rather than just another recipe.+pub struct Smelt {+    pub in1: u8, pub n1: i32,+    pub in2: u8, pub n2: i32,+    pub out: u8, pub out_n: i32,+    pub secs: f32,+    pub blast: bool,+}+const fn smelt(in1: u8, n1: i32, in2: u8, n2: i32, out: u8, out_n: i32, secs: f32, blast: bool) -> Smelt {+    Smelt { in1, n1, in2, n2, out, out_n, secs, blast }+}+pub const SMELTING: [Smelt; 13] = [+    smelt(Block::CoalOre as u8,     1, 0, 0, 157, 1,  6.0, false), // coal+    smelt(Block::IronOre as u8,     1, 0, 0, 154, 1,  8.0, false), // iron ingot+    smelt(Block::DiamondOre as u8,  1, 0, 0, 155, 1, 10.0, false),+    smelt(Block::EmeraldOre as u8,  1, 0, 0, 156, 1, 10.0, false),+    smelt(Block::RedstoneOre as u8, 1, 0, 0, 158, 1,  6.0, false),+    smelt(Block::SilverOre as u8,   1, 0, 0, 193, 1,  9.0, false), // silver ingot+    smelt(Block::Sand as u8,        2, 0, 0, Block::Glass as u8,  1, 5.0, false),+    smelt(Block::Cobble as u8,      4, 0, 0, Block::Stone as u8,  1, 5.0, false),+    smelt(Block::Clay as u8,        4, 0, 0, Block::Brick as u8,  1, 6.0, false),+    // Blast furnace only: the alloy line.+    smelt(Block::SulfurOre as u8,   1, 0, 0, 192, 2,  5.0, true),  // sulfur+    smelt(Block::CinnabarOre as u8, 1, 0, 0, 194, 1,  7.0, true),  // quicksilver+    smelt(154, 1, 192, 1, 195, 1, 12.0, true),                     // iron + sulfur -> steel+    smelt(195, 4, 194, 2, 196, 1, 20.0, true),                     // steel + quicksilver -> adamant+];++// Seconds of furnace burn a stack item is worth. Anything not listed can't be used as fuel.+pub fn fuel_secs(id: u8) -> f32 {+    match id {+        157 => 80.0,                                        // coal+        84 => 200.0,                                        // a lava block+        192 => 60.0,                                        // sulfur burns hot+        4 | 26 | 29 | 47 | 50 | 51 => 15.0,                 // logs+        10 | 27 | 30 | 49 | 52 => 15.0,                     // planks+        159 => 5.0,                                         // sticks+        _ => 0.0,+    }+}+// Fuels with no use other than burning, tried before anything a player might be saving.+const DEDICATED_FUELS: [u8; 3] = [157, 84, 192];+ // Villager trades: (cost_id, cost_count, give_id, give_count). Emerald = item 156. pub const TRADES: [(u8, i32, u8, i32); 7] = [     (156, 3, 168, 1),  // 3 Emerald -> Iron Sword@@ -122,10 +151,13 @@ impl Inventory {         self.placed += 1;         Some(id)     }-    pub fn add_block(&mut self, id: u8) {-        if id == 0 { return; }-        for slot in self.slots.iter_mut() { if slot.id == id && slot.count < STACK { slot.count += 1; return; } }-        for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = 1; return; } }+    pub fn add_block(&mut self, id: u8) { self.try_add_block(id); }+    // Add one unit, reporting whether it actually fit anywhere.+    pub fn try_add_block(&mut self, id: u8) -> bool {+        if id == 0 { return false; }+        for slot in self.slots.iter_mut() { if slot.id == id && slot.count < STACK { slot.count += 1; return true; } }+        for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = 1; return true; } }+        false     }     pub fn select(&mut self, idx: usize) { if idx < HOTBAR { self.selected = idx; } } @@ -176,8 +208,9 @@ impl Inventory {         true     }     // Place a non-stacking item (tool/armor) into the first empty slot with a given count (durability).-    pub fn add_item_with_count(&mut self, id: u8, count: i32) {-        for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = count; return; } }+    pub fn add_item_with_count(&mut self, id: u8, count: i32) -> bool {+        for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = count; return true; } }+        false     }     pub fn selected_count(&self) -> i32 { if self.selected < HOTBAR { self.slots[self.selected].count } else { 0 } }     // Remove the whole selected stack, returning (id, count). Used to equip armor without losing durability.@@ -211,6 +244,60 @@ impl Inventory {         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 ----+    pub fn can_smelt(&self, s: &Smelt) -> bool {+        self.count_of(s.in1) >= s.n1 && (s.in2 == 0 || self.count_of(s.in2) >= s.n2)+    }+    // Consume one batch of a smelt recipe's inputs and bank its output. Callers must check+    // `can_smelt` first; this is only reached once the furnace has finished a cycle.+    pub fn take_smelt_inputs(&mut self, s: &Smelt) {+        self.remove_count(s.in1, s.n1);+        if s.in2 != 0 { self.remove_count(s.in2, s.n2); }+    }+    pub fn give_smelt_output(&mut self, s: &Smelt) {+        for _ in 0..s.out_n { self.add_block(s.out); }+    }+    // Whether `n` of `id` would actually fit. Used to pause a furnace rather than smelt into a full+    // inventory and drop the result on the floor.+    pub fn has_room_for(&self, id: u8, n: i32) -> bool {+        if crate::item::has_durability(id) { return self.slots.iter().any(|s| s.id == 0); }+        let mut need = n;+        for s in self.slots.iter() {+            if s.id == 0 { need -= STACK; } else if s.id == id { need -= STACK - s.count; }+            if need <= 0 { return true; }+        }+        need <= 0+    }+    // Burn one fuel item, returning how many seconds of heat it provides. `spare` lists ids the+    // active recipe needs as ingredients so the furnace never eats its own input (sulfur is both a+    // fuel and the second half of the steel recipe). Dedicated fuels are preferred over logs and+    // planks so a smelt doesn't quietly consume the player's building stock.+    pub fn consume_fuel(&mut self, spare: &[u8]) -> Option<f32> {+        let usable = |s: &InvSlot| s.count > 0 && fuel_secs(s.id) > 0.0 && !spare.contains(&s.id);+        let idx = self.slots.iter().position(|s| usable(s) && DEDICATED_FUELS.contains(&s.id))+            .or_else(|| self.slots.iter().position(usable))?;+        let secs = fuel_secs(self.slots[idx].id);+        self.slots[idx].count -= 1;+        if self.slots[idx].count <= 0 { self.slots[idx] = InvSlot::default(); }+        Some(secs)+    }++    // ---- Containers ----+    // Pull a stack out of a container slot. Whatever doesn't fit stays in `slot`, so a full+    // inventory can never silently void a chest.+    pub fn take_from(&mut self, slot: &mut InvSlot) {+        if slot.id == 0 || slot.count <= 0 { return; }+        if crate::item::has_durability(slot.id) {+            if self.add_item_with_count(slot.id, slot.count) { *slot = InvSlot::default(); }+            return;+        }+        while slot.count > 0 {+            if !self.try_add_block(slot.id) { return; }+            slot.count -= 1;+        }+        *slot = InvSlot::default();+    }     // Wear down each equipped piece by 1 when the player is hurt.     pub fn damage_armor(&mut self) {         for s in self.armor.iter_mut() { if s.id != 0 { s.count -= 1; if s.count <= 0 { *s = InvSlot::default(); } } }@@ -233,3 +320,111 @@ mod serde_slots {         Ok(out)     } }++#[cfg(test)]+mod tests {+    use super::*;++    // Every crafting and smelting output must have a sane recipe: no zero ids, no free lunches.+    #[test]+    fn recipe_tables_are_well_formed() {+        for (i, &(in1, n1, in2, n2, out, out_n)) in RECIPES.iter().enumerate() {+            assert!(in1 != 0 && n1 > 0, "recipe {i} has no first ingredient");+            assert!(out != 0 && out_n > 0, "recipe {i} has no output");+            assert!(in2 != 0 || n2 == 0, "recipe {i} has a count for a missing second ingredient");+            assert!(in2 == 0 || n2 > 0, "recipe {i} has a second ingredient with no count");+        }+        for (i, s) in SMELTING.iter().enumerate() {+            assert!(s.in1 != 0 && s.n1 > 0, "smelt {i} has no input");+            assert!(s.out != 0 && s.out_n > 0, "smelt {i} has no output");+            assert!(s.secs > 0.0, "smelt {i} would finish instantly");+        }+    }++    // The alloy line is the Matcha progression gate: it must stay blast-furnace only, and the+    // three Blessings must remain craftable so they aren't creative-only content again.+    #[test]+    fn alloy_line_is_gated_and_blessings_are_craftable() {+        let steel = SMELTING.iter().find(|s| s.out == 195).expect("steel must be smeltable");+        let adamant = SMELTING.iter().find(|s| s.out == 196).expect("adamant must be smeltable");+        assert!(steel.blast && adamant.blast, "the alloy line must require a blast furnace");+        for blessing in [160u8, 161, 162] {+            assert!(RECIPES.iter().any(|r| r.4 == blessing), "blessing {blessing} has no recipe");+        }+    }++    #[test]+    fn smelting_consumes_inputs_and_fuel() {+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot::default(); }+        inv.slots[0] = InvSlot { id: 19, count: 3 };  // 3 iron ore+        inv.slots[1] = InvSlot { id: 157, count: 1 }; // 1 coal++        let recipe = SMELTING.iter().find(|s| s.out == 154).unwrap();+        assert!(inv.can_smelt(recipe));+        assert_eq!(inv.consume_fuel(&[recipe.in1, recipe.in2]), Some(fuel_secs(157)));+        assert_eq!(inv.count_of(157), 0, "the coal should be burnt");++        inv.take_smelt_inputs(recipe);+        inv.give_smelt_output(recipe);+        assert_eq!(inv.count_of(19), 2, "one ore should be consumed");+        assert_eq!(inv.count_of(154), 1, "one ingot should be produced");++        // With no fuel left the furnace can't run again.+        assert_eq!(inv.consume_fuel(&[recipe.in1, recipe.in2]), None);+    }++    // Sulfur is both a fuel and the second half of the steel recipe. Burning it would consume the+    // input and leave the player with nothing.+    #[test]+    fn a_recipe_never_burns_its_own_ingredients() {+        let steel = SMELTING.iter().find(|s| s.out == 195).unwrap();+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot::default(); }+        inv.slots[0] = InvSlot { id: 154, count: 1 };  // iron ingot+        inv.slots[1] = InvSlot { id: 192, count: 1 };  // the only sulfur, also a valid fuel++        assert!(inv.can_smelt(steel));+        assert_eq!(inv.consume_fuel(&[steel.in1, steel.in2]), None, "the sulfur input must be spared");+        assert_eq!(inv.count_of(192), 1);+        assert!(inv.can_smelt(steel), "the recipe must still be runnable");+    }++    // Coal exists to be burnt; planks and logs are building material, so reach for coal first.+    #[test]+    fn dedicated_fuel_is_burnt_before_building_material() {+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot::default(); }+        inv.slots[0] = InvSlot { id: 10, count: 4 };   // planks, earlier in the inventory+        inv.slots[5] = InvSlot { id: 157, count: 2 };  // coal++        assert_eq!(inv.consume_fuel(&[]), Some(fuel_secs(157)));+        assert_eq!(inv.count_of(10), 4, "the planks should be untouched");+        assert_eq!(inv.count_of(157), 1);+    }++    // A full inventory must not let a furnace eat its inputs and throw the result away.+    #[test]+    fn a_full_inventory_has_no_room() {+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot { id: 2, count: STACK }; }+        assert!(!inv.has_room_for(154, 1), "no free slot and no matching stack");+        assert!(!inv.has_room_for(2, 1), "every dirt stack is already full");++        inv.slots[3] = InvSlot { id: 154, count: STACK - 2 };+        assert!(inv.has_room_for(154, 2));+        assert!(!inv.has_room_for(154, 3), "only 2 of 3 would fit");++        inv.slots[4] = InvSlot::default();+        assert!(inv.has_room_for(154, 3));+        assert!(inv.has_room_for(169, 1), "an empty slot can hold a tool");+    }++    #[test]+    fn only_listed_items_burn() {+        assert!(fuel_secs(157) > 0.0);   // coal+        assert!(fuel_secs(10) > 0.0);    // planks+        assert_eq!(fuel_secs(155), 0.0); // diamonds are not firewood+        assert_eq!(fuel_secs(0), 0.0);+    }+}
games/voxels/src/main/rust/src/item.rs
diff --git a/games/voxels/src/main/rust/src/item.rs b/games/voxels/src/main/rust/src/item.rsindex 702f0d63df..d894fa7961 100644--- a/games/voxels/src/main/rust/src/item.rs+++ b/games/voxels/src/main/rust/src/item.rs@@ -101,3 +101,49 @@ pub fn food_effects(id: u8) -> Option<&'static [(Effect, f32, u8)]> {         _ => return None,     }) }++#[cfg(test)]+mod tests {+    use super::*;++    // Blocks and items share one u8 id space split at ITEM_BASE. If a new block ever crosses that+    // line it would silently become unplaceable, so pin the invariant down.+    #[test]+    fn block_ids_stay_below_the_item_base() {+        assert!(crate::world::block::MAX_BLOCK_ID < ITEM_BASE);+        assert!(!is_item(crate::world::block::MAX_BLOCK_ID));+    }++    // armor_slot() does range arithmetic over three disjoint id blocks; a wrong mapping would let+    // a helmet occupy the boots slot.+    #[test]+    fn armor_maps_to_the_right_slot() {+        for (id, slot) in [(171u8, 0usize), (172, 1), (173, 2), (174, 3),   // iron+                           (175, 0), (176, 1), (177, 2), (178, 3),          // diamond+                           (199, 0), (200, 1), (201, 2), (202, 3),          // adamant+                           (188, 1)] {                                      // elytra -> chest+            assert!(is_armor(id), "{id} should be armor");+            assert_eq!(armor_slot(id), slot, "{id} mapped to the wrong slot");+        }+    }++    #[test]+    fn tools_and_armor_do_not_overlap() {+        for id in 0..=255u8 {+            assert!(!(is_tool(id) && is_armor(id)), "{id} is both a tool and armor");+            if is_tool(id) { assert!(is_pickaxe(id) ^ is_sword(id), "{id} must be exactly one tool kind"); }+            if is_tool(id) || is_armor(id) { assert!(max_durability(id) > 0, "{id} has no durability"); }+        }+    }++    // Adamant is the top tier: it must beat diamond everywhere it competes.+    #[test]+    fn adamant_outclasses_diamond() {+        assert!(sword_damage(198) > sword_damage(170));+        assert!(pick_damage(197) > pick_damage(169));+        for (adamant, diamond) in [(199u8, 175u8), (200, 176), (201, 177), (202, 178)] {+            assert!(armor_defense(adamant) > armor_defense(diamond), "{adamant} must beat {diamond}");+        }+        assert!(max_durability(197) > max_durability(169));+    }+}
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 7bf014c427..0cb1fe89db 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -1,4 +1,5 @@ pub mod world;+pub mod container; pub mod entity; pub mod item; pub mod player;@@ -284,6 +285,65 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getHe     } } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getSmeltingJson<'l>(+    mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+    let null = std::ptr::null_mut();+    match env.new_string(engine::get_smelting_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getSmeltJson<'l>(+    mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+    let null = std::ptr::null_mut();+    match env.new_string(engine::get_smelt_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_startSmelt<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>, recipe: jint, blast: jboolean,+) -> jboolean {+    engine::start_smelt(recipe.max(0) as usize, blast != 0) as jboolean+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_stopSmelt<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>,+) {+    engine::stop_smelt();+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getContainerJson<'l>(+    mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+    let null = std::ptr::null_mut();+    match env.new_string(engine::get_container_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_containerTake<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>, idx: jint,+) -> jboolean {+    engine::container_take(idx.max(0) as usize) as jboolean+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_containerPut<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>, idx: jint,+) -> jboolean {+    engine::container_put(idx.max(0) as usize) as jboolean+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_closeContainer<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>,+) {+    engine::close_container();+}+ #[cfg(test)] mod tests {     use crate::world::chunk::{Chunk, ChunkPos};
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 ef192c03cf..f6a42c5264 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -69,14 +69,18 @@ pub struct ProgressSave {     #[serde(default)] pub end_dragon_dead: bool,     #[serde(default)] pub nether_wither_dead: bool,     #[serde(default)] pub world_secs: f32,+    #[serde(default)] pub best_beacon: i32,+    #[serde(default = "default_deepest")] pub deepest_y: i32, } fn default_max_health() -> f32 { 20.0 }+fn default_deepest() -> i32 { 128 } impl Default for ProgressSave {     fn default() -> Self {         Self {             armor: Vec::new(), max_health: default_max_health(), dim: 0,             dim_pos: Vec::new(), dim_visited: Vec::new(), respawn: None,             end_dragon_dead: false, nether_wither_dead: false, world_secs: 0.0,+            best_beacon: 0, deepest_y: default_deepest(),         }     } }
scripts/voxels/build_atlas.py
diff --git a/scripts/voxels/build_atlas.py b/scripts/voxels/build_atlas.pyindex ed0dacf47e..90e2de271e 100644--- a/scripts/voxels/build_atlas.py+++ b/scripts/voxels/build_atlas.py@@ -351,11 +351,14 @@ def main():         raise SystemExit("unexpected atlas.bin size %d" % len(raw))      os.makedirs(ASSETS, exist_ok=True)+    # Icons that COPY_ICONS renames are skipped here so the pack filename isn't also left behind.+    renamed = {src for _, src in COPY_ICONS.values()}     for idx, fname in sorted(NEW_TILES.items()):         src = os.path.join(PACK, fname)         w, h, rgba = decode_png(src)         blit(new, NEW_W, idx, NEW_COLS, rgba, w)-        shutil.copyfile(src, os.path.join(ASSETS, fname))+        if fname not in renamed:+            shutil.copyfile(src, os.path.join(ASSETS, fname))         print("tile %3d <- %s (%dx%d)" % (idx, fname, w, h))      for idx, rgb in sorted(PROC_TILES.items()):