diff --git a/crates/horizon-client/src/ambience.rs b/crates/horizon-client/src/ambience.rs new file mode 100644 index 000000000..a033606dc --- /dev/null +++ b/crates/horizon-client/src/ambience.rs @@ -0,0 +1,416 @@ +//! The player's ambient sound handlers: `BiomeAmbientSoundsHandler` (biome +//! loops with 40-tick cross-fades, random additions, cave mood) driven by the +//! `minecraft:audio/ambient_sounds` attribute, `UnderwaterAmbientSoundHandler` +//! and the underwater loop (`UnderLiquidAmbientSoundInstance`). +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +/// `AmbientMoodSettings`. +#[derive(Clone, Debug, PartialEq)] +pub struct Mood { + pub sound: String, + pub tick_delay: i32, + pub block_search_extent: i32, + pub offset: f64, +} +/// `AmbientSounds`: the attribute value. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AmbientSounds { + pub r#loop: Option, + pub mood: Option, + /// (sound, tick chance) + pub additions: Vec<(String, f64)>, +} +impl AmbientSounds { + fn parse(v: &Value) -> Self { + let mood = &v["mood"]; + let addition = |a: &Value| Some((a["sound"].as_str()?.to_owned(), a["tick_chance"].as_f64()?)); + Self { + r#loop: v["loop"].as_str().map(str::to_owned), + mood: mood["sound"].as_str().map(|sound| Mood { + sound: sound.to_owned(), + tick_delay: mood["tick_delay"].as_i64().unwrap_or(6000) as i32, + block_search_extent: mood["block_search_extent"].as_i64().unwrap_or(8) as i32, + offset: mood["offset"].as_f64().unwrap_or(2.0), + }), + // A single addition or a list of them. + additions: match &v["additions"] { + Value::Array(list) => list.iter().filter_map(addition).collect(), + single => addition(single).into_iter().collect(), + }, + } + } +} +/// Ambient sound attributes by dimension type and biome. +#[derive(Clone, Debug, Default)] +pub struct AmbientTables { + dimensions: HashMap, + biomes: HashMap, +} +impl AmbientTables { + pub fn load(root: &Path) -> Self { + let read = |dir: &str| -> HashMap { + let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { return HashMap::new() }; + entries + .flatten() + .filter_map(|e| { + let path = e.path(); + let name = path.file_stem()?.to_str()?.to_owned(); + let json: Value = serde_json::from_slice(&fs::read(&path).ok()?).ok()?; + let v = &json["attributes"]["minecraft:audio/ambient_sounds"]; + (!v.is_null()).then(|| (format!("minecraft:{name}"), AmbientSounds::parse(v))) + }) + .collect() + }; + Self { dimensions: read("dimension_type"), biomes: read("worldgen/biome") } + } + /// `EnvironmentAttributes.AMBIENT_SOUNDS` at a position. + pub fn get(&self, dimension: &str, biome: &str) -> AmbientSounds { + self.biomes.get(biome).or_else(|| self.dimensions.get(dimension)).cloned().unwrap_or_default() + } +} +/// The sound engine side of the handlers. +pub trait AmbientOutput { + /// A relative tickable instance; None when it could not start. + fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option; + fn set_volume(&mut self, id: u64, volume: f32); + fn stop(&mut self, id: u64); + fn is_active(&self, id: u64) -> bool; + /// A positional one-shot (`SimpleSoundInstance`, linear attenuation). + fn play_at(&mut self, event: &str, at: [f64; 3]); +} +impl AmbientOutput for crate::audio::Audio { + fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { + crate::audio::Audio::play_tracked(self, event, volume, looping) + } + fn set_volume(&mut self, id: u64, volume: f32) { + self.set_tracked_volume(id, volume); + } + fn stop(&mut self, id: u64) { + self.stop_tracked(id); + } + fn is_active(&self, id: u64) -> bool { + self.tracked_active(id) + } + fn play_at(&mut self, event: &str, at: [f64; 3]) { + self.play(event, Some(at), 1.0, 1.0); + } +} +/// `BiomeAmbientSoundsHandler.LoopSoundInstance`. +struct LoopSound { + id: Option, + fade: i32, + direction: i32, + stopped: bool, +} +impl LoopSound { + fn tick(&mut self) -> f32 { + if self.fade < 0 { + self.stopped = true; + } + self.fade += self.direction; + (self.fade as f32 / 40.0).clamp(0.0, 1.0) + } + fn fade_out(&mut self) { + self.fade = self.fade.min(40); + self.direction = -1; + } + fn fade_in(&mut self) { + self.fade = self.fade.max(0); + self.direction = 1; + } +} +/// What the handlers read about the player and level each tick. +pub struct AmbientContext<'a> { + pub sounds: &'a AmbientSounds, + /// Feet and eye position. + pub position: [f64; 3], + pub eye_y: f64, + pub underwater: bool, + /// Raw (sky, block) light at a block. + pub light: &'a dyn Fn([i32; 3]) -> (u8, u8), +} +/// The local player's ambient sound handlers. +pub struct Ambience { + /// The client level's random. + random: LegacyRandom, + loops: Vec<(String, LoopSound)>, + previous_loop: Option, + pub moodiness: f32, + underwater_delay: i32, + /// The underwater loop instance and its fade. + underwater_loop: Option<(u64, i32)>, + /// UnderLiquidSubSound instances (stop when the player leaves the water). + sub_sounds: Vec, + was_underwater: bool, +} +impl Default for Ambience { + fn default() -> Self { + let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as i64); + Self::new(seed) + } +} +impl Ambience { + pub fn new(seed: i64) -> Self { + Self { + random: LegacyRandom::new(seed), + loops: Vec::new(), + previous_loop: None, + moodiness: 0.0, + underwater_delay: 0, + underwater_loop: None, + sub_sounds: Vec::new(), + was_underwater: false, + } + } + /// Stop everything (leaving the world). + pub fn clear(&mut self, out: &mut impl AmbientOutput) { + for (_, l) in self.loops.drain(..) { + if let Some(id) = l.id { + out.stop(id); + } + } + if let Some((id, _)) = self.underwater_loop.take() { + out.stop(id); + } + for id in self.sub_sounds.drain(..) { + out.stop(id); + } + self.previous_loop = None; + self.moodiness = 0.0; + self.was_underwater = false; + } + /// `LocalPlayer.updateIsUnderwater` enter/exit sounds and loop, then + /// `UnderwaterAmbientSoundHandler`, `BubbleColumn` (absent) and + /// `BiomeAmbientSoundsHandler` ticks, then the tickable instances. + pub fn tick(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { + let feet = ctx.position; + if !self.was_underwater && ctx.underwater { + out.play_at("minecraft:ambient.underwater.enter", feet); + if let Some((id, _)) = self.underwater_loop.take() { + out.stop(id); + } + self.underwater_loop = out.play_tracked("minecraft:ambient.underwater.loop", 0.0, true).map(|id| (id, 0)); + } + if self.was_underwater && !ctx.underwater { + out.play_at("minecraft:ambient.underwater.exit", feet); + } + self.was_underwater = ctx.underwater; + self.tick_underwater(ctx, out); + self.tick_biome(ctx, out); + self.tick_instances(ctx, out); + } + fn tick_underwater(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { + self.underwater_delay -= 1; + if self.underwater_delay <= 0 && ctx.underwater { + let rand = self.random.next_float(); + let sound = if rand < 1.0E-4 { + Some("minecraft:ambient.underwater.loop.additions.ultra_rare") + } else if rand < 0.001 { + Some("minecraft:ambient.underwater.loop.additions.rare") + } else if rand < 0.01 { + Some("minecraft:ambient.underwater.loop.additions") + } else { + None + }; + if let Some(sound) = sound { + self.underwater_delay = 0; + if let Some(id) = out.play_tracked(sound, 1.0, false) { + self.sub_sounds.push(id); + } + } + } + } + fn tick_biome(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { + self.loops.retain(|(_, l)| !l.stopped); + let sounds = ctx.sounds; + if sounds.r#loop != self.previous_loop { + self.previous_loop = sounds.r#loop.clone(); + for (_, l) in &mut self.loops { + l.fade_out(); + } + if let Some(event) = &sounds.r#loop { + if !self.loops.iter().any(|(e, _)| e == event) { + let id = out.play_tracked(event, 0.0, true); + self.loops.push((event.clone(), LoopSound { id, fade: 0, direction: 0, stopped: false })); + } + if let Some((_, l)) = self.loops.iter_mut().find(|(e, _)| e == event) { + l.fade_in(); + } + } + } + for (sound, chance) in &sounds.additions { + if self.random.next_double() < *chance { + if let Some(id) = out.play_tracked(sound, 1.0, false) { + // forAmbientAddition: a one-shot nobody ticks. + let _ = id; + } + } + } + let Some(mood) = &sounds.mood else { return }; + let extent = mood.block_search_extent; + let span = extent * 2 + 1; + let mut offset = || self.random.next_int_bound(span).unwrap_or(0) - extent; + let (dx, dy, dz) = (offset(), offset(), offset()); + let sample = [ + (ctx.position[0] + f64::from(dx)).floor() as i32, + (ctx.eye_y + f64::from(dy)).floor() as i32, + (ctx.position[2] + f64::from(dz)).floor() as i32, + ]; + let (sky, block) = (ctx.light)(sample); + if sky > 0 { + self.moodiness -= f32::from(sky) / 15.0 * 0.001; + } else { + self.moodiness -= (f32::from(block) - 1.0) / mood.tick_delay as f32; + } + if self.moodiness >= 1.0 { + let d = [ + f64::from(sample[0]) + 0.5 - ctx.position[0], + f64::from(sample[1]) + 0.5 - ctx.eye_y, + f64::from(sample[2]) + 0.5 - ctx.position[2], + ]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let source = distance + mood.offset; + out.play_at( + &mood.sound, + [ + ctx.position[0] + d[0] / distance * source, + ctx.eye_y + d[1] / distance * source, + ctx.position[2] + d[2] / distance * source, + ], + ); + self.moodiness = 0.0; + } else { + self.moodiness = self.moodiness.max(0.0); + } + } + /// The tickable instances' own ticks (SoundEngine.tickInGameSound). + fn tick_instances(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { + for (_, l) in &mut self.loops { + let volume = l.tick(); + if let Some(id) = l.id { + if l.stopped { + out.stop(id); + } else { + out.set_volume(id, volume); + } + } + } + // UnderLiquidAmbientSoundInstance: +1 per tick under water, -2 out of it. + if let Some((id, fade)) = self.underwater_loop.as_mut() { + if *fade >= 0 { + *fade += if ctx.underwater { 1 } else { -2 }; + *fade = (*fade).min(40); + out.set_volume(*id, (*fade as f32 / 40.0).clamp(0.0, 1.0)); + } else { + out.stop(*id); + self.underwater_loop = None; + } + } + // UnderLiquidSubSound: stops when the player leaves the water. + self.sub_sounds.retain(|&id| { + let keep = ctx.underwater && out.is_active(id); + if !keep { + out.stop(id); + } + keep + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Fake { + next: u64, + live: HashMap, + at: Vec, + } + impl AmbientOutput for Fake { + fn play_tracked(&mut self, event: &str, volume: f32, _looping: bool) -> Option { + self.next += 1; + self.live.insert(self.next, (event.to_owned(), volume)); + Some(self.next) + } + fn set_volume(&mut self, id: u64, volume: f32) { + if let Some(v) = self.live.get_mut(&id) { + v.1 = volume; + } + } + fn stop(&mut self, id: u64) { + self.live.remove(&id); + } + fn is_active(&self, id: u64) -> bool { + self.live.contains_key(&id) + } + fn play_at(&mut self, event: &str, _at: [f64; 3]) { + self.at.push(event.to_owned()); + } + } + fn ctx<'a>(sounds: &'a AmbientSounds, underwater: bool, light: &'a dyn Fn([i32; 3]) -> (u8, u8)) -> AmbientContext<'a> { + AmbientContext { sounds, position: [0.5, 10.0, 0.5], eye_y: 11.62, underwater, light } + } + + #[test] + fn loops_cross_fade_over_forty_ticks() { + let mut a = Ambience::new(1); + let mut out = Fake::default(); + let dark = |_: [i32; 3]| (15u8, 0u8); + let crimson = AmbientSounds { r#loop: Some("crimson".into()), ..Default::default() }; + for _ in 0..40 { + a.tick(&ctx(&crimson, false, &dark), &mut out); + } + assert_eq!(out.live.values().map(|v| v.1).collect::>(), [1.0]); + let warped = AmbientSounds { r#loop: Some("warped".into()), ..Default::default() }; + for _ in 0..20 { + a.tick(&ctx(&warped, false, &dark), &mut out); + } + let mut volumes: Vec<_> = out.live.values().map(|v| (v.0.clone(), v.1)).collect(); + volumes.sort_by(|x, y| x.0.cmp(&y.0)); + assert_eq!(volumes, [("crimson".to_owned(), 0.5), ("warped".to_owned(), 0.5)]); + for _ in 0..30 { + a.tick(&ctx(&warped, false, &dark), &mut out); + } + assert_eq!(out.live.values().map(|v| v.0.as_str()).collect::>(), ["warped"]); + } + + #[test] + fn mood_builds_in_the_dark_and_plays_a_cave_sound() { + let mut a = Ambience::new(2); + let mut out = Fake::default(); + let cave = |_: [i32; 3]| (0u8, 0u8); + let sounds = AmbientSounds { + mood: Some(Mood { sound: "minecraft:ambient.cave".into(), tick_delay: 6000, block_search_extent: 8, offset: 2.0 }), + ..Default::default() + }; + // Block light 0: +1/6000 per tick (float), so the sound plays around tick 6000. + let mut ticks = 0; + while out.at.is_empty() && ticks < 7000 { + a.tick(&ctx(&sounds, false, &cave), &mut out); + ticks += 1; + } + assert!((5990..=6010).contains(&ticks), "{ticks}"); + assert_eq!(out.at, ["minecraft:ambient.cave"]); + assert_eq!(a.moodiness, 0.0); + } + + #[test] + fn entering_water_plays_enter_and_fades_the_loop_in() { + let mut a = Ambience::new(3); + let mut out = Fake::default(); + let lit = |_: [i32; 3]| (15u8, 0u8); + let none = AmbientSounds::default(); + a.tick(&ctx(&none, true, &lit), &mut out); + assert_eq!(out.at, ["minecraft:ambient.underwater.enter"]); + let id = a.underwater_loop.unwrap().0; + assert_eq!(out.live[&id].1, 1.0 / 40.0); + a.tick(&ctx(&none, false, &lit), &mut out); + assert_eq!(out.at.last().unwrap(), "minecraft:ambient.underwater.exit"); + // Fade 1 -> -1 stops on the next tick. + a.tick(&ctx(&none, false, &lit), &mut out); + assert!(!out.live.contains_key(&id)); + } +} diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index b790ffc05..77408d411 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -30,6 +30,24 @@ struct Voice { #[derive(Default)] struct Mixer { voices: Vec, + /// The streaming music track (`SoundSource.MUSIC`), kept apart from the + /// voice cap and scaled by `music_gain` (MusicManager's fade). + music: Option, + music_gain: f32, + /// Tickable sound instances the game keeps a handle to (ambient loops). + tracked: Vec, +} +struct Tracked { + id: u64, + voice: Voice, + looping: bool, + volume: f32, +} +/// The current music track: decoding on a worker until the voice exists. +struct MusicTrack { + event: String, + /// Set by the decoder thread once the voice is in the mixer (or failed). + ready: Arc, } pub struct Audio { _stream: Option, @@ -42,6 +60,8 @@ pub struct Audio { pub listener: [f64; 3], pub listener_yaw: f32, pub master: f32, + music: Option, + next_tracked: u64, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -111,7 +131,7 @@ impl Audio { events.insert(format!("minecraft:{name}"), variants); } } - let mixer = Arc::new(Mutex::new(Mixer::default())); + let mixer = Arc::new(Mutex::new(Mixer { music_gain: 1.0, ..Mixer::default() })); let (stream, rate) = match Self::open(mixer.clone()) { Ok(v) => (Some(v.0), v.1), Err(e) => { @@ -130,6 +150,8 @@ impl Audio { listener: [0.0; 3], listener_yaw: 0.0, master: 1.0, + music: None, + next_tracked: 0, } } fn open(mixer: Arc>) -> Result<(cpal::Stream, u32)> { @@ -156,6 +178,32 @@ impl Audio { r += s * v.right; v.position += v.step; } + for t in mixer.tracked.iter_mut() { + let v = &mut t.voice; + let mut i = v.position as usize; + if t.looping && i + 1 >= v.samples.len() { + v.position = 0.0; + i = 0; + } + if i + 1 < v.samples.len() { + let f = (v.position - i as f64) as f32; + let s = (v.samples[i] * (1.0 - f) + v.samples[i + 1] * f) * t.volume; + l += s * v.left; + r += s * v.right; + v.position += v.step; + } + } + let gain = mixer.music_gain; + if let Some(v) = mixer.music.as_mut() { + let i = v.position as usize; + if i + 1 < v.samples.len() { + let t = (v.position - i as f64) as f32; + let s = (v.samples[i] * (1.0 - t) + v.samples[i + 1] * t) * gain; + l += s * v.left; + r += s * v.right; + v.position += v.step; + } + } if channels >= 2 { frame[0] = l.clamp(-1.0, 1.0); frame[1] = r.clamp(-1.0, 1.0); @@ -164,6 +212,10 @@ impl Audio { } } mixer.voices.retain(|v| (v.position as usize) + 1 < v.samples.len()); + mixer.tracked.retain(|t| t.looping || (t.voice.position as usize) + 1 < t.voice.samples.len()); + if mixer.music.as_ref().is_some_and(|v| (v.position as usize) + 1 >= v.samples.len()) { + mixer.music = None; + } }, |e| eprintln!("Horizon: audio stream error: {e}"), None, @@ -244,4 +296,110 @@ impl Audio { }); } } + /// `SoundManager.play` of a music instance (`SimpleSoundInstance.forMusic`: + /// non-positional, streamed). Decoding runs on a worker thread; the track + /// counts as active from now on. Returns false when nothing can play. + pub fn play_music(&mut self, event: &str) -> bool { + self.stop_music(); + if self._stream.is_none() { + return false; + } + let Some(variant) = self.resolve(event, 0) else { return false }; + let path = self.root.join(format!("assets/minecraft/sounds/{}.ogg", variant.name.trim_start_matches("minecraft:"))); + let volume = variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); + let step_scale = f64::from(variant.pitch.clamp(0.5, 2.0)) / f64::from(self.rate); + let ready = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (mixer, done) = (self.mixer.clone(), ready.clone()); + std::thread::spawn(move || { + if let Some((samples, rate)) = decode(&path) + && let Ok(mut m) = mixer.lock() + && !done.load(std::sync::atomic::Ordering::Acquire) + { + m.music = Some(Voice { + samples: Arc::new(samples), + position: 0.0, + step: f64::from(rate) * step_scale, + left: volume, + right: volume, + }); + } + done.store(true, std::sync::atomic::Ordering::Release); + }); + self.music = Some(MusicTrack { event: event.to_owned(), ready }); + true + } + /// `SoundManager.stop` of the music instance. + pub fn stop_music(&mut self) { + if let Some(track) = self.music.take() { + // A decoder still running sees the flag and drops its result. + track.ready.store(true, std::sync::atomic::Ordering::Release); + } + if let Ok(mut m) = self.mixer.lock() { + m.music = None; + } + } + /// `SoundManager.isActive`: decoding or still sounding. + pub fn music_active(&mut self) -> bool { + let Some(track) = &self.music else { return false }; + if !track.ready.load(std::sync::atomic::Ordering::Acquire) { + return true; + } + let playing = self.mixer.lock().is_ok_and(|m| m.music.is_some()); + if !playing { + self.music = None; + } + playing + } + /// The event of the current music track. + pub fn music_event(&self) -> Option<&str> { + self.music.as_ref().map(|t| t.event.as_str()) + } + /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. + pub fn set_music_gain(&mut self, gain: f32) { + if let Ok(mut m) = self.mixer.lock() { + m.music_gain = gain; + } + } + /// Play a relative (non-positional) tickable sound instance the caller + /// keeps a handle to: ambient loops (`looping`) and sub-sounds. + pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { + self._stream.as_ref()?; + let variant = self.resolve(event, 0)?; + let file = variant.name.trim_start_matches("minecraft:").to_owned(); + let root = &self.root; + let (samples, rate) = self + .cache + .entry(file.clone()) + .or_insert_with(|| decode(&root.join(format!("assets/minecraft/sounds/{file}.ogg"))).map(|(s, r)| (Arc::new(s), r))) + .clone()?; + let gain = variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); + let step = f64::from(rate) / f64::from(self.rate) * f64::from(variant.pitch.clamp(0.5, 2.0)); + self.next_tracked += 1; + let id = self.next_tracked; + let mut m = self.mixer.lock().ok()?; + m.tracked.push(Tracked { + id, + voice: Voice { samples, position: 0.0, step, left: gain, right: gain }, + looping, + volume: volume.clamp(0.0, 1.0), + }); + Some(id) + } + /// A tracked instance's volume (`AbstractTickableSoundInstance.volume`). + pub fn set_tracked_volume(&mut self, id: u64, volume: f32) { + if let Ok(mut m) = self.mixer.lock() + && let Some(t) = m.tracked.iter_mut().find(|t| t.id == id) + { + t.volume = volume.clamp(0.0, 1.0); + } + } + pub fn stop_tracked(&mut self, id: u64) { + if let Ok(mut m) = self.mixer.lock() { + m.tracked.retain(|t| t.id != id); + } + } + /// Still sounding (a finished one-shot is gone). + pub fn tracked_active(&self, id: u64) -> bool { + self.mixer.lock().is_ok_and(|m| m.tracked.iter().any(|t| t.id == id)) + } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a9605ec10..c0eef3845 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -24,6 +24,7 @@ mod creatures; mod render_control; mod render_tick; mod sign_edit; +mod music; use horizon_client::{ Result, assets::Assets, @@ -340,6 +341,8 @@ pub struct Resources { block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer, animate: horizon_client::animate_tick::AnimateTables, fog: horizon_client::fog::FogRenderer, + music: horizon_client::music::MusicTables, + ambient: horizon_client::ambience::AmbientTables, screen_fx: horizon_client::screen_effects::ScreenEffects, nether_environment: Environment, end_environment: Environment, @@ -408,6 +411,8 @@ struct Game<'a> { save: Arc, level: Level, audio: Audio, + music: horizon_client::music::MusicManager, + ambience: horizon_client::ambience::Ambience, dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, @@ -3019,6 +3024,7 @@ impl Game<'_> { Ok(()) } fn close_world(&mut self) -> Result<()> { + self.ambience.clear(&mut self.audio); if self.remote.is_some() { return self.leave_server(None); } @@ -4480,7 +4486,9 @@ impl ApplicationHandler for Game<'_> { for _ in 0..steps { if self.title.is_none() { self.tick()?; + self.tick_ambience(); } + self.tick_music(); } let rendered = self.render()?; let finished = self.renderer.as_mut().and_then(|r| r.screenshot_result.take()); @@ -4633,6 +4641,8 @@ pub fn run() -> Result<()> { block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load(&root, ®istry_owner.registry)?, animate, fog, + music: horizon_client::music::MusicTables::load(&root), + ambient: horizon_client::ambience::AmbientTables::load(&root), screen_fx: Default::default(), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, @@ -4708,6 +4718,8 @@ pub fn run() -> Result<()> { save, level, audio, + music: Default::default(), + ambience: Default::default(), dropped: Vec::new(), next_entity: 0, particles, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index cc0f7121b..88b78fe76 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -458,6 +458,7 @@ impl Game<'_> { "frames": self.frames, "ticks": self.ticks, "day_time": self.world.day_time, + "music": self.music.current(), "render_distance": self.streaming.radius, "chunks": self.world.chunks.len(), "pending_chunks": self.streaming.pending(), diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs new file mode 100644 index 000000000..b0198046f --- /dev/null +++ b/crates/horizon-client/src/game/music.rs @@ -0,0 +1,55 @@ +//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager. +use super::Game; +use horizon_client::{blocks::Fluid, music::Music}; + +impl Game<'_> { + /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. + pub(super) fn tick_music(&mut self) { + let (music, volume) = self.situational_music(); + // LevelLoadingScreen: no new track before the player is in the world. + let loading = self.title.is_none() && self.player.is_none(); + self.music.tick(music.as_ref(), volume, loading, &mut self.audio); + } + fn situational_music(&self) -> (Option, f32) { + // Title screen: no player, Musics.MENU at full volume. + if self.title.is_some() { + return (Some(Music::menu()), 1.0); + } + let Some(eye) = self.eye_position() else { return (Some(Music::menu()), 1.0) }; + let (x, y, z) = (eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32); + let biome = self + .world + .chunks + .get(&(x >> 4, z >> 4)) + .map_or("minecraft:plains", |c| self.res.biomes.list[c.biome(x, y, z) as usize].name.as_str()); + let dimension = self.dim.id(); + let tables = &self.res.music; + // Player.isUnderWater: eyes in water. + let underwater = self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water; + let music = tables.background(dimension, biome).select(self.creative, underwater).cloned(); + (music, tables.volume(dimension, biome)) + } +} + +impl Game<'_> { + /// The local player's ambient sound handlers (LocalPlayer.tick). + pub(super) fn tick_ambience(&mut self) { + let Some(p) = self.player.as_ref() else { return }; + let feet = [p.position.x, p.position.y, p.position.z]; + let eye_y = feet[1] + f64::from(p.dimensions.eye_height); + let (x, z) = (feet[0].floor() as i32, feet[2].floor() as i32); + let world = &self.world; + let biome = world + .chunks + .get(&(x >> 4, z >> 4)) + .map_or("minecraft:plains", |c| self.res.biomes.list[c.biome(x, feet[1].floor() as i32, z) as usize].name.as_str()); + let sounds = self.res.ambient.get(self.dim.id(), biome); + let underwater = self.res.facts.get(world.block(x, eye_y.floor() as i32, z)).fluid == Fluid::Water; + let light = |b: [i32; 3]| { + let l = world.light(b[0], b[1], b[2]); + (l >> 4, l & 15) + }; + let ctx = horizon_client::ambience::AmbientContext { sounds: &sounds, position: feet, eye_y, underwater, light: &light }; + self.ambience.tick(&ctx, &mut self.audio); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 3fd072579..d8367363e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -1,6 +1,7 @@ //! Horizon native client: resources, world streaming, rendering and the //! bindings between the validated simulation pieces and the game loop. #![forbid(unsafe_code)] +pub mod ambience; pub mod animate_tick; pub mod assets; pub mod attribute_updates; @@ -39,6 +40,7 @@ pub mod landing; pub mod light; pub mod merchant; pub mod mesher; +pub mod music; pub mod mobs; pub mod models; pub mod motion; diff --git a/crates/horizon-client/src/music.rs b/crates/horizon-client/src/music.rs new file mode 100644 index 000000000..5dfec1571 --- /dev/null +++ b/crates/horizon-client/src/music.rs @@ -0,0 +1,372 @@ +//! Situational music: `MusicManager.tick` choosing tracks from +//! `Minecraft.getSituationalMusic`, with the `minecraft:audio/background_music` +//! and `minecraft:audio/music_volume` environment attributes of dimension +//! types and biomes (a biome value overrides its dimension's). +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +/// `Music`: a sound event and the delay range (ticks) before it starts. +#[derive(Clone, Debug, PartialEq)] +pub struct Music { + pub sound: String, + pub min_delay: i32, + pub max_delay: i32, + pub replace_current_music: bool, +} +impl Music { + fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self { + Self { sound: sound.to_owned(), min_delay, max_delay, replace_current_music } + } + /// `Musics.MENU`. + pub fn menu() -> Self { + Self::new("minecraft:music.menu", 20, 600, true) + } + /// `Musics.CREDITS`. + pub fn credits() -> Self { + Self::new("minecraft:music.credits", 0, 0, true) + } + /// `Musics.END_BOSS`. + pub fn end_boss() -> Self { + Self::new("minecraft:music.dragon", 0, 0, true) + } + /// `Music.CODEC`. + fn parse(v: &Value) -> Option { + let sound = v["sound"].as_str()?; + let int = |k: &str| v[k].as_i64().unwrap_or(0) as i32; + Some(Self::new(sound, int("min_delay"), int("max_delay"), v["replace_current_music"].as_bool().unwrap_or(false))) + } +} +/// `BackgroundMusic`: the attribute value. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BackgroundMusic { + pub default: Option, + pub creative: Option, + pub underwater: Option, +} +impl BackgroundMusic { + fn parse(v: &Value) -> Self { + Self { + default: Music::parse(&v["default"]), + creative: Music::parse(&v["creative"]), + underwater: Music::parse(&v["underwater"]), + } + } + /// `BackgroundMusic.select`. + pub fn select(&self, creative: bool, underwater: bool) -> Option<&Music> { + if underwater && self.underwater.is_some() { + self.underwater.as_ref() + } else if creative && self.creative.is_some() { + self.creative.as_ref() + } else { + self.default.as_ref() + } + } +} +#[derive(Clone, Debug, Default)] +struct Layer { + music: Option, + volume: Option, +} +impl Layer { + fn parse(json: &Value) -> Self { + let attributes = &json["attributes"]; + let music = &attributes["minecraft:audio/background_music"]; + Self { + music: (!music.is_null()).then(|| BackgroundMusic::parse(music)), + volume: attributes["minecraft:audio/music_volume"].as_f64().map(|v| v.clamp(0.0, 1.0) as f32), + } + } +} +/// Music attributes by dimension type and biome. +#[derive(Clone, Debug, Default)] +pub struct MusicTables { + dimensions: HashMap, + biomes: HashMap, +} +impl MusicTables { + pub fn load(root: &Path) -> Self { + let read = |dir: &str| -> HashMap { + let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { return HashMap::new() }; + entries + .flatten() + .filter_map(|e| { + let path = e.path(); + let name = path.file_stem()?.to_str()?.to_owned(); + let json: Value = serde_json::from_slice(&fs::read(&path).ok()?).ok()?; + Some((format!("minecraft:{name}"), Layer::parse(&json))) + }) + .collect() + }; + Self { dimensions: read("dimension_type"), biomes: read("worldgen/biome") } + } + /// `EnvironmentAttributes.BACKGROUND_MUSIC` at a position. + pub fn background(&self, dimension: &str, biome: &str) -> BackgroundMusic { + self.biomes + .get(biome) + .and_then(|l| l.music.clone()) + .or_else(|| self.dimensions.get(dimension).and_then(|l| l.music.clone())) + .unwrap_or_default() + } + /// `EnvironmentAttributes.MUSIC_VOLUME` at a position (default 1). + pub fn volume(&self, dimension: &str, biome: &str) -> f32 { + self.biomes + .get(biome) + .and_then(|l| l.volume) + .or_else(|| self.dimensions.get(dimension).and_then(|l| l.volume)) + .unwrap_or(1.0) + } +} +/// `MusicManager.MusicFrequency` (the `musicFrequency` option). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MusicFrequency { + #[default] + Default, + Frequent, + Constant, +} +impl MusicFrequency { + pub fn parse(name: &str) -> Self { + match name { + "FREQUENT" => Self::Frequent, + "CONSTANT" => Self::Constant, + _ => Self::Default, + } + } + fn max_frequency(self) -> i32 { + match self { + Self::Default => 20 * 1200, + Self::Frequent => 10 * 1200, + Self::Constant => 0, + } + } + fn next_song_delay(self, music: Option<&Music>, random: &mut LegacyRandom) -> i32 { + let Some(music) = music else { return self.max_frequency() }; + if self == Self::Constant { + return 100; + } + let min = music.min_delay.min(self.max_frequency()); + let max = music.max_delay.min(self.max_frequency()); + next_int(random, min, max) + } +} +/// `Mth.nextInt(random, min, max)`: inclusive. +fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { + if min >= max { min } else { random.next_int_bound(max - min + 1).unwrap_or(0) + min } +} +/// What the music manager drives (the sound engine's music channel). +pub trait MusicOutput { + /// Start a track; false when nothing can play. + fn play(&mut self, event: &str) -> bool; + fn stop(&mut self); + fn is_active(&mut self) -> bool; + /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. + fn set_gain(&mut self, gain: f32); +} +impl MusicOutput for crate::audio::Audio { + fn play(&mut self, event: &str) -> bool { + self.play_music(event) + } + fn stop(&mut self) { + self.stop_music(); + } + fn is_active(&mut self) -> bool { + self.music_active() + } + fn set_gain(&mut self, gain: f32) { + self.set_music_gain(gain); + } +} +/// `MusicManager`. +pub struct MusicManager { + random: LegacyRandom, + /// The sound event of the current track. + current: Option, + current_gain: f32, + next_song_delay: i32, + pub frequency: MusicFrequency, +} +impl Default for MusicManager { + fn default() -> Self { + // RandomSource.create(): seeded from the clock, not the world. + let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as i64); + Self::new(seed) + } +} +impl MusicManager { + pub fn new(seed: i64) -> Self { + Self { + random: LegacyRandom::new(seed), + current: None, + current_gain: 1.0, + next_song_delay: 100, + frequency: MusicFrequency::Default, + } + } + pub fn current(&self) -> Option<&str> { + self.current.as_deref() + } + /// `MusicManager.tick` with the situational music and music volume; + /// `loading` holds back a new track (`LevelLoadingScreen`). + pub fn tick(&mut self, music: Option<&Music>, volume: f32, loading: bool, out: &mut impl MusicOutput) { + if self.current.is_some() && self.current_gain != volume && !self.fade(volume, music, out) { + return; + } + let Some(music) = music else { + self.next_song_delay = self.next_song_delay.max(100); + return; + }; + if let Some(current) = &self.current { + if music.replace_current_music && music.sound != *current { + out.stop(); + self.next_song_delay = next_int(&mut self.random, 0, music.min_delay / 2); + } + if !out.is_active() { + self.current = None; + let delay = self.frequency.next_song_delay(Some(music), &mut self.random); + self.next_song_delay = self.next_song_delay.min(delay); + } + } + self.next_song_delay = self.next_song_delay.min(music.max_delay); + if self.current.is_none() && !loading { + self.next_song_delay -= 1; + if self.next_song_delay <= 0 { + self.start(music, out); + } + } + } + /// `MusicManager.startPlaying`. + fn start(&mut self, music: &Music, out: &mut impl MusicOutput) { + // The instance is current even if it could not start; the next tick + // finds it inactive and schedules another. + out.play(&music.sound); + self.current = Some(music.sound.clone()); + self.next_song_delay = i32::MAX; + } + /// `MusicManager.stopPlaying`. + pub fn stop(&mut self, situational: Option<&Music>, out: &mut impl MusicOutput) { + if self.current.take().is_some() { + out.stop(); + } + self.next_song_delay = self.frequency.next_song_delay(situational, &mut self.random) + 100; + } + /// `MusicManager.fadePlaying`: false once the track faded out and stopped. + fn fade(&mut self, volume: f32, situational: Option<&Music>, out: &mut impl MusicOutput) -> bool { + if self.current.is_none() { + return false; + } + if self.current_gain == volume { + return true; + } + if self.current_gain < volume { + self.current_gain += self.current_gain.clamp(5.0E-4, 0.005); + if self.current_gain > volume { + self.current_gain = volume; + } + } else { + self.current_gain = 0.03 * volume + 0.97 * self.current_gain; + if (self.current_gain - volume).abs() < 1.0E-4 || self.current_gain < volume { + self.current_gain = volume; + } + } + self.current_gain = self.current_gain.clamp(0.0, 1.0); + if self.current_gain <= 1.0E-4 { + self.stop(situational, out); + false + } else { + out.set_gain(self.current_gain); + true + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Fake { + playing: Option, + started: Vec, + gain: f32, + } + impl MusicOutput for Fake { + fn play(&mut self, event: &str) -> bool { + self.playing = Some(event.to_owned()); + self.started.push(event.to_owned()); + true + } + fn stop(&mut self) { + self.playing = None; + } + fn is_active(&mut self) -> bool { + self.playing.is_some() + } + fn set_gain(&mut self, gain: f32) { + self.gain = gain; + } + } + + #[test] + fn menu_music_starts_within_its_delay_and_game_music_replaces_nothing() { + let mut m = MusicManager::new(1); + let mut out = Fake::default(); + let menu = Music::menu(); + // nextSongDelay starts at 100, capped to MENU's max delay 600: starts on tick 100. + for _ in 0..99 { + m.tick(Some(&menu), 1.0, false, &mut out); + } + assert!(out.started.is_empty()); + m.tick(Some(&menu), 1.0, false, &mut out); + assert_eq!(out.started, ["minecraft:music.menu"]); + // Game music does not replace the current track. + let game = Music::new("minecraft:music.game", 12000, 24000, false); + m.tick(Some(&game), 1.0, false, &mut out); + assert_eq!(m.current(), Some("minecraft:music.menu")); + // When the menu track ends, the next delay comes from the game music range. + out.playing = None; + m.tick(Some(&game), 1.0, false, &mut out); + assert!(m.current().is_none()); + assert!((12000..=24000).contains(&m.next_song_delay)); + } + + #[test] + fn replacing_music_stops_the_current_track() { + let mut m = MusicManager::new(2); + let mut out = Fake::default(); + m.start(&Music::menu(), &mut out); + let end = Music::new("minecraft:music.end", 6000, 24000, true); + m.tick(Some(&end), 1.0, false, &mut out); + assert!(out.playing.is_none()); + assert!(m.current().is_none()); + assert!(m.next_song_delay <= 3000); + } + + #[test] + fn zero_music_volume_fades_out_and_stops() { + let mut m = MusicManager::new(3); + let mut out = Fake::default(); + let game = Music::new("minecraft:music.game", 12000, 24000, false); + m.start(&game, &mut out); + let mut ticks = 0; + while m.current().is_some() && ticks < 1000 { + m.tick(Some(&game), 0.0, false, &mut out); + ticks += 1; + } + // 0.97^n < 1e-4 after ~303 ticks. + assert!((290..=310).contains(&ticks), "{ticks}"); + assert!(out.playing.is_none()); + } + + #[test] + fn select_prefers_underwater_then_creative() { + let bg = BackgroundMusic { + default: Some(Music::new("a", 0, 0, false)), + creative: Some(Music::new("b", 0, 0, false)), + underwater: Some(Music::new("c", 0, 0, false)), + }; + assert_eq!(bg.select(true, true).unwrap().sound, "c"); + assert_eq!(bg.select(true, false).unwrap().sound, "b"); + assert_eq!(bg.select(false, false).unwrap().sound, "a"); + } +}