Compare the ambient sound handlers tick by tick with vanilla LocalPlayer

The oracle runs the real updateIsUnderwater, UnderwaterAmbientSoundHandler
and BiomeAmbientSoundsHandler over the real SoundEngine, comparing every
level random draw, loop fade, mood sample and playing instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 21:57:02 +02:00
parent 6eee2e3262
commit 9e4811dd6e
4 changed files with 553 additions and 0 deletions
@@ -0,0 +1,161 @@
//! Replays `tools/test_ambient_sound_parity.py` scripts through Horizon's
//! ambient sound handlers over its `SoundEngine`:
//! `ambient_fixture ROOT INPUT OUTPUT`.
#[path = "audio_common/mod.rs"]
mod common;
use common::{Fake, d, f, flush};
use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood};
use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking};
use horizon_client::sound_events::{SoundRegistry, normalize};
use horizon_core::random::RandomSource;
use std::io::Write;
/// The oracle's scripted brightness.
fn light(mode: i32, x: i32, y: i32, z: i32) -> (u8, u8) {
let h = x.wrapping_mul(73856093) ^ y.wrapping_mul(19349663) ^ z.wrapping_mul(83492791);
let u = h as u32;
match mode {
0 => (15, 0),
1 => (0, 0),
2 => (0, ((u >> 4) & 15) as u8),
_ => (
if h & 3 == 0 { ((u >> 8) & 15) as u8 } else { 0 },
((u >> 12) & 15) as u8,
),
}
}
fn sounds(a: &[&str]) -> AmbientSounds {
AmbientSounds {
r#loop: (a[1] != "-").then(|| normalize(a[1])),
mood: (a[2] != "-").then(|| {
let m: Vec<&str> = a[2].split(',').collect();
Mood {
sound: normalize(m[0]),
tick_delay: m[1].parse().expect("delay"),
block_search_extent: m[2].parse().expect("extent"),
offset: d(m[3]),
}
}),
additions: a[3..]
.iter()
.map(|s| {
let p: Vec<&str> = s.split(',').collect();
(normalize(p[0]), d(p[1]))
})
.collect(),
}
}
fn main() {
let args: Vec<String> = 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 ambience = Ambience::new(0);
let mut current = AmbientSounds::default();
let (mut position, mut eye, mut eye_in_water, mut spectator, mut removed, mut mode) =
([0.0f64; 3], 0.0f32, false, false, false, 0);
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" => {
engine.stop_all(&mut backend);
ambience.clear(&mut Bound {
engine: &mut engine,
backend: &mut backend,
});
ambience = Ambience::new(a[1].parse().expect("seed"));
current = AmbientSounds::default();
(position, eye, eye_in_water, spectator, removed, mode) =
([0.0; 3], 0.0, false, false, false, 0);
}
"sounds" => current = sounds(&a),
"player" => {
position = [d(a[1]), d(a[2]), d(a[3])];
eye = f(a[4]);
eye_in_water = a[5] == "1";
spectator = a[6] == "1";
removed = a[7] == "1";
mode = a[8].parse().expect("mode");
}
"volume" => {
let source: usize = a[1].parse().expect("source");
engine.source_volumes[source] = f(a[2]);
engine.refresh_category_volume(source, &mut backend);
}
"tick" => {
let light = |b: [i32; 3]| light(mode, b[0], b[1], b[2]);
let ctx = AmbientContext {
sounds: &current,
position,
eye_y: position[1] + f64::from(eye),
underwater: eye_in_water,
spectator,
light: &light,
};
ambience.tick(
&ctx,
&mut Bound {
engine: &mut engine,
backend: &mut backend,
},
);
let tick = TickContext {
player_underwater: ambience.was_underwater(),
player_removed: removed,
};
engine.tick(false, &tick, &mut backend);
}
_ => panic!("{line}"),
}
writeln!(
out,
" rand={} mood={:08x} underwater={} delay={}",
ambience.random.clone().next_long(),
ambience.moodiness.to_bits(),
ambience.was_underwater(),
ambience.underwater_delay()
)
.expect("write");
for (event, id) in ambience.loops() {
let i = engine.instance(*id).expect("loop");
let Ticking::BiomeLoop { fade, direction } = i.ticking else {
panic!("loop kind");
};
writeln!(
out,
" loop {event} fade={fade} direction={direction} stopped={} active={}",
i.stopped,
engine.is_active(*id)
)
.expect("write");
}
let mut playing: Vec<String> = engine
.active_instances()
.into_iter()
.map(|id| {
let i = engine.instance(id).expect("instance");
format!(
" playing {} volume={:08x} looping={} relative={} at={:016x},{:016x},{:016x} stopped={}",
i.identifier,
i.volume.to_bits(),
i.looping,
i.relative,
i.position[0].to_bits(),
i.position[1].to_bits(),
i.position[2].to_bits(),
i.tickable() && i.stopped
)
})
.collect();
playing.sort();
for p in playing {
writeln!(out, "{p}").expect("write");
}
flush(&mut engine, &mut out);
}
}
+8
View File
@@ -128,6 +128,14 @@ impl Ambience {
pub fn was_underwater(&self) -> bool {
self.was_underwater
}
/// `BiomeAmbientSoundsHandler.loopSounds`.
pub fn loops(&self) -> &[(String, InstanceId)] {
&self.loops
}
/// `UnderwaterAmbientSoundHandler.tickDelay`.
pub fn underwater_delay(&self) -> i32 {
self.underwater_delay
}
/// A new player (leaving or changing worlds): fresh handlers.
pub fn clear(&mut self, sounds: &mut impl Sounds) {
for (_, id) in self.loops.drain(..) {
@@ -0,0 +1,216 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.resources.sounds.*;
import net.minecraft.client.sounds.ChannelAccess;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.TagKey;
import net.minecraft.util.RandomSource;
import net.minecraft.world.attribute.*;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.phys.Vec3;
/**
* Runs the local player's real ambient sound path over the real SoundEngine
* (VanillaSoundRig): LocalPlayer.updateIsUnderwater (enter/exit sounds through
* ClientLevel.playLocalSound and the UnderLiquidAmbientSoundInstance), the
* UnderwaterAmbientSoundHandler and the BiomeAmbientSoundsHandler, then
* SoundManager.tick, once per client tick. Inputs: the AMBIENT_SOUNDS value
* (a constant attribute layer), the player's position, eye height, whether
* its eyes are in water, spectator and removed flags, and the level's sky and
* block brightness (a hash of the position). Prints the level random's next
* long (without drawing it), the handlers' state and every playing instance.
*/
public final class VanillaAmbientOracle {
public static final class Actor extends LocalPlayer {
boolean eyeInWater, spectator;
Actor() {
super(null, null, null, null, null, null, false, null, null);
}
@Override
public boolean isEyeInFluid(final TagKey<Fluid> type) {
return type == FluidTags.WATER && eyeInWater;
}
@Override
public boolean isSpectator() {
return spectator;
}
}
public static final class Lvl extends ClientLevel {
int mode;
Lvl() {
super(null, null, null, null, 0, 0, null, false, 0L, 0);
}
@Override
public int getBrightness(final LightLayer layer, final BlockPos pos) {
return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1];
}
}
/** The scripted brightness: (sky, block) for a light mode and block. */
static int[] light(int mode, int x, int y, int z) {
int h = x * 73856093 ^ y * 19349663 ^ z * 83492791;
return switch (mode) {
case 0 -> new int[]{15, 0};
case 1 -> new int[]{0, 0};
case 2 -> new int[]{0, (h >>> 4) & 15};
default -> new int[]{(h & 3) == 0 ? (h >>> 8) & 15 : 0, (h >>> 12) & 15};
};
}
static float f(String hex) {
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
}
static double d(String hex) {
return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16));
}
static Holder<SoundEvent> event(String id) {
return Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(id)));
}
/** "loop|- mood|- addition..." with mood "sound,delay,extent,offsetbits" and additions "sound,chancebits". */
static AmbientSounds sounds(String[] a) {
Optional<Holder<SoundEvent>> loop = a[1].equals("-") ? Optional.empty() : Optional.of(event(a[1]));
Optional<AmbientMoodSettings> mood = Optional.empty();
if (!a[2].equals("-")) {
String[] m = a[2].split(",");
mood = Optional.of(new AmbientMoodSettings(event(m[0]), Integer.parseInt(m[1]), Integer.parseInt(m[2]), d(m[3])));
}
var additions = new ArrayList<AmbientAdditionsSettings>();
for (int i = 3; i < a.length; i++) {
String[] p = a[i].split(",");
additions.add(new AmbientAdditionsSettings(event(p[0]), d(p[1])));
}
return new AmbientSounds(loop, mood, additions);
}
/** LegacyRandomSource's next nextLong(), read from its state. */
static long peek(RandomSource random) throws Exception {
long s = ((java.util.concurrent.atomic.AtomicLong) VanillaSoundRig.get(random,
Class.forName("net.minecraft.world.level.levelgen.LegacyRandomSource"), "seed")).get();
long m = 0x5DEECE66DL, mask = (1L << 48) - 1;
long s1 = (s * m + 0xBL) & mask;
long s2 = (s1 * m + 0xBL) & mask;
return ((long) (int) (s1 >>> 16) << 32) + (int) (s2 >>> 16);
}
static String bits(double v) {
return String.format("%016x", Double.doubleToRawLongBits(v));
}
@SuppressWarnings("unchecked")
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]));
var mc = VanillaSoundRig.make(Minecraft.class);
VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager);
var renderer = VanillaSoundRig.make(GameRenderer.class);
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", VanillaSoundRig.make(Camera.class));
VanillaSoundRig.set(VanillaSoundRig.get(renderer, GameRenderer.class, "mainCamera"), Camera.class, "position", Vec3.ZERO);
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
Method update = LocalPlayer.class.getDeclaredMethod("updateIsUnderwater");
update.setAccessible(true);
var instanceToChannel = VanillaSoundRig.field(SoundEngine.class, "instanceToChannel");
Lvl level = null;
Actor actor = null;
UnderwaterAmbientSoundHandler underwater = null;
BiomeAmbientSoundsHandler biome = null;
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 new level and player: fresh handlers on a seeded level random.
rig.manager.stop();
level = VanillaSoundRig.make(Lvl.class);
VanillaSoundRig.set(level, Level.class, "random", RandomSource.create(Long.parseLong(a[1])));
VanillaSoundRig.set(level, ClientLevel.class, "minecraft", mc);
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", EnvironmentAttributeSystem.builder().build());
actor = VanillaSoundRig.make(Actor.class);
VanillaSoundRig.set(actor, Entity.class, "level", level);
VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO);
VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc);
underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager);
biome = new BiomeAmbientSoundsHandler(actor, rig.manager);
}
case "sounds" -> {
AmbientSounds value = sounds(a);
var system = EnvironmentAttributeSystem.builder()
.addConstantLayer(EnvironmentAttributes.AMBIENT_SOUNDS, base -> value)
.build();
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", system);
}
case "player" -> {
// player x y z eyeHeight eyeInWater spectator removed lightMode
VanillaSoundRig.set(actor, Entity.class, "position", new Vec3(d(a[1]), d(a[2]), d(a[3])));
VanillaSoundRig.set(actor, Entity.class, "eyeHeight", f(a[4]));
actor.eyeInWater = a[5].equals("1");
actor.spectator = a[6].equals("1");
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[7].equals("1") ? Entity.RemovalReason.DISCARDED : null);
level.mode = Integer.parseInt(a[8]);
}
case "volume" -> {
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
}
case "tick" -> {
update.invoke(actor);
underwater.tick();
biome.tick();
rig.manager.tick(false);
}
default -> throw new IllegalArgumentException(line);
}
out.printf(" rand=%d mood=%08x underwater=%s delay=%d%n", peek(level.getRandom()), Float.floatToRawIntBits(biome.getMoodiness()),
actor.isUnderWater(), (int) VanillaSoundRig.get(underwater, UnderwaterAmbientSoundHandler.class, "tickDelay"));
var loops = (Map<Holder<SoundEvent>, BiomeAmbientSoundsHandler.LoopSoundInstance>) VanillaSoundRig.get(biome,
BiomeAmbientSoundsHandler.class, "loopSounds");
for (var e : loops.entrySet()) {
var loop = e.getValue();
out.printf(" loop %s fade=%d direction=%d stopped=%s active=%s%n", e.getKey().value().location(),
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fade"),
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fadeDirection"), loop.isStopped(),
rig.manager.isActive(loop));
}
var playing = new ArrayList<String>();
for (SoundInstance i : ((Map<SoundInstance, ChannelAccess.ChannelHandle>) instanceToChannel.get(rig.engine)).keySet()) {
float volume = (float) VanillaSoundRig.get(i, AbstractSoundInstance.class, "volume");
playing.add(String.format(" playing %s volume=%08x looping=%s relative=%s at=%s,%s,%s stopped=%s", i.getIdentifier(),
Float.floatToRawIntBits(volume), i.isLooping(), i.isRelative(), bits(i.getX()), bits(i.getY()), bits(i.getZ()),
i instanceof TickableSoundInstance t && t.isStopped()));
}
Collections.sort(playing);
for (String p : playing) out.println(p);
rig.flush(out);
}
}
System.exit(0);
}
}
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Compare the local player's ambient sounds with the vanilla 26.3 client.
The oracle runs the real `LocalPlayer.updateIsUnderwater` (enter/exit sounds
seeded from the level random, the `UnderLiquidAmbientSoundInstance`),
`UnderwaterAmbientSoundHandler` and `BiomeAmbientSoundsHandler` over the real
`SoundEngine` (see VanillaSoundRig), then `SoundManager.tick`, once per client
tick. The `AMBIENT_SOUNDS` value (loops, moods and additions from the biomes
and dimensions of the data pack plus faster custom moods), the player's
position, eye height, eyes in water, spectator and removed flags and the
level's brightness are script inputs. Every step prints the level random's
next long (so every draw is compared), moodiness, the underwater state and
delay, the handler's loop instances (fade, direction, stopped, active), each
playing instance and the subtitle notifications. Horizon's `Ambience` and
`SoundEngine` replay the scripts.
"""
import json
import random
import struct
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def dbits(v):
return struct.pack('>d', v).hex()
def settings():
"""Every AMBIENT_SOUNDS value in the data pack."""
data = h.RESOURCES / 'data/minecraft'
values = []
for path in sorted(list((data / 'worldgen/biome').glob('*.json')) + list((data / 'dimension_type').glob('*.json'))):
v = json.loads(path.read_text()).get('attributes', {}).get('minecraft:audio/ambient_sounds')
if v is None:
continue
additions = v.get('additions', [])
if isinstance(additions, dict):
additions = [additions]
mood = v.get('mood')
values.append(dict(loop=v.get('loop'), mood=None if mood is None else (mood['sound'], mood['tick_delay'], mood['block_search_extent'], mood['offset']),
additions=[(a['sound'], a['tick_chance']) for a in additions]))
return values
class Script:
def __init__(self):
self.lines = []
def add(self, *parts):
self.lines.append(' '.join(map(str, parts)))
def sounds(self, value):
mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3]))
self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']])
def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0):
self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode)
def tick(self, n=1):
for _ in range(n):
self.add('tick')
def scripted(s, values):
by_loop = [v for v in values if v['loop']]
cave = next(v for v in values if v['mood'] and v['mood'][0] == 'minecraft:ambient.cave' and not v['loop'])
s.add('start', 1)
s.sounds(cave)
s.player(mode=1)
s.tick(6100)
s.player((100.25, -20.0, -7.75), mode=2)
s.tick(400)
s.player((3.5, 12.0, 3.5), mode=3)
s.tick(400)
# Biome loops cross-fading, back and forth.
s.add('start', 2)
for v in by_loop:
s.sounds(v)
s.tick(30)
s.sounds(by_loop[0])
s.tick(20)
s.sounds(by_loop[1])
s.tick(5)
s.sounds(by_loop[0])
s.tick(60)
s.sounds(dict(loop=None, mood=None, additions=[]))
s.tick(60)
# Water: enter, the loop's fade, sub-sounds, exit, re-entering mid-fade, spectators.
s.add('start', 3)
s.sounds(cave)
s.player(water=1, mode=0)
s.tick(300)
s.player(water=0)
s.tick(10)
s.player(water=1)
s.tick(3)
s.player(water=0)
s.tick(2)
s.player(water=1)
s.tick(60)
s.player(water=1, spectator=1)
s.tick(5)
s.player(water=0, spectator=1)
s.tick(5)
s.player(water=1, removed=1)
s.tick(5)
s.player(water=0)
s.tick(25)
# Silent ambient category: loops never start and linger.
s.add('start', 4)
s.add('volume', 8, h.bits(0.0))
s.sounds(by_loop[0])
s.tick(50)
s.add('volume', 8, h.bits(1.0))
s.sounds(by_loop[1])
s.tick(50)
s.sounds(by_loop[0])
s.tick(50)
def fuzz(s, rng, values, steps):
s.add('start', rng.getrandbits(63))
for _ in range(steps):
op = rng.random()
if op < 0.05:
v = rng.choice(values + [dict(loop=None, mood=None, additions=[])])
if rng.random() < 0.5 and v['mood']:
v = dict(v, mood=(v['mood'][0], rng.choice([20, 60, 150]), rng.choice([1, 4, 8, 16]), rng.choice([0.0, 2.0, 5.5])))
s.sounds(v)
elif op < 0.12:
at = (rng.uniform(-3e4, 3e4) if rng.random() < 0.2 else rng.uniform(-200, 200), rng.uniform(-64, 320), rng.uniform(-200, 200))
s.player(at, rng.choice([1.62, 1.27, 0.4, 0.2]), int(rng.random() < 0.4), int(rng.random() < 0.05), int(rng.random() < 0.03), rng.randrange(4))
elif op < 0.13:
s.add('volume', rng.choice([0, 8]), h.bits(rng.choice([0.0, 1.0, 0.5])))
else:
s.tick(rng.randrange(1, 40))
def fixtures():
values = settings()
s = Script()
scripted(s, values)
rng = random.Random(0x414d4249)
for _ in range(40):
fuzz(s, rng, values, 150)
return s.lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'ambient', 'VanillaAmbientOracle', 'ambient_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/ambience.rs',
h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'],
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, '
'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance '
'ticking in the real SoundEngine: every level random draw, handler state, playing instance and notification per tick. The '
'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler is not compared.')
print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()