Give the fire charge's use sound its own pitch

Placing fire with a fire charge played item.firecharge.use at the flint and
steel's pitch (nextFloat * 0.4 + 0.8, one draw). FireChargeItem.playSound
uses (nextFloat - nextFloat) * 0.2 + 1.0, two draws from the level random.
The pitch is now horizon_client::items::fire_starter_pitch, checked against
the real FireChargeItem.playSound by tools/test_fire_starter_sound_parity.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-14 15:27:13 +02:00
parent 66ce394d2d
commit 162e3d36f7
5 changed files with 156 additions and 10 deletions
@@ -0,0 +1,32 @@
#![forbid(unsafe_code)]
//! Runs tools/test_fire_starter_sound_parity.py's level random seeds through
//! the fire charge's use sound (`horizon_client::items::fire_starter_pitch`).
use horizon_client::{
Result,
items::{fire_starter_pitch, fire_starter_sound},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = BufReader::new(File::open(&args[1])?);
let mut out = BufWriter::new(File::create(&args[2])?);
for line in input.lines() {
let mut random = LegacyRandom::new(line?.trim().parse()?);
let pitch = fire_starter_pitch(true, &mut random);
writeln!(
out,
"{} {} {} {}",
fire_starter_sound(true),
1.0f32.to_bits() as i32,
pitch.to_bits() as i32,
random.next_long()
)?;
}
out.flush()?;
Ok(())
}
+5 -10
View File
@@ -6267,17 +6267,12 @@ impl Game<'_> {
if !self.try_light_portal(target)? {
self.set_state_named(target, "minecraft:fire", &[])?;
}
let sound = if item == "fire_charge" {
"minecraft:item.firecharge.use"
} else {
"minecraft:item.flintandsteel.use"
};
self.audio.play(
sound,
Some(at(target)),
1.0,
self.world.random.next_float() * 0.4 + 0.8,
let sound = horizon_client::items::fire_starter_sound(item == "fire_charge");
let pitch = horizon_client::items::fire_starter_pitch(
item == "fire_charge",
&mut self.world.random,
);
self.audio.play(sound, Some(at(target)), 1.0, pitch);
if item == "fire_charge" {
self.consume_held();
} else {
+21
View File
@@ -12,6 +12,27 @@ use std::{
sync::Arc,
};
/// A fire starter's use sound: `SoundEvents.FIRECHARGE_USE` or
/// `FLINTANDSTEEL_USE`.
pub fn fire_starter_sound(fire_charge: bool) -> &'static str {
if fire_charge {
"minecraft:item.firecharge.use"
} else {
"minecraft:item.flintandsteel.use"
}
}
/// The pitch of a fire starter's use sound, from the level's random:
/// `FlintAndSteelItem.useOn`'s `nextFloat() * 0.4 + 0.8`, or
/// `FireChargeItem.playSound`'s `(nextFloat() - nextFloat()) * 0.2 + 1.0`.
pub fn fire_starter_pitch(fire_charge: bool, random: &mut impl RandomSource) -> f32 {
if fire_charge {
(random.next_float() - random.next_float()) * 0.2 + 1.0
} else {
random.next_float() * 0.4 + 0.8
}
}
#[derive(Clone, Debug)]
pub struct ToolRule {
pub blocks: Vec<String>,
@@ -0,0 +1,66 @@
package dev.horizonlab.parity;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.FireChargeItem;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
/**
* Original oracle for the fire charge's use sound: the real private
* FireChargeItem.playSound (used for both a lit campfire or candle and a
* placed fire) on a level stand-in whose random is seeded from the case,
* recording the sound, its volume and pitch and the level random's next long
* (which shows how many values the sound drew).
*/
public final class VanillaFireStarterSoundOracle {
static final StringBuilder sounds = new StringBuilder();
static final class World extends ServerLevel {
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z,
net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) {
sounds.append(s.unwrapKey().orElseThrow().identifier()).append(' ')
.append(Float.floatToIntBits(v)).append(' ').append(Float.floatToIntBits(pitch));
}
}
static void put(Object unsafe, Object target, String name, Object value) throws Exception {
Field f = Level.class.getDeclaredField(name);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, target, offset, value);
}
public static void main(String[] args) throws Exception {
ParityData.init();
var u = Class.forName("sun.misc.Unsafe");
Field theUnsafe = u.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Object unsafe = theUnsafe.get(null);
World world = (World) u.getMethod("allocateInstance", Class.class).invoke(unsafe, World.class);
Method play = FireChargeItem.class.getDeclaredMethod("playSound", Level.class, BlockPos.class);
play.setAccessible(true);
var item = (FireChargeItem) Items.FIRE_CHARGE;
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (var line : (Iterable<String>) lines::iterator) {
long seed = Long.parseLong(line.trim());
RandomSource random = RandomSource.create(seed);
put(unsafe, world, "random", random);
put(unsafe, world, "soundSeedGenerator", RandomSource.create(0));
sounds.setLength(0);
play.invoke(item, world, new BlockPos(3, 64, -7));
out.println(sounds + " " + random.nextLong());
}
}
System.exit(0);
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Compare the fire charge's use sound with the pinned client: the real
FireChargeItem.playSound (lighting a campfire or candle and placing fire both
use it) on level randoms from many seeds, comparing the sound, its volume and
pitch bits, and the level random's next value (how many values it drew)."""
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def make_cases(build):
path = build / 'cases.txt'
rng = random.Random(0x46495245)
seeds = [0, 1, -1, 42, 2**63 - 1, -2**63] + [rng.randrange(-2**63, 2**63) for _ in range(20000)]
path.write_text(''.join(f'{s}\n' for s in seeds))
return path, len(seeds)
def main():
scope = ('The real private FireChargeItem.playSound on a ServerLevel stand-in with a seeded LegacyRandomSource: '
'the sound event, volume, pitch ((nextFloat - nextFloat) * 0.2 + 1) and the random afterwards. '
'FireChargeItem.useOn\'s choice between lighting and placing fire is not exercised.')
harness.differential(
'rust-fire-starter-sound-parity', 'VanillaFireStarterSoundOracle', 'fire_starter_sound_probe', make_cases,
scope, sources=[lab.ROOT / 'crates/horizon-client/src/items.rs'])
if __name__ == '__main__':
main()