Play bubble column inside sounds as BubbleColumnAmbientSoundHandler does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 22:03:51 +02:00
parent 9e4811dd6e
commit b93f72c0da
6 changed files with 204 additions and 12 deletions
@@ -4,7 +4,7 @@
#[path = "audio_common/mod.rs"]
mod common;
use common::{Fake, d, f, flush};
use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood};
use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood, bubble_column_in};
use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking};
use horizon_client::sound_events::{SoundRegistry, normalize};
use horizon_core::random::RandomSource;
@@ -56,6 +56,8 @@ fn main() {
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 mut height = 1.8f32;
let mut columns: Vec<([i32; 3], bool)> = Vec::new();
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() {
@@ -72,6 +74,8 @@ fn main() {
current = AmbientSounds::default();
(position, eye, eye_in_water, spectator, removed, mode) =
([0.0; 3], 0.0, false, false, false, 0);
height = 1.8;
columns.clear();
}
"sounds" => current = sounds(&a),
"player" => {
@@ -81,6 +85,15 @@ fn main() {
spectator = a[6] == "1";
removed = a[7] == "1";
mode = a[8].parse().expect("mode");
height = f(a[9]);
columns = a[10..]
.iter()
.map(|c| {
let p: Vec<&str> = c.split(',').collect();
let n = |i: usize| p[i].parse::<i32>().expect("column");
([n(0), n(1), n(2)], p[3] == "1")
})
.collect();
}
"volume" => {
let source: usize = a[1].parse().expect("source");
@@ -96,6 +109,17 @@ fn main() {
underwater: eye_in_water,
spectator,
light: &light,
bubble_column: bubble_column_in(
[
position[0] - f64::from(0.3f32),
position[1],
position[2] - f64::from(0.3f32),
position[0] + f64::from(0.3f32),
position[1] + f64::from(height),
position[2] + f64::from(0.3f32),
],
|b| columns.iter().find(|c| c.0 == b).map(|c| c.1),
),
};
ambience.tick(
&ctx,
+88 -6
View File
@@ -3,7 +3,7 @@
//! `minecraft:audio/ambient_sounds` attribute, `UnderwaterAmbientSoundHandler`
//! and `LocalPlayer.updateIsUnderwater` (enter/exit sounds and the
//! `UnderLiquidAmbientSoundInstance` loop), played through the sound engine.
use crate::sound_engine::{AMBIENT, InstanceId, SoundEngine, SoundInstance, Sounds};
use crate::sound_engine::{AMBIENT, InstanceId, PLAYERS, SoundEngine, SoundInstance, Sounds};
use horizon_core::random::{LegacyRandom, RandomSource};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -94,6 +94,51 @@ pub struct AmbientContext<'a> {
pub spectator: bool,
/// `Level.getBrightness` (sky, block) at a block.
pub light: &'a dyn Fn([i32; 3]) -> (u8, u8),
/// The bubble column in the player's box (its `drag` property), from
/// `bubble_column_in`.
pub bubble_column: Option<bool>,
}
/// `BubbleColumnAmbientSoundHandler`'s lookup: the first bubble column
/// (x fastest, then y, then z) in the player's bounding box inflated by
/// (0, -0.4F, 0) and deflated by 1.0E-6, as `drag_down`. `state` gives the
/// bubble column at a block (None for anything else).
pub fn bubble_column_in(bb: [f64; 6], state: impl Fn([i32; 3]) -> Option<bool>) -> Option<bool> {
// AABB keeps min <= max on every construction.
let make = |a: [f64; 6]| {
[
a[0].min(a[3]),
a[1].min(a[4]),
a[2].min(a[5]),
a[0].max(a[3]),
a[1].max(a[4]),
a[2].max(a[5]),
]
};
let inflate = |b: [f64; 6], x: f64, y: f64, z: f64| {
make([b[0] - x, b[1] - y, b[2] - z, b[3] + x, b[4] + y, b[5] + z])
};
let b = inflate(make(bb), 0.0, f64::from(-0.4f32), 0.0);
let b = inflate(b, -1.0E-6, -1.0E-6, -1.0E-6);
let (x0, y0, z0) = (
b[0].floor() as i32,
b[1].floor() as i32,
b[2].floor() as i32,
);
let (x1, y1, z1) = (
b[3].floor() as i32,
b[4].floor() as i32,
b[5].floor() as i32,
);
for z in z0..=z1 {
for y in y0..=y1 {
for x in x0..=x1 {
if let Some(drag) = state([x, y, z]) {
return Some(drag);
}
}
}
}
None
}
/// The local player's ambient sound handlers.
pub struct Ambience {
@@ -107,6 +152,9 @@ pub struct Ambience {
underwater_delay: i32,
/// `LocalPlayer.wasUnderwater`.
was_underwater: bool,
/// `BubbleColumnAmbientSoundHandler.wasInBubbleColumn` / `firstTick`.
was_in_bubble_column: bool,
first_tick: bool,
}
impl Default for Ambience {
fn default() -> Self {
@@ -122,6 +170,8 @@ impl Ambience {
moodiness: 0.0,
underwater_delay: 0,
was_underwater: false,
was_in_bubble_column: false,
first_tick: true,
}
}
/// `LocalPlayer.isUnderWater`.
@@ -145,11 +195,13 @@ impl Ambience {
self.moodiness = 0.0;
self.underwater_delay = 0;
self.was_underwater = false;
self.was_in_bubble_column = false;
self.first_tick = true;
}
/// `ClientLevel.playLocalSound(x, y, z, sound, AMBIENT, 1, 1, false)`.
fn play_local(&mut self, event: &str, at: [f64; 3], sounds: &mut impl Sounds) {
/// `ClientLevel.playLocalSound(x, y, z, sound, source, 1, 1, false)`.
fn play_local(&mut self, event: &str, source: usize, at: [f64; 3], sounds: &mut impl Sounds) {
let seed = self.random.next_long();
let instance = SoundInstance::at(event, AMBIENT, 1.0, 1.0, LegacyRandom::new(seed), at);
let instance = SoundInstance::at(event, source, 1.0, 1.0, LegacyRandom::new(seed), at);
sounds.play_instance(instance, false);
}
/// `LocalPlayer.updateIsUnderwater`, then the `ambientSoundHandlers`
@@ -159,7 +211,12 @@ impl Ambience {
self.was_underwater = ctx.underwater;
if !ctx.spectator {
if !old && ctx.underwater {
self.play_local("minecraft:ambient.underwater.enter", ctx.position, sounds);
self.play_local(
"minecraft:ambient.underwater.enter",
AMBIENT,
ctx.position,
sounds,
);
let instance = SoundInstance::under_liquid_loop(
"minecraft:ambient.underwater.loop",
SoundEngine::unseeded(),
@@ -167,12 +224,36 @@ impl Ambience {
sounds.play_instance(instance, false);
}
if old && !ctx.underwater {
self.play_local("minecraft:ambient.underwater.exit", ctx.position, sounds);
self.play_local(
"minecraft:ambient.underwater.exit",
AMBIENT,
ctx.position,
sounds,
);
}
}
self.tick_underwater(sounds);
self.tick_bubble_column(ctx, sounds);
self.tick_biome(ctx, sounds);
}
/// `BubbleColumnAmbientSoundHandler.tick`: entering a column plays its
/// inside sound (`LocalPlayer.playSound`, on PLAYERS).
fn tick_bubble_column(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) {
if let Some(drag_down) = ctx.bubble_column {
if !self.was_in_bubble_column && !self.first_tick && !ctx.spectator {
let event = if drag_down {
"minecraft:block.bubble_column.whirlpool_inside"
} else {
"minecraft:block.bubble_column.upwards_inside"
};
self.play_local(event, PLAYERS, ctx.position, sounds);
}
self.was_in_bubble_column = true;
} else {
self.was_in_bubble_column = false;
}
self.first_tick = false;
}
/// `UnderwaterAmbientSoundHandler.tick`.
fn tick_underwater(&mut self, sounds: &mut impl Sounds) {
self.underwater_delay -= 1;
@@ -317,6 +398,7 @@ mod tests {
underwater,
spectator: false,
light,
bubble_column: None,
}
}
+26
View File
@@ -101,6 +101,31 @@ impl Game<'_> {
let l = world.light(b[0], b[1], b[2]);
(l >> 4, l & 15)
};
let (half, height) = (
f64::from(p.dimensions.width / 2.0),
f64::from(p.dimensions.height),
);
let registry = &self.res.assets.registry;
let facts = &self.res.facts;
let bubble_column = horizon_client::ambience::bubble_column_in(
[
feet[0] - half,
feet[1],
feet[2] - half,
feet[0] + half,
feet[1] + height,
feet[2] + half,
],
|b| {
let state = world.block(b[0], b[1], b[2]);
(&*facts.get(state).name == "minecraft:bubble_column").then(|| {
registry
.state(state)
.and_then(|s| s.properties.get("drag"))
.is_some_and(|d| d == "true")
})
},
);
let ctx = horizon_client::ambience::AmbientContext {
sounds: &sounds,
position: feet,
@@ -108,6 +133,7 @@ impl Game<'_> {
underwater,
spectator: self.spectator(),
light: &light,
bubble_column,
};
self.ambience.tick(&ctx, &mut self.audio);
}
@@ -17,6 +17,7 @@ use std::collections::HashMap;
pub const MASTER: usize = 0;
pub const MUSIC: usize = 1;
pub const RECORDS: usize = 2;
pub const PLAYERS: usize = 7;
pub const AMBIENT: usize = 8;
pub const UI: usize = 10;
/// The pool sizes `Library.init` derives from OpenAL Soft's default 255 mono
@@ -24,6 +24,10 @@ 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.block.Blocks;
import net.minecraft.world.level.block.BubbleColumnBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.phys.Vec3;
@@ -59,6 +63,7 @@ public final class VanillaAmbientOracle {
public static final class Lvl extends ClientLevel {
int mode;
final Map<BlockPos, Boolean> columns = new HashMap<>();
Lvl() {
super(null, null, null, null, 0, 0, null, false, 0L, 0);
@@ -68,6 +73,17 @@ public final class VanillaAmbientOracle {
public int getBrightness(final LightLayer layer, final BlockPos pos) {
return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1];
}
@Override
public BlockState getBlockState(final BlockPos pos) {
Boolean drag = columns.get(pos);
return drag == null ? Blocks.AIR.defaultBlockState() : Blocks.BUBBLE_COLUMN.defaultBlockState().setValue(BubbleColumnBlock.DRAG_DOWN, drag);
}
@Override
public boolean hasChunksAt(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) {
return true;
}
}
/** The scripted brightness: (sky, block) for a light mode and block. */
@@ -81,6 +97,11 @@ public final class VanillaAmbientOracle {
};
}
/** The player's box (EntityDimensions.makeBoundingBox, width 0.6F). */
static AABB box(Vec3 at, float height) {
return new AABB(at.x - 0.3F, at.y, at.z - 0.3F, at.x + 0.3F, at.y + height, at.z + 0.3F);
}
static float f(String hex) {
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
}
@@ -141,6 +162,7 @@ public final class VanillaAmbientOracle {
Actor actor = null;
UnderwaterAmbientSoundHandler underwater = null;
BiomeAmbientSoundsHandler biome = null;
BubbleColumnAmbientSoundHandler bubble = null;
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
for (String line : Files.readAllLines(Path.of(args[1]))) {
out.println(line);
@@ -156,8 +178,11 @@ public final class VanillaAmbientOracle {
actor = VanillaSoundRig.make(Actor.class);
VanillaSoundRig.set(actor, Entity.class, "level", level);
VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO);
VanillaSoundRig.set(actor, Entity.class, "bb", box(Vec3.ZERO, 1.8F));
VanillaSoundRig.set(level, Lvl.class, "columns", new HashMap<BlockPos, Boolean>());
VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc);
underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager);
bubble = new BubbleColumnAmbientSoundHandler(actor);
biome = new BiomeAmbientSoundsHandler(actor, rig.manager);
}
case "sounds" -> {
@@ -175,6 +200,13 @@ public final class VanillaAmbientOracle {
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]);
var at = new Vec3(d(a[1]), d(a[2]), d(a[3]));
VanillaSoundRig.set(actor, Entity.class, "bb", box(at, f(a[9])));
level.columns.clear();
for (int i = 10; i < a.length; i++) {
String[] c = a[i].split(",");
level.columns.put(new BlockPos(Integer.parseInt(c[0]), Integer.parseInt(c[1]), Integer.parseInt(c[2])), c[3].equals("1"));
}
}
case "volume" -> {
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
@@ -183,6 +215,7 @@ public final class VanillaAmbientOracle {
case "tick" -> {
update.invoke(actor);
underwater.tick();
bubble.tick();
biome.tick();
rig.manager.tick(false);
}
+31 -5
View File
@@ -3,7 +3,8 @@
The oracle runs the real `LocalPlayer.updateIsUnderwater` (enter/exit sounds
seeded from the level random, the `UnderLiquidAmbientSoundInstance`),
`UnderwaterAmbientSoundHandler` and `BiomeAmbientSoundsHandler` over the real
`UnderwaterAmbientSoundHandler`, `BubbleColumnAmbientSoundHandler` 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
@@ -56,8 +57,9 @@ class Script:
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 player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()):
self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height),
*[f'{x},{y},{z},{d}' for x, y, z, d in columns])
def tick(self, n=1):
for _ in range(n):
@@ -119,6 +121,25 @@ def scripted(s, values):
s.tick(50)
s.sounds(by_loop[0])
s.tick(50)
# Bubble columns: entering, staying, the first tick, spectators, small boxes.
s.add('start', 5)
column = [(0, 64, 0, 1), (0, 65, 0, 1)]
s.player((0.5, 64.0, 0.5), water=1, columns=column)
s.tick(3)
s.player((3.5, 64.0, 0.5), water=1, columns=column)
s.tick(2)
s.player((0.5, 64.0, 0.5), water=1, columns=column)
s.tick(2)
s.player((0.5, 64.0, 0.5), water=1, columns=[(0, 64, 0, 0), (1, 64, 0, 1)])
s.tick(2)
s.player((3.5, 64.0, 0.5))
s.tick(2)
s.player((0.9, 64.5, 0.5), water=1, height=0.6, columns=[(1, 64, 0, 0), (0, 64, 0, 1)])
s.tick(2)
s.player((3.5, 64.0, 0.5))
s.tick(1)
s.player((0.5, 63.7, 0.5), spectator=1, columns=column)
s.tick(2)
def fuzz(s, rng, values, steps):
@@ -132,7 +153,12 @@ def fuzz(s, rng, values, steps):
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))
columns = []
if rng.random() < 0.3:
bx, by, bz = int(at[0] // 1), int(at[1] // 1), int(at[2] // 1)
columns = [(bx + rng.randrange(-1, 2), by + rng.randrange(-1, 3), bz + rng.randrange(-1, 2), rng.randrange(2)) for _ in range(rng.randrange(1, 4))]
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),
rng.choice([1.8, 1.5, 0.6]), columns)
elif op < 0.13:
s.add('volume', rng.choice([0, 8]), h.bits(rng.choice([0.0, 1.0, 0.5])))
else:
@@ -160,7 +186,7 @@ def main():
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.')
'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler runs on a scripted block world.')
print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True)