voxels: various features
- Commit
2baece1aad1a186482a0abbde168c663592d81c8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-30 01:19 UTC (4 months ago)
- Parents
9a1ee00
Diff
games/voxels/src/main/assets/block/beacon.png
diff --git a/games/voxels/src/main/assets/block/beacon.png b/games/voxels/src/main/assets/block/beacon.pngnew file mode 100644index 0000000000..06ffa3ff07Binary files /dev/null and b/games/voxels/src/main/assets/block/beacon.png differ
games/voxels/src/main/assets/block/chest.png
diff --git a/games/voxels/src/main/assets/block/chest.png b/games/voxels/src/main/assets/block/chest.pngnew file mode 100644index 0000000000..b3f9727246Binary files /dev/null and b/games/voxels/src/main/assets/block/chest.png differ
games/voxels/src/main/assets/block/elytra.png
diff --git a/games/voxels/src/main/assets/block/elytra.png b/games/voxels/src/main/assets/block/elytra.pngnew file mode 100644index 0000000000..c5a1071eefBinary files /dev/null and b/games/voxels/src/main/assets/block/elytra.png differ
games/voxels/src/main/assets/block/end_stone.png
diff --git a/games/voxels/src/main/assets/block/end_stone.png b/games/voxels/src/main/assets/block/end_stone.pngnew file mode 100644index 0000000000..275a74ae6bBinary files /dev/null and b/games/voxels/src/main/assets/block/end_stone.png differ
games/voxels/src/main/assets/block/ender_pearl.png
diff --git a/games/voxels/src/main/assets/block/ender_pearl.png b/games/voxels/src/main/assets/block/ender_pearl.pngnew file mode 100644index 0000000000..a9e88ea1d6Binary files /dev/null and b/games/voxels/src/main/assets/block/ender_pearl.png differ
games/voxels/src/main/assets/block/firework_rocket.png
diff --git a/games/voxels/src/main/assets/block/firework_rocket.png b/games/voxels/src/main/assets/block/firework_rocket.pngnew file mode 100644index 0000000000..a44280c97fBinary files /dev/null and b/games/voxels/src/main/assets/block/firework_rocket.png differ
games/voxels/src/main/assets/block/flint_and_steel.png
diff --git a/games/voxels/src/main/assets/block/flint_and_steel.png b/games/voxels/src/main/assets/block/flint_and_steel.pngnew file mode 100644index 0000000000..76afe8a0a8Binary files /dev/null and b/games/voxels/src/main/assets/block/flint_and_steel.png differ
games/voxels/src/main/assets/block/lava.png
diff --git a/games/voxels/src/main/assets/block/lava.png b/games/voxels/src/main/assets/block/lava.pngnew file mode 100644index 0000000000..88f4f13e0dBinary files /dev/null and b/games/voxels/src/main/assets/block/lava.png differ
games/voxels/src/main/assets/block/nether_star.png
diff --git a/games/voxels/src/main/assets/block/nether_star.png b/games/voxels/src/main/assets/block/nether_star.pngnew file mode 100644index 0000000000..58a3e9a288Binary files /dev/null and b/games/voxels/src/main/assets/block/nether_star.png differ
games/voxels/src/main/assets/block/purpur_block.png
diff --git a/games/voxels/src/main/assets/block/purpur_block.png b/games/voxels/src/main/assets/block/purpur_block.pngnew file mode 100644index 0000000000..bfb26da603Binary files /dev/null and b/games/voxels/src/main/assets/block/purpur_block.png differ
games/voxels/src/main/assets/block/snowball.png
diff --git a/games/voxels/src/main/assets/block/snowball.png b/games/voxels/src/main/assets/block/snowball.pngnew file mode 100644index 0000000000..f80c3cbf40Binary files /dev/null and b/games/voxels/src/main/assets/block/snowball.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 bbccfce1d0..4867675eb5 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@@ -37,6 +37,7 @@ class MainActivity : ComponentActivity() { } } com.vayunmathur.games.voxels.util.SoundFx.init(this)+ com.vayunmathur.games.voxels.util.MusicFx.startAmbient(this) setContent { VoxelsTheme { var inventoryJson by remember { mutableStateOf("""{"selected":0,"slots":[{"id":3,"count":64},{"id":2,"count":64},{"id":1,"count":64},{"id":4,"count":16},{"id":10,"count":32},{"id":6,"count":32},{"id":7,"count":16},{"id":8,"count":16},{"id":9,"count":16}]}""") }@@ -132,6 +133,8 @@ class MainActivity : ComponentActivity() { 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+ 41 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace() // ignited a portal } } catch (_: Exception) {} }, onBreak = { off -> try { if (VoxelsNative.breakBlockAt(off.x, off.y)) com.vayunmathur.games.voxels.util.SoundFx.playBreak() } catch (_: Exception) {} }@@ -187,6 +190,14 @@ class MainActivity : ComponentActivity() { Box(Modifier.align(Alignment.BottomStart).padding(start = 16.dp, bottom = 78.dp)) { HealthOverlay(healthJson) }+ // Boss health bar (Ender Dragon) at the top.+ Box(Modifier.align(Alignment.TopCenter).padding(top = 70.dp)) {+ BossBar(healthJson)+ }+ // Elytra glide indicator, above the hotbar.+ Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 92.dp)) {+ GlideIndicator(healthJson)+ } Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp)) { Hotbar(inventoryJson = inventoryJson,
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 599bf5e12c..c650445532 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@@ -8,9 +8,12 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.remember@@ -34,7 +37,23 @@ data class InvSlot(val id: Int, val count: Int) data class InventoryState(val selected: Int = 0, val slots: List<InvSlot> = List(9) { InvSlot(0, 0) }, val armor: List<InvSlot> = emptyList()) // Ids 163..178 are tools/armor whose slot `count` is durability (not a stack size).-fun isDurabilityItem(id: Int) = id in 163..178+fun isDurabilityItem(id: Int) = id in 163..178 || id == 186 || id == 188++val maxDurability = mapOf(+ 163 to 60, 164 to 60, 165 to 132, 166 to 132, 167 to 250, 168 to 250, 169 to 1562, 170 to 1562,+ 171 to 240, 172 to 240, 173 to 240, 174 to 240, 175 to 528, 176 to 528, 177 to 528, 178 to 528,+ 186 to 64, 188 to 432+)++@Composable+fun DurabilityBar(id: Int, count: Int, modifier: Modifier = Modifier) {+ val max = maxDurability[id] ?: return+ if (count <= 0 || count >= max) return+ val frac = (count.toFloat() / max).coerceIn(0f, 1f)+ Box(modifier.fillMaxWidth(0.78f).height(3.dp).background(Color.Black.copy(0.65f), RoundedCornerShape(1.dp))) {+ Box(Modifier.fillMaxWidth(frac).fillMaxHeight().background(Color(1f - frac, frac, 0.15f), RoundedCornerShape(1.dp)))+ }+} val blockNames = mapOf( 0 to "·", 1 to "Stone", 2 to "Dirt", 3 to "Grass", 4 to "Wood", 5 to "Leaves",@@ -63,9 +82,11 @@ val blockNames = mapOf( 167 to "Iron Pickaxe", 168 to "Iron Sword", 169 to "Diamond Pickaxe", 170 to "Diamond Sword", 171 to "Iron Helmet", 172 to "Iron Chestplate", 173 to "Iron Leggings", 174 to "Iron Boots", 175 to "Diamond Helmet", 176 to "Diamond Chestplate", 177 to "Diamond Leggings", 178 to "Diamond Boots",- 82 to "Jukebox",+ 82 to "Jukebox", 83 to "Chest", 84 to "Lava", 85 to "End Stone", 88 to "Beacon", 89 to "Purpur", 179 to "Disc: Golden", 180 to "Disc: Lullaby", 181 to "Disc: Forest", 182 to "Disc: Deep Mining",- 183 to "Disc: Winter", 184 to "Disc: Piano", 185 to "Disc: Gift"+ 183 to "Disc: Winter", 184 to "Disc: Piano", 185 to "Disc: Gift",+ 186 to "Flint & Steel", 187 to "Nether Star", 188 to "Elytra", 189 to "Firework Rocket",+ 190 to "Snowball", 191 to "Ender Pearl" ) // Music disc item id -> track asset in assets/music/.@@ -104,23 +125,25 @@ val blockIconFile = mapOf( 167 to "iron_pickaxe.png", 168 to "iron_sword.png", 169 to "diamond_pickaxe.png", 170 to "diamond_sword.png", 171 to "iron_helmet.png", 172 to "iron_chestplate.png", 173 to "iron_leggings.png", 174 to "iron_boots.png", 175 to "diamond_helmet.png", 176 to "diamond_chestplate.png", 177 to "diamond_leggings.png", 178 to "diamond_boots.png",- 82 to "jukebox.png",+ 82 to "jukebox.png", 83 to "chest.png", 84 to "lava.png", 85 to "end_stone.png", 88 to "beacon.png", 89 to "purpur_block.png", 179 to "music_disc_13.png", 180 to "music_disc_cat.png", 181 to "music_disc_blocks.png", 182 to "music_disc_chirp.png",- 183 to "music_disc_5.png", 184 to "music_disc_11.png", 185 to "music_disc_bounce.png"+ 183 to "music_disc_5.png", 184 to "music_disc_11.png", 185 to "music_disc_bounce.png",+ 186 to "flint_and_steel.png", 187 to "nether_star.png", 188 to "elytra.png", 189 to "firework_rocket.png",+ 190 to "snowball.png", 191 to "ender_pearl.png" ) // Creative catalog, split into tabs. val catalogNatural = listOf(3, 2, 40, 46, 60, 39, 41, 71, 1, 6, 38, 36, 37, 14, 16, 17, 15, 45, 79, 75, 70,- 4, 5, 26, 28, 29, 31, 47, 48, 50, 51, 80, 11, 42, 43, 44, 32, 13)+ 4, 5, 26, 28, 29, 31, 47, 48, 50, 51, 80, 11, 42, 43, 44, 32, 84, 85, 13) val catalogOres = listOf(18, 19, 20, 21, 22, 23, 24, 25, 73) val catalogOcean = listOf(61, 62, 63, 64, 65, 66, 67, 68, 69) val catalogItems = listOf(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153,- 154, 155, 156, 157, 158, 159, 160, 161, 162)+ 154, 155, 156, 157, 158, 159, 160, 161, 162, 187, 189, 190, 191) val catalogGear = listOf(163, 164, 165, 166, 167, 168, 169, 170,- 171, 172, 173, 174, 175, 176, 177, 178)+ 171, 172, 173, 174, 175, 176, 177, 178, 186, 188) 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)+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, 88, 89) @Composable fun rememberBlockIcon(id: Int): androidx.compose.ui.graphics.ImageBitmap? {@@ -181,6 +204,7 @@ fun Hotbar( Text(text = "${slot.count}", style = MaterialTheme.typography.labelSmall, color = Color.White) } }+ if (isDurabilityItem(slot.id)) DurabilityBar(slot.id, slot.count, Modifier.align(Alignment.BottomCenter).padding(bottom = 3.dp)) } } }@@ -199,7 +223,37 @@ fun Hotbar( data class EffJson(val k: String = "", val amp: Int = 0, val t: Int = 0) @Serializable-data class HealthJson(val hp: Float = 20f, val max: Float = 20f, val absorb: Float = 0f, val dead: Boolean = false, val estus: Int = 0, val effects: List<EffJson> = emptyList())+data class HealthJson(val hp: Float = 20f, val max: Float = 20f, val absorb: Float = 0f, val dead: Boolean = false, val estus: Int = 0, val effects: List<EffJson> = emptyList(), val boss: Float = -1f, val bossName: String = "", val elytra: Boolean = false, val gliding: Boolean = false)++// Small chip shown while an elytra is equipped: prompts to deploy, or confirms gliding.+@Composable+fun GlideIndicator(healthJson: String, modifier: Modifier = Modifier) {+ val hj = remember(healthJson) {+ try { Json { ignoreUnknownKeys = true }.decodeFromString<HealthJson>(healthJson) } catch (_: Exception) { HealthJson() }+ }+ if (!hj.elytra) return+ val (label, tint) = if (hj.gliding) "Gliding" to Color(0xFF7CE0FF) else "Tap ▲ mid-air to glide" to Color.White.copy(0.75f)+ Box(modifier.background(Color.Black.copy(0.45f), RoundedCornerShape(6.dp)).padding(horizontal = 8.dp, vertical = 4.dp)) {+ Text(label, color = tint, style = MaterialTheme.typography.labelMedium)+ }+}++@Composable+fun BossBar(healthJson: String, modifier: Modifier = Modifier) {+ val hj = remember(healthJson) {+ try { Json { ignoreUnknownKeys = true }.decodeFromString<HealthJson>(healthJson) } catch (_: Exception) { HealthJson() }+ }+ if (hj.boss < 0f) return+ val wither = hj.bossName == "The Wither"+ val textColor = if (wither) Color(0xFFBDBDBD) else Color(0xFFB388FF)+ val barColor = if (wither) Color(0xFF4A4A55) else Color(0xFF9B30FF)+ Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {+ Text(hj.bossName.ifEmpty { "Boss" }, color = textColor, style = MaterialTheme.typography.labelMedium)+ Box(Modifier.width(220.dp).height(7.dp).background(Color.Black.copy(0.6f), RoundedCornerShape(3.dp))) {+ Box(Modifier.fillMaxWidth(hj.boss.coerceIn(0f, 1f)).fillMaxHeight().background(barColor, RoundedCornerShape(3.dp)))+ }+ }+} private val effectNames = mapOf( "regen" to "Regen", "poison" to "Poison", "resist" to "Resist", "strength" to "Strength",
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 b9d070de82..01a2477b27 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@@ -145,7 +145,8 @@ private fun SlotBox(index: Int, slot: InvSlot, bounds: MutableMap<Int, Rect>, dr if (slot.id != 0) { if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(30.dp), filterQuality = FilterQuality.None) else Text(blockNames[slot.id]?.take(2) ?: "", color = Color.White, fontSize = 10.sp)- if (slot.count > 1) Box(Modifier.align(Alignment.BottomEnd)) { Text("${slot.count}", 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/util/MusicFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.ktindex 2eda136513..2afb7ccb38 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt@@ -3,33 +3,66 @@ package com.vayunmathur.games.voxels.util import android.content.Context import android.media.MediaPlayer -// Looping jukebox music played from assets/music/*.ogg. Best-effort; never throws into the UI.+// Background music manager. Cycles the track playlist ambiently at a low volume; a jukebox disc+// temporarily takes over (pausing ambient) until stopped. Best-effort; never throws into the UI. object MusicFx {- private var mp: MediaPlayer? = null- private var current: String? = null-- // Toggle a track: tapping the jukebox with the same disc stops it; a different disc switches;- // a null asset (holding no disc) stops.- fun toggle(ctx: Context, asset: String?) {- if (asset == null || asset == current) { stop(); return }- stop()- try {- val afd = ctx.assets.openFd("music/$asset")+ private var ambient: MediaPlayer? = null+ private var disc: MediaPlayer? = null+ private var currentDisc: String? = null+ private var ctx: Context? = null+ private var idx = 0+ private val playlist = listOf(+ "mcl_forest.ogg", "mcl_piano.ogg", "mcl_winter.ogg", "mcl_gift.ogg",+ "golden.ogg", "mcl_mining.ogg", "lullaby.ogg"+ )++ private fun make(c: Context, asset: String, loop: Boolean, vol: Float, onDone: (() -> Unit)?): MediaPlayer? {+ return try {+ val afd = c.assets.openFd("music/$asset") val p = MediaPlayer() p.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length) afd.close()- p.isLooping = true+ p.isLooping = loop+ p.setVolume(vol, vol) p.setOnPreparedListener { it.start() }- p.setOnErrorListener { _, _, _ -> stop(); true }+ p.setOnErrorListener { _, _, _ -> true }+ if (onDone != null) p.setOnCompletionListener { onDone() } p.prepareAsync()- mp = p- current = asset- } catch (_: Throwable) { stop() }+ p+ } catch (_: Throwable) { null }+ }++ fun startAmbient(c: Context) {+ ctx = c.applicationContext+ if (ambient == null && disc == null) playNextAmbient()+ }++ private fun playNextAmbient() {+ val c = ctx ?: return+ val asset = playlist[idx % playlist.size]+ idx+++ ambient?.let { try { it.release() } catch (_: Throwable) {} }+ ambient = make(c, asset, loop = false, vol = 0.45f, onDone = { playNextAmbient() }) } - fun stop() {- try { mp?.let { if (it.isPlaying) it.stop(); it.release() } } catch (_: Throwable) {}- mp = null- current = null+ // Jukebox: same disc again -> stop and resume ambient; a new disc -> take over; null -> resume.+ fun toggle(c: Context, asset: String?) {+ if (asset == null || asset == currentDisc) { stopDisc(); resumeAmbient(); return }+ stopDisc()+ try { ambient?.pause() } catch (_: Throwable) {}+ disc = make(c, asset, loop = true, vol = 0.8f, onDone = null)+ currentDisc = asset }++ private fun stopDisc() {+ disc?.let { try { it.release() } catch (_: Throwable) {} }+ disc = null; currentDisc = null+ }++ private fun resumeAmbient() {+ val a = ambient+ if (a != null) { try { a.start() } catch (_: Throwable) { playNextAmbient() } } else playNextAmbient()+ }++ fun stop() { stopDisc(); ambient?.let { try { it.release() } catch (_: Throwable) {} }; ambient = null } }
games/voxels/src/main/rust/Cargo.lock
diff --git a/games/voxels/src/main/rust/Cargo.lock b/games/voxels/src/main/rust/Cargo.lockindex d4b87a3195..94504355c8 100644--- a/games/voxels/src/main/rust/Cargo.lock+++ b/games/voxels/src/main/rust/Cargo.lock@@ -29,18 +29,6 @@ dependencies = [ "libloading", ] -[[package]]-name = "autocfg"-version = "1.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"--[[package]]-name = "bytes"-version = "1.12.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"- [[package]] name = "cesu8" version = "1.1.0"@@ -53,27 +41,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]]-name = "combine"-version = "4.6.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"-dependencies = [- "bytes",- "memchr",-]--[[package]]-name = "getrandom"-version = "0.1.16"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"-dependencies = [- "cfg-if",- "libc",- "wasi",-]- [[package]] name = "glam" version = "0.27.0"@@ -104,7 +71,6 @@ name = "jni" version = "0.21.1" dependencies = [ "cesu8",- "combine", "jni-sys 0.3.1", "log", "thiserror",@@ -138,12 +104,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]]-name = "libc"-version = "0.2.189"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"- [[package]] name = "libloading" version = "0.8.9"@@ -166,41 +126,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]]-name = "noise"-version = "0.8.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9ba869e17168793186c10ca82c7079a4ffdeac4f1a7d9e755b9491c028180e40"-dependencies = [- "num-traits",- "rand",- "rand_xorshift",-]--[[package]]-name = "num-traits"-version = "0.2.19"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"-dependencies = [- "autocfg",-]- [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]]-name = "ppv-lite86"-version = "0.2.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"-dependencies = [- "zerocopy",-]- [[package]] name = "proc-macro2" version = "1.0.107"@@ -219,56 +150,6 @@ dependencies = [ "proc-macro2", ] -[[package]]-name = "rand"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"-dependencies = [- "getrandom",- "libc",- "rand_chacha",- "rand_core",- "rand_hc",-]--[[package]]-name = "rand_chacha"-version = "0.2.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"-dependencies = [- "ppv-lite86",- "rand_core",-]--[[package]]-name = "rand_core"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"-dependencies = [- "getrandom",-]--[[package]]-name = "rand_hc"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"-dependencies = [- "rand_core",-]--[[package]]-name = "rand_xorshift"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "77d416b86801d23dde1aa643023b775c3a462efc0ed96443add11546cdf1dca8"-dependencies = [- "rand_core",-]- [[package]] name = "serde" version = "1.0.229"@@ -336,22 +217,22 @@ dependencies = [ [[package]] name = "thiserror"-version = "1.0.69"+version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl"-version = "1.0.69"+version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd" dependencies = [ "proc-macro2", "quote",- "syn 2.0.119",+ "syn 3.0.3", ] [[package]]@@ -374,18 +255,10 @@ dependencies = [ "glam", "hashbrown", "jni",- "noise",- "once_cell", "serde", "serde_json", ] -[[package]]-name = "wasi"-version = "0.9.0+wasi-snapshot-preview1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"- [[package]] name = "windows-link" version = "0.2.1"
games/voxels/src/main/rust/Cargo.toml
diff --git a/games/voxels/src/main/rust/Cargo.toml b/games/voxels/src/main/rust/Cargo.tomlindex 2bd1e38b88..6dc58af763 100644--- a/games/voxels/src/main/rust/Cargo.toml+++ b/games/voxels/src/main/rust/Cargo.toml@@ -19,11 +19,12 @@ crate-type = ["cdylib", "rlib"] jni.workspace = true ash = { version = "0.38", default-features = false, features = ["loaded"] } hashbrown = "0.14"-noise = "0.8"+# noise removed – replaced by src/world/perlin.rs (exact-math Perlin), which also+# drops the whole stale rand 0.7 stack noise pulled (8 crates total). glam = { version = "0.27", features = ["serde"] } serde = { version = "1", features = ["derive"] } serde_json = "1"-once_cell = "1.19"+# once_cell removed – it was declared but never used in src [profile.release] opt-level = 3
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 034ff37573..69b858226e 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/shaders/entity_atlas.bin
diff --git a/games/voxels/src/main/rust/shaders/entity_atlas.bin b/games/voxels/src/main/rust/shaders/entity_atlas.binindex 2bd323f93d..de0fe80583 100644Binary files a/games/voxels/src/main/rust/shaders/entity_atlas.bin and b/games/voxels/src/main/rust/shaders/entity_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 7c6140c01c..353dbc2df0 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -1,7 +1,7 @@ use crate::world::{ChunkMap, block::Block}; use crate::player::Player; use crate::inventory::Inventory;-use crate::entity::{Mob, MobKind, Particle, build_entity_mesh, tick_particles, append_particles};+use crate::entity::{Mob, MobKind, Particle, Projectile, ProjKind, build_entity_mesh, tick_particles, append_particles, append_projectiles}; use crate::world::mesher; use crate::vulkan::context::{VulkanContext, ANativeWindow}; use crate::vulkan::renderer::VulkanRenderer;@@ -27,7 +27,20 @@ pub struct EngineState { pub spawn_rng: u32, pub respawn: Option<Vec3>, pub checkpoint_cd: f32,+ pub beacon_cd: f32, pub particles: Vec<Particle>,+ pub projectiles: Vec<Projectile>,+ // Dimensions: 0 overworld, 1 nether, 2 end. `chunks` is the active dimension; the others are+ // stashed here while inactive.+ pub dim: u8,+ pub seed: u32,+ pub stored: [Option<ChunkMap>; 3],+ pub dim_pos: [Vec3; 3],+ pub dim_visited: [bool; 3],+ pub portal_armed: bool, // must step out of a portal before it fires again (no auto-bounce)+ pub portal_charge: f32,+ pub end_dragon_dead: bool,+ pub nether_wither_dead: bool, } unsafe impl Send for EngineState {}@@ -96,7 +109,18 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { spawn_rng: seed ^ 0x9E3779B9, respawn: None, checkpoint_cd: 0.0,+ beacon_cd: 0.0, particles: Vec::new(),+ projectiles: Vec::new(),+ dim: 0,+ seed,+ stored: [None, None, None],+ dim_pos: [Vec3::ZERO; 3],+ dim_visited: [true, false, false],+ portal_armed: true,+ portal_charge: 0.0,+ end_dragon_dead: false,+ nether_wither_dead: false, }); INIT_DONE.store(true, Ordering::SeqCst); true@@ -141,6 +165,8 @@ pub fn destroy_engine() { }; let _ = crate::world::save::save_player(&state.save_dir, &ps); 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(); } if let Some(mut renderer) = state.renderer.take() { unsafe { renderer.destroy();@@ -243,8 +269,35 @@ pub fn tick_and_render() { let move_len = (input.move_forward*input.move_forward + input.move_right*input.move_right).sqrt(); if move_len > 0.9 { input_mut.sprint = true; } + // 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); state.player.tick_status(dt);+ // Lava burns (Fire Resistance negates it).+ {+ let p = state.player.pos;+ let feet = state.chunks.get_block_world(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);+ let head = state.chunks.get_block_world(p.x.floor() as i32, (p.y + 1.0).floor() as i32, p.z.floor() as i32);+ if (feet == 84 || head == 84) && !state.player.has_effect(crate::item::Effect::FireResistance) {+ state.player.health -= 6.0 * dt;+ if state.player.health <= 0.0 { state.player.health = 0.0; state.player.dead = true; }+ }+ }+ // Portal traversal: step out to re-arm, dwell inside to travel.+ {+ let p = state.player.pos;+ let bl = state.chunks.get_block_world(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);+ if bl != 86 && bl != 87 {+ state.portal_armed = true;+ state.portal_charge = 0.0;+ } else if state.portal_armed {+ state.portal_charge += dt;+ if state.portal_charge > 0.4 {+ let target = if bl == 86 { if state.dim == 1 { 0 } else { 1 } } else if state.dim == 2 { 0 } else { 2 };+ switch_dimension(state, target);+ }+ }+ } // Warding stone checkpoint: standing near one sets respawn + slowly refills Estus (bonfire). state.checkpoint_cd = (state.checkpoint_cd - dt).max(0.0);@@ -269,6 +322,35 @@ pub fn tick_and_render() { } } + // Beacon: a lit beacon standing on a pyramid of mineral blocks projects buffs to nearby players.+ // Scan (throttled) for the nearest beacon around the player, grade its pyramid, and grant effects.+ state.beacon_cd = (state.beacon_cd - dt).max(0.0);+ if state.beacon_cd <= 0.0 {+ state.beacon_cd = 0.5;+ let p = state.player.pos;+ let (bx, by, bz) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);+ let mut best: Option<(i32, i32)> = None; // (tier, dist2) of the nearest in-range beacon+ for dy in -12..=12 { for dx in -16..=16 { for dz in -16..=16 {+ if state.chunks.get_block_world(bx + dx, by + dy, bz + dz) == 88 {+ let tier = beacon_tier(&state.chunks, bx + dx, by + dy, bz + dz);+ if tier == 0 { continue; }+ let d2 = dx * dx + dz * dz;+ let range = tier * 10 + 10;+ if d2 <= range * range && best.map_or(true, |b| d2 < b.1) {+ best = Some((tier, d2));+ }+ }+ }}}+ if let Some((tier, _)) = best {+ use crate::item::Effect::*;+ let e = &mut state.player;+ e.add_effect(Speed, 6.0, 0);+ if tier >= 2 { e.add_effect(Haste, 6.0, 0); }+ if tier >= 3 { e.add_effect(Resistance, 6.0, 0); }+ if tier >= 4 { e.add_effect(Strength, 6.0, 0); e.add_effect(Regeneration, 3.0, 0); e.add_effect(JumpBoost, 6.0, 0); }+ }+ }+ let px = state.player.pos.x as i32; let pz = state.player.pos.z as i32; state.chunks.ensure_radius(px, pz);@@ -286,21 +368,50 @@ pub fn tick_and_render() { let solid = |x: i32, y: i32, z: i32| { let id = chunks.get_block_world(x, y, z); id != 0 && Block::from_id(id).is_solid() }; for m in state.mobs.iter_mut() { m.tick(dt, player_pos, &solid); } }- // Mob melee contact damage + creeper fuse.+ // Mob melee contact damage + creeper fuse + ranged fire. let mut incoming = 0.0f32; let mut explosions: Vec<Vec3> = Vec::new();+ let mut new_shots: Vec<Projectile> = Vec::new();+ let eye = player_pos + vec3(0.0, 1.2, 0.0); for m in state.mobs.iter_mut() { m.attack_cd = (m.attack_cd - dt).max(0.0); let d = (m.pos - player_pos).length();+ let ranged = matches!(m.kind, MobKind::Blaze | MobKind::Shulker | MobKind::Ghast);+ let max_range = if m.kind == MobKind::Ghast { 42.0 } else { 30.0 }; if m.kind == MobKind::Creeper { if d < 3.2 { m.fuse += dt; if m.fuse >= 1.4 { explosions.push(m.pos); m.health = 0.0; } } else { m.fuse = (m.fuse - dt * 0.6).max(0.0); }- } else if m.kind.hostile() && d < 1.7 && m.attack_cd <= 0.0 {+ } else if ranged && d > 3.0 && d < max_range && m.attack_cd <= 0.0 {+ // Fire a projectile at the player's chest.+ m.attack_cd = match m.kind { MobKind::Blaze => 1.6, MobKind::Ghast => 3.0, _ => 2.2 };+ let origin = m.pos + vec3(0.0, m.kind.height() * 0.6, 0.0);+ let dir = (eye - origin).normalize_or_zero();+ let (kind, spd, dmg, explosive) = match m.kind {+ MobKind::Blaze => (ProjKind::Fireball, 16.0, 5.0, false),+ MobKind::Ghast => (ProjKind::Fireball, 12.0, 7.0, true),+ _ => (ProjKind::ShulkerBullet, 9.0, 4.0, false),+ };+ new_shots.push(Projectile { pos: origin, vel: dir * spd, life: 5.0, kind, from_player: false, damage: dmg, explosive });+ } else if m.kind.is_boss() && d < 5.0 && m.attack_cd <= 0.0 {+ m.attack_cd = 1.0; incoming += m.kind.contact_damage();+ } else if m.kind.hostile() && !m.kind.is_boss() && !ranged && d < 1.7 && m.attack_cd <= 0.0 { m.attack_cd = 0.8; incoming += m.kind.contact_damage(); } }+ state.projectiles.extend(new_shots);+ tick_projectiles(state, dt); if incoming > 0.0 { hurt_player(state, incoming); } for c in explosions { explode(state, c, 3.0); }+ // Slain Ender Dragon: mark defeated + a victory burst of particles.+ if let Some(dpos) = state.mobs.iter().find(|m| m.kind == MobKind::Dragon && m.health <= 0.0).map(|m| m.pos) {+ state.end_dragon_dead = true;+ spawn_particles(&mut state.spawn_rng, &mut state.particles, dpos, 60, [0.7, 0.3, 0.95], 8.0, 1.4, 0.4);+ }+ // Slain Wither: mark defeated + drop the Nether Star (via loot) + a dark burst.+ if let Some(wpos) = state.mobs.iter().find(|m| m.kind == MobKind::Wither && m.health <= 0.0).map(|m| m.pos) {+ state.nether_wither_dead = true;+ spawn_particles(&mut state.spawn_rng, &mut state.particles, wpos, 60, [0.15, 0.15, 0.2], 8.0, 1.4, 0.4);+ } // Remove dead mobs and auto-collect their drops. let mut loot: Vec<u8> = Vec::new(); state.mobs.retain(|m| if m.health <= 0.0 { loot.extend_from_slice(m.kind.loot()); false } else { true });@@ -328,7 +439,13 @@ pub fn tick_and_render() { let day_t = (world_time / 120.0) % 1.0; // Sun is below the horizon (night) near the ends of the cycle; ~noon at day_t=0.5. let night = day_t < 0.25 || day_t > 0.75;- let kind = if night {+ let kind = if state.dim == 1 {+ // Nether: hostile natives only (Ghasts are rarer floating threats).+ match (rand(&mut rng) * 8.0) as u32 { 0 => MobKind::Ghast, 1 | 2 => MobKind::Blaze, 3 | 4 => MobKind::WitherSkeleton, _ => MobKind::Zombie }+ } else if state.dim == 2 {+ // Sparse End hostiles: End-city Shulker guardians + wandering wither skeletons.+ if rand(&mut rng) < 0.4 { MobKind::Shulker } else { MobKind::WitherSkeleton }+ } else if night { if rand(&mut rng) < 0.5 { MobKind::Zombie } else { MobKind::Creeper } } else if rand(&mut rng) < 0.18 { MobKind::Villager@@ -365,11 +482,22 @@ pub fn tick_and_render() { state.player.air_max_y = state.player.pos.y; state.mobs.clear(); }+ // Elytra glide vapor trail: white streaks off both shoulders (the visible "wings" in 1st person).+ if state.player.gliding {+ let base = state.player.pos + vec3(0.0, 1.25, 0.0);+ let r = state.player.right();+ for &side in &[-1.0f32, 1.0] {+ if state.particles.len() < 400 {+ state.particles.push(Particle { pos: base + r * (0.55 * side), vel: Vec3::ZERO, life: 0.5, max_life: 0.5, size: 0.09, color: [0.88, 0.95, 1.0] });+ }+ }+ } tick_particles(&mut state.particles, dt); let (mut entity_verts, mut entity_indices) = build_entity_mesh(&state.mobs); { let right = state.player.right(); append_particles(&mut entity_verts, &mut entity_indices, &state.particles, right, Vec3::Y);+ append_projectiles(&mut entity_verts, &mut entity_indices, &state.projectiles, right, Vec3::Y); } if let Some(renderer) = state.renderer.as_mut() {@@ -396,8 +524,9 @@ pub fn tick_and_render() { let eb = (eye.x.floor() as i32, eye.y.floor() as i32, eye.z.floor() as i32); let underwater = if state.chunks.get_block_world(eb.0, eb.1, eb.2) == 12 { 1.0 } else { 0.0 }; let nv = if state.player.night_vision() { 1.0 } else { 0.0 };+ let dim = state.dim; unsafe {- renderer.update_ubo(view_proj, state.player.pos, time, underwater, nv);+ renderer.update_ubo(view_proj, state.player.pos, time, underwater, nv, dim); renderer.upload_entity_mesh(&entity_verts, &entity_indices); let _ = renderer.draw_frame(); }@@ -443,9 +572,13 @@ fn publish_ui(state: &EngineState) { 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(); let estus: i32 = state.inventory.slots.iter().filter(|s| s.id == 128).map(|s| s.count).sum();+ let boss_mob = state.mobs.iter().find(|m| m.kind.is_boss());+ let boss: f32 = boss_mob.map(|m| (m.health / m.kind.max_health()).clamp(0.0, 1.0)).unwrap_or(-1.0);+ let boss_name = match boss_mob.map(|m| m.kind) { Some(MobKind::Dragon) => "Ender Dragon", Some(MobKind::Wither) => "The Wither", _ => "" }; let health = serde_json::json!({ "hp": state.player.health, "max": state.player.max_health, "absorb": state.player.absorption,- "dead": state.player.dead, "estus": estus, "effects": effects,+ "dead": state.player.dead, "estus": estus, "effects": effects, "boss": boss, "bossName": boss_name,+ "elytra": state.player.elytra, "gliding": state.player.gliding, }).to_string(); if let Ok(mut c) = cref(&DEBUG_CACHE, "{}").lock() { *c = debug; } if let Ok(mut c) = cref(&STATS_CACHE, "{}").lock() { *c = stats; }@@ -494,6 +627,157 @@ fn screen_ray(state: &EngineState, px: f32, py: f32) -> (Vec3, Vec3) { (eye, dir) } +fn dim_dir(base: &str, dim: u8) -> String {+ match dim { 1 => format!("{}/nether", base), 2 => format!("{}/end", base), _ => base.to_string() }+}++// Travel to another dimension: stash the current world, swap in the target, place the player on a+// safe landing (or their saved position), and rebuild all chunk meshes (mesh keys are per-coord).+// A beacon's power tier = how many complete pyramid layers of mineral blocks sit beneath it.+// Layer k (k=1..4) at depth k must be a full (2k+1)x(2k+1) square of iron/diamond/emerald blocks+// centred under the beacon. Tier stops at the first incomplete layer.+fn beacon_tier(chunks: &ChunkMap, x: i32, y: i32, z: i32) -> i32 {+ let is_mineral = |id: u8| matches!(id, 23 | 24 | 25);+ let mut tier = 0;+ for k in 1..=4i32 {+ let mut full = true;+ 'layer: for dx in -k..=k { for dz in -k..=k {+ if !is_mineral(chunks.get_block_world(x + dx, y - k, z + dz)) { full = false; break 'layer; }+ }}+ if full { tier = k; } else { break; }+ }+ tier+}++fn switch_dimension(state: &mut EngineState, target: u8) {+ if target == state.dim { return; }+ let from = state.dim;+ state.dim_pos[from as usize] = state.player.pos;+ let placeholder = ChunkMap::new_dim(state.seed, dim_dir(&state.save_dir, target), target);+ let cur = std::mem::replace(&mut state.chunks, placeholder);+ state.stored[from as usize] = Some(cur);+ if let Some(m) = state.stored[target as usize].take() { state.chunks = m; }+ state.dim = target;++ let prev = state.player.pos;+ let (mut ax, mut az) = (prev.x, prev.z);+ if target == 1 { ax /= 8.0; az /= 8.0; } // nether is 8x compressed+ else if target == 0 && from == 1 { ax *= 8.0; az *= 8.0; }+ if target == 2 { ax = 0.0; az = 0.0; } // end: central island+ state.chunks.ensure_radius(ax as i32, az as i32);++ if state.dim_visited[target as usize] {+ state.player.pos = state.dim_pos[target as usize];+ } else {+ let (bx, bz) = (ax as i32, az as i32);+ let py: i32 = match target { 1 => 42, 2 => 66, _ => 70 };+ let mat = if target == 2 { 85 } else { 32 };+ for dx in -2..=2 { for dz in -2..=2 {+ state.chunks.set_block_world(bx + dx, py - 1, bz + dz, mat);+ state.chunks.set_block_world(bx + dx, py, bz + dz, 0);+ state.chunks.set_block_world(bx + dx, py + 1, bz + dz, 0);+ state.chunks.set_block_world(bx + dx, py + 2, bz + dz, 0);+ }}+ // Build a return portal beside the landing so the player can travel back.+ if target == 1 || target == 0 {+ build_nether_portal(&mut state.chunks, bx + 2, py, bz);+ } else if target == 2 {+ state.chunks.set_block_world(bx + 2, py - 1, bz, 85);+ state.chunks.set_block_world(bx + 2, py, bz, 87); // end return portal+ }+ state.player.pos = vec3(bx as f32 + 0.5, py as f32 + 0.2, bz as f32 + 0.5);+ state.dim_pos[target as usize] = state.player.pos;+ }+ state.dim_visited[target as usize] = true;+ state.portal_armed = false;+ state.portal_charge = 0.0;+ state.player.vel = Vec3::ZERO;+ state.player.air_max_y = state.player.pos.y;+ state.mobs.clear();+ state.particles.clear();+ state.projectiles.clear();+ // Summon the Ender Dragon on arrival in the End (once).+ if target == 2 && !state.end_dragon_dead {+ state.mobs.push(Mob::new(MobKind::Dragon, vec3(0.0, 86.0, 30.0), 0xD2A6));+ }+ // Summon the Wither on arrival in the Nether (once).+ if target == 1 && !state.nether_wither_dead {+ let wpos = vec3(state.player.pos.x, state.player.pos.y + 12.0, state.player.pos.z - 16.0);+ state.mobs.push(Mob::new(MobKind::Wither, wpos, 0x175E));+ }++ if let Some(r) = state.renderer.as_mut() { unsafe { r.clear_meshes(); } }+ let positions: Vec<_> = state.chunks.chunks_iter().map(|(p, _)| *p).collect();+ for pos in positions { rebuild_chunk_meshes(state, pos); }+}++// Build a small obsidian nether-portal frame (interior filled with portal blocks) in the X-Y plane.+fn build_nether_portal(chunks: &mut ChunkMap, x: i32, y: i32, z: i32) {+ for gx in -1..=2 { for gy in -1..=3 {+ let border = gx == -1 || gx == 2 || gy == -1 || gy == 3;+ chunks.set_block_world(x + gx, y + gy, z, if border { 78 } else { 86 });+ }}+}++// Flood the air interior enclosed by obsidian in a vertical plane (axis 0 = X-Y, 1 = Z-Y).+fn portal_interior(chunks: &ChunkMap, sx: i32, sy: i32, sz: i32, axis: u8) -> Option<Vec<(i32, i32, i32)>> {+ if chunks.get_block_world(sx, sy, sz) != 0 { return None; }+ let mut region: Vec<(i32, i32, i32)> = Vec::new();+ let mut stack = vec![(sx, sy, sz)];+ while let Some(c) = stack.pop() {+ if region.contains(&c) { continue; }+ if chunks.get_block_world(c.0, c.1, c.2) != 0 { continue; }+ if region.len() > 18 { return None; } // not enclosed+ region.push(c);+ let nbrs = if axis == 0 {+ [(c.0 + 1, c.1, c.2), (c.0 - 1, c.1, c.2), (c.0, c.1 + 1, c.2), (c.0, c.1 - 1, c.2)]+ } else {+ [(c.0, c.1, c.2 + 1), (c.0, c.1, c.2 - 1), (c.0, c.1 + 1, c.2), (c.0, c.1 - 1, c.2)]+ };+ for n in nbrs {+ let nb = chunks.get_block_world(n.0, n.1, n.2);+ if nb == 0 { if !region.contains(&n) && !stack.contains(&n) { stack.push(n); } }+ else if nb != 78 { return None; } // border must be obsidian+ }+ }+ if (2..=15).contains(®ion.len()) { Some(region) } else { None }+}++// Ignite a nether portal by tapping its obsidian frame: fill the enclosed interior with portal blocks.+fn light_portal(state: &mut EngineState, x: i32, y: i32, z: i32) -> bool {+ for axis in 0..2u8 {+ if let Some(cells) = portal_interior(&state.chunks, x, y + 1, z, axis) {+ for (cx, cy, cz) in &cells {+ state.chunks.set_block_world(*cx, *cy, *cz, 86);+ mark_neighbors_dirty(state, *cx, *cz);+ }+ return true;+ }+ }+ 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); }+ }+ }+}+ // Apply damage to the player through equipped armor (each defense point cuts ~4%, capped), wearing // the armor down when a hit actually lands. fn hurt_player(state: &mut EngineState, amt: f32) {@@ -504,6 +788,73 @@ fn hurt_player(state: &mut EngineState, amt: f32) { if state.player.health < before { state.inventory.damage_armor(); } } +// Advance projectiles: move, home (shulker bullets), trail sparks, and resolve block/mob/player hits.+// Player-thrown projectiles damage mobs; ender pearls teleport the player; ghast fireballs explode.+fn tick_projectiles(state: &mut EngineState, dt: f32) {+ let eye = state.player.pos + vec3(0.0, 1.0, 0.0);+ let mut projs = std::mem::take(&mut state.projectiles);+ let mut survivors: Vec<Projectile> = Vec::with_capacity(projs.len());+ let mut explosions: Vec<Vec3> = Vec::new();+ let mut teleport: Option<Vec3> = None;+ let mut bursts: Vec<(Vec3, [f32; 3], bool)> = Vec::new(); // (pos, color, big)+ let mut incoming = 0.0f32;+ for mut p in projs.drain(..) {+ p.life -= dt;+ // Motion: shulker bullets home; fireworks rise; snowballs/pearls fall; fireballs fly straight.+ match p.kind {+ ProjKind::ShulkerBullet => {+ let want = (eye - p.pos).normalize_or_zero() * p.vel.length();+ p.vel = (p.vel * 0.90 + want * 0.10).normalize_or_zero() * p.vel.length();+ }+ ProjKind::Firework => { p.vel.y += 6.0 * dt; }+ _ => { p.vel.y -= p.gravity() * dt; }+ }+ p.pos += p.vel * dt;+ // Block collision.+ let (bx, by, bz) = (p.pos.x.floor() as i32, p.pos.y.floor() as i32, p.pos.z.floor() as i32);+ let solid = { let id = state.chunks.get_block_world(bx, by, bz); id != 0 && Block::from_id(id).is_solid() };+ let mut hit = p.life <= 0.0 || solid;+ // Player-thrown projectiles hit mobs.+ if !hit && p.from_player {+ for m in state.mobs.iter_mut() {+ let center = m.pos + vec3(0.0, m.kind.height() * 0.5, 0.0);+ if (center - p.pos).length() < m.kind.hit_radius() + 0.4 {+ let dmg = match p.kind { ProjKind::Fireball => 6.0, ProjKind::Snowball => 1.0, _ => 0.0 };+ if dmg > 0.0 { m.health -= dmg; }+ hit = true; break;+ }+ }+ }+ // Enemy projectiles hit the player.+ if !hit && !p.from_player && (p.pos - eye).length() < 0.8 { incoming += p.damage; hit = true; }+ if hit {+ match p.kind {+ ProjKind::EnderPearl => teleport = Some(p.pos),+ ProjKind::Fireball if p.explosive => explosions.push(p.pos),+ _ => bursts.push((p.pos, p.color(), matches!(p.kind, ProjKind::Fireball | ProjKind::Firework))),+ }+ continue;+ }+ // Trail spark.+ if state.particles.len() < 400 { state.particles.push(Particle { pos: p.pos, vel: Vec3::ZERO, life: 0.3, max_life: 0.3, size: p.size() * 0.7, color: p.color() }); }+ survivors.push(p);+ }+ state.projectiles = survivors;+ if incoming > 0.0 { hurt_player(state, incoming); }+ for c in explosions { explode(state, c, 2.5); }+ if let Some(tp) = teleport {+ state.player.pos = tp + vec3(0.0, 0.5, 0.0);+ state.player.vel = Vec3::ZERO;+ state.player.air_max_y = state.player.pos.y; // no fall damage from the teleport+ state.player.damage(2.0); // ender pearls jar you a little+ spawn_particles(&mut state.spawn_rng, &mut state.particles, tp, 16, [0.25, 0.85, 0.7], 4.0, 0.6, 0.14);+ }+ for (pos, color, big) in bursts {+ let n = if big { 24 } else { 10 };+ spawn_particles(&mut state.spawn_rng, &mut state.particles, pos, n, color, if big { 5.0 } else { 3.0 }, 0.6, if big { 0.22 } else { 0.13 });+ }+}+ // Spawn a small burst of particles (capped so the buffer never overflows). fn spawn_particles(rng: &mut u32, out: &mut Vec<Particle>, center: Vec3, n: usize, color: [f32; 3], speed: f32, life: f32, size: f32) { let mut r = |s: &mut u32| { let mut x = *s; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *s = x; (x >> 8) as f32 / 16_777_216.0 * 2.0 - 1.0 };@@ -530,8 +881,9 @@ fn nearest_mob_hit(state: &EngineState, origin: Vec3, dir: Vec3, reach: f32, lim let mut best: Option<(usize, f32)> = None; for (i, m) in state.mobs.iter().enumerate() { let h = m.kind.height();- let min = vec3(m.pos.x - 0.45, m.pos.y, m.pos.z - 0.45);- let max = vec3(m.pos.x + 0.45, m.pos.y + h, m.pos.z + 0.45);+ let hr = m.kind.hit_radius();+ let min = vec3(m.pos.x - hr, m.pos.y, m.pos.z - hr);+ let max = vec3(m.pos.x + hr, m.pos.y + h, m.pos.z + hr); let mut tmin = 0.0f32; let mut tmax = reach.min(limit); let mut hit = true; for a in 0..3 {@@ -560,6 +912,46 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { return true; } }+ // Firework rocket: consume one to launch a burst; boosts the player forward while gliding.+ if item::is_firework(sel) && state.player.eat_cd <= 0.0 {+ if state.inventory.consume_selected().is_some() {+ state.player.firework_boost();+ let f = state.player.forward();+ let origin = state.player.eye_pos() + f * 0.5;+ state.projectiles.push(Projectile { pos: origin, vel: f * 5.0 + vec3(0.0, 7.0, 0.0), life: 1.1, kind: ProjKind::Firework, from_player: true, damage: 0.0, explosive: false });+ state.player.eat_cd = 0.4;+ return true;+ }+ }+ // Throwables: snowball (light damage/knock) and ender pearl (teleport to impact).+ if (sel == 190 || sel == 191) && state.player.eat_cd <= 0.0 {+ if state.inventory.consume_selected().is_some() {+ let f = state.player.forward();+ let origin = state.player.eye_pos() + f * 0.5;+ let (kind, spd) = if sel == 191 { (ProjKind::EnderPearl, 16.0) } else { (ProjKind::Snowball, 20.0) };+ state.projectiles.push(Projectile { pos: origin, vel: f * spd, life: 5.0, kind, from_player: true, damage: 0.0, explosive: false });+ state.player.eat_cd = 0.4;+ return true;+ }+ }+ // Deflect an incoming fireball by attacking it — bats it back (now player-owned) at the shooter.+ {+ let eye_pos = state.player.eye_pos();+ let f = state.player.forward();+ let mut best: Option<(usize, f32)> = None;+ for (i, p) in state.projectiles.iter().enumerate() {+ if p.from_player || p.kind != ProjKind::Fireball { continue; }+ let to = p.pos - eye_pos;+ let d = to.length();+ if d < 4.5 && to.normalize_or_zero().dot(f) > 0.5 && best.map_or(true, |b| d < b.1) { best = Some((i, d)); }+ }+ if let Some((i, _)) = best {+ let p = &mut state.projectiles[i];+ p.vel = -p.vel * 1.15;+ p.from_player = true;+ return true;+ }+ } // Consumables (hold to use): eat food any time, drink estus / use heart container when applicable. if state.player.eat_cd <= 0.0 { // Food can be eaten any time (even at full health) to gain its effects.@@ -611,6 +1003,12 @@ 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);+ state.chunks.set_block_world(x, y, z, 0);+ mark_neighbors_dirty(state, x, z);+ return true;+ } if id != 0 { // Stone/ore only drops when mined with a pickaxe; soft blocks always drop. let drops = !Block::from_id(id).needs_pickaxe() || item::is_pickaxe(sel);@@ -690,7 +1088,18 @@ pub fn place_block_at(px: f32, py: f32) -> i32 { } if let Some(hit) = block_hit { let (x, y, z) = hit.pos;- let m = crate::world::block::Block::from_id(state.chunks.get_block_world(x, y, z)).menu();+ 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);+ return 30;+ }+ // Tap an obsidian frame with flint & steel to ignite a nether portal.+ if id == 78 && state.dim != 2 && crate::item::is_flint_steel(state.inventory.selected_block()) {+ if light_portal(state, x, y, z) { state.inventory.damage_selected(); return 41; }+ }+ let m = crate::world::block::Block::from_id(id).menu(); if m != 0 { return 10 + m; } } }
games/voxels/src/main/rust/src/entity.rs
diff --git a/games/voxels/src/main/rust/src/entity.rs b/games/voxels/src/main/rust/src/entity.rsindex 8ad7a7a0e3..7d90576a6b 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -9,7 +9,7 @@ const CELL: f32 = ENTITY_CELL as f32; const PX: f32 = 1.0 / 16.0; // one skin pixel in blocks #[derive(Clone, Copy, PartialEq, Eq)]-pub enum MobKind { Pig, Cow, Sheep, Chicken, Creeper, Zombie, Villager }+pub enum MobKind { Pig, Cow, Sheep, Chicken, Creeper, Zombie, Villager, Dragon, Wither, Blaze, WitherSkeleton, Shulker, Ghast } // A model part: an axis-aligned box textured from the skin. struct Part {@@ -50,6 +50,53 @@ static CREEPER: &[Part] = &[ p([4.,6.,4.], [-0.125, 0.1875, 0.125], [0.,16.], 0.0, -1.0), p([4.,6.,4.], [0.125, 0.1875, 0.125], [0.,16.], 0.0, 1.0), ];+// Ender Dragon: a large flyer — head, body, two broad wings, tail. Uniform purple skin.+static DRAGON: &[Part] = &[+ p([12.,10.,16.], [0.0, 3.1, -1.9], [0.,0.], 0.0, 0.0), // head+ p([16.,14.,26.], [0.0, 2.8, 0.4], [0.,0.], 0.0, 0.0), // body+ p([40.,3.,20.], [-1.7, 3.3, 0.3], [0.,0.], 0.0, 1.0), // left wing (flaps)+ p([40.,3.,20.], [1.7, 3.3, 0.3], [0.,0.], 0.0, -1.0), // right wing+ p([8.,8.,24.], [0.0, 2.9, 2.2], [0.,0.], 0.0, 0.0), // tail+];++// Wither: a floating three-headed boss (central + two side heads on a ribcage body).+static WITHER: &[Part] = &[+ p([8.,8.,8.], [0.0, 2.6, 0.0], [0.,0.], 0.0, 0.0), // central head+ p([6.,6.,6.], [-0.55, 2.4, 0.0], [0.,0.], 0.0, 0.0), // left head+ p([6.,6.,6.], [0.55, 2.4, 0.0], [0.,0.], 0.0, 0.0), // right head+ p([4.,14.,4.], [0.0, 1.7, 0.0], [0.,0.], 0.0, 0.0), // spine+ p([18.,3.,3.], [0.0, 2.0, 0.0], [0.,0.], 0.0, 0.0), // ribs+];++// Blaze: a floating head ringed by spinning rods (no legs). Uniform procedural skin.+static BLAZE: &[Part] = &[+ p([8.,8.,8.], [0.0, 1.4, 0.0], [0.,0.], 0.0, 0.0), // head+ p([2.,8.,2.], [-0.2, 0.9, -0.2], [0.,0.], 0.0, 1.0),+ p([2.,8.,2.], [0.2, 0.9, 0.2], [0.,0.], 0.0, -1.0),+ p([2.,8.,2.], [0.2, 0.9, -0.2], [0.,0.], 0.0, -1.0),+ p([2.,8.,2.], [-0.2, 0.9, 0.2], [0.,0.], 0.0, 1.0),+];++// Ghast: a big floating pale body with nine dangling tentacles. Uniform white skin.+static GHAST: &[Part] = &[+ p([16.,16.,16.], [0.0, 2.0, 0.0], [0.,0.], 0.0, 0.0), // body+ p([2.,10.,2.], [-0.4, 0.6, -0.4], [0.,0.], 0.0, 1.0),+ p([2.,10.,2.], [0.0, 0.6, -0.4], [0.,0.], 0.0, -1.0),+ p([2.,10.,2.], [0.4, 0.6, -0.4], [0.,0.], 0.0, 1.0),+ p([2.,10.,2.], [-0.4, 0.6, 0.0], [0.,0.], 0.0, -1.0),+ p([2.,10.,2.], [0.4, 0.6, 0.0], [0.,0.], 0.0, 1.0),+ p([2.,10.,2.], [-0.4, 0.6, 0.4], [0.,0.], 0.0, -1.0),+ p([2.,10.,2.], [0.0, 0.6, 0.4], [0.,0.], 0.0, 1.0),+ p([2.,10.,2.], [0.4, 0.6, 0.4], [0.,0.], 0.0, -1.0),+];++// Shulker: a stationary boxy End-city turret — a thick shell with a small head peeking out.+static SHULKER: &[Part] = &[+ p([12.,8.,12.], [0.0, 0.25, 0.0], [0.,0.], 0.0, 0.0), // shell base+ p([8.,8.,8.], [0.0, 0.75, 0.0], [0.,0.], 0.0, 0.0), // shell lid+ p([6.,6.,6.], [0.0, 0.65, 0.0], [0.,0.], 0.0, 0.0), // head peeking out+];+ // Chicken: small body, head, two thin legs. static CHICKEN: &[Part] = &[ p([6.,8.,6.], [0.0, 0.38, 0.0], [0.,9.], 0.0, 0.0),@@ -59,25 +106,38 @@ static CHICKEN: &[Part] = &[ ]; impl MobKind {- fn cell(self) -> u32 { match self { MobKind::Pig=>0, MobKind::Cow=>1, MobKind::Sheep=>2, MobKind::Chicken=>3, MobKind::Creeper=>4, MobKind::Zombie=>5, MobKind::Villager=>6 } }- pub fn hostile(self) -> bool { matches!(self, MobKind::Creeper | MobKind::Zombie) }- pub fn max_health(self) -> f32 { match self { MobKind::Zombie | MobKind::Creeper => 20.0, MobKind::Villager => 20.0, _ => 10.0 } }- pub fn height(self) -> f32 { match self { MobKind::Zombie | MobKind::Villager => 1.9, MobKind::Creeper => 1.6, MobKind::Chicken => 0.7, _ => 0.9 } }- pub fn contact_damage(self) -> f32 { match self { MobKind::Zombie => 4.0, _ => 0.0 } }+ fn cell(self) -> u32 { match self { MobKind::Pig=>0, MobKind::Cow=>1, MobKind::Sheep=>2, MobKind::Chicken=>3, MobKind::Creeper=>4, MobKind::Zombie=>5, MobKind::Villager=>6, MobKind::Dragon=>7, MobKind::Wither=>8, MobKind::Blaze=>9, MobKind::WitherSkeleton=>10, MobKind::Shulker=>11, MobKind::Ghast=>12 } }+ pub fn hostile(self) -> bool { matches!(self, MobKind::Creeper | MobKind::Zombie | MobKind::Dragon | MobKind::Wither | MobKind::Blaze | MobKind::WitherSkeleton | MobKind::Shulker | MobKind::Ghast) }+ pub fn is_boss(self) -> bool { matches!(self, MobKind::Dragon | MobKind::Wither) }+ pub fn flies(self) -> bool { matches!(self, MobKind::Dragon | MobKind::Wither | MobKind::Ghast) }+ // Procedurally-skinned mobs sample their cell centre uniformly (no real texture map).+ pub fn uniform_skin(self) -> bool { matches!(self, MobKind::Dragon | MobKind::Wither | MobKind::Blaze | MobKind::WitherSkeleton | MobKind::Shulker | MobKind::Ghast) }+ pub fn max_health(self) -> f32{ match self { MobKind::Dragon => 200.0, MobKind::Wither => 150.0, MobKind::Shulker | MobKind::Ghast => 30.0, MobKind::Zombie | MobKind::Creeper | MobKind::Villager | MobKind::Blaze | MobKind::WitherSkeleton => 20.0, _ => 10.0 } }+ pub fn height(self) -> f32 { match self { MobKind::Dragon => 4.0, MobKind::Ghast => 4.0, MobKind::Wither => 3.2, MobKind::WitherSkeleton => 2.4, MobKind::Zombie | MobKind::Villager => 1.9, MobKind::Blaze => 1.8, MobKind::Creeper => 1.6, MobKind::Shulker => 1.0, MobKind::Chicken => 0.7, _ => 0.9 } }+ pub fn hit_radius(self) -> f32 { match self { MobKind::Dragon => 2.2, MobKind::Ghast => 2.0, MobKind::Wither => 1.3, MobKind::Shulker => 0.55, _ => 0.45 } }+ pub fn contact_damage(self) -> f32 { match self { MobKind::Zombie => 4.0, MobKind::Dragon => 7.0, MobKind::Wither => 6.0, MobKind::Blaze | MobKind::WitherSkeleton => 5.0, MobKind::Shulker => 4.0, _ => 0.0 } } // Item ids dropped on death (auto-collected into the inventory). pub fn loot(self) -> &'static [u8] { match self { MobKind::Pig => &[132], MobKind::Cow => &[137, 132], MobKind::Sheep => &[130], MobKind::Chicken => &[135],- MobKind::Creeper => &[138], MobKind::Zombie => &[131], MobKind::Villager => &[],+ MobKind::Creeper => &[138], MobKind::Zombie => &[131], MobKind::Villager => &[], MobKind::Dragon => &[85, 25, 25],+ MobKind::Wither => &[187, 155, 155],+ MobKind::Blaze => &[157], MobKind::WitherSkeleton => &[157, 154], MobKind::Shulker => &[89, 191],+ MobKind::Ghast => &[138, 138], } }- fn speed(self) -> f32 { match self { MobKind::Chicken=>1.6, MobKind::Creeper=>1.5, MobKind::Zombie=>1.7, MobKind::Villager=>0.9, _=>1.15 } }+ fn speed(self) -> f32 { match self { MobKind::Chicken=>1.6, MobKind::Creeper=>1.5, MobKind::Zombie=>1.7, MobKind::Blaze=>1.4, MobKind::WitherSkeleton=>1.8, MobKind::Shulker=>0.0, MobKind::Villager=>0.9, _=>1.15 } } fn parts(self) -> &'static [Part] { match self { MobKind::Pig | MobKind::Cow | MobKind::Sheep => QUAD,- MobKind::Zombie | MobKind::Villager => BIPED,+ MobKind::Zombie | MobKind::Villager | MobKind::WitherSkeleton => BIPED, MobKind::Creeper => CREEPER, MobKind::Chicken => CHICKEN,+ MobKind::Dragon => DRAGON,+ MobKind::Wither => WITHER,+ MobKind::Blaze => BLAZE,+ MobKind::Shulker => SHULKER,+ MobKind::Ghast => GHAST, } } }@@ -109,6 +169,30 @@ impl Mob { } pub fn tick(&mut self, dt: f32, player: Vec3, solid: &dyn Fn(i32, i32, i32) -> bool) {+ // Flying bosses (Dragon/Wither): no gravity/collision; orbit + periodic swoop at the player.+ if self.kind.flies() {+ let _ = solid;+ self.attack_cd = (self.attack_cd - dt).max(0.0);+ self.wander -= dt;+ if self.wander <= 0.0 { self.wander = 9.0; }+ // Ghasts hover high and never dive (they attack purely at range); bosses swoop.+ let (center, radius, spd, diving) = match self.kind {+ MobKind::Dragon => (Vec3::new(0.0, 86.0, 0.0), 30.0, 13.0, self.wander < 2.0),+ MobKind::Ghast => (player + Vec3::new(0.0, 14.0, 0.0), 20.0, 6.0, false),+ _ => (player + Vec3::new(0.0, 6.0, 0.0), 9.0, 9.0, self.wander < 2.0),+ };+ let target = if diving {+ player + Vec3::new(0.0, 1.0, 0.0)+ } else {+ let a = self.anim * 0.5;+ center + Vec3::new(a.cos() * radius, (a * 1.3).sin() * 3.0, a.sin() * radius)+ };+ let dir = target - self.pos;+ let d = dir.length();+ if d > 0.5 { let v = dir / d; self.pos += v * spd * dt; self.yaw = v.x.atan2(-v.z); }+ self.anim += dt * 3.0;+ return;+ } self.wander -= dt; let to_player = player - self.pos; let pdist = to_player.length();@@ -177,6 +261,8 @@ impl Mob { fn append_mesh(&self, verts: &mut Vec<Vertex>, indices: &mut Vec<u32>) { let col = (self.kind.cell() % 4) as f32 * CELL; let row = (self.kind.cell() / 4) as f32 * CELL;+ // Procedural skins are uniform, so sample the cell centre for every face.+ let uniform = self.kind.uniform_skin(); let (yc, ys) = (self.yaw.cos(), self.yaw.sin()); for part in self.kind.parts() { let swing = if part.leg != 0.0 { self.anim.sin() * 0.55 * part.leg } else { 0.0 };@@ -225,7 +311,8 @@ impl Mob { // yaw about Y through the mob origin. let (rx, rz) = (wp.x*yc - wp.z*ys, wp.x*ys + wp.z*yc); wp = Vec3::new(rx, wp.y, rz) + self.pos;- let uv = [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS];+ let uv = if uniform { [(col + 32.0) / ATLAS, (row + 32.0) / ATLAS] }+ else { [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS] }; verts.push(Vertex { pos: [wp.x, wp.y, wp.z], uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 0.0, normal: nrm, light: 0.0 }); } indices.extend_from_slice(&[base, base+1, base+2, base, base+2, base+3]);@@ -242,6 +329,50 @@ pub fn build_entity_mesh(mobs: &[Mob]) -> (Vec<Vertex>, Vec<u32>) { (verts, indices) } +// ---- Projectiles: flying attacks (blaze fireballs, shulker bullets) and firework rockets. ----+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum ProjKind { Fireball, ShulkerBullet, Firework, Snowball, EnderPearl }++pub struct Projectile {+ pub pos: Vec3,+ pub vel: Vec3,+ pub life: f32,+ pub kind: ProjKind,+ pub from_player: bool, // fired by the player (doesn't hurt the player)+ pub damage: f32,+ pub explosive: bool, // fireball detonates terrain on impact (ghast) vs. just bursting (blaze)+}++impl Projectile {+ pub fn color(&self) -> [f32; 3] {+ match self.kind {+ ProjKind::Fireball => [1.0, 0.55, 0.12],+ ProjKind::ShulkerBullet => [0.75, 0.55, 0.85],+ ProjKind::Firework => [1.0, 0.9, 0.5],+ ProjKind::Snowball => [0.95, 0.98, 1.0],+ ProjKind::EnderPearl => [0.25, 0.85, 0.7],+ }+ }+ pub fn size(&self) -> f32 { match self.kind { ProjKind::Fireball => 0.28, ProjKind::ShulkerBullet => 0.18, ProjKind::Firework => 0.16, ProjKind::Snowball => 0.14, ProjKind::EnderPearl => 0.16 } }+ // Snowballs/ender pearls fall under gravity; the rest fly straight.+ pub fn gravity(&self) -> f32 { match self.kind { ProjKind::Snowball | ProjKind::EnderPearl => 14.0, _ => 0.0 } }+}++// Render projectiles as bright, un-fading billboard quads (reuses the particle white-swatch UV).+pub fn append_projectiles(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, ps: &[Projectile], right: Vec3, up: Vec3) {+ for p in ps {+ let s = p.size();+ let c = p.color();+ let (r, u) = (right * s, up * s);+ let corners = [p.pos - r - u, p.pos + r - u, p.pos + r + u, p.pos - r + u];+ let base = verts.len() as u32;+ for cc in corners {+ verts.push(Vertex { pos: [cc.x, cc.y, cc.z], uv: [PARTICLE_UV, PARTICLE_UV], color: c, ao: 1.0, tile_idx: 0.0, normal: [0.0, 1.0, 0.0], light: 0.0 });+ }+ indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);+ }+}+ // ---- Particles: short-lived billboarded quads (block break, hits, explosions). ---- pub struct Particle { pub pos: Vec3, pub vel: Vec3, pub life: f32, pub max_life: f32, pub size: f32, pub color: [f32; 3] }
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 754ede5b2f..43c3ce2152 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -24,7 +24,11 @@ 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); 34] = [+pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 38] = [+ (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+ (Block::Snow as u8, 1, 0, 0, 190, 4), // snow -> snowballs (Block::Wood as u8, 1, 0, 0, Block::Planks as u8, 4), (Block::BirchLog as u8, 1, 0, 0, Block::BirchPlanks as u8, 4), (Block::SpruceLog as u8, 1, 0, 0, Block::SprucePlanks as u8,4),
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 d7c1244a1c..caf978055d 100644--- a/games/voxels/src/main/rust/src/item.rs+++ b/games/voxels/src/main/rust/src/item.rs@@ -39,9 +39,12 @@ pub fn is_food(id: u8) -> bool { food_effects(id).is_some() } pub fn is_tool(id: u8) -> bool { (163..=170).contains(&id) } pub fn is_pickaxe(id: u8) -> bool { matches!(id, 163 | 165 | 167 | 169) } pub fn is_sword(id: u8) -> bool { matches!(id, 164 | 166 | 168 | 170) }-pub fn is_armor(id: u8) -> bool { (171..=178).contains(&id) }-pub fn armor_slot(id: u8) -> usize { ((id - 171) % 4) as usize } // 0 helm, 1 chest, 2 legs, 3 boots-pub fn has_durability(id: u8) -> bool { is_tool(id) || is_armor(id) }+pub fn is_elytra(id: u8) -> bool { id == 188 }+pub fn is_armor(id: u8) -> bool { (171..=178).contains(&id) || id == 188 } // elytra occupies the chest slot+pub fn armor_slot(id: u8) -> usize { if id == 188 { 1 } else { ((id - 171) % 4) as usize } } // 0 helm, 1 chest, 2 legs, 3 boots+pub fn is_flint_steel(id: u8) -> bool { id == 186 }+pub fn is_firework(id: u8) -> bool { id == 189 }+pub fn has_durability(id: u8) -> bool { is_tool(id) || is_armor(id) || id == 186 } pub fn sword_damage(id: u8) -> f32 { match id { 164 => 5.0, 166 => 6.0, 168 => 7.0, 170 => 9.0, _ => 0.0 } } pub fn pick_damage(id: u8) -> f32 { match id { 163 => 2.0, 165 => 3.0, 167 => 4.0, 169 => 5.0, _ => 0.0 } }@@ -49,6 +52,7 @@ pub fn armor_defense(id: u8) -> f32 { match id { 171 => 2.0, 172 => 6.0, 173 => 5.0, 174 => 2.0, // iron helm/chest/legs/boots 175 => 3.0, 176 => 8.0, 177 => 6.0, 178 => 3.0, // diamond+ 188 => 1.0, // elytra (mostly for mobility, minor defense) _ => 0.0, } }@@ -56,6 +60,8 @@ pub fn max_durability(id: u8) -> i32 { match id { 163 | 164 => 60, 165 | 166 => 132, 167 | 168 => 250, 169 | 170 => 1562, // wood/stone/iron/diamond tools 171..=174 => 240, 175..=178 => 528, // iron/diamond armor+ 186 => 64, // flint & steel+ 188 => 432, // elytra _ => 0, } }
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 4efd4a0d86..bbb8e16f93 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -12,6 +12,11 @@ pub struct Player { pub pitch: f32, pub on_ground: bool, pub flying: bool,+ pub elytra: bool, // an elytra is equipped (gliding is possible)+ pub gliding: bool, // currently in an elytra glide (published for UI/animation)+ glide_armed: bool, // wings deployed: toggled with a mid-air jump tap+ prev_jump: bool, // for edge-detecting jump taps+ glide_boost: f32, // extra glide speed from a firework rocket (decays) pub walk_dist: f32, pub sneaking: bool, // Survival state.@@ -28,7 +33,7 @@ pub struct Player { impl Player { pub fn new(x: f32, y: f32, z: f32) -> Self {- Self { pos: vec3(x,y,z), vel: Vec3::ZERO, yaw: 0.0, pitch: 0.0, on_ground: false, flying: false, walk_dist: 0.0, sneaking: false,+ Self { pos: vec3(x,y,z), vel: Vec3::ZERO, yaw: 0.0, pitch: 0.0, on_ground: false, flying: false, elytra: false, gliding: false, glide_armed: false, prev_jump: false, glide_boost: 0.0, walk_dist: 0.0, sneaking: false, health: 20.0, max_health: 20.0, absorption: 0.0, effects: Vec::new(), hurt_cd: 0.0, attack_cd: 0.0, eat_cd: 0.0, air_max_y: y, dead: false } } @@ -54,6 +59,14 @@ impl Player { } } pub fn heal(&mut self, amt: f32) { self.health = (self.health + amt).min(self.max_health); }+ // Firework rocket: while gliding, surge forward and gain a little altitude.+ pub fn firework_boost(&mut self) {+ if self.gliding {+ self.glide_boost = (self.glide_boost + 16.0).min(26.0);+ self.vel.y = self.vel.y.max(0.0) + 5.0;+ self.air_max_y = self.pos.y;+ }+ } pub fn damage(&mut self, amt: f32) { if self.dead || self.hurt_cd > 0.0 || amt <= 0.0 { return; } let amt = amt * self.resistance_mult();@@ -86,6 +99,12 @@ impl Player { pub fn tick(&mut self, dt: f32, input: &crate::input::InputState, chunks: &ChunkMap) { self.sneaking = input.sneak;+ let jump_edge = input.jump_held && !self.prev_jump;+ self.prev_jump = input.jump_held;+ // Deploy/retract elytra wings with a mid-air jump tap; retract automatically on the ground.+ if self.elytra && jump_edge && !self.on_ground && !self.flying { self.glide_armed = !self.glide_armed; }+ if self.on_ground || !self.elytra { self.glide_armed = false; }+ self.glide_boost = (self.glide_boost - 10.0 * dt).max(0.0); let fwd = if self.flying { self.forward() } else {@@ -116,7 +135,15 @@ impl Player { while lift < 3.0 && self.collides_at(self.pos, chunks) { self.pos.y += 0.1; lift += 0.1; } self.vel.y = 0.0; }- let horiz_vel = vec3(wish.x * speed, 0.0, wish.z * speed);+ // Elytra glide: once wings are deployed (mid-air jump tap), sail forward along the look+ // direction with a slow, controlled fall instead of walking control.+ self.gliding = self.glide_armed && !self.on_ground;+ let horiz_vel = if self.gliding {+ let f = self.forward();+ vec3(f.x, 0.0, f.z).normalize_or_zero() * (11.0 + self.glide_boost)+ } else {+ vec3(wish.x * speed, 0.0, wish.z * speed)+ }; let mut new_pos = self.pos; // X axis: step up small ledges when grounded; when sneaking, refuse to walk off edges. let try_x = vec3(new_pos.x + horiz_vel.x * dt, new_pos.y, new_pos.z);@@ -138,6 +165,7 @@ impl Player { // Vertical: gravity + collision, resting at whatever height horizontal step-up left us at. let base_y = new_pos.y; self.vel.y -= 28.0 * dt;+ if self.gliding { self.vel.y = self.vel.y.max(-3.5); } // slow, gliding descent new_pos.y = base_y + self.vel.y * dt; if self.collides_at(new_pos, chunks) { new_pos.y = base_y;@@ -157,7 +185,8 @@ impl Player { } if self.pos.y < 0.1 { self.pos.y = 0.1; self.vel.y = 0.0; self.on_ground = true; } // Fall damage: track peak airborne height, hurt on landing beyond a safe margin.- if self.flying {+ // Flying and elytra gliding never accrue fall damage.+ if self.flying || self.gliding { self.air_max_y = self.pos.y; } else if !self.on_ground { if self.pos.y > self.air_max_y { self.air_max_y = self.pos.y; }
games/voxels/src/main/rust/src/vulkan/renderer.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/renderer.rs b/games/voxels/src/main/rust/src/vulkan/renderer.rsindex 86cddc11ec..7451c18168 100644--- a/games/voxels/src/main/rust/src/vulkan/renderer.rs+++ b/games/voxels/src/main/rust/src/vulkan/renderer.rs@@ -68,6 +68,7 @@ pub struct VulkanRenderer { pub ts_written: Vec<bool>, pub pass_ms: [f32; 4], pub drawn_sections: u32,+ pub dim: u8, // active dimension (0 overworld, 1 nether, 2 end) — gates sky/cloud passes } impl VulkanRenderer {@@ -105,7 +106,7 @@ impl VulkanRenderer { let img_count = swapchain.images.len(); let query_pool = device.create_query_pool(&vk::QueryPoolCreateInfo::default().query_type(vk::QueryType::TIMESTAMP).query_count(img_count as u32 * 5), None).map_err(|e| format!("query pool {e:?}"))?; let ts_period = ctx.device_properties.limits.timestamp_period;- Ok(Self { ctx, swapchain, atlas, entity_atlas, entity_vbuf, entity_ibuf, entity_index_count: 0, shadow, postfx, pipelines, command_pool, command_buffers, image_available, render_finished, in_flight_fences, ubo_buffer, ubo_data: UboData::default(), queued_meshes: HashMap::new(), gpu_meshes: HashMap::new(), current_frame: 0, frame_count: 0, width, height, query_pool, ts_period, ts_written: vec![false; img_count], pass_ms: [0.0;4], drawn_sections: 0 })+ Ok(Self { ctx, swapchain, atlas, entity_atlas, entity_vbuf, entity_ibuf, entity_index_count: 0, shadow, postfx, pipelines, command_pool, command_buffers, image_available, render_finished, in_flight_fences, ubo_buffer, ubo_data: UboData::default(), queued_meshes: HashMap::new(), gpu_meshes: HashMap::new(), current_frame: 0, frame_count: 0, width, height, query_pool, ts_period, ts_written: vec![false; img_count], pass_ms: [0.0;4], drawn_sections: 0, dim: 0 }) } pub unsafe fn resize(&mut self, width: u32, height: u32) -> Result<(), String> { if width==0 || height==0 { return Ok(()); }@@ -122,6 +123,17 @@ impl VulkanRenderer { pub unsafe fn enqueue_mesh(&mut self, chunk_x: i32, sec_y: i32, chunk_z: i32, mesh: Option<MeshData>) { self.queued_meshes.insert((chunk_x, sec_y, chunk_z), mesh); }+ // Destroy all chunk meshes (used when switching dimensions — mesh keys are per chunk coord).+ pub unsafe fn clear_meshes(&mut self) {+ self.ctx.device.device_wait_idle().ok();+ for (_, mut m) in self.gpu_meshes.drain() {+ m.vertex_buffer.destroy(&self.ctx.device);+ m.index_buffer.destroy(&self.ctx.device);+ if let Some(mut wb) = m.water_vertex_buffer.take() { wb.destroy(&self.ctx.device); }+ if let Some(mut wb) = m.water_index_buffer.take() { wb.destroy(&self.ctx.device); }+ }+ self.queued_meshes.clear();+ } // Replace the mob mesh for this frame (host-visible buffers, clamped to capacity). pub unsafe fn upload_entity_mesh(&mut self, verts: &[VulkanVertex], indices: &[u32]) { let nv = verts.len().min(MAX_ENTITY_VERTS);@@ -173,11 +185,12 @@ impl VulkanRenderer { } Ok(()) }- pub unsafe fn update_ubo(&mut self, view_proj: Mat4, player_pos: Vec3, time: f32, underwater: f32, night_vision: f32) {+ pub unsafe fn update_ubo(&mut self, view_proj: Mat4, player_pos: Vec3, time: f32, underwater: f32, night_vision: f32, dim: u8) {+ self.dim = dim; let day_cycle=120.0; let day_t=(time/day_cycle)%1.0; let sun_angle=day_t*std::f32::consts::TAU - std::f32::consts::FRAC_PI_2; let sun_dir=Vec3::new(sun_angle.cos()*0.3, sun_angle.sin(), sun_angle.cos()*0.1).normalize_or_zero();- let day_factor=(sun_dir.y*0.5+0.5).clamp(0.0,1.0).powf(0.6);+ let mut day_factor=(sun_dir.y*0.5+0.5).clamp(0.0,1.0).powf(0.6); // Horizon sky colour approximating the sky shader, so distance fog melts terrain into the sky. let sun_up = smoothstep(-0.10, 0.22, sun_dir.y); let day_sky = Vec3::new(0.52, 0.66, 0.86);@@ -199,7 +212,17 @@ impl VulkanRenderer { let half = 90.0; let light_proj = Mat4::orthographic_rh(-half, half, -half, half, 1.0, light_dist * 2.0); let light_view_proj = light_proj * light_view;- self.ubo_data=UboData{ view_proj: view_proj.to_cols_array_2d(), sun_dir: sun_dir.to_array(), time, fog_color: fog_color.to_array(), fog_density: 0.008 / (1.0+day_factor*0.8).max(0.2), player_pos: [player_pos.x, player_pos.y, player_pos.z, underwater], day_factor, _pad: [0.0;3], inv_view_proj: inv_view_proj.to_cols_array_2d(), sun_color: sun_color.to_array(), cloud_shadow: 0.6, ambient_color: ambient_color.to_array(), _pad2: night_vision, light_view_proj: light_view_proj.to_cols_array_2d() };+ // Per-dimension atmosphere: red haze in the Nether, dark void in the End (no sun there).+ let (mut fog_color, mut sun_color, mut ambient_color, mut cloud_shadow) = (fog_color, sun_color, ambient_color, 0.6f32);+ if dim == 1 {+ fog_color = Vec3::new(0.32, 0.09, 0.07); ambient_color = Vec3::new(0.52, 0.30, 0.24);+ sun_color = Vec3::ZERO; day_factor = 1.0; cloud_shadow = 0.0;+ } else if dim == 2 {+ fog_color = Vec3::new(0.05, 0.03, 0.09); ambient_color = Vec3::new(0.44, 0.38, 0.54);+ sun_color = Vec3::ZERO; day_factor = 0.9; cloud_shadow = 0.0;+ }+ let _ = (&mut fog_color, &mut sun_color, &mut ambient_color, &mut cloud_shadow);+ self.ubo_data=UboData{ view_proj: view_proj.to_cols_array_2d(), sun_dir: sun_dir.to_array(), time, fog_color: fog_color.to_array(), fog_density: 0.008 / (1.0+day_factor*0.8).max(0.2), player_pos: [player_pos.x, player_pos.y, player_pos.z, underwater], day_factor, _pad: [0.0;3], inv_view_proj: inv_view_proj.to_cols_array_2d(), sun_color: sun_color.to_array(), cloud_shadow, ambient_color: ambient_color.to_array(), _pad2: night_vision, light_view_proj: light_view_proj.to_cols_array_2d() }; let bytes=unsafe { std::slice::from_raw_parts((&self.ubo_data as *const UboData) as *const u8, std::mem::size_of::<UboData>()) }; self.ubo_buffer.upload(&self.ctx.device, bytes); }@@ -288,11 +311,13 @@ impl VulkanRenderer { device.cmd_bind_index_buffer(cmd, self.entity_ibuf.buffer, 0, vk::IndexType::UINT32); device.cmd_draw_indexed(cmd, self.entity_index_count, 1, 0, 0, 0); }- device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, self.pipelines.sky_pipeline);- device.cmd_draw(cmd, 3, 1, 0, 0);- // Volumetric clouds: depth-tested layer at fixed altitude, blended over sky + terrain.- device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, self.pipelines.cloud_pipeline);- device.cmd_draw(cmd, 3, 1, 0, 0);+ // Sky + volumetric clouds only in the overworld; Nether/End use the flat fog clear colour.+ if self.dim == 0 {+ device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, self.pipelines.sky_pipeline);+ device.cmd_draw(cmd, 3, 1, 0, 0);+ device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, self.pipelines.cloud_pipeline);+ device.cmd_draw(cmd, 3, 1, 0, 0);+ } device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, self.pipelines.water_pipeline); for ((cx,sec_y,cz), gpu_mesh) in self.gpu_meshes.iter() { if gpu_mesh.water_index_count == 0 { continue; }
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 4fe8b36fad..cf926d50e3 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -88,9 +88,16 @@ pub enum Block { AzaleaLeaves = 80, WardingStone = 81, Jukebox = 82,+ Chest = 83,+ Lava = 84,+ EndStone = 85,+ NetherPortal = 86,+ EndPortal = 87,+ Beacon = 88,+ Purpur = 89, } -pub const MAX_BLOCK_ID: u8 = 82;+pub const MAX_BLOCK_ID: u8 = 89; impl Block { pub fn from_id(id: u8) -> Self {@@ -98,9 +105,9 @@ impl Block { } pub fn id(self) -> u8 { self as u8 } pub fn is_air(self) -> bool { matches!(self, Self::Air) }- pub fn is_solid(self) -> bool { !matches!(self, Self::Air | Self::Water | Self::Glass) }+ 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)+ 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() } @@ -195,6 +202,13 @@ impl Block { Self::AzaleaLeaves => 116, Self::WardingStone => 117, Self::Jukebox => 118,+ Self::Chest => 119,+ Self::Lava => 120,+ Self::EndStone => 121,+ Self::NetherPortal => 122,+ Self::EndPortal => 123,+ Self::Beacon => 124,+ Self::Purpur => 125, } } pub fn tile_bottom(self) -> u32 {@@ -251,13 +265,14 @@ impl Block { | Self::IronBlock | Self::DiamondBlock | Self::EmeraldBlock | Self::Netherrack | Self::Furnace | Self::RedSandstone | Self::Sandstone | Self::GraniteBricks | Self::DeepslateBricks | Self::NetherBricks | Self::EndStoneBricks | Self::CobbledDeepslate | Self::Prismarine | Self::DarkPrismarine | Self::Dripstone- | Self::Amethyst | Self::Calcite | Self::Tuff | Self::Magma | Self::Obsidian | Self::PackedIce | Self::BlueIce)+ | Self::Amethyst | Self::Calcite | Self::Tuff | Self::Magma | Self::Obsidian | Self::PackedIce | Self::BlueIce | Self::Purpur) } // Block light emitted (0..15) for dynamic lighting. pub fn light_emission(self) -> u8 { match self {- Self::Glowstone | Self::SeaLantern => 15,+ Self::Glowstone | Self::SeaLantern | Self::Lava | Self::Beacon => 15, Self::WardingStone => 13,+ Self::NetherPortal | Self::EndPortal => 12, Self::Magma => 11, _ => 0, }
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 b2b021f4b9..aae6a84d63 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -11,9 +11,11 @@ pub struct ChunkMap { } impl ChunkMap {- pub fn new(seed: u32, save_dir: String) -> Self {- Self { chunks: HashMap::new(), gen: TerrainGen::new(seed), save_dir, render_distance: 12 }+ pub fn new(seed: u32, save_dir: String) -> Self { Self::new_dim(seed, save_dir, 0) }+ pub fn new_dim(seed: u32, save_dir: String, dim: u8) -> Self {+ Self { chunks: HashMap::new(), gen: TerrainGen::new_dim(seed, dim), save_dir, render_distance: 12 } }+ pub fn dim(&self) -> u8 { self.gen.dim } pub fn get_block_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);
games/voxels/src/main/rust/src/world/generator.rs
diff --git a/games/voxels/src/main/rust/src/world/generator.rs b/games/voxels/src/main/rust/src/world/generator.rsindex 09a7f38606..a9f924daa2 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -1,6 +1,6 @@ use super::chunk::{Chunk, CHUNK_SIZE, CHUNK_HEIGHT};-use noise::NoiseFn;-use noise::Perlin;+use crate::world::perlin::NoiseFn;+use crate::world::perlin::Perlin; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -17,22 +17,281 @@ pub enum Biome { JaggedPeaks, FrozenPeaks, StonyPeaks, } +// ---- Multi-chunk villages (deterministic region grid) ----+const VILLAGE_REGION: i32 = 6; // chunks per region side; at most one village per region++const B_HOUSE: u8 = 0;+const B_WELL: u8 = 1;+const B_LAMP: u8 = 2;+const B_BIGHOUSE: u8 = 3;+const B_FARM: u8 = 4;+const B_BLACKSMITH: u8 = 5;+const B_CHURCH: u8 = 6;++// Level a village column: dirt foundation down a few blocks, clear terrain above up to `clear_to`.+fn level_column(chunk: &mut Chunk, lx: usize, lz: usize, base: usize, clear_to: usize, floor: u8) {+ for dyb in 1..=3 { if base >= dyb { chunk.set_block(lx, base - dyb, lz, 2); } } // dirt foundation+ chunk.set_block(lx, base, lz, floor);+ for dy in 1..=clear_to { if base + dy < CHUNK_HEIGHT { chunk.set_block(lx, base + dy, lz, 0); } }+}++fn hash3(a: i32, b: i32, c: u32) -> u64 {+ let mut h = DefaultHasher::new();+ (a, b, c).hash(&mut h);+ h.finish()+}+fn in_chunk(wx: i32, wz: i32, ox: i32, oz: i32) -> bool { wx >= ox && wx < ox + 16 && wz >= oz && wz < oz + 16 }++// Render a single village building, writing only the columns that fall inside this chunk (so a+// building straddling a chunk border is completed by whichever chunks overlap it).+fn render_building(chunk: &mut Chunk, ox: i32, oz: i32, bx: i32, bz: i32, w: i32, d: i32, base: usize, kind: u8) {+ if base + 7 >= CHUNK_HEIGHT { return; }+ match kind {+ B_WELL => {+ for gx in 0..3 { for gz in 0..3 {+ let (wx, wz) = (bx + gx, bz + gz);+ if !in_chunk(wx, wz, ox, oz) { continue; }+ let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize);+ let id = if gx == 1 && gz == 1 { 12 } else { 8 };+ chunk.set_block(lx, base, lz, id);+ let corner = (gx == 0 || gx == 2) && (gz == 0 || gz == 2);+ if corner { for dy in 1..=2 { chunk.set_block(lx, base + dy, lz, 8); } }+ }}+ }+ B_LAMP => {+ if in_chunk(bx, bz, ox, oz) {+ let (lx, lz) = ((bx - ox) as usize, (bz - oz) as usize);+ for dy in 1..=3 { chunk.set_block(lx, base + dy, lz, 4); }+ chunk.set_block(lx, base + 4, lz, 77); // glowstone lamp+ }+ }+ B_FARM => {+ for gx in 0..w { for gz in 0..d {+ let (wx, wz) = (bx + gx, bz + gz);+ if !in_chunk(wx, wz, ox, oz) { continue; }+ let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize);+ let water = gx == w / 2; // central irrigation channel+ level_column(chunk, lx, lz, base, 3, if water { 12 } else { 59 }); // water / farmland+ if !water && (gx + gz) % 2 == 0 && base + 1 < CHUNK_HEIGHT {+ chunk.set_block(lx, base + 1, lz, 58); // hay = ripe crop stand-in+ }+ }}+ }+ _ => {+ let height: usize = match kind { B_BIGHOUSE => 6, B_CHURCH => 9, _ => 4 };+ for gx in 0..w { for gz in 0..d {+ let (wx, wz) = (bx + gx, bz + gz);+ if !in_chunk(wx, wz, ox, oz) { continue; }+ let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize);+ level_column(chunk, lx, lz, base, height + 2, 8); // foundation + cobble floor + clear+ let edge = gx == 0 || gx == w - 1 || gz == 0 || gz == d - 1;+ if edge {+ for dy in 1..height {+ let door = gz == 0 && gx == w / 2 && dy <= 2;+ if door { continue; }+ let window = dy == 2 && (((gx == 0 || gx == w - 1) && gz == d / 2) || (gz == d - 1 && gx == w / 2));+ chunk.set_block(lx, base + dy, lz, if window { 7 } else { 10 });+ }+ }+ chunk.set_block(lx, base + height, lz, 10); // roof+ }}+ let (cxw, czw) = (bx + w / 2, bz + d / 2);+ if in_chunk(cxw, czw, ox, oz) {+ chunk.set_block((cxw - ox) as usize, base, (czw - oz) as usize, if kind == B_BIGHOUSE { 81 } else { 77 });+ }+ // Blacksmith forge: furnace + magma fire + iron-block anvil inside.+ if kind == B_BLACKSMITH {+ for &(dx, dz, dy, id) in &[(1i32, 1i32, 1usize, 35u8), (2, 1, 0, 76), (3, 1, 1, 23)] {+ let (wx, wz) = (bx + dx, bz + dz);+ if in_chunk(wx, wz, ox, oz) { chunk.set_block((wx - ox) as usize, base + dy, (wz - oz) as usize, id); }+ }+ }+ // Church spire: a sea-lantern beacon above the roof.+ if kind == B_CHURCH && in_chunk(cxw, czw, ox, oz) && base + height + 2 < CHUNK_HEIGHT {+ chunk.set_block((cxw - ox) as usize, base + height + 1, (czw - oz) as usize, 67);+ }+ }+ }+}++// A partial obsidian ruined-portal frame standing at the surface.+fn build_ruined_portal(chunk: &mut Chunk, cx: usize, cz: usize, base: usize) {+ if cx + 4 >= 16 || base + 6 >= CHUNK_HEIGHT { return; }+ for gx in 0..4i32 { for gy in 0..5i32 {+ let edge = gx == 0 || gx == 3 || gy == 0 || gy == 4;+ if !edge { continue; }+ // Broken: skip a few frame blocks pseudo-randomly.+ if (gx * 7 + gy * 13) % 5 == 0 { continue; }+ chunk.set_block(cx + gx as usize, base + gy as usize, cz, 78); // obsidian+ }}+ // A little rubble at the base, with scattered magma and glowstone.+ for gx in -1i32..=4 {+ let x = cx as i32 + gx;+ if x >= 0 && x < 16 {+ let rub = match (gx.rem_euclid(3), gx.rem_euclid(5)) { (0, _) => 76, (_, 0) => 77, _ => 78 }; // magma/glowstone/obsidian+ chunk.set_block(x as usize, base, cz, rub);+ }+ }+ // Loot chest beside the ruined frame.+ if cx + 4 < 16 { chunk.set_block(cx + 4, base + 1, cz, 83); }+}++// Carve one 3-wide mineshaft corridor arm from a centre along (dirx,dirz), with a plank floor,+// periodic wood support frames, and only the columns inside this chunk written.+fn carve_corridor(chunk: &mut Chunk, ox: i32, oz: i32, cx: i32, cz: i32, dirx: i32, dirz: i32, len: i32, fy: usize) {+ for i in 0..len {+ let (ax, az) = (cx + dirx * i, cz + dirz * i);+ for p in -1..=1 {+ let wx = ax + if dirx != 0 { 0 } else { p };+ let wz = az + if dirz != 0 { 0 } else { p };+ if !in_chunk(wx, wz, ox, oz) { continue; }+ let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize);+ chunk.set_block(lx, fy, lz, 10); // plank floor+ for dy in 1..=2 { if fy + dy < CHUNK_HEIGHT { chunk.set_block(lx, fy + dy, lz, 0); } }+ }+ if i % 6 == 0 {+ for &p in &[-1i32, 1] {+ let wx = ax + if dirx != 0 { 0 } else { p };+ let wz = az + if dirz != 0 { 0 } else { p };+ if in_chunk(wx, wz, ox, oz) { let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize); for dy in 1..=2 { if fy + dy < CHUNK_HEIGHT { chunk.set_block(lx, fy + dy, lz, 4); } } } // posts+ }+ for p in -1..=1 {+ let wx = ax + if dirx != 0 { 0 } else { p };+ let wz = az + if dirz != 0 { 0 } else { p };+ if in_chunk(wx, wz, ox, oz) && fy + 3 < CHUNK_HEIGHT { chunk.set_block((wx - ox) as usize, fy + 3, (wz - oz) as usize, 4); } // beam+ }+ }+ }+}++// A small underground dungeon room: mossy-cobble shell, a light, and a couple of loot blocks.+fn build_dungeon(chunk: &mut Chunk, cx: usize, cz: usize, y: usize, r: u64) {+ if cx + 4 >= 16 || cz + 4 >= 16 || y + 5 >= CHUNK_HEIGHT || y < 2 { return; }+ for gx in 0..5 { for gz in 0..5 { for gy in 0..5 {+ let edge = gx == 0 || gx == 4 || gz == 0 || gz == 4 || gy == 0 || gy == 4;+ let id = if edge { if (gx + gz + gy) % 3 == 0 { 15 } else { 8 } } else { 0 };+ chunk.set_block(cx + gx, y + gy, cz + gz, id);+ }}}+ chunk.set_block(cx + 2, y + 3, cz + 2, 77); // glowstone light+ let _ = r;+ // Loot chests in the corners.+ chunk.set_block(cx + 1, y + 1, cz + 1, 83);+ chunk.set_block(cx + 3, y + 1, cz + 3, 83);+}++// A stepped sandstone desert temple with a small hidden chamber of loot chests underneath.+fn build_temple(chunk: &mut Chunk, cx: usize, cz: usize, base: usize) {+ let (c, cz2) = (cx as i32, cz as i32);+ if c - 4 < 0 || c + 4 >= 16 || cz2 - 4 < 0 || cz2 + 4 >= 16 || base + 6 >= CHUNK_HEIGHT { return; }+ for gy in 0..6i32 {+ let r = 4 - gy;+ for gx in -r..=r { for gz in -r..=r {+ chunk.set_block((c + gx) as usize, base + gy as usize, (cz2 + gz) as usize, 38); // sandstone+ }}+ }+ for gy in 1..=3 { for gx in -1i32..=1 { for gz in -1i32..=1 {+ let y = base as i32 - gy;+ if y >= 1 { chunk.set_block((c + gx) as usize, y as usize, (cz2 + gz) as usize, 0); }+ }}}+ let fy = base as i32 - 3;+ if fy >= 1 {+ chunk.set_block((c - 1) as usize, fy as usize, (cz2 - 1) as usize, 83);+ chunk.set_block((c + 1) as usize, fy as usize, (cz2 + 1) as usize, 83);+ if base >= 1 { chunk.set_block(cx, base - 1, cz, 77); }+ }+}++// An underground stronghold room: brick/cobble shell, loot chests, and a decorative obsidian frame.+fn build_stronghold(chunk: &mut Chunk, cx: usize, cz: usize, y: usize) {+ if cx + 6 >= 16 || cz + 6 >= 16 || y + 5 >= CHUNK_HEIGHT || y < 2 { return; }+ for gx in 0..7 { for gz in 0..7 { for gy in 0..5 {+ let edge = gx == 0 || gx == 6 || gz == 0 || gz == 6 || gy == 0 || gy == 4;+ let id = if edge { if (gx + gz + gy) % 4 == 0 { 54 } else { 8 } } else { 0 };+ chunk.set_block(cx + gx, y + gy, cz + gz, id);+ }}}+ chunk.set_block(cx + 1, y + 1, cz + 1, 83);+ chunk.set_block(cx + 5, y + 1, cz + 5, 83);+ chunk.set_block(cx + 3, y + 3, cz + 3, 77); // glowstone+ for gx in 2..=4 { chunk.set_block(cx + gx, y + 1, cz + 3, 78); chunk.set_block(cx + gx, y + 3, cz + 3, 78); }+ for gy in 1..=3 { chunk.set_block(cx + 2, y + gy, cz + 3, 78); chunk.set_block(cx + 4, y + gy, cz + 3, 78); }+ // Active End portal: a 2x2 pool of end-portal blocks on the floor — walk in to reach the End.+ for gx in 2..=3 { for gz in 2..=3 {+ chunk.set_block(cx + gx, y, cz + gz, 85); // end-stone rim under the portal+ chunk.set_block(cx + gx, y + 1, cz + gz, 87); // end portal+ }}+}++// A nether-brick fortress bridge section carved into the netherrack: a walkway with railings,+// arched pillars, glowstone lamps and loot chests. Built above the lava line in the Nether.+fn build_nether_fortress(chunk: &mut Chunk, cx: usize, cz: usize, base: usize, r: u64) {+ if cx + 8 >= 16 || cz + 8 >= 16 || base + 8 >= CHUNK_HEIGHT || base < 2 { return; }+ // Hollow out a hall.+ for gx in 0..9 { for gz in 0..9 { for gy in 1..7 { chunk.set_block(cx + gx, base + gy, cz + gz, 0); }}}+ // Nether-brick floor + surrounding railing.+ for gx in 0..9 { for gz in 0..9 {+ chunk.set_block(cx + gx, base, cz + gz, 55);+ let edge = gx == 0 || gx == 8 || gz == 0 || gz == 8;+ if edge && (gx + gz) % 2 == 0 { chunk.set_block(cx + gx, base + 1, cz + gz, 55); } // low railing+ }}+ // Four arched corner pillars up to the ceiling beam.+ for &(px, pz) in &[(0usize, 0usize), (8, 0), (0, 8), (8, 8)] {+ for gy in 1..=6 { chunk.set_block(cx + px, base + gy, cz + pz, 55); }+ }+ // Ceiling beams across the top.+ for gx in 0..9 { chunk.set_block(cx + gx, base + 6, cz, 55); chunk.set_block(cx + gx, base + 6, cz + 8, 55); }+ for gz in 0..9 { chunk.set_block(cx, base + 6, cz + gz, 55); chunk.set_block(cx + 8, base + 6, cz + gz, 55); }+ // Glowstone lamps hung under the beams + loot chests along the walkway.+ chunk.set_block(cx + 4, base + 6, cz + 4, 77);+ chunk.set_block(cx + 2, base + 5, cz + 2, 77);+ chunk.set_block(cx + 6, base + 5, cz + 6, 77);+ chunk.set_block(cx + 1, base + 1, cz + 4, 83);+ chunk.set_block(cx + 7, base + 1, cz + 4, 83);+ let _ = r;+}++// An End City: a tall purpur tower on an end-stone island, capped with a loot chest. Simple and+// deterministic (single chunk), rising from the island surface.+fn build_end_city(chunk: &mut Chunk, cx: usize, cz: usize, base: usize, r: u64) {+ if cx + 4 >= 16 || cz + 4 >= 16 || base + 18 >= CHUNK_HEIGHT { return; }+ let height = 12 + (r % 6) as usize;+ // Hollow purpur tower shell (5x5) with a room every few floors.+ for gy in 0..height { for gx in 0..5 { for gz in 0..5 {+ let edge = gx == 0 || gx == 4 || gz == 0 || gz == 4;+ let floor = gy % 5 == 0;+ chunk.set_block(cx + gx, base + gy, cz + gz, if edge || floor { 89 } else { 0 });+ }}}+ // Battlement crown of end-stone bricks.+ for gx in 0..5 { for gz in 0..5 {+ if (gx == 0 || gx == 4 || gz == 0 || gz == 4) && (gx + gz) % 2 == 0 {+ chunk.set_block(cx + gx, base + height, cz + gz, 56);+ }+ }}+ // Glowstone lantern + loot chest in the top room.+ let top = base + height - 4;+ chunk.set_block(cx + 2, base + height - 1, cz + 2, 77);+ chunk.set_block(cx + 1, top, cz + 1, 83);+ chunk.set_block(cx + 3, top, cz + 3, 83);+}+ pub struct TerrainGen { perlin_height: Perlin, perlin_detail: Perlin, perlin_cave: Perlin, perlin_biome: Perlin, seed: u32,+ pub dim: u8, // 0 overworld, 1 nether, 2 end } impl TerrainGen {- pub fn new(seed: u32) -> Self {+ pub fn new(seed: u32) -> Self { Self::new_dim(seed, 0) }+ pub fn new_dim(seed: u32, dim: u8) -> Self { Self { perlin_height: Perlin::new(seed), perlin_detail: Perlin::new(seed.wrapping_add(101)), perlin_cave: Perlin::new(seed.wrapping_add(202)), perlin_biome: Perlin::new(seed.wrapping_add(303)), seed,+ dim, } } // Per-biome grass tint (multiplied over the grayscale grass_top / grass_side textures). Uses the@@ -180,6 +439,89 @@ impl TerrainGen { if t < 0.28 { 0 } else if t < 0.5 { 1 } else if t < 0.72 { 2 } else { 3 } } pub fn fill_chunk(&self, chunk: &mut Chunk) {+ match self.dim {+ 1 => self.fill_nether(chunk),+ 2 => self.fill_end(chunk),+ _ => self.fill_overworld(chunk),+ }+ chunk.generated = true;+ chunk.mesh_dirty = true;+ }++ // Nether: netherrack shell riddled with large 3D-noise caverns, a lava sea in the low y range,+ // glowstone clusters on ceilings, and magma patches. No sky (solid roof + floor).+ fn fill_nether(&self, chunk: &mut Chunk) {+ let (ox, oz) = chunk.pos.world_origin();+ const ROOF: i32 = 120;+ const LAVA: i32 = 31;+ for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {+ let wx = (ox + dx as i32) as f64;+ let wz = (oz + dz as i32) as f64;+ for y in 0..=ROOF {+ let yy = y as usize;+ // Solid bedrock cap at floor/roof.+ if y <= 2 || y >= ROOF - 2 { chunk.set_block(dx, yy, dz, 13); continue; }+ // Carve big caverns with 3D noise; solid netherrack elsewhere.+ let n = self.perlin_cave.get([wx * 0.035, y as f64 * 0.045, wz * 0.035])+ + 0.5 * self.perlin_detail.get([wx * 0.07, y as f64 * 0.09, wz * 0.07]);+ if n > 0.15 {+ if y <= LAVA { chunk.set_block(dx, yy, dz, 84); } // lava sea in the open low area+ } else {+ // Magma near the lava line, netherrack elsewhere.+ let id = if y <= LAVA + 1 && n > 0.02 { 76 } else { 32 };+ chunk.set_block(dx, yy, dz, id);+ }+ }+ // Glowstone clusters hanging from the ceiling.+ let g = self.perlin_biome.get([wx * 0.08, wz * 0.08]);+ if g > 0.72 {+ for k in 0..3 { let y = (ROOF - 3 - k) as usize; if chunk.get_block(dx, y, dz) == 32 { chunk.set_block(dx, y, dz, 77); } }+ }+ }}+ // Nether-brick fortress section (~1/60 chunks), sitting on a platform above the lava sea.+ let fh = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x0F02417E);+ if fh % 60 == 0 {+ let base = LAVA as usize + 6 + (fh % 20) as usize;+ build_nether_fortress(chunk, 4, 4, base, fh);+ }+ }++ // End: floating end-stone islands in a void (no floor). A guaranteed central island near origin.+ fn fill_end(&self, chunk: &mut Chunk) {+ let (ox, oz) = chunk.pos.world_origin();+ for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {+ let wx = (ox + dx as i32) as f64;+ let wz = (oz + dz as i32) as f64;+ let dist = (wx * wx + wz * wz).sqrt();+ for y in 40..90 {+ // Island mass: 3D noise thresholded, biased to a slab around y=64; central island guaranteed.+ let slab = 1.0 - ((y as f64 - 64.0).abs() / 22.0);+ let n = self.perlin_cave.get([wx * 0.02, y as f64 * 0.03, wz * 0.02]) + slab * 0.6;+ let central = dist < 34.0 && (y as f64 - 62.0).abs() < 6.0;+ if n > 0.55 || central { chunk.set_block(dx, y as usize, dz, 85); }+ }+ }}+ // Obsidian pillars on the central island.+ if ox.abs() < 16 && oz.abs() < 16 {+ for &(px, pz) in &[(2i32, 2i32), (12, 3), (4, 12), (11, 11)] {+ if px >= 0 && px < 16 && pz >= 0 && pz < 16 {+ for y in 63..70 { chunk.set_block(px as usize, y, pz as usize, 78); }+ }+ }+ }+ // End City (~1/40 outer chunks): a purpur tower rising from the island top, away from origin+ // so it never clashes with the dragon-fight central island.+ let dist0 = ((ox + 8) as f64).hypot((oz + 8) as f64);+ let ch = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x0E7DC17E);+ if dist0 > 80.0 && ch % 40 == 0 {+ // Find the island surface at local (6,6): topmost end-stone in the column.+ let mut top = None;+ for y in (40..90).rev() { if chunk.get_block(6, y, 6) == 85 { top = Some(y); break; } }+ if let Some(sy) = top { build_end_city(chunk, 6, 6, sy + 1, ch); }+ }+ }++ fn fill_overworld(&self, chunk: &mut Chunk) { let (ox, oz) = chunk.pos.world_origin(); let mut heightmap = [[0i32; CHUNK_SIZE]; CHUNK_SIZE]; for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE {@@ -375,10 +717,139 @@ impl TerrainGen { _ => {} } }+ // Multi-chunk villages + mineshafts (deterministic across their region grids).+ self.place_villages(chunk);+ self.place_mineshafts(chunk);+ // Ruined portal (surface) + dungeon (underground) — independent rare rolls.+ let ph = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x0B51D1A4);+ if ph % 130 == 0 {+ let (bx, bz) = (ox + 6, oz + 8);+ let sh = self.height_at(bx as f64, bz as f64);+ if sh >= Self::SEA_LEVEL as i32 { build_ruined_portal(chunk, 6, 8, sh as usize); }+ }+ let dh = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x0D0465E0);+ if dh % 80 == 0 {+ let (cxw, czw) = (ox + 5, oz + 5);+ let surf = self.height_at(cxw as f64, czw as f64);+ let y = 16 + (dh % 22) as i32;+ if y + 6 < surf { build_dungeon(chunk, 5, 5, y as usize, dh); }+ }+ // Desert temple (surface, desert/badlands).+ let te = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x7E0917E5);+ if te % 150 == 0 {+ let (bx, bz) = (ox + 8, oz + 8);+ let sh = self.height_at(bx as f64, bz as f64);+ if sh >= Self::SEA_LEVEL as i32 && matches!(self.biome_at(bx as f64, bz as f64, sh), Biome::Desert | Biome::Badlands) {+ build_temple(chunk, 8, 8, sh as usize);+ }+ }+ // Stronghold (deep underground).+ let st = hash3(chunk.pos.0, chunk.pos.1, self.seed ^ 0x0517A011);+ if st % 240 == 0 {+ let surf = self.height_at((ox + 7) as f64, (oz + 7) as f64);+ let y = 10 + (st % 12) as i32;+ if y + 6 < surf { build_stronghold(chunk, 4, 4, y as usize); }+ } chunk.generated = true; chunk.mesh_dirty = true; } + // Deterministic building list for a village centred at world (cx, cz): (bx, bz, w, d, kind).+ fn village_layout(&self, cx: i32, cz: i32) -> Vec<(i32, i32, i32, i32, u8)> {+ let mut list = vec![(cx - 1, cz - 1, 3, 3, B_WELL)];+ let plots = [(-22, -18), (6, -22), (20, -6), (-20, 8), (8, 18), (-8, -20), (22, 14), (-24, -4), (4, 8)];+ for (i, (dx, dz)) in plots.iter().enumerate() {+ let hh = hash3(cx + dx, cz + dz, self.seed ^ 0x8171A6E);+ match i {+ 0 => list.push((cx + dx, cz + dz, 7, 7, B_BIGHOUSE)),+ 1 => list.push((cx + dx, cz + dz, 6, 6, B_BLACKSMITH)),+ 4 => list.push((cx + dx, cz + dz, 5, 5, B_CHURCH)),+ 3 | 6 => list.push((cx + dx, cz + dz, 7, 5, B_FARM)),+ _ => {+ if hh % 10 < 7 {+ let (w, d) = (5 + (hh % 3) as i32, 5 + ((hh / 3) % 3) as i32);+ list.push((cx + dx, cz + dz, w, d, B_HOUSE));+ } else if hh % 10 == 8 {+ list.push((cx + dx, cz + dz, 1, 1, B_LAMP));+ }+ }+ }+ }+ list+ }++ // Render any village buildings/roads that overlap this chunk (checking the 3x3 nearby regions).+ fn place_villages(&self, chunk: &mut Chunk) {+ let (ox, oz) = chunk.pos.world_origin();+ let crx = chunk.pos.0.div_euclid(VILLAGE_REGION);+ let crz = chunk.pos.1.div_euclid(VILLAGE_REGION);+ for rrx in (crx - 1)..=(crx + 1) { for rrz in (crz - 1)..=(crz + 1) {+ let hv = hash3(rrx, rrz, self.seed ^ 0x5A11A6E);+ if hv % 100 >= 30 { continue; } // 30% of regions hold a village+ let ccx = rrx * VILLAGE_REGION + (hv % VILLAGE_REGION as u64) as i32;+ let ccz = rrz * VILLAGE_REGION + ((hv / 7) % VILLAGE_REGION as u64) as i32;+ let (cx, cz) = (ccx * 16 + 8, ccz * 16 + 8);+ let base_i = self.height_at(cx as f64, cz as f64);+ if base_i < Self::SEA_LEVEL as i32 + 1 { continue; }+ if !matches!(self.biome_at(cx as f64, cz as f64, base_i), Biome::Plains | Biome::Meadow | Biome::Savanna) { continue; }+ let base = base_i as usize;+ if base + 7 >= CHUNK_HEIGHT { continue; }+ // Crossroads (packed-dirt), bounded to the village footprint.+ for wz in oz..oz + 16 {+ if (wz - cz).abs() > 28 { continue; }+ for w in -1..=1 { let wx = cx + w; if in_chunk(wx, wz, ox, oz) {+ level_column(chunk, (wx - ox) as usize, (wz - oz) as usize, base, 3, 60);+ }}+ }+ for wx in ox..ox + 16 {+ if (wx - cx).abs() > 28 { continue; }+ for w in -1..=1 { let wz = cz + w; if in_chunk(wx, wz, ox, oz) {+ level_column(chunk, (wx - ox) as usize, (wz - oz) as usize, base, 3, 60);+ }}+ }+ for (bx, bz, w, d, kind) in self.village_layout(cx, cz) {+ render_building(chunk, ox, oz, bx, bz, w, d, base, kind);+ }+ }}+ }++ // Render mineshaft corridors (deterministic region grid, ~7 chunks) overlapping this chunk.+ fn place_mineshafts(&self, chunk: &mut Chunk) {+ const MINE_REGION: i32 = 7;+ let (ox, oz) = chunk.pos.world_origin();+ let crx = chunk.pos.0.div_euclid(MINE_REGION);+ let crz = chunk.pos.1.div_euclid(MINE_REGION);+ for rrx in (crx - 1)..=(crx + 1) { for rrz in (crz - 1)..=(crz + 1) {+ let hv = hash3(rrx, rrz, self.seed ^ 0x319E5417);+ if hv % 100 >= 25 { continue; } // 25% of regions+ let ccx = rrx * MINE_REGION + (hv % MINE_REGION as u64) as i32;+ let ccz = rrz * MINE_REGION + ((hv / 5) % MINE_REGION as u64) as i32;+ let (cx, cz) = (ccx * 16 + 8, ccz * 16 + 8);+ let fy = 16 + (hv % 14) as usize; // depth 16..29+ let surf = self.height_at(cx as f64, cz as f64);+ if (surf as usize) < fy + 6 { continue; } // must be underground+ // Central junction room (5x5).+ for gx in -2..=2 { for gz in -2..=2 {+ let (wx, wz) = (cx + gx, cz + gz);+ if !in_chunk(wx, wz, ox, oz) { continue; }+ let (lx, lz) = ((wx - ox) as usize, (wz - oz) as usize);+ chunk.set_block(lx, fy, lz, 10);+ for dy in 1..=2 { if fy + dy < CHUNK_HEIGHT { chunk.set_block(lx, fy + dy, lz, 0); } }+ }}+ for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {+ carve_corridor(chunk, ox, oz, cx, cz, dx, dz, 44, fy);+ }+ // A bit of loot + light in the junction.+ if in_chunk(cx, cz, ox, oz) {+ let (lx, lz) = ((cx - ox) as usize, (cz - oz) as usize);+ if fy + 3 < CHUNK_HEIGHT { chunk.set_block(lx, fy + 3, lz, 77); } // glowstone+ }+ if in_chunk(cx + 2, cz + 2, ox, oz) {+ chunk.set_block((cx + 2 - ox) as usize, fy + 1, (cz + 2 - oz) as usize, 83); // loot chest+ }+ }}+ }+ pub const SEA_LEVEL: usize = 62; // Fill each column's air above the *intended terrain surface* up to sea level with water.@@ -386,6 +857,7 @@ impl TerrainGen { // oceans/lakes. Using height_at (not the scanned solid top) means cave shafts carved into high // land are NOT flooded — only genuine lowland columns (surface below sea) hold water. pub fn ensure_water(&self, chunk: &mut Chunk) {+ if self.dim != 0 { return; } let (ox, oz) = chunk.pos.world_origin(); for dz in 0..CHUNK_SIZE { for dx in 0..CHUNK_SIZE { let wx = (ox + dx as i32) as f64;
games/voxels/src/main/rust/src/world/mod.rs
diff --git a/games/voxels/src/main/rust/src/world/mod.rs b/games/voxels/src/main/rust/src/world/mod.rsindex f9818f459f..55d32e4513 100644--- a/games/voxels/src/main/rust/src/world/mod.rs+++ b/games/voxels/src/main/rust/src/world/mod.rs@@ -1,5 +1,6 @@ pub mod block; pub mod chunk;+pub mod perlin; pub mod chunk_map; pub mod mesher; pub mod generator;
games/voxels/src/main/rust/src/world/perlin.rs
diff --git a/games/voxels/src/main/rust/src/world/perlin.rs b/games/voxels/src/main/rust/src/world/perlin.rsnew file mode 100644index 0000000000..ae62bd3643--- /dev/null+++ b/games/voxels/src/main/rust/src/world/perlin.rs@@ -0,0 +1,224 @@+//! Perlin noise — a self-contained replacement for the `noise` crate (which was+//! used *only* for `Perlin` + `NoiseFn` here and pulled in a whole stale `rand`+//! 0.7 ecosystem: `rand`, `rand_chacha` 0.2, `rand_core` 0.5, `rand_hc`,+//! `rand_xorshift`, `ppv-lite86`, `getrandom` 0.1 — 8 crates for a 256-byte+//! permutation table).+//!+//! The noise math (gradient scheme, quintic fade, √N scaling, hash fold, output+//! range and clamp) is reproduced **exactly** from `noise` 0.8, so 2D/3D output+//! is character- and range-identical. The only difference is how the per-seed+//! permutation table is built: `noise` seeded a `XorShiftRng` and ran rand 0.7's+//! Fisher–Yates; we use a SplitMix64-seeded Fisher–Yates instead. Terrain for a+//! given seed therefore differs from the old build going forward — already-saved+//! chunks are loaded from disk and are unaffected.++/// Mirror of `noise::NoiseFn<T>`: a noise source sampled at a point of type `T`.+pub trait NoiseFn<T> {+ fn get(&self, point: T) -> f64;+}++/// Classic 2D/3D Perlin gradient noise, output in `[-1, 1]`.+#[derive(Clone)]+pub struct Perlin {+ /// 256-entry permutation table (same role as `noise`'s `PermutationTable`).+ values: [u8; 256],+}++impl Perlin {+ /// Deterministically build a permutation table from a `u32` seed.+ pub fn new(seed: u32) -> Self {+ let mut values = [0u8; 256];+ for (i, v) in values.iter_mut().enumerate() {+ *v = i as u8;+ }++ // SplitMix64 stream seeded from `seed`.+ let mut state = 0x9E37_79B9_7F4A_7C15u64+ ^ (seed as u64).wrapping_mul(0x2545_F491_4F6C_DD1D);+ let mut next = || -> u64 {+ state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = state;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ };++ // Fisher–Yates.+ for i in (1..256).rev() {+ let j = (next() % (i as u64 + 1)) as usize;+ values.swap(i, j);+ }+ Perlin { values }+ }++ /// Hash fold identical to `noise`'s `PermutationTable::hash`.+ #[inline]+ fn hash2(&self, x: isize, y: isize) -> usize {+ let index = self.values[(x & 0xff) as usize] as usize ^ (y & 0xff) as usize;+ self.values[index] as usize+ }++ #[inline]+ fn hash3(&self, x: isize, y: isize, z: isize) -> usize {+ let a = self.values[(x & 0xff) as usize] as usize ^ (y & 0xff) as usize;+ let index = self.values[a] as usize ^ (z & 0xff) as usize;+ self.values[index] as usize+ }+}++/// Quintic fade `6t⁵ − 15t⁴ + 10t³` (matches `noise`'s `map_quintic`).+#[inline]+fn quintic(t: f64) -> f64 {+ t * t * t * (t * (t * 6.0 - 15.0) + 10.0)+}++/// 2D gradient · vector, matching `noise::core::perlin::perlin_2d`.+#[inline]+fn grad2(perm: usize, x: f64, y: f64) -> f64 {+ match perm & 0b11 {+ 0 => x + y,+ 1 => -x + y,+ 2 => x - y,+ _ => -x - y,+ }+}++/// 3D gradient · vector, matching `noise::core::perlin::perlin_3d`.+#[inline]+fn grad3(perm: usize, x: f64, y: f64, z: f64) -> f64 {+ match perm & 0b1111 {+ 0 | 12 => x + y,+ 1 | 13 => -x + y,+ 2 => x - y,+ 3 => -x - y,+ 4 => x + z,+ 5 => -x + z,+ 6 => x - z,+ 7 => -x - z,+ 8 => y + z,+ 9 | 14 => -y + z,+ 10 => y - z,+ _ => -y - z, // 11 | 15+ }+}++impl NoiseFn<[f64; 2]> for Perlin {+ fn get(&self, point: [f64; 2]) -> f64 {+ // 1/(sqrt(2)/2) = sqrt(2).+ const SCALE_FACTOR: f64 = std::f64::consts::SQRT_2;++ let [px, py] = point;+ let fx = px.floor();+ let fy = py.floor();+ let cx = fx as isize;+ let cy = fy as isize;+ let dx = px - fx;+ let dy = py - fy;++ let g00 = grad2(self.hash2(cx, cy), dx, dy);+ let g10 = grad2(self.hash2(cx + 1, cy), dx - 1.0, dy);+ let g01 = grad2(self.hash2(cx, cy + 1), dx, dy - 1.0);+ let g11 = grad2(self.hash2(cx + 1, cy + 1), dx - 1.0, dy - 1.0);++ let u = quintic(dx);+ let v = quintic(dy);++ let k0 = g00;+ let k1 = g10 - g00;+ let k2 = g01 - g00;+ let k3 = g00 + g11 - g10 - g01;+ let unscaled = k0 + k1 * u + k2 * v + k3 * u * v;++ (unscaled * SCALE_FACTOR).clamp(-1.0, 1.0)+ }+}++impl NoiseFn<[f64; 3]> for Perlin {+ fn get(&self, point: [f64; 3]) -> f64 {+ // 2/sqrt(3), high-precision constant per the noise crate.+ const SCALE_FACTOR: f64 = 1.154_700_538_379_251_5;++ let [px, py, pz] = point;+ let fx = px.floor();+ let fy = py.floor();+ let fz = pz.floor();+ let cx = fx as isize;+ let cy = fy as isize;+ let cz = fz as isize;+ let dx = px - fx;+ let dy = py - fy;+ let dz = pz - fz;++ let g000 = grad3(self.hash3(cx, cy, cz), dx, dy, dz);+ let g100 = grad3(self.hash3(cx + 1, cy, cz), dx - 1.0, dy, dz);+ let g010 = grad3(self.hash3(cx, cy + 1, cz), dx, dy - 1.0, dz);+ let g110 = grad3(self.hash3(cx + 1, cy + 1, cz), dx - 1.0, dy - 1.0, dz);+ let g001 = grad3(self.hash3(cx, cy, cz + 1), dx, dy, dz - 1.0);+ let g101 = grad3(self.hash3(cx + 1, cy, cz + 1), dx - 1.0, dy, dz - 1.0);+ let g011 = grad3(self.hash3(cx, cy + 1, cz + 1), dx, dy - 1.0, dz - 1.0);+ let g111 = grad3(self.hash3(cx + 1, cy + 1, cz + 1), dx - 1.0, dy - 1.0, dz - 1.0);++ let a = quintic(dx);+ let b = quintic(dy);+ let c = quintic(dz);++ let k0 = g000;+ let k1 = g100 - g000;+ let k2 = g010 - g000;+ let k3 = g001 - g000;+ let k4 = g000 + g110 - g100 - g010;+ let k5 = g000 + g101 - g100 - g001;+ let k6 = g000 + g011 - g010 - g001;+ let k7 = g100 + g010 + g001 + g111 - g000 - g110 - g101 - g011;++ let unscaled =+ k0 + k1 * a + k2 * b + k3 * c + k4 * a * b + k5 * a * c + k6 * b * c + k7 * a * b * c;++ (unscaled * SCALE_FACTOR).clamp(-1.0, 1.0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn output_in_range_and_deterministic() {+ let p = Perlin::new(1337);+ let p2 = Perlin::new(1337);+ for i in 0..50 {+ let x = i as f64 * 0.37;+ let y = i as f64 * -0.21 + 3.0;+ let z = i as f64 * 0.11;+ let a = p.get([x, y]);+ let b = p.get([x, y, z]);+ assert!((-1.0..=1.0).contains(&a));+ assert!((-1.0..=1.0).contains(&b));+ // Same seed → identical output.+ assert_eq!(a, p2.get([x, y]));+ assert_eq!(b, p2.get([x, y, z]));+ }+ }++ #[test]+ fn integer_lattice_points_are_zero() {+ // Perlin noise is exactly 0 at integer lattice points.+ let p = Perlin::new(42);+ assert!(p.get([3.0, -5.0]).abs() < 1e-12);+ assert!(p.get([1.0, 2.0, 3.0]).abs() < 1e-12);+ }++ #[test]+ fn different_seeds_differ() {+ // A single point can coincide across seeds (only 4 gradient choices),+ // so compare the fields over a range of points.+ let a = Perlin::new(1);+ let b = Perlin::new(2);+ let any_diff = (0..64).any(|i| {+ let x = i as f64 * 0.13 + 0.5;+ let y = i as f64 * 0.29 + 0.5;+ a.get([x, y]) != b.get([x, y])+ });+ assert!(any_diff, "distinct seeds produced identical noise fields");+ }+}