From 13e434d49d48af726a8f4f9d09f98664953956e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:49:11 +0200 Subject: [PATCH] Compare the music manager tick by tick with the real vanilla MusicManager The oracle drives MusicManager over the real SoundEngine with the situation as input; the script covers delays, replacements, frequencies, fades, loading screens, pauses, silent starts, toasts and unplayable events. Co-Authored-By: Claude Opus 5.5 --- .../examples/audio_common/mod.rs | 176 +++++++++++++++++ .../horizon-client/examples/music_fixture.rs | 108 +++++++++++ .../examples/sound_engine_fixture.rs | 177 +----------------- crates/horizon-client/src/game/music.rs | 16 +- .../horizonlab/parity/VanillaMusicOracle.java | 145 ++++++++++++++ tools/test_music_parity.py | 167 +++++++++++++++++ 6 files changed, 611 insertions(+), 178 deletions(-) create mode 100644 crates/horizon-client/examples/audio_common/mod.rs create mode 100644 crates/horizon-client/examples/music_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java create mode 100644 tools/test_music_parity.py diff --git a/crates/horizon-client/examples/audio_common/mod.rs b/crates/horizon-client/examples/audio_common/mod.rs new file mode 100644 index 000000000..3b177eba5 --- /dev/null +++ b/crates/horizon-client/examples/audio_common/mod.rs @@ -0,0 +1,176 @@ +//! Shared by the audio fixtures: a backend recording what an OpenAL source +//! would hold, and the per-step dump the Java oracles print. +#![allow(dead_code)] +use horizon_client::sound_engine::{Backend, ChannelId, InstanceId, PlayResult, SoundEngine}; +use horizon_client::sound_events::Sound; +use std::collections::HashMap; +use std::io::Write; + +const INITIAL: u32 = 0x1011; +const PLAYING: u32 = 0x1012; +const PAUSED: u32 = 0x1013; +const STOPPED: u32 = 0x1014; + +/// An OpenAL source's state as `alGetSource*` reports it. +#[derive(Clone)] +pub struct Source { + pub state: u32, + pub gain: f32, + pub pitch: f32, + pub position: [f32; 3], + pub relative: bool, + pub looping: bool, + pub model: u32, + pub max: f32, + pub rolloff: f32, + pub reference: f32, +} +impl Default for Source { + fn default() -> Self { + Self { + state: INITIAL, + gain: 1.0, + pitch: 1.0, + position: [0.0; 3], + relative: false, + looping: false, + model: 0xD002, + max: f32::MAX, + rolloff: 1.0, + reference: 1.0, + } + } +} +/// Buffers and streams are ready at once (silence in the oracle); stopping an +/// initial source leaves it initial, as in OpenAL Soft. +#[derive(Default)] +pub struct Fake { + pub sources: HashMap, + next: ChannelId, +} +impl Backend for Fake { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + self.sources.insert(self.next, Source::default()); + Some(self.next) + } + fn destroy(&mut self, channel: ChannelId) { + self.sources.remove(&channel); + } + fn set_pitch(&mut self, c: ChannelId, pitch: f32) { + self.sources.get_mut(&c).expect("source").pitch = pitch; + } + fn set_volume(&mut self, c: ChannelId, volume: f32) { + self.sources.get_mut(&c).expect("source").gain = volume; + } + fn set_attenuation(&mut self, c: ChannelId, linear: Option) { + let s = self.sources.get_mut(&c).expect("source"); + match linear { + Some(max) => { + s.model = 0xD003; + s.max = max; + s.rolloff = 1.0; + s.reference = 0.0; + } + None => s.model = 0, + } + } + fn set_looping(&mut self, c: ChannelId, looping: bool) { + self.sources.get_mut(&c).expect("source").looping = looping; + } + fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { + self.sources.get_mut(&c).expect("source").position = + [p[0] as f32, p[1] as f32, p[2] as f32]; + } + fn set_relative(&mut self, c: ChannelId, relative: bool) { + self.sources.get_mut(&c).expect("source").relative = relative; + } + fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { + self.sources.get_mut(&c).expect("source").state = PLAYING; + } + fn stop(&mut self, c: ChannelId) { + if let Some(s) = self.sources.get_mut(&c) + && s.state != INITIAL + { + s.state = STOPPED; + } + } + fn pause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PLAYING { + s.state = PAUSED; + } + } + fn unpause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PAUSED { + s.state = PLAYING; + } + } + fn stopped(&mut self, c: ChannelId) -> bool { + self.sources.get(&c).is_none_or(|s| s.state == STOPPED) + } +} +pub fn bits(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +pub fn f(hex: &str) -> f32 { + f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) +} +pub fn d(hex: &str) -> f64 { + f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) +} +/// The shared per-step dump (instances, notifications, pool counts). +pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { + let mut s = format!(" {name} active={}", engine.is_active(id)); + match engine.channel(id).and_then(|c| backend.sources.get(&c)) { + None => s.push_str(" channel=-"), + Some(src) => s.push_str(&format!( + " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", + src.state, + bits(src.gain), + bits(src.pitch), + bits(src.position[0]), + bits(src.position[1]), + bits(src.position[2]), + u8::from(src.relative), + u8::from(src.looping), + src.model, + bits(src.max), + bits(src.rolloff), + bits(src.reference) + )), + } + s +} +pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { + for n in std::mem::take(&mut engine.notifications) { + writeln!( + out, + "notify {} {} {} {} {:016x} {:016x} {:016x}", + n.identifier, + n.subtitle.as_deref().unwrap_or("-"), + bits(n.range), + n.looping, + n.position[0].to_bits(), + n.position[1].to_bits(), + n.position[2].to_bits() + ) + .expect("write"); + } + let [used, streaming] = engine.used_channels(); + writeln!( + out, + " Sounds: {used}/{} + {streaming}/{}", + engine.limits[0], engine.limits[1] + ) + .expect("write"); +} + +pub fn result_name(r: PlayResult) -> &'static str { + match r { + PlayResult::Started => "STARTED", + PlayResult::StartedSilently => "STARTED_SILENTLY", + PlayResult::NotStarted => "NOT_STARTED", + } +} diff --git a/crates/horizon-client/examples/music_fixture.rs b/crates/horizon-client/examples/music_fixture.rs new file mode 100644 index 000000000..29ccb99b2 --- /dev/null +++ b/crates/horizon-client/examples/music_fixture.rs @@ -0,0 +1,108 @@ +//! Replays `tools/test_music_parity.py` scripts through Horizon's +//! `MusicManager` over its `SoundEngine`: `music_fixture ROOT INPUT OUTPUT`. +#[path = "audio_common/mod.rs"] +mod common; +use common::{Fake, describe, f, flush}; +use horizon_client::music::{Music, MusicFrequency, MusicManager}; +use horizon_client::sound_engine::{Bound, MUSIC, SoundEngine, TickContext}; +use horizon_client::sound_events::SoundRegistry; +use std::io::Write; + +fn music(spec: &str) -> Option { + if spec == "-" { + return None; + } + let p: Vec<&str> = spec.split(',').collect(); + Some(Music::new( + &horizon_client::sound_events::normalize(p[0]), + p[1].parse().expect("min"), + p[2].parse().expect("max"), + p[3] == "1", + )) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); + engine.listening = true; + let mut backend = Fake::default(); + let mut manager = MusicManager::new(0); + let (mut situation, mut volume) = (None::, 1.0f32); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + writeln!(out, "{line}").expect("write"); + let a: Vec<&str> = line.split(' ').collect(); + match a[0] { + "start" => { + if let Some(id) = manager.current_instance() { + engine.release(id); + } + manager = MusicManager::new(a[1].parse().expect("seed")); + manager.frequency = MusicFrequency::parse(a[2]); + engine.stop_all(&mut backend); + } + "situation" => { + situation = music(a[1]); + volume = f(a[2]); + } + "tick" => { + let mut sounds = Bound { + engine: &mut engine, + backend: &mut backend, + }; + manager.tick(situation.as_ref(), volume, a[1] == "1", &mut sounds); + engine.tick(a[2] == "1", &TickContext::default(), &mut backend); + } + "finish" => { + if let Some(c) = manager.current_instance().and_then(|id| engine.channel(id)) { + horizon_client::sound_engine::Backend::stop(&mut backend, c); + } + } + "stop" => manager.stop_playing( + situation.as_ref(), + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ), + "stopmusic" => { + let m = music(a[1]).expect("music"); + manager.stop_playing_music( + &m, + situation.as_ref(), + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); + } + "freq" => manager.set_frequency(MusicFrequency::parse(a[1]), situation.as_ref()), + "toast" => manager.show_now_playing_toast_if_needed(), + "volume" => { + let source: usize = a[1].parse().expect("source"); + engine.source_volumes[source] = f(a[2]); + engine.refresh_category_volume(source, &mut backend); + } + "stopall" => engine.stop_all(&mut backend), + _ => panic!("{line}"), + } + writeln!( + out, + " current={} delay={} gain={:08x} toastShown={} musicGain={:08x}", + manager.current(&engine).unwrap_or("-"), + manager.next_song_delay(), + manager.current_gain().to_bits(), + manager.toast_shown(), + engine.category_gain(MUSIC).to_bits() + ) + .expect("write"); + for show in std::mem::take(&mut manager.toast_requests) { + writeln!(out, " toast {}", if show { "show" } else { "hide" }).expect("write"); + } + if let Some(id) = manager.current_instance() { + writeln!(out, "{}", describe(&engine, &backend, "music", id)).expect("write"); + } + flush(&mut engine, &mut out); + } +} diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/sound_engine_fixture.rs index a9dfbbb02..5bc8f1a61 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/sound_engine_fixture.rs @@ -1,175 +1,17 @@ //! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's //! `SoundEngine` with a backend recording what an OpenAL source would hold: //! `sound_engine_fixture ROOT INPUT OUTPUT`. +#[path = "audio_common/mod.rs"] +mod common; +use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ - Attenuation, Backend, ChannelId, InstanceId, SoundEngine, SoundInstance, TickContext, + Attenuation, Backend, InstanceId, SoundEngine, SoundInstance, TickContext, }; -use horizon_client::sound_events::{Sound, SoundRegistry}; +use horizon_client::sound_events::SoundRegistry; use horizon_core::random::LegacyRandom; -use std::collections::{BTreeMap, HashMap}; +use std::collections::BTreeMap; use std::io::Write; -const INITIAL: u32 = 0x1011; -const PLAYING: u32 = 0x1012; -const PAUSED: u32 = 0x1013; -const STOPPED: u32 = 0x1014; - -/// An OpenAL source's state as `alGetSource*` reports it. -#[derive(Clone)] -pub struct Source { - pub state: u32, - pub gain: f32, - pub pitch: f32, - pub position: [f32; 3], - pub relative: bool, - pub looping: bool, - pub model: u32, - pub max: f32, - pub rolloff: f32, - pub reference: f32, -} -impl Default for Source { - fn default() -> Self { - Self { - state: INITIAL, - gain: 1.0, - pitch: 1.0, - position: [0.0; 3], - relative: false, - looping: false, - model: 0xD002, - max: f32::MAX, - rolloff: 1.0, - reference: 1.0, - } - } -} -/// Buffers and streams are ready at once (silence in the oracle); stopping an -/// initial source leaves it initial, as in OpenAL Soft. -#[derive(Default)] -pub struct Fake { - pub sources: HashMap, - next: ChannelId, -} -impl Backend for Fake { - fn create(&mut self, _streaming: bool) -> Option { - self.next += 1; - self.sources.insert(self.next, Source::default()); - Some(self.next) - } - fn destroy(&mut self, channel: ChannelId) { - self.sources.remove(&channel); - } - fn set_pitch(&mut self, c: ChannelId, pitch: f32) { - self.sources.get_mut(&c).expect("source").pitch = pitch; - } - fn set_volume(&mut self, c: ChannelId, volume: f32) { - self.sources.get_mut(&c).expect("source").gain = volume; - } - fn set_attenuation(&mut self, c: ChannelId, linear: Option) { - let s = self.sources.get_mut(&c).expect("source"); - match linear { - Some(max) => { - s.model = 0xD003; - s.max = max; - s.rolloff = 1.0; - s.reference = 0.0; - } - None => s.model = 0, - } - } - fn set_looping(&mut self, c: ChannelId, looping: bool) { - self.sources.get_mut(&c).expect("source").looping = looping; - } - fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { - self.sources.get_mut(&c).expect("source").position = - [p[0] as f32, p[1] as f32, p[2] as f32]; - } - fn set_relative(&mut self, c: ChannelId, relative: bool) { - self.sources.get_mut(&c).expect("source").relative = relative; - } - fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { - self.sources.get_mut(&c).expect("source").state = PLAYING; - } - fn stop(&mut self, c: ChannelId) { - if let Some(s) = self.sources.get_mut(&c) - && s.state != INITIAL - { - s.state = STOPPED; - } - } - fn pause(&mut self, c: ChannelId) { - let s = self.sources.get_mut(&c).expect("source"); - if s.state == PLAYING { - s.state = PAUSED; - } - } - fn unpause(&mut self, c: ChannelId) { - let s = self.sources.get_mut(&c).expect("source"); - if s.state == PAUSED { - s.state = PLAYING; - } - } - fn stopped(&mut self, c: ChannelId) -> bool { - self.sources.get(&c).is_none_or(|s| s.state == STOPPED) - } -} -fn bits(v: f32) -> String { - format!("{:08x}", v.to_bits()) -} -fn f(hex: &str) -> f32 { - f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) -} -fn d(hex: &str) -> f64 { - f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) -} -/// The shared per-step dump (instances, notifications, pool counts). -pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { - let mut s = format!(" {name} active={}", engine.is_active(id)); - match engine.channel(id).and_then(|c| backend.sources.get(&c)) { - None => s.push_str(" channel=-"), - Some(src) => s.push_str(&format!( - " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", - src.state, - bits(src.gain), - bits(src.pitch), - bits(src.position[0]), - bits(src.position[1]), - bits(src.position[2]), - u8::from(src.relative), - u8::from(src.looping), - src.model, - bits(src.max), - bits(src.rolloff), - bits(src.reference) - )), - } - s -} -pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { - for n in std::mem::take(&mut engine.notifications) { - writeln!( - out, - "notify {} {} {} {} {:016x} {:016x} {:016x}", - n.identifier, - n.subtitle.as_deref().unwrap_or("-"), - bits(n.range), - n.looping, - n.position[0].to_bits(), - n.position[1].to_bits(), - n.position[2].to_bits() - ) - .expect("write"); - } - let [used, streaming] = engine.used_channels(); - writeln!( - out, - " Sounds: {used}/{} + {streaming}/{}", - engine.limits[0], engine.limits[1] - ) - .expect("write"); -} - fn main() { let args: Vec = std::env::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); @@ -264,10 +106,3 @@ fn main() { flush(&mut engine, &mut out); } } -fn result_name(r: horizon_client::sound_engine::PlayResult) -> &'static str { - match r { - horizon_client::sound_engine::PlayResult::Started => "STARTED", - horizon_client::sound_engine::PlayResult::StartedSilently => "STARTED_SILENTLY", - horizon_client::sound_engine::PlayResult::NotStarted => "NOT_STARTED", - } -} diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index a7e054fdb..699996e11 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -1,11 +1,7 @@ //! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager, //! the local player's ambient sound handlers and the sound engine tick. use super::Game; -use horizon_client::{ - blocks::Fluid, - music::Music, - sound_engine::TickContext, -}; +use horizon_client::{blocks::Fluid, music::Music, sound_engine::TickContext}; impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. @@ -59,12 +55,18 @@ impl Game<'_> { } /// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position. fn biome_at(&self, p: [f64; 3]) -> &str { - let (x, y, z) = (p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32); + let (x, y, z) = ( + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ); 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() + self.res.biomes.list[c.biome(x, y, z) as usize] + .name + .as_str() }) } /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java new file mode 100644 index 000000000..19af845e5 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java @@ -0,0 +1,145 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.components.toasts.ToastManager; +import net.minecraft.client.gui.screens.LevelLoadingScreen; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.sounds.MusicManager; +import net.minecraft.client.sounds.SoundEngine; +import net.minecraft.client.sounds.SoundManager; +import net.minecraft.core.Holder; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.Music; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; + +/** + * Drives the real MusicManager over the real SoundEngine (VanillaSoundRig). + * The situation, Minecraft.getSituationalMusic and getMusicVolume, is the + * script's input; the loading screen is a LevelLoadingScreen in the Gui; the + * toast manager records showNowPlayingToast/hideNowPlayingToast. Each client + * tick is musicManager.tick() then soundManager.tick(pause), as Minecraft.tick + * runs them. Prints the manager's state and the music channel every step. + */ +public final class VanillaMusicOracle { + public static final class Mc extends Minecraft { + Music music; + float volume = 1.0F; + + Mc() { + super(null); + } + + @Override + public Music getSituationalMusic() { + return music; + } + + @Override + public float getMusicVolume() { + return volume; + } + } + + public static final class Toasts extends ToastManager { + final List calls = new ArrayList<>(); + + Toasts() { + super(null, null); + } + + @Override + public void showNowPlayingToast() { + calls.add("show"); + } + + @Override + public void hideNowPlayingToast() { + calls.add("hide"); + } + } + + static Music music(String spec) { + if (spec.equals("-")) return null; + String[] p = spec.split(","); + return new Music(Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(p[0]))), Integer.parseInt(p[1]), + Integer.parseInt(p[2]), p[3].equals("1")); + } + + static float f(String hex) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var rig = new VanillaSoundRig(Path.of(args[0])); + Mc mc = VanillaSoundRig.make(Mc.class); + Gui gui = VanillaSoundRig.make(Gui.class); + Toasts toasts = VanillaSoundRig.make(Toasts.class); + VanillaSoundRig.set(toasts, Toasts.class, "calls", new ArrayList()); + VanillaSoundRig.set(gui, Gui.class, "toastManager", toasts); + VanillaSoundRig.set(mc, Minecraft.class, "gui", gui); + VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager); + var loading = VanillaSoundRig.make(LevelLoadingScreen.class); + MusicManager manager = null; + var gains = VanillaSoundRig.field(SoundEngine.class, "gainBySource"); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + for (String line : Files.readAllLines(Path.of(args[1]))) { + out.println(line); + String[] a = line.split(" "); + switch (a[0]) { + case "start" -> { + // A fresh manager: MusicManager(minecraft) with a seeded random. + manager = VanillaSoundRig.make(MusicManager.class); + VanillaSoundRig.set(manager, MusicManager.class, "minecraft", mc); + VanillaSoundRig.set(manager, MusicManager.class, "random", RandomSource.create(Long.parseLong(a[1]))); + VanillaSoundRig.set(manager, MusicManager.class, "gameMusicFrequency", MusicManager.MusicFrequency.valueOf(a[2])); + VanillaSoundRig.set(manager, MusicManager.class, "currentGain", 1.0F); + VanillaSoundRig.set(manager, MusicManager.class, "nextSongDelay", 100); + rig.manager.stop(); + } + case "situation" -> { + mc.music = music(a[1]); + mc.volume = f(a[2]); + } + case "tick" -> { + VanillaSoundRig.set(gui, Gui.class, "screen", a[1].equals("1") ? loading : null); + manager.tick(); + rig.manager.tick(a[2].equals("1")); + } + case "finish" -> { + var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic"); + if (current != null) rig.finish(current); + } + case "stop" -> manager.stopPlaying(); + case "stopmusic" -> manager.stopPlaying(music(a[1])); + case "freq" -> manager.setMinutesBetweenSongs(MusicManager.MusicFrequency.valueOf(a[1])); + case "toast" -> manager.showNowPlayingToastIfNeeded(); + case "volume" -> { + rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]); + } + case "stopall" -> rig.manager.stop(); + default -> throw new IllegalArgumentException(line); + } + var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic"); + out.printf(" current=%s delay=%d gain=%08x toastShown=%s musicGain=%08x%n", current == null ? "-" : current.getIdentifier(), + (int) VanillaSoundRig.get(manager, MusicManager.class, "nextSongDelay"), + Float.floatToRawIntBits((float) VanillaSoundRig.get(manager, MusicManager.class, "currentGain")), + VanillaSoundRig.get(manager, MusicManager.class, "toastShown"), + Float.floatToRawIntBits(((it.unimi.dsi.fastutil.objects.Object2FloatMap) gains.get(rig.engine)).getFloat(SoundSource.MUSIC))); + for (String call : toasts.calls) out.println(" toast " + call); + toasts.calls.clear(); + if (current != null) out.println(rig.describe("music", current)); + rig.flush(out); + } + } + System.exit(0); + } +} diff --git a/tools/test_music_parity.py b/tools/test_music_parity.py new file mode 100644 index 000000000..7d41be5f1 --- /dev/null +++ b/tools/test_music_parity.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Compare the music manager with the vanilla 26.3 client. + +The oracle runs the real `MusicManager` over the real `SoundEngine` (OpenAL +Soft "No Output" device, see VanillaSoundRig). The situation +(`getSituationalMusic`, `getMusicVolume`), the loading screen, pauses, the +end of a track, `stopPlaying`, `setMinutesBetweenSongs`, the music category +volume and `showNowPlayingToastIfNeeded` are script inputs; every step prints +the current track, `nextSongDelay`, `currentGain`, `toastShown`, the toast +calls, the MUSIC category gain and the music channel's AL source. Horizon's +`MusicManager` and `SoundEngine` replay the scripts. Tracks use events whose +variants share one volume, since `forMusic` resolves with an unseeded random. +""" +import random + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + +TRACKS = ['minecraft:music.credits', 'minecraft:music.dragon', 'minecraft:music.end', 'minecraft:music.under_water', + 'minecraft:music.overworld.swamp', 'minecraft:music_disc.cat', 'minecraft:music_disc.13'] +ODD = ['minecraft:music.nether.warped_forest', 'minecraft:not.a.track'] + + +class Script: + def __init__(self): + self.lines = [] + + def add(self, *parts): + self.lines.append(' '.join(map(str, parts))) + + def situation(self, sound=None, lo=0, hi=0, replace=0, volume=1.0): + self.add('situation', '-' if sound is None else f'{sound},{lo},{hi},{replace}', h.bits(volume)) + + def tick(self, n=1, loading=0, paused=0): + for _ in range(n): + self.add('tick', loading, paused) + + +def scripted(s): + end, dragon, water, credits, cat = TRACKS[2], TRACKS[1], TRACKS[3], TRACKS[0], TRACKS[5] + s.add('start', 1, 'DEFAULT') + # Menu-like music: 20..600 ticks, replacing. + s.situation(end, 20, 600, 1) + s.tick(3, loading=1) + s.tick(120) + s.add('finish') + s.tick(650) + # Game music does not replace, and the next delay comes from its range. + s.situation(water, 12000, 24000, 0) + s.tick(5) + s.add('finish') + s.tick(30) + s.add('freq', 'FREQUENT') + s.tick(3) + s.add('freq', 'CONSTANT') + s.tick(110) + s.add('freq', 'DEFAULT') + s.tick(2) + # A replacing track stops the current one over the following ticks. + s.situation(dragon, 0, 0, 1) + s.tick(30) + s.situation(credits, 0, 0, 1) + s.tick(30) + s.situation(None) + s.tick(5) + s.add('finish') + s.tick(5) + s.situation(end, 6000, 24000, 1) + s.tick(130) + # Music volume fades: down to silence, then up from a partial volume. + s.situation(end, 6000, 24000, 1, volume=0.0) + s.tick(320) + s.situation(cat, 0, 0, 1, volume=0.25) + s.tick(5) + s.situation(cat, 0, 0, 1, volume=1.0) + s.tick(400) + s.situation(cat, 0, 0, 1, volume=0.6) + s.tick(80) + # Silent starts and the toast, stops, pauses. + s.add('volume', 1, h.bits(0.0)) + s.add('stop') + s.situation(dragon, 0, 0, 1) + s.tick(105) + s.add('toast') + s.add('volume', 1, h.bits(0.5)) + s.add('toast') + s.tick(2) + s.add('stopmusic', f'{end},0,0,1') + s.add('stopmusic', f'{dragon},0,0,1') + s.tick(105, paused=1) + s.add('finish') + s.tick(3, paused=1) + s.tick(5) + s.add('stopall') + s.tick(5) + # Events that cannot play. + for event in ODD: + s.add('start', 7, 'DEFAULT') + s.situation(event, 0, 40, 1) + s.tick(150) + # Real Musics delays over a long session. + s.add('start', 99, 'DEFAULT') + s.situation(water, 12000, 24000, 0) + s.tick(130) + s.add('finish') + s.tick(24100) + + +def fuzz(s, rng, steps): + s.add('start', rng.getrandbits(63), rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT'])) + for _ in range(steps): + op = rng.random() + if op < 0.08: + sound = rng.choice(TRACKS + ODD[:1]) if rng.random() < 0.9 else None + lo = rng.choice([0, 20, 100, 300]) + s.situation(sound, lo, lo + rng.choice([0, 50, 280, 600]), int(rng.random() < 0.5), + rng.choice([1.0, 1.0, 1.0, 0.0, 0.5, rng.random()])) + elif op < 0.13: + s.add('finish') + elif op < 0.15: + s.add('stop') + elif op < 0.16: + s.add('stopmusic', f'{rng.choice(TRACKS)},0,0,1') + elif op < 0.17: + s.add('freq', rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT'])) + elif op < 0.18: + s.add('toast') + elif op < 0.20: + s.add('volume', rng.choice([0, 1]), h.bits(rng.choice([0.0, 1.0, 0.5]))) + elif op < 0.21: + s.add('stopall') + elif op < 0.25: + s.tick(rng.randrange(1, 30), loading=1) + elif op < 0.28: + s.tick(rng.randrange(1, 30), paused=1) + else: + s.tick(rng.randrange(1, 60)) + + +def fixtures(): + s = Script() + scripted(s) + rng = random.Random(0x4d55534943) + for _ in range(60): + fuzz(s, rng, 120) + return s.lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', + h.lab.ROOT / 'crates/horizon-client/src/music.rs', + h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded ' + 'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading ' + 'screen hold, fades and the MUSIC category gain, silent starts, toasts, pauses, track ends and unplayable events. The situation ' + '(getSituationalMusic/getMusicVolume) is an input here; see test_audio_attributes_parity.py for the attribute values.') + print(f'{matched:,} music lines match the pinned client ({len(lines):,} steps): {report}', flush=True) + + +if __name__ == '__main__': + main()