voxels: add footsteps, cave ambience and Matcha's eerie score
- Commit
87ea78144c35952c7775732c10e8d326241ab7d2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 17:11 UTC (4 months ago)
- Parents
a1b01ed
Diff
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 fe5b5033f7..cf4b21faa0 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@@ -78,9 +78,29 @@ class MainActivity : ComponentActivity() { LaunchedEffect(Unit) { var prevHp = 20f+ // Footsteps and atmosphere cues arrive as monotonic counters; a change means the+ // engine wants a sound. See ambience.rs.+ var prevStep = -1+ var prevCue = -1 while (isActive) { if (VoxelsNative.isAvailable) { try {+ try {+ val amb = org.json.JSONObject(VoxelsNative.getAmbienceJson())+ val stepN = amb.optInt("stepN", prevStep)+ if (prevStep >= 0 && stepN != prevStep) {+ com.vayunmathur.games.voxels.util.SoundFx.playStep(amb.optInt("stepMat", 0))+ }+ prevStep = stepN+ val cueN = amb.optInt("cueN", prevCue)+ if (prevCue >= 0 && cueN != prevCue) {+ when (amb.optInt("cueKind", 0)) {+ 1 -> com.vayunmathur.games.voxels.util.SoundFx.playCave()+ 2 -> com.vayunmathur.games.voxels.util.SoundFx.playStalk()+ }+ }+ prevCue = cueN+ } catch (_: Exception) {} inventoryJson = VoxelsNative.getInventoryJson() debugJson = VoxelsNative.getDebugJson() if (furnaceOpen) smeltJson = VoxelsNative.getSmeltJson()
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.ktindex f93a4fdc61..f39bdac9e7 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt@@ -17,6 +17,10 @@ object SoundFx { private var hurtId = 0 private var eatId = 0 private var explodeId = 0+ // One per surface class (see ambience.rs STEP_*), plus the two atmosphere one-shots.+ private val stepIds = IntArray(6)+ private var caveId = 0+ private var stalkId = 0 fun init(ctx: Context) { if (pool != null) return@@ -27,6 +31,14 @@ object SoundFx { hurtId = p.load(wav(ctx, "vox_hurt.wav", gen(90.0, 0.22, 0.7, true)), 1) eatId = p.load(wav(ctx, "vox_eat.wav", gen(200.0, 0.10, 0.4, true)), 1) explodeId = p.load(wav(ctx, "vox_explode.wav", gen(60.0, 0.5, 0.9, true)), 1)+ for (m in STEP_TIMBRES.indices) {+ val (freq, dur, amp, decay) = STEP_TIMBRES[m]+ stepIds[m] = p.load(wav(ctx, "vox_step$m.wav", step(freq, dur, amp, decay)), 1)+ }+ // Cave ambience: a low, slowly-swelling drone. Stalking: the same idea an octave down and+ // longer, so it reads as something large rather than something dripping.+ caveId = p.load(wav(ctx, "vox_cave.wav", drone(58.0, 2.4, 0.30)), 1)+ stalkId = p.load(wav(ctx, "vox_stalk.wav", drone(31.0, 4.0, 0.42)), 1) pool = p } catch (_: Throwable) {} }@@ -36,6 +48,63 @@ object SoundFx { fun playHurt() { try { pool?.play(hurtId, 0.7f, 0.7f, 1, 0, 1f) } catch (_: Throwable) {} } fun playEat() { try { pool?.play(eatId, 0.5f, 0.5f, 1, 0, 1f) } catch (_: Throwable) {} } fun playExplode() { try { pool?.play(explodeId, 0.9f, 0.9f, 1, 0, 1f) } catch (_: Throwable) {} }+ /// `mat` is an ambience.rs STEP_* class. Each footfall is pitched slightly differently so a walk+ /// doesn't turn into a metronome.+ fun playStep(mat: Int) {+ val id = stepIds.getOrNull(mat) ?: return+ val rate = 0.92f + Random.nextFloat() * 0.16f+ try { pool?.play(id, 0.22f, 0.22f, 0, 0, rate) } catch (_: Throwable) {}+ }+ fun playCave() { try { pool?.play(caveId, 0.35f, 0.35f, 0, 0, 0.9f + Random.nextFloat() * 0.2f) } catch (_: Throwable) {} }+ fun playStalk() { try { pool?.play(stalkId, 0.5f, 0.5f, 0, 0, 0.85f + Random.nextFloat() * 0.3f) } catch (_: Throwable) {} }++ // Per-surface footstep timbre: (base frequency, duration, amplitude, envelope decay). Hard+ // surfaces are short and bright; soft ones are duller and longer.+ private data class Timbre(val freq: Double, val dur: Double, val amp: Double, val decay: Double)+ private val STEP_TIMBRES = arrayOf(+ Timbre(240.0, 0.07, 0.55, 60.0), // stone+ Timbre(170.0, 0.09, 0.50, 45.0), // wood+ Timbre(120.0, 0.11, 0.38, 34.0), // grass+ Timbre(320.0, 0.12, 0.30, 26.0), // sand+ Timbre(420.0, 0.13, 0.26, 22.0), // snow+ Timbre(150.0, 0.16, 0.34, 18.0), // water+ )++ // A footstep is a filtered noise burst with a touch of tone, so surfaces stay distinguishable+ // without sounding like a musical instrument.+ private fun step(freq: Double, dur: Double, amp: Double, decay: Double): ShortArray {+ val n = (SR * dur).toInt()+ val out = ShortArray(n)+ var lp = 0.0+ // Lower base frequency -> heavier low-pass, which is what makes grass sound soft next to stone.+ val k = (freq / 900.0).coerceIn(0.06, 0.7)+ for (i in 0 until n) {+ val t = i.toDouble() / SR+ val noise = Random.nextDouble() * 2.0 - 1.0+ lp += k * (noise - lp)+ val body = lp * 0.85 + sin(2.0 * Math.PI * freq * t) * 0.15+ val env = exp(-t * decay)+ out[i] = (body * env * amp * Short.MAX_VALUE).toInt().coerceIn(-32768, 32767).toShort()+ }+ return out+ }++ // A slow swell: two detuned low sines under a band of noise, faded in and out so it has no attack.+ private fun drone(freq: Double, dur: Double, amp: Double): ShortArray {+ val n = (SR * dur).toInt()+ val out = ShortArray(n)+ var lp = 0.0+ for (i in 0 until n) {+ val t = i.toDouble() / SR+ val u = t / dur+ // Raised-cosine envelope: no click at either end.+ val env = 0.5 - 0.5 * kotlin.math.cos(2.0 * Math.PI * u)+ lp += 0.02 * ((Random.nextDouble() * 2.0 - 1.0) - lp)+ val tone = sin(2.0 * Math.PI * freq * t) * 0.6 + sin(2.0 * Math.PI * freq * 1.013 * t) * 0.4+ out[i] = ((tone * 0.7 + lp * 2.5) * env * amp * Short.MAX_VALUE).toInt().coerceIn(-32768, 32767).toShort()+ }+ return out+ } // Decaying tone (or noise burst); mono 16-bit PCM. private fun gen(freq: Double, dur: Double, amp: Double, noise: Boolean): ShortArray {
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.ktindex dc9a439ae0..dd98fa7e74 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt@@ -44,6 +44,7 @@ object VoxelsNative { // Furnace: recipe catalog, live job state, and start/stop. external fun getSmeltingJson(): String external fun getSmeltJson(): String+ external fun getAmbienceJson(): String external fun startSmelt(recipe: Int, blast: Boolean): Boolean external fun stopSmelt() // Chest containers, keyed by the block the player last opened.
games/voxels/src/main/rust/src/ambience.rs
diff --git a/games/voxels/src/main/rust/src/ambience.rs b/games/voxels/src/main/rust/src/ambience.rsnew file mode 100644index 0000000000..3a7e5e233d--- /dev/null+++ b/games/voxels/src/main/rust/src/ambience.rs@@ -0,0 +1,186 @@+// Atmosphere: footsteps, cave ambience, and Matcha's eerie score.+//+// Matcha's signature mood system is `set_eerie_score` / `village_eerie_sound` / `initial_stalking`: a+// scalar that builds while the player is somewhere dark and lonely and drives occasional stalking+// sounds. This is that idea, plus the footstep and cave-ambience sounds the pack also adds.+//+// Nothing here plays audio. The engine advances the state and publishes counters; the Kotlin side+// edge-detects them and synthesises the sound (see `util/SoundFx.kt` — this game has no audio assets+// and doesn't need any).++/// Surface classes a footstep can land on. The Kotlin synthesiser picks a timbre per class.+pub const STEP_STONE: u8 = 0;+pub const STEP_WOOD: u8 = 1;+pub const STEP_GRASS: u8 = 2;+pub const STEP_SAND: u8 = 3;+pub const STEP_SNOW: u8 = 4;+pub const STEP_WATER: u8 = 5;++/// One-shot cues, distinct from the per-step sound.+pub const CUE_NONE: u8 = 0;+pub const CUE_CAVE: u8 = 1;+pub const CUE_STALK: u8 = 2;++/// Blocks travelled between footfalls.+const STRIDE: f32 = 2.2;+/// The eerie score has to reach this before anything starts stalking you.+pub const STALK_AT: f32 = 0.55;+const EERIE_DARK_RISE: f32 = 0.045;+const EERIE_DEEP_RISE: f32 = 0.055;+const EERIE_DECAY: f32 = 0.11;+/// Gap between one-shots at minimum and maximum dread.+const CUE_GAP_CALM: f32 = 46.0;+const CUE_GAP_TENSE: f32 = 13.0;++/// What a footstep on this block should sound like.+pub fn step_material(id: u8) -> u8 {+ match id {+ 12 => STEP_WATER,+ 11 | 42 | 43 | 44 => STEP_SNOW,+ 6 | 14 | 36 | 37 | 38 | 79 => STEP_SAND,+ 4 | 10 | 26 | 27 | 29 | 30 | 33 | 34 | 47 | 49 | 50 | 51 | 52 | 82 => STEP_WOOD,+ 2 | 3 | 5 | 28 | 31 | 39 | 40 | 41 | 45 | 46 | 48 | 58 | 59 | 60 | 66 | 71 | 72 | 80 => STEP_GRASS,+ _ => STEP_STONE,+ }+}++/// Advance the eerie score. It climbs in the dark, climbs faster underground, and burns off in+/// daylight — so the dread is something the player can walk out of.+pub fn eerie_step(score: f32, dark: bool, deep: bool, dt: f32) -> f32 {+ let rate = if dark || deep {+ (if dark { EERIE_DARK_RISE } else { 0.0 }) + (if deep { EERIE_DEEP_RISE } else { 0.0 })+ } else {+ -EERIE_DECAY+ };+ (score + rate * dt).clamp(0.0, 1.0)+}++/// How long to wait before the next one-shot. The more dread, the closer together they come.+pub fn cue_gap(score: f32) -> f32 {+ let t = score.clamp(0.0, 1.0);+ CUE_GAP_CALM + (CUE_GAP_TENSE - CUE_GAP_CALM) * t+}++#[derive(Default)]+pub struct Ambience {+ pub eerie: f32,+ /// Distance walked since the last footfall.+ step_dist: f32,+ /// Monotonic counters. The UI plays a sound whenever one of these changes.+ pub step_n: u32,+ pub step_mat: u8,+ pub cue_n: u32,+ pub cue_kind: u8,+ cue_cd: f32,+}++impl Ambience {+ /// `walked` is the distance covered this tick, `under` the block being stood on.+ #[allow(clippy::too_many_arguments)]+ pub fn tick(&mut self, dt: f32, walked: f32, on_ground: bool, under: u8, dark: bool, deep: bool, roll: f32) {+ if on_ground && under != 0 {+ self.step_dist += walked;+ if self.step_dist >= STRIDE {+ self.step_dist = 0.0;+ self.step_mat = step_material(under);+ self.step_n = self.step_n.wrapping_add(1);+ }+ } else {+ // Falling or flying: land on the next surface with a fresh stride rather than mid-cycle.+ self.step_dist = 0.0;+ }++ self.eerie = eerie_step(self.eerie, dark, deep, dt);+ self.cue_cd -= dt;+ if self.cue_cd <= 0.0 {+ self.cue_cd = cue_gap(self.eerie) * (0.6 + 0.8 * roll);+ // Deep and dark gets cave ambience; genuine dread gets something following you.+ self.cue_kind = if self.eerie >= STALK_AT { CUE_STALK } else if deep { CUE_CAVE } else { CUE_NONE };+ if self.cue_kind != CUE_NONE { self.cue_n = self.cue_n.wrapping_add(1); }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dread_builds_in_the_dark_and_burns_off_in_daylight() {+ // A night above ground fills the meter, but not instantly.+ let mut s = 0.0;+ for _ in 0..10 { s = eerie_step(s, true, false, 1.0); }+ assert!(s > 0.0 && s < 0.9, "ten seconds of dark shouldn't max it out, got {s}");++ // Underground in the dark is worse than either alone.+ let dark_only = eerie_step(0.0, true, false, 1.0);+ let both = eerie_step(0.0, true, true, 1.0);+ assert!(both > dark_only);++ // It saturates rather than running away.+ let mut s = 0.0;+ for _ in 0..10_000 { s = eerie_step(s, true, true, 1.0); }+ assert_eq!(s, 1.0);++ // And daylight clears it, down to zero and no further.+ let mut s = 1.0;+ for _ in 0..10_000 { s = eerie_step(s, false, false, 1.0); }+ assert_eq!(s, 0.0);+ }++ #[test]+ fn cues_come_faster_the_more_frightened_you_are() {+ assert!(cue_gap(0.0) > cue_gap(1.0));+ for t in [0.0f32, 0.3, 0.7, 1.0, -5.0, 9.0] {+ let g = cue_gap(t);+ assert!((CUE_GAP_TENSE..=CUE_GAP_CALM).contains(&g), "gap {g} out of range for {t}");+ }+ }++ #[test]+ fn footsteps_land_one_stride_apart() {+ let mut a = Ambience::default();+ // Walking on grass.+ for _ in 0..100 { a.tick(1.0 / 60.0, 0.05, true, 3, false, false, 0.5); }+ assert_eq!(a.step_mat, STEP_GRASS);+ let walked = 100.0 * 0.05;+ let expected = (walked / STRIDE) as u32;+ assert_eq!(a.step_n, expected, "{walked} blocks should be {expected} steps");++ // Standing still makes no sound.+ let before = a.step_n;+ for _ in 0..600 { a.tick(1.0 / 60.0, 0.0, true, 3, false, false, 0.5); }+ assert_eq!(a.step_n, before);++ // Neither does being airborne, however far you travel.+ for _ in 0..600 { a.tick(1.0 / 60.0, 0.2, false, 3, false, false, 0.5); }+ assert_eq!(a.step_n, before);+ }++ #[test]+ fn the_surface_underfoot_picks_the_sound() {+ assert_eq!(step_material(1), STEP_STONE); // stone+ assert_eq!(step_material(8), STEP_STONE); // cobble+ assert_eq!(step_material(10), STEP_WOOD); // planks+ assert_eq!(step_material(3), STEP_GRASS); // grass+ assert_eq!(step_material(6), STEP_SAND); // sand+ assert_eq!(step_material(11), STEP_SNOW); // snow+ assert_eq!(step_material(12), STEP_WATER); // water+ // Anything unrecognised still makes a noise rather than silence.+ assert_eq!(step_material(200), STEP_STONE);+ }++ // A calm player above ground should never be stalked, and a frightened one always should be.+ #[test]+ fn stalking_only_starts_once_the_dread_is_real() {+ let mut calm = Ambience::default();+ for _ in 0..60 * 300 { calm.tick(1.0 / 60.0, 0.0, true, 3, false, false, 0.5); }+ assert_eq!(calm.cue_n, 0, "nothing should stalk a player standing in daylight");++ let mut spooked = Ambience::default();+ for _ in 0..60 * 300 { spooked.tick(1.0 / 60.0, 0.0, true, 1, true, true, 0.5); }+ assert!(spooked.eerie >= STALK_AT);+ assert!(spooked.cue_n > 0, "five minutes alone in the dark should produce something");+ assert_eq!(spooked.cue_kind, CUE_STALK);+ }+}
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 7330bf19f9..8a7e4aed8e 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -63,6 +63,9 @@ pub struct EngineState { pub weather: u8, pub weather_cd: f32, pub rain: f32,+ // Footsteps, cave ambience and the eerie score; see ambience.rs.+ pub ambience: crate::ambience::Ambience,+ prev_walk: f32, } // One furnace job at a time, owned by the world rather than by a specific furnace block: the player@@ -250,6 +253,8 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { weather_cd: progress.weather_cd.clamp(0.0, WEATHER_MAX_SECS), // Resume mid-downpour rather than fading in from a clear sky. rain: rain_target(progress.weather),+ ambience: crate::ambience::Ambience::default(),+ prev_walk: 0.0, }); INIT_DONE.store(true, Ordering::SeqCst); true@@ -672,6 +677,7 @@ pub fn tick_and_render() { } tick_particles(&mut state.particles, dt); tick_weather(state, dt, player_pos);+ tick_ambience(state, dt, player_pos); let (mut entity_verts, mut entity_indices) = build_entity_mesh(&state.mobs); { let right = state.player.right();@@ -725,6 +731,7 @@ static INV_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static STATS_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static HEALTH_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static SMELT_CACHE: OnceLock<Mutex<String>> = OnceLock::new();+static AMBIENCE_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); fn cref(c: &'static OnceLock<Mutex<String>>, default: &str) -> &'static Mutex<String> { c.get_or_init(|| Mutex::new(default.to_string())) } // Called from the render tick (holds the engine lock) to refresh the UI caches.@@ -791,6 +798,13 @@ fn publish_ui(state: &EngineState) { "blast": sm.blast, }).to_string(); if let Ok(mut c) = cref(&SMELT_CACHE, "{}").lock() { *c = smelt; }+ let a = &state.ambience;+ let ambience = serde_json::json!({+ "stepN": a.step_n, "stepMat": a.step_mat,+ "cueN": a.cue_n, "cueKind": a.cue_kind,+ "eerie": a.eerie, "rain": state.rain,+ }).to_string();+ if let Ok(mut c) = cref(&AMBIENCE_CACHE, "{}").lock() { *c = ambience; } } pub fn get_debug_json() -> String { cref(&DEBUG_CACHE, r#"{"error":"no engine"}"#).lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) }@@ -798,6 +812,7 @@ pub fn get_inventory_json() -> String { cref(&INV_CACHE, r#"{"selected":0,"slots pub fn get_stats_json() -> String { cref(&STATS_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn get_health_json() -> String { cref(&HEALTH_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn get_smelt_json() -> String { cref(&SMELT_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) }+pub fn get_ambience_json() -> String { cref(&AMBIENCE_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn inventory_move(from: usize, to: usize) { with_engine(|s| s.inventory.move_item(from, to)); } pub fn inventory_give(id: u8) { with_engine(|s| s.inventory.give(id)); }@@ -1099,6 +1114,33 @@ fn tick_projectiles(state: &mut EngineState, dt: f32) { } } +// Feed the atmosphere system: how far the player walked, what they're standing on, and how dark and+// deep it is where they are.+fn tick_ambience(state: &mut EngineState, dt: f32, player_pos: Vec3) {+ let walked = (state.player.walk_dist - state.prev_walk).max(0.0);+ state.prev_walk = state.player.walk_dist;++ let (px, pz) = (player_pos.x.floor() as i32, player_pos.z.floor() as i32);+ let under = state.chunks.get_block_world(px, (player_pos.y - 0.1).floor() as i32, pz);++ // "Deep" means genuinely enclosed: a solid ceiling somewhere overhead, well below the surface.+ let head = player_pos.y.floor() as i32 + 2;+ let covered = (head..head + 40).any(|y| {+ let id = state.chunks.get_block_world(px, y, pz);+ id != 0 && Block::from_id(id).blocks_light()+ });+ let deep = covered && player_pos.y < 50.0;+ // The Nether and End are always oppressive; the overworld only after dark.+ let dark = state.dim != 0 || state.is_night();++ let mut r = state.spawn_rng;+ r ^= r << 13; r ^= r >> 17; r ^= r << 5;+ state.spawn_rng = r;+ let roll = (r >> 8) as f32 / 16_777_216.0;++ state.ambience.tick(dt, walked, state.player.on_ground, under, dark, deep, roll);+}+ // Advance the weather random walk and drop precipitation around the player. Only the overworld has a // sky to rain from; the Nether and End are left alone. fn tick_weather(state: &mut EngineState, dt: f32, player_pos: Vec3) {
games/voxels/src/main/rust/src/lib.rs
diff --git a/games/voxels/src/main/rust/src/lib.rs b/games/voxels/src/main/rust/src/lib.rsindex a8d07b9225..490d3a09b7 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -8,6 +8,7 @@ pub mod raycast; pub mod input; pub mod inventory; pub mod villager;+pub mod ambience; pub mod engine; pub mod texture_atlas; pub mod vulkan;@@ -303,6 +304,14 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getSm match env.new_string(engine::get_smelt_json()) { Ok(s) => s.into_raw(), Err(_) => null } } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getAmbienceJson<'l>(+ mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+ let null = std::ptr::null_mut();+ match env.new_string(engine::get_ambience_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_startSmelt<'l>( _env: JNIEnv<'l>, _class: JClass<'l>, recipe: jint, blast: jboolean,