Merge branch 'parity-base' into parity/saves

This commit is contained in:
Ludovic Marie
2026-10-11 14:12:55 +02:00
174 changed files with 23474 additions and 4007 deletions
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Shared runner for the audio differential harnesses.
Each harness writes an input file, runs a Java oracle against the pinned
client (the real SoundManager / SoundEngine / MusicManager / ambient handlers;
OpenAL runs on OpenAL Soft's "No Output" device so channel parameters can be
read back from real AL sources) and a Rust example replaying the same inputs
through Horizon's audio code, then requires byte-identical output.
"""
import json
import os
from pathlib import Path
import platform
import subprocess
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
RESOURCES = lab.LOCAL / 'horizon-client/26.3'
COMMON_SOURCES = [
lab.ROOT / 'tools/audio_harness.py',
lab.ROOT / 'tools/test_rust_parity.py',
lab.ROOT / 'tools/lab.py',
lab.ROOT / 'Cargo.toml',
lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-client/Cargo.toml',
lab.ROOT / 'crates/horizon-client/src/sound_events.rs',
lab.ROOT / 'crates/horizon-client/src/sound_engine.rs',
]
def require_sounds():
if not (RESOURCES / 'assets/minecraft/sounds.json').is_file():
raise SystemExit('Sound assets missing: run tools/fetch_sounds.py first')
def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800):
"""Run oracle and example on inputs; returns the number of matched lines."""
require_sounds()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / f'rust-{name}'
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java'
example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs'
sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]]
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
inputs.write_text(inputs_text)
input_hash = lab.digest(inputs, 'sha256')
def run(command, log, env=None):
with (build / (log + ".log")).open("w") as out:
try:
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env)
except subprocess.CalledProcessError:
raise SystemExit(f"{log} failed: see {build / (log + '.log')}") from None
classes = build / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java',
'-cp', dependencies, '-d', classes, oracle_path], 'compile-java')
run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else ''))
run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust')
env = dict(os.environ, ALSOFT_DRIVERS='null')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'],
'client', env=env)
matched = base.compare(build / 'client.txt', build / 'rust.txt')
base.ensure_sources_unchanged(sources, tested)
if input_hash != lab.digest(inputs, 'sha256'):
raise AssertionError('Input fixtures changed')
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'], platform=platform.platform(),
rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'),
sounds_json_sha256=lab.digest(RESOURCES / 'assets/minecraft/sounds.json', 'sha256'),
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope))
return matched, report
def bits(value):
import struct
return struct.pack('>f', value).hex()
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Generate crates/horizon-client/src/lan/command_suggestions.rs: the argument
nodes of vanilla's command tree that have a custom suggestion provider, and
the provider's network name (ClientboundCommandsPacket sends it; the commands
report does not). The list comes from VanillaCommandSuggestionsExporter run
against the pinned client jar:
javac --release 25 -proc:none -sourcepath mods/horizon/src/test/java -cp CLIENT_CP \\
-d BUILD mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java
java -cp BUILD:CLIENT_CP dev.horizonlab.parity.VanillaCommandSuggestionsExporter suggestions.tsv
generate_command_suggestions.py suggestions.tsv
"""
import argparse
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("tsv", type=Path)
parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/command_suggestions.rs")
args = parser.parse_args()
rows = sorted(tuple(line.split("\t")) for line in args.tsv.read_text().splitlines() if line.strip())
if len(rows) < 50:
raise SystemExit(f"only {len(rows)} nodes")
lines = [
"//! Argument nodes of vanilla's command tree with a custom suggestion",
"//! provider (path of node names from the root, provider network name).",
"//! Generated by tools/generate_command_suggestions.py from",
"//! VanillaCommandSuggestionsExporter; do not edit by hand.",
"",
"pub const SUGGESTIONS: &[(&str, &str)] = &[",
]
lines += [f' ("{path}", "{provider}"),' for path, provider in rows]
lines += ["];", ""]
args.out.write_text("\n".join(lines))
print(f"wrote {len(rows)} nodes to {args.out}")
if __name__ == "__main__":
main()
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Generate crates/horizon-client/src/lan/tracking.rs: every entity type's
tracking settings (EntityType.Builder clientTrackingRange, updateInterval and
trackDeltas, which ChunkMap.TrackedEntity and ServerEntity use to decide who
sees an entity and how often its movement is sent), read from the decompiled
EntityTypes.java.
generate_entity_tracking.py [--sources .local/minecraft/26.3/sources/client]
"""
import argparse
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
INT_MAX = 2147483647
def parse(sources):
text = (sources / "net/minecraft/world/entity/EntityTypes.java").read_text()
out = []
for m in re.finditer(r"public static final EntityType<[\w.]+> (\w+) = register\((.*?)\n \);", text, re.S):
name, body = m.group(1).lower(), m.group(2)
range_ = re.findall(r"\.clientTrackingRange\((\d+)\)", body)
interval = re.findall(r"\.updateInterval\((\w+(?:\.\w+)?)\)", body)
track = ".dontTrackDeltas()" not in body
r = int(range_[-1]) if range_ else 5
if ".noUpdateInterval()" in body or (interval and interval[-1] == "Integer.MAX_VALUE"):
i = 0
else:
i = int(interval[-1]) if interval else 3
out.append((f"minecraft:{name}", r, i, track))
return sorted(out)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--sources", type=Path, default=ROOT / ".local/minecraft/26.3/sources/client")
parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/tracking.rs")
args = parser.parse_args()
rows = parse(args.sources)
if len(rows) < 100:
raise SystemExit(f"only {len(rows)} entity types found")
lines = [
"//! Entity tracking settings per entity type (EntityType.Builder",
"//! clientTrackingRange in chunks, updateInterval in ticks with 0 for never,",
"//! trackDeltas). Generated by tools/generate_entity_tracking.py from the",
"//! decompiled EntityTypes.java; do not edit by hand.",
"",
"/// (entity type, tracking range in chunks, update interval, track deltas), sorted.",
"pub const TRACKING: &[(&str, u8, u32, bool)] = &[",
]
lines += [f' ("{n}", {r}, {i}, {str(t).lower()}),' for n, r, i, t in rows]
lines += [
"];",
"",
"/// The settings of one entity type; unknown types get the builder defaults.",
"pub fn settings(kind: &str) -> (u8, u32, bool) {",
" TRACKING",
" .binary_search_by(|row| row.0.cmp(kind))",
" .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3))",
"}",
"",
]
args.out.write_text("\n".join(lines))
print(f"wrote {len(rows)} entity types to {args.out}")
if __name__ == "__main__":
main()
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""A decoding TCP proxy for the Minecraft 26.3 protocol (offline mode, no
encryption): clients connect to LISTEN, it forwards to TARGET and records
every packet in both directions as JSON lines (time, direction, state, id,
name, size and the payload), following the connection state through the
handshake, login, configuration and play (and back to configuration).
net_capture.py --listen 25570 --target localhost:25565 --out capture.jsonl
The packet names come from crates/horizon-protocol/src/ids.rs, which is
generated from vanilla's packets report. `summary` prints what a capture
contains, `diff` compares the packet sequences of two captures (for example
Horizon hosting and a vanilla server serving the same world).
"""
import argparse
import json
import re
import socket
import sys
import threading
import time
import zlib
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STATES = ["handshake", "status", "login", "configuration", "play"]
def load_names(path=ROOT / "crates/horizon-protocol/src/ids.rs"):
"""{(state, direction): [name by id]} from the generated id tables."""
text = path.read_text()
names = {}
for state in STATES:
block = re.search(r"pub mod %s \{(.*?)\n\}" % state, text, re.S)
if not block:
continue
for direction in ("clientbound", "serverbound"):
part = re.search(r"pub mod %s \{.*?NAMES: &\[&str\] = &\[(.*?)\];" % direction,
block.group(1), re.S)
if part:
names[(state, direction)] = re.findall(r'"([^"]+)"', part.group(1))
return names
def read_varint(data, pos):
value = shift = 0
while True:
if pos >= len(data):
raise IndexError("truncated varint")
b = data[pos]
pos += 1
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
if value & 0x80000000:
value -= 1 << 32
return value, pos
if shift > 35:
raise ValueError("varint too long")
class Session:
"""The state both directions of one connection share."""
def __init__(self, conn_id, out, names, lock, full):
self.id = conn_id
self.state = {"clientbound": "handshake", "serverbound": "handshake"}
self.threshold = -1
self.out = out
self.names = names
self.lock = lock
self.full = full
self.start = time.time()
self.closed = threading.Event()
def name(self, direction, packet_id):
table = self.names.get((self.state[direction], direction), [])
return table[packet_id] if 0 <= packet_id < len(table) else f"unknown_{packet_id}"
def record(self, direction, packet_id, payload):
state = self.state[direction]
name = self.name(direction, packet_id)
entry = {
"conn": self.id,
"t": round(time.time() - self.start, 4),
"dir": "s2c" if direction == "clientbound" else "c2s",
"state": state,
"id": packet_id,
"name": name,
"size": len(payload),
}
if self.full or len(payload) <= 4096:
entry["data"] = payload.hex()
else:
entry["head"] = payload[:512].hex()
with self.lock:
self.out.write(json.dumps(entry) + "\n")
self.out.flush()
self.transition(direction, name, payload)
def transition(self, direction, name, payload):
s = self.state
if direction == "serverbound":
if s["serverbound"] == "handshake" and name == "intention":
pos = read_varint(payload, 0)[1]
length, pos = read_varint(payload, pos)
intent = read_varint(payload, pos + length + 2)[0]
nxt = {1: "status", 2: "login", 3: "login"}.get(intent, "login")
s["serverbound"] = s["clientbound"] = nxt
elif s["serverbound"] == "login" and name == "login_acknowledged":
s["serverbound"] = s["clientbound"] = "configuration"
elif s["serverbound"] == "configuration" and name == "finish_configuration":
s["serverbound"] = s["clientbound"] = "play"
elif s["serverbound"] == "play" and name == "configuration_acknowledged":
s["serverbound"] = s["clientbound"] = "configuration"
elif s["clientbound"] == "login" and name == "login_compression":
self.pending_threshold = read_varint(payload, 0)[0]
class Pipe(threading.Thread):
def __init__(self, session, direction, src, dst):
super().__init__(daemon=True)
self.session, self.direction, self.src, self.dst = session, direction, src, dst
def run(self):
buffer = b""
s = self.session
try:
while True:
chunk = self.src.recv(1 << 16)
if not chunk:
break
buffer += chunk
frames = []
while True:
try:
length, pos = read_varint(buffer, 0)
except IndexError:
break
if len(buffer) < pos + length:
break
frames.append(buffer[:pos + length])
body, buffer = buffer[pos:pos + length], buffer[pos + length:]
threshold = s.threshold
if threshold >= 0:
size, p = read_varint(body, 0)
body = zlib.decompress(body[p:]) if size else body[p:]
packet_id, p = read_varint(body, 0)
s.record(self.direction, packet_id, body[p:])
# The compression threshold applies after its packet, in
# both directions; the client answers only after reading it.
pending = getattr(s, "pending_threshold", None)
if pending is not None:
s.threshold = pending
s.pending_threshold = None
# State switches must be in effect before the peer can
# answer, so forward each frame after recording it.
self.dst.sendall(frames.pop())
except (OSError, ValueError, zlib.error) as e:
with s.lock:
s.out.write(json.dumps({"conn": s.id, "event": "error", "dir": self.direction,
"error": str(e)}) + "\n")
s.out.flush()
finally:
for sock in (self.src, self.dst):
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
s.closed.set()
def serve(listen, target, out_path, full=False, ready=None, stop=None):
names = load_names()
host, port = target.rsplit(":", 1)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", listen))
server.listen()
server.settimeout(0.5)
lock = threading.Lock()
conn_id = 0
with open(out_path, "a") as out:
if ready:
ready.set()
while not (stop and stop.is_set()):
try:
client, _ = server.accept()
except socket.timeout:
continue
conn_id += 1
try:
upstream = socket.create_connection((host, int(port)))
except OSError as e:
client.close()
with lock:
out.write(json.dumps({"conn": conn_id, "event": "error",
"error": f"upstream: {e}"}) + "\n")
continue
for sock in (client, upstream):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
session = Session(conn_id, out, names, lock, full)
Pipe(session, "serverbound", client, upstream).start()
Pipe(session, "clientbound", upstream, client).start()
server.close()
def start_background(listen, target, out_path, full=False):
"""Run the proxy on a thread; returns the stop event."""
ready, stop = threading.Event(), threading.Event()
threading.Thread(target=serve, args=(listen, target, out_path, full, ready, stop),
daemon=True).start()
ready.wait(5)
return stop
def load(path):
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
def play_sessions(entries):
"""Connections that reached the play state."""
return sorted({e["conn"] for e in entries if e.get("state") == "play"})
def summary(entries, conn=None):
lines = []
conns = [conn] if conn else sorted({e["conn"] for e in entries})
for c in conns:
mine = [e for e in entries if e["conn"] == c and "name" in e]
lines.append(f"connection {c}: {len(mine)} packets")
counts = Counter((e["dir"], e["state"], e["name"]) for e in mine)
for (d, s, n), k in sorted(counts.items()):
size = sum(e["size"] for e in mine if (e["dir"], e["state"], e["name"]) == (d, s, n))
lines.append(f" {d} {s:13} {n:40} x{k:<6} {size} bytes")
for e in entries:
if e["conn"] == c and e.get("event") == "error":
lines.append(f" error ({e.get('dir')}): {e['error']}")
return "\n".join(lines)
def sequence(entries, conn, direction="s2c", until="player_position"):
"""Packet names in order, up to and including the first `until`."""
out = []
for e in entries:
if e["conn"] != conn or e.get("dir") != direction or "name" not in e:
continue
out.append(f"{e['state']}/{e['name']}")
if e["name"] == until and e["state"] == "play":
break
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("proxy")
p.add_argument("--listen", type=int, required=True)
p.add_argument("--target", required=True)
p.add_argument("--out", type=Path, required=True)
p.add_argument("--full", action="store_true", help="keep every payload in full")
s = sub.add_parser("summary")
s.add_argument("capture", type=Path)
d = sub.add_parser("diff")
d.add_argument("a", type=Path)
d.add_argument("b", type=Path)
d.add_argument("--until", default="player_position")
args = parser.parse_args()
if args.command == "proxy":
serve(args.listen, args.target, args.out, args.full)
elif args.command == "summary":
print(summary(load(args.capture)))
else:
import difflib
a, b = load(args.a), load(args.b)
sa = sequence(a, play_sessions(a)[0], until=args.until)
sb = sequence(b, play_sessions(b)[0], until=args.until)
sys.stdout.writelines(difflib.unified_diff([x + "\n" for x in sa], [x + "\n" for x in sb],
str(args.a), str(args.b)))
if __name__ == "__main__":
main()
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Query the pinned vanilla bytecode through REA (Reverse Engineer Anything).
REA drives a headless JADX over the shipped game JAR, so answers come from the
bytecode Mojang ships rather than from the Vineflower sources: callers through
lambdas and bridges, every overload of a method, and members the decompiled
sources fold away. Prints REA's normalized result as JSON.
python3 tools/rea_vanilla.py classes DispenserBlock
python3 tools/rea_vanilla.py class net.minecraft.world.level.block.DispenserBlock
python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom
python3 tools/rea_vanilla.py callers net.minecraft.server.level.ServerLevel tickChunk
python3 tools/rea_vanilla.py --jar server-game classes DedicatedServer
The first run downloads the pinned JADX engine into .local/tools/; REA itself
runs from the global `rea` command when it is the pinned version, otherwise
through npx. Needs Node.js 22.19+ and Java 17+.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import lab
COMMANDS = {
"classes": ("search-android-classes", ["query"]),
"class": ("inspect-android-class", ["class_name"]),
"method": ("inspect-android-method", ["class_name", "method_name"]),
"callers": ("trace-android-references", ["class_name", "method_name"]),
"refs": ("trace-android-references", ["class_name"]),
}
def engine(lock):
pin = lock["jadx_headless_mcp"]
jar = lab.LOCAL / "tools" / f"jadx-headless-mcp-{pin['version']}-all.jar"
return lab.download(pin["url"], jar, pin["sha256"], "sha256")
def target(game_dir, name):
"""REA admits JADX targets by their .apk name; JADX reads the class files either way."""
source = game_dir / "jars" / f"{name}.jar"
if not source.exists():
raise SystemExit(f"{source} is missing; run python3 tools/prepare_native_client.py --prepare")
copy = lab.LOCAL / "rea" / f"{name}-{lab.digest(source, 'sha256')[:16]}.apk"
if not copy.exists():
copy.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, copy)
return copy
def rea_command(lock):
pin = lock["rea"]
installed = shutil.which("rea")
if installed:
version = subprocess.run([installed, "--version"], capture_output=True, text=True).stdout.strip()
if version == pin["version"]:
return [installed]
return ["npx", "-y", f"{pin['package']}@{pin['version']}"]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--jar", default="client", choices=["client", "server-game"])
parser.add_argument("--overload-index", type=int)
parser.add_argument("--raw", action="store_true", help="print REA's whole evidence record")
parser.add_argument("command", choices=COMMANDS)
parser.add_argument("arguments", nargs="+")
args = parser.parse_args()
subcommand, names = COMMANDS[args.command]
if len(args.arguments) != len(names):
parser.error(f"{args.command} takes {' '.join(names).upper()}")
lock, game_dir = lab.config()
command = rea_command(lock) + [subcommand, str(target(game_dir, args.jar))]
if args.command in ("callers", "refs"):
command += [args.arguments[0]] + (["--method-name", args.arguments[1]] if args.command == "callers" else [])
else:
command += args.arguments
if args.overload_index is not None:
command += ["--overload-index", str(args.overload_index)]
environment = dict(os.environ, REA_JADX_MCP_JAR=str(engine(lock)))
result = subprocess.run(command + ["--json"], capture_output=True, text=True, env=environment)
try:
record = json.loads(result.stdout)
except json.JSONDecodeError:
sys.stderr.write(result.stdout + result.stderr)
return result.returncode or 1
if "normalized_result" not in record:
details = record.get("details", {})
reasons = [issue["message"] for issue in details.get("issues", [])] or [details.get("reason")]
print(record.get("message"), *filter(None, reasons), sep="\n", file=sys.stderr)
return 1
body = record if args.raw else record["normalized_result"]
if not args.raw:
body.pop("engine", None)
if args.command == "method" and not args.raw and body.get("source", {}).get("text"):
print(f"// {body['class_name']}.{body['method']['reported_signature']}"
f" (overload {body['method']['overload_index']} of {body['overload_count']}, {body['source']['status']})")
print(body["source"]["text"])
else:
print(json.dumps(body, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())
+194
View File
@@ -0,0 +1,194 @@
#!/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`, `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
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, 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):
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)
# 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):
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))
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:
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 runs on a scripted block world.')
print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Compare the audio environment attributes with the vanilla 26.3 data pack.
The oracle evaluates vanilla's `EnvironmentAttributeSystem` (dimension layer,
biome positional layer, dimension timelines, weather layers) for every
dimension type and biome and prints `BACKGROUND_MUSIC` (all three tracks and
`BackgroundMusic.select` for each creative/underwater combination),
`MUSIC_VOLUME` and `AMBIENT_SOUNDS` (loop, mood, additions), plus the
`Musics` constants. Horizon's `MusicTables` and `AmbientTables` answer the same.
"""
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
data = h.RESOURCES / 'data/minecraft'
biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json'))
dimensions = sorted('minecraft:' + p.stem for p in (data / 'dimension_type').glob('*.json'))
return [f'{d} {b} {t}' for d in dimensions for b in biomes for t in (0, 13000)]
def main():
lines = fixtures()
matched, report = h.run_harness(
'audio-attributes', 'VanillaAudioAttributesOracle', 'audio_attributes_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs'],
rust_args=[h.RESOURCES],
scope='Vanilla EnvironmentAttributeSystem values of audio/background_music (with BackgroundMusic.select), audio/music_volume and '
'audio/ambient_sounds for every dimension type x biome at two times of day, and the Musics constants.')
print(f'{matched:,} audio attribute lines match the pinned data ({len(lines):,} cases): {report}', flush=True)
if __name__ == '__main__':
main()
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Compare auto-jump with the pinned client: the real LocalPlayer.updateAutoJump
(and canAutoJump) on a player standing in an independently built copy of the
client's resident test scene, against MotionWorld::update_auto_jump over the
client's actual resources, collision registry and block-collision scan, for
steps, slabs, stairs, fences, walls, snow, carpets, honey, low ceilings and
overhangs approached from every angle with varied speeds, input vectors,
sizes, jump boost and the canAutoJump preconditions."""
import json
import math
import os
from pathlib import Path
import platform
import random
import struct
import subprocess
try:
from . import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking, \
test_native_client as client
except ImportError:
import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking
import test_native_client as client
def fbits(v):
return struct.pack('>f', v).hex()
def dbits(v):
return struct.pack('>d', v).hex()
BLOCKS = [
('stone', {}), ('stone', {}), ('stone', {}),
('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}),
('oak_stairs', {'facing': 'north', 'half': 'bottom'}), ('oak_stairs', {'facing': 'east', 'half': 'bottom'}),
('oak_stairs', {'facing': 'south', 'half': 'top'}), ('oak_stairs', {'facing': 'west', 'half': 'bottom', 'shape': 'outer_left'}),
('oak_fence', {}), ('oak_fence', {'north': 'true', 'south': 'true'}), ('oak_fence_gate', {}),
('cobblestone_wall', {}), ('cobblestone_wall', {'up': 'true', 'east': 'tall'}),
('snow', {'layers': '1'}), ('snow', {'layers': '4'}), ('snow', {'layers': '8'}),
('white_carpet', {}), ('honey_block', {}), ('soul_sand', {}), ('farmland', {}), ('dirt_path', {}),
('chest', {}), ('enchanting_table', {}), ('oak_trapdoor', {}), ('oak_trapdoor', {'half': 'top'}),
('oak_trapdoor', {'open': 'true', 'facing': 'east'}), ('daylight_detector', {}), ('glass', {}), ('iron_bars', {}),
('lantern', {}), ('cake', {}), ('anvil', {}), ('hopper', {}), ('oak_leaves', {}), ('cobweb', {}), ('ladder', {}),
('red_bed', {'part': 'foot'}),
]
ORIGIN = (20, 4, -4)
def placed(rng, count):
blocks = {}
ox, oy, oz = ORIGIN
for _ in range(count):
x, y, z = ox + rng.randint(-3, 3), oy + rng.choice([0, 0, 0, 1, 1, 2, 3]), oz + rng.randint(-3, 3)
name, props = rng.choice(BLOCKS)
blocks[(x, y, z)] = [x, y, z, 'minecraft:' + name, props]
return list(blocks.values())
DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), (0.6000000238418579, 1.7999999523162842)]
def player(rng, x, y, z, yaw):
w, h = rng.choice(DIMS)
return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08,
yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])),
speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])),
move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677),
(0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])],
width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]),
enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2]))
def cases(rng):
ox, oy, oz = ORIGIN
# Walk straight at each block from the four sides, at several speeds.
for name, props in BLOCKS:
for yaw, (dx, dz) in [(0.0, (0, 1)), (90.0, (-1, 0)), (180.0, (0, -1)), (-90.0, (1, 0)), (45.0, (-0.7, 0.7))]:
for step in (0.1, 0.215, 0.03, 0.0):
for lift in (0, 1):
blocks = [[ox, oy + lift, oz, 'minecraft:' + name, props]]
if lift:
blocks.append([ox, oy, oz, 'minecraft:stone', {}])
x = ox + 0.5 - dx * 1.1
z = oz + 0.5 - dz * 1.1
p = player(rng, x, float(oy), z, yaw)
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0))
yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step))
# Ceilings above the player and above the step.
for ceiling in range(2, 6):
for step_height in (0, 1):
blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}],
[ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]]
p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0)
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
width=fbits(0.6), height=fbits(1.8))
yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0))
for _ in range(9000):
blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30]))
x = ox + rng.uniform(-2, 3)
z = oz + rng.uniform(-2, 3)
y = float(oy) + rng.choice([0.0, 0.0, 0.0, 0.5, 1.0, 0.0625, 0.9375])
yaw = rng.choice([0.0, 90.0, 180.0, -90.0, 45.0, rng.uniform(-360, 360)])
p = player(rng, x, y, z, yaw)
move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)])
angle = rng.uniform(0, 6.283)
yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move))
def main():
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-auto-jump-parity'
build.mkdir(exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
resources_before = client.resource_fingerprint(resources)
oracle = 'VanillaAutoJumpOracle'
parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py',
parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java',
parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs',
lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs']
tested = base.source_hashes(sources)
fixtures = list(cases(random.Random(0x4155544f)))
inputs = build / 'cases.jsonl'
inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures))
input_hash = lab.digest(inputs, 'sha256')
classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major'])
binary = harness.build_probe(build, 'auto_jump_probe')
harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600)
harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client')
matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures))
base.ensure_sources_unchanged(sources, tested)
if input_hash != lab.digest(inputs, 'sha256') or resources_before != client.resource_fingerprint(resources):
raise AssertionError('Fixtures or resources changed during validation')
jumps = sum(1 for line in (build / 'rust.txt').read_text().splitlines() if line == 'jump 1')
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'],
platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], fixtures=len(fixtures),
auto_jumps=jumps, sources_sha256=tested, input_sha256=input_hash, resources=resources_before,
client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=matched,
output_sha256=lab.digest(build / 'rust.txt', 'sha256'),
scope='The actual LocalPlayer.updateAutoJump with canAutoJump (option, autoJumpTime, onGround, '
'isStayingOnGroundSurface, passenger, input move vector, getBlockJumpFactor over the real level) on a '
'LocalPlayer shell in an independently constructed copy of the resident test scene with each case\'s '
'real block states placed; collisions through CollisionGetter.getCollisions/BlockCollisions with the '
'player\'s EntityCollisionContext and real collision shapes, jump boost from a real MobEffectInstance. '
'Rust runs MotionWorld::update_auto_jump over the client\'s loaded resources, collision registry and '
'block-collision scan. Entity collisions (none in the scene) and the riding/minecart paths are not exercised.'))
print(f'{len(fixtures):,} auto-jump cases ({jumps:,} jumps) match the pinned client: {report}', flush=True)
if __name__ == '__main__':
main()
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env python3
"""Compare block-entity rendering with the vanilla 26.3 client renderers.
The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla
block entity, sets its animation fields, runs the real BlockEntityRenderer's
extractRenderState and submit, and captures what it submits: model vertices
after setupAnim and the pose stack (sprite-local UVs, tint, normal, light),
text calls and items. `examples/block_entity_render_fixture` replays the case
through Horizon's BlockEntityRenderer. Quads are matched by texture and
position; colours compare vanilla's tint times the entity shader's
`minecraft_mix_light` for the vanilla normal with Horizon's baked colour.
test_block_entity_render_parity.py [--filter SUBSTRING] [--detail N] [--tolerance EPS]
"""
import argparse
import json
import math
import os
from pathlib import Path
import random
import subprocess
import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
HORIZONTAL = ['north', 'south', 'west', 'east']
ALL = HORIZONTAL + ['up', 'down']
NO_OVERLAY = 10 << 16
def cases():
rng = random.Random(0x42454e44)
out = []
def add(block, **extra):
case = {'block': block, 'pos': [rng.randint(-40, 40), rng.randint(-20, 90), rng.randint(-40, 40)],
'light': [rng.randint(0, 15), rng.randint(0, 15)], 'partial': round(rng.random(), 4),
'camera': [0.5, 70.0, 0.5]}
case.update(extra)
out.append(case)
for block in ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'weathered_copper_chest',
'oxidized_copper_chest', 'waxed_copper_chest', 'waxed_oxidized_copper_chest']:
for facing in HORIZONTAL:
for kind in ['single', 'left', 'right']:
add(f'minecraft:{block}[facing={facing},type={kind}]', open=rng.choice([0.0, 0.25, 0.7, 1.0]))
for facing in HORIZONTAL:
add(f'minecraft:ender_chest[facing={facing}]', open=rng.choice([0.0, 0.5, 1.0]))
texts = [['Hello', '', 'World', ''], ['A much longer line that cannot fit', 'mid', 'iii', 'WWWWWWWWWWWWWWW'],
['', '', '', ''], ['x', 'Sign text', '#1 (test)', '!']]
for wood in ['oak', 'spruce', 'cherry', 'crimson', 'bamboo', 'pale_oak']:
signs = [f'minecraft:{wood}_sign[rotation={r}]' for r in (0, 3, 8, 13)] + \
[f'minecraft:{wood}_wall_sign[facing={f}]' for f in HORIZONTAL] + \
[f'minecraft:{wood}_hanging_sign[rotation={r},attached={a}]' for r, a in ((0, 'false'), (6, 'true'), (11, 'false'))] + \
[f'minecraft:{wood}_wall_hanging_sign[facing={f}]' for f in HORIZONTAL]
for block in signs:
side = lambda: {'lines': rng.choice(texts), 'color': rng.choice(DYES), 'glowing': rng.random() < 0.4}
add(block, sign={'front': side(), 'back': side(), 'near': rng.random() < 0.5})
patterns = ['minecraft:stripe_bottom', 'minecraft:creeper', 'minecraft:gradient', 'minecraft:flower',
'minecraft:border', 'minecraft:skull', 'minecraft:globe', 'minecraft:piglin']
for color in ['white', 'red', 'light_gray', 'black']:
for r in (0, 5, 12):
add(f'minecraft:{color}_banner[rotation={r}]',
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 3))])
for f in HORIZONTAL:
add(f'minecraft:{color}_wall_banner[facing={f}]',
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))])
add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)])
for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head',
'piglin_head', 'player_head']:
wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head')
for r in (0, 4, 9):
add(f'minecraft:{skull}[rotation={r}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)])
for f in HORIZONTAL:
add(f'minecraft:{wall}[facing={f}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)])
for color in [None, 'white', 'light_gray', 'purple', 'black']:
name = 'shulker_box' if color is None else f'{color}_shulker_box'
for f in ALL:
p = rng.choice([0.0, 0.0, 0.3, 1.0])
add(f'minecraft:{name}[facing={f}]', progress=p, progressOld=max(0.0, p - 0.1))
for attach in ['floor', 'ceiling', 'single_wall', 'double_wall']:
for f in HORIZONTAL:
shake = rng.choice([None] + HORIZONTAL)
extra = {'bellTicks': rng.randint(0, 50)}
if shake:
extra['shake'] = shake
add(f'minecraft:bell[attachment={attach},facing={f}]', **extra)
sherds = ['', 'minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:skull_pottery_sherd',
'minecraft:heart_pottery_sherd', 'minecraft:flow_pottery_sherd']
for f in HORIZONTAL:
for wobble in [None, ['POSITIVE', 0.3], ['NEGATIVE', 0.6], ['POSITIVE', 1.2]]:
extra = {'sherds': [rng.choice(sherds) for _ in range(4)]}
if wobble:
extra['wobble'] = wobble
add(f'minecraft:decorated_pot[facing={f}]', **extra)
for active in (False, True):
for _ in range(4):
add('minecraft:conduit', conduit={'tickCount': rng.randint(0, 400), 'active': active,
'hunting': rng.random() < 0.5, 'activeRotation': rng.uniform(0, 300)},
yaw=round(rng.uniform(-180, 180), 2), pitch=round(rng.uniform(-90, 90), 2))
for _ in range(6):
o = rng.random()
add('minecraft:enchanting_table', book={'time': rng.randint(0, 2000), 'flip': rng.uniform(-3, 3),
'oFlip': rng.uniform(-3, 3), 'open': o, 'oOpen': max(0.0, o - 0.1),
'rot': rng.uniform(-3.1, 3.1), 'oRot': rng.uniform(-3.1, 3.1)})
for f in HORIZONTAL:
add(f'minecraft:lectern[facing={f},has_book=true]')
add(f'minecraft:lectern[facing={f},has_book=false]')
for prefix in ['', 'exposed_', 'weathered_', 'oxidized_', 'waxed_']:
for pose in ['standing', 'running', 'sitting', 'star']:
add(f'minecraft:{prefix}copper_golem_statue[facing={rng.choice(HORIZONTAL)},copper_golem_pose={pose}]')
for _ in range(8):
add('minecraft:beacon', gameTime=rng.randint(0, 10 ** 6),
camera=[rng.uniform(-300, 300), 70.0, rng.uniform(-300, 300)],
beam=[[0xFF000000 | rng.randint(0, 0xFFFFFF), rng.randint(1, 30)] for _ in range(rng.randint(1, 3))])
for block in ['end_portal', 'end_gateway', 'campfire[facing=north]', 'spawner',
'trial_spawner', 'vault', 'suspicious_sand', 'oak_shelf[facing=east]']:
add('minecraft:' + block)
return out
def light_coords(light):
"""Horizon light (sky*16 low byte, block*16 next) as vanilla light coords."""
return ((light & 0xFF) << 16) | ((light >> 8) & 0xFF)
def lights():
def norm(v):
n = math.sqrt(sum(x * x for x in v))
return [x / n for x in v]
return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7])
L0, L1 = lights()
def mix(normal):
d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal)))
return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4)
def vanilla_quads(submits):
quads, other = [], []
for s in submits:
custom = s['type'] == 'submitCustomGeometry'
if s['type'] != 'submitModel' and not custom:
other.append(s)
continue
verts = s['vertices']
for i in range(0, len(verts), 4):
q = verts[i:i + 4]
tint = q[0][3] & 0xFFFFFFFF
# Custom geometry (beacon beams) is unlit; models get the entity shader's mix light.
b = 1.0 if custom else mix(q[0][8:11])
ch = lambda shift: int(((tint >> shift) & 255) * b)
quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q],
'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7],
'overlay': q[0][6], 'type': s['renderType'], 'custom': custom})
return quads, other
def area(q):
import itertools
p = [v[:3] for v in q]
a = [p[1][i] - p[0][i] for i in range(3)]
b = [p[2][i] - p[0][i] for i in range(3)]
c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
a2 = [p[3][i] - p[0][i] for i in range(3)]
d = [b[1] * a2[2] - b[2] * a2[1], b[2] * a2[0] - b[0] * a2[2], b[0] * a2[1] - b[1] * a2[0]]
return math.sqrt(sum(x * x for x in c)) + math.sqrt(sum(x * x for x in d))
def pair(vq, rq):
"""Matches quads of the same texture globally by ascending vertex distance."""
candidates = []
for i, a in enumerate(vq):
for j, b in enumerate(rq):
if a['texture'] == b['texture']:
d = sum((a['v'][k][c] - b['v'][k][c]) ** 2 for k in range(4) for c in range(5))
candidates.append((d, i, j))
candidates.sort()
match, used = {}, set()
for d, i, j in candidates:
if i not in match and j not in used:
match[i] = j
used.add(j)
return [(a, rq[match[i]] if i in match else None) for i, a in enumerate(vq)], \
[b for j, b in enumerate(rq) if j not in used]
def compare_case(v, r, tol):
problems = []
vq, other = vanilla_quads(v['submits'])
for s in other:
if s['type'] == 'submitText':
continue
problems.append(f'unsupported vanilla submit {s["type"]}')
rq = r.get('quads', [])
if len(vq) != len(rq):
tex = lambda qs: sorted({q['texture'] for q in qs})
problems.append(f'{len(vq)} vanilla quads {tex(vq)} vs {len(rq)} Horizon quads {tex(rq)}')
pairs, extra = pair(vq, rq)
for b in extra[:1]:
problems.append(f'extra Horizon quad {b["texture"]} {b["v"]}')
for a, b in pairs:
if b is None:
problems.append(f'missing {a["texture"]} quad {a["v"]}')
break
bad = [(i, j) for i in range(4) for j in range(5) if abs(a['v'][i][j] - b['v'][i][j]) > tol * (1 + abs(a['v'][i][j]))]
if bad:
problems.append(f'{a["texture"]} vertices {a["v"]} != {b["v"]}')
break
if a['custom']:
# Horizon packs the beam sprite's v range into the light bytes (its shader wraps v).
got = b['color']
if [got & 255, (got >> 8) & 255, (got >> 16) & 255, got >> 24] != a['rgb'] + [a['alpha']]:
problems.append(f'{a["texture"]} colour {a["rgb"]}/{a["alpha"]} != {got:#x}')
break
continue
if a['overlay'] != NO_OVERLAY:
problems.append(f'overlay {a["overlay"]}')
got = b['color']
rgb = [got & 255, (got >> 8) & 255, (got >> 16) & 255]
# A zero-area quad shows nothing: vanilla shades it by its face normal, Horizon cannot derive one.
if area(a['v']) > 1e-9 and (any(abs(x - y) > 1 for x, y in zip(a['rgb'], rgb)) or (got >> 24) != a['alpha']):
problems.append(f'{a["texture"]} colour {a["rgb"]}/{a["alpha"]} != {rgb}/{got >> 24} at {a["v"]}')
break
if a['light'] != light_coords(b['light']):
problems.append(f'{a["texture"]} light {a["light"]:#x} != {light_coords(b["light"]):#x}')
break
vt = [s for s in v['submits'] if s['type'] == 'submitText' and s['text']]
rt = r.get('texts', [])
if len(vt) != len(rt):
problems.append(f'{len(vt)} vanilla texts {[t["text"] for t in vt]} vs {len(rt)} Horizon texts {[t["text"] for t in rt]}')
for a, b in zip(vt, rt):
for k in ('text', 'x', 'y', 'color', 'outline', 'light'):
av, bv = a[k], b[k]
if k in ('color', 'outline'):
av &= 0xFFFFFFFF
if (abs(av - bv) > 1e-4) if isinstance(av, float) else av != bv:
problems.append(f'text {a["text"]!r} {k} {av!r} != {bv!r}')
if any(abs(x - y) > tol * (1 + abs(x)) for x, y in zip(a['matrix'], b['matrix'])):
problems.append(f'text {a["text"]!r} matrix {a["matrix"]} != {b["matrix"]}')
return problems
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--filter', default='')
parser.add_argument('--detail', type=int, default=2)
parser.add_argument('--tolerance', type=float, default=2e-5)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-block-entity-render-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
chosen = [c for c in cases() if args.filter in c['block']]
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
classes = build / 'classes'; classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaBlockEntityRenderOracle'))], 'compile-java')
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityRenderOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s})
(build / 'textures.txt').write_text(''.join(t + '\n' for t in textures))
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--',
resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust')
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust), (len(vanilla), len(rust))
groups, errors, skipped, passed = {}, {}, {}, 0
for v, r in zip(vanilla, rust):
block = v['case']['block'].split('[')[0]
if 'error' in v:
errors.setdefault(block, v['error']); continue
if 'skip' in r:
if not v['submits']:
passed += 1 # vanilla submits nothing either (e.g. a lectern without a book)
else:
skipped.setdefault(r['skip'], set()).add(block)
continue
problems = compare_case(v, r, args.tolerance)
if problems:
groups.setdefault(block, []).append((v['case'], problems))
else:
passed += 1
for reason, blocks in sorted(skipped.items()):
print(f'NOT RENDERED by Horizon ({reason}): {", ".join(sorted(blocks))}')
for block, error in sorted(errors.items()):
print(f'ORACLE ERROR {block}: {error}')
for block, items in sorted(groups.items()):
print(f'MISMATCH {block}: {len(items)} cases')
for case, problems in items[:args.detail]:
print(' ', json.dumps(case))
for p in problems[:4]:
print(' ', p[:600])
total = len(vanilla)
print(f'{passed}/{total} cases match; {sum(len(b) for b in skipped.values())} not rendered; {len(errors)} oracle errors')
if groups or errors or skipped:
sys.exit(1)
print('block entity render parity ok')
if __name__ == '__main__':
main()
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Compare the camera with the pinned client: Camera.tick (eye height and
field-of-view easing), alignWithEntity (view rotation quaternion and basis,
interpolated eye, third person back and front, camera distance and scale
attributes with mounts, getMaxZoom clipping against visual shapes, sleeping),
calculateFov/calculateHudFov (option, modifier, death and fluid effects,
panoramic mode), AbstractClientPlayer.getFieldOfViewModifier (flight, speed
attribute against walking speed, bow draw, spyglass), the walk and bob
history (ClientAvatarState, updateBob) and GameRenderer.bobHurt/bobView,
driven tick by tick and frame by frame with identical scripted states."""
import json
import random
import struct
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def fbits(v):
return struct.pack('>f', v).hex()
def dbits(v):
return struct.pack('>d', v).hex()
def f32(v):
return struct.unpack('>f', struct.pack('>f', v))[0]
WALK = [0.1, 0.0, 0.05, 0.2, 1e-3, -0.1, 0.15]
SPEED = [f32(0.1), f32(0.1) * 1.3, 0.0, 0.03, 0.5, 1024.0, 0.13, f32(0.1) * 0.85, f32(0.1) * 1.4]
TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3]
def fov_fields(rng):
use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]])
return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])),
speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use)
def fov_cases(rng):
for flying in (False, True):
for ws in WALK:
for speed in SPEED:
for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]:
for fp in (False, True):
for scale in (0.0, 0.5, 1.0):
yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale))
for _ in range(3000):
yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()])))
FULL = [[0, 0, 0, 1, 1, 1]]
SHAPES = [FULL, FULL, [[0, 0, 0, 1, 0.5, 1]], [[0, 0.5, 0, 1, 1, 1]], [[0, 0, 0, 1, 1, 0.125]], [[0.375, 0, 0.375, 0.625, 1, 0.625]],
[[0, 0, 0, 0.5, 1, 1], [0.5, 0, 0.5, 1, 1, 1]], []]
def world(rng, center):
cells = {}
cx, cy, cz = center
for _ in range(rng.choice([0, 3, 10, 40, 120])):
p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6))
cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)]
return cells
ANGLES = [0.0, 90.0, -90.0, 180.0, -180.0, 45.0, 360.0, 720.5, -33.3, 1e-3, 89.9]
def angle(rng):
return rng.choice(ANGLES + [rng.uniform(-90, 90), rng.uniform(-400, 400)])
def entity_state(rng, center):
pos = [center[i] + rng.uniform(0, 1) for i in range(3)]
prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos]
kind = 'player' if rng.random() < 0.85 else 'marker'
xr, yr = angle(rng), angle(rng)
s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr),
xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])),
eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)])))
s.update(fov_fields(rng))
s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])),
dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])),
sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]),
dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]),
mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]]))
return s
def camera_cases(rng):
for n in range(2500):
center = rng.choice([(0, 64, 0), (-10, -60, 7), (1000, 120, -3000), (0, 0, 0)])
ops = []
for _ in range(rng.randrange(1, 40)):
kind = rng.choice(['entity', 'tick', 'tick', 'tick', 'frame', 'frame', 'frame', 'type'])
if not ops:
kind = 'entity'
if kind == 'entity':
ops.append(['entity', entity_state(rng, center)])
elif kind == 'tick':
ops.append(['tick'])
elif kind == 'frame':
pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()])
ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05])
else:
ops.append(['type', rng.randrange(3)])
yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]),
effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]),
cells=world(rng, center), ops=ops)
# A walled-in third-person camera stepping through every distance bound.
for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]:
for wall in range(0, 6):
for yaw in [0.0, 90.0, 180.0, 270.0, 45.0]:
cells = {}
for dx in range(-6, 7):
for dy in range(62, 68):
cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL]
cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL]
s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)],
xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False,
ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist),
sleeping=None, dead=None, mount=None)
ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] for pt in (0.0, 0.5, 1.0)]
yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops)
def bob_cases(rng):
for n in range(6000):
living = None
if rng.random() < 0.8:
living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])),
duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])),
death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))]))
player = None
if rng.random() < 0.8:
player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])),
fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))]
yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])),
view=rng.random() < 0.8)
def avatar_cases(rng):
for n in range(1500):
ops = []
for _ in range(rng.randrange(1, 60)):
kind = rng.choice(['tick', 'move', 'move', 'bob', 'bob', 'frame', 'frame', 'reset'])
if kind == 'tick':
ops.append(['tick'])
elif kind == 'move':
ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))])
elif kind == 'bob':
v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])]
ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]])
elif kind == 'frame':
ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))])
else:
ops.append(['reset'])
yield dict(t='avatar', ops=ops)
def make_cases(build):
rng = random.Random(0x43414d45)
path = build / 'cases.jsonl'
cases = build / 'cases'
cases.mkdir(exist_ok=True)
count = 0
with path.open('w') as out:
for generator in (fov_cases, camera_cases, bob_cases, avatar_cases):
for case in generator(rng):
text = json.dumps(case, separators=(',', ':'))
out.write(text + '\n')
if count < 20000:
(cases / str(count)).write_text(text)
count += 1
return path, count
def main():
scope = ('Real Camera.tick, tickFov, alignWithEntity (setRotation quaternion and forwards/up/left basis, move, '
'interpolated eye with eye-height easing, first person, third person back and mirrored front, scale and '
'camera_distance attributes including a living mount, getMaxZoom over the actual Level.clip with '
'ClipContext.Block.VISUAL against controlled visual shapes, sleeping bed orientation), calculateFov and '
'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), '
'AbstractClientPlayer.getFieldOfViewModifier with real Abilities, attribute maps and item stacks, '
'ClientAvatarState walk/bob history with AbstractClientPlayer.updateBob, and GameRenderer.bobHurt/bobView '
'as the full JOML pose matrix with its property flags. The camera entity is a shell with controlled '
'queries; getFluidInCamera is supplied (the fog harnesses cover fluid detection) and the new-minecart '
'interpolation branch is not exercised.')
harness.differential(
'rust-camera-parity', 'VanillaCameraOracle', 'camera_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/camera.rs'])
if __name__ == '__main__':
main()
+17 -3
View File
@@ -141,7 +141,8 @@ def parse_nbt(text, i=0):
def nbt_matches(vanilla, rust, default):
"""Horizon stores the placed data only; vanilla saves defaults too. Every key
Horizon sets must match, and every other vanilla key must be the fresh default."""
Horizon sets must match, and every other vanilla key must be what vanilla
loads for an absent key (the oracle's second form)."""
if isinstance(vanilla, dict) and isinstance(rust, dict):
default = default if isinstance(default, dict) else {}
if 'LootTableSeed' in rust and 'LootTable' not in rust:
@@ -154,7 +155,11 @@ def nbt_matches(vanilla, rust, default):
return False
elif value != default.get(key):
return False
return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD for key in rust)
return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD
or omitted_on_save(key, rust) for key in rust)
if isinstance(vanilla, tuple) and vanilla[0] == 'str' and isinstance(rust, dict) and set(rust) == {'text'}:
# A literal text component saves as its plain string: {text:"a"} is "a".
return vanilla == rust['text']
if isinstance(vanilla, list) and isinstance(rust, list):
return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust))
if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil':
@@ -163,6 +168,14 @@ def nbt_matches(vanilla, rust, default):
return vanilla == rust
def omitted_on_save(key, rust):
"""Template keys that vanilla's codecs leave out when re-saving the loaded block entity."""
if key == 'patterns' and rust[key] == []:
return True # BannerBlockEntity saves its patterns only when there are some
# SignText saves filtered_messages only when some line differs from messages.
return key == 'filtered_messages' and rust[key] == rust.get('messages')
def entity_matches(vanilla, rust):
if vanilla is None:
return False
@@ -258,6 +271,7 @@ def pick_structures(starts, per_kind, rng):
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seeds', type=int, default=3)
parser.add_argument('--seed', type=int, action='append', help='run only this seed (repeatable)')
parser.add_argument('--per-structure', type=int, default=2)
parser.add_argument('--sites', type=int, default=6, help='terrain sites per overworld seed')
parser.add_argument('--radius', type=int, default=1, help='chunk radius around each site')
@@ -281,7 +295,7 @@ def main():
biome_seen = set()
structure_seen = Counter()
started = time.time()
for seed in SEEDS[:args.seeds]:
for seed in args.seed or SEEDS[:args.seeds]:
rng = random.Random(seed)
for dimension in dimensions:
rects, labels = [], []
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Compare entity death drops (loot tables, equipment drops, experience) with vanilla.
Java (VanillaEntityDeathLootOracle) builds the real victim, killer and damage
source on a stand-in ServerLevel and runs LivingEntity.die's drop step; Rust
(entity_death_loot_fixture) runs horizon_client::mobs::drops on the same cases.
Every living entity type with a loot table is killed by a player with and
without looting, by nothing, on fire, with a smelting weapon, as a baby, with
luck and with worn equipment, plus each table's special conditions (sheep
colours, cube sizes, frog kills, skeleton and charged creeper kills, fireballs,
lightning, raid captains and vehicles). Loot draws come from the world's random
sequences; several victims are killed in turn per case.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# Living entity types with an entity loot table that the corpus skips: players
# and stands are not mobs, the dragon dies over 200 ticks, and the giant and
# the copper golem are not Horizon mob types.
SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'}
# Types Horizon keeps body armour for in the head slot: their corpus wears
# body items instead of helmets.
BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama',
'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'}
WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2',
'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1']
ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings',
'feet': 'minecraft:diamond_boots', 'mainhand': 'minecraft:iron_sword', 'offhand': 'minecraft:shield'}
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
def corpus(types):
rng = random.Random(0x4C4F4F54)
cases = []
def add(name, **kv):
kv.setdefault('seed', rng.randrange(-2**63, 2**63))
kv.setdefault('rand', rng.randrange(-2**47, 2**47))
cases.append(name + ''.join(f' {k}={v}' for k, v in kv.items()))
for t in types:
n = t.split(':')[1]
add(f'{n}-player', type=t, killer='player', weapon='minecraft:iron_sword', kills=4)
add(f'{n}-none', type=t, source='generic', kills=3)
add(f'{n}-mob', type=t, killer='minecraft:spider', kills=2)
for i, weapon in enumerate(WEAPONS[1:]):
add(f'{n}-weapon{i}', type=t, killer='player', weapon=weapon, kills=4)
add(f'{n}-fire', type=t, killer='player', fire=1, kills=3)
add(f'{n}-fire-nokill', type=t, fire=1, source='fire', kills=2)
add(f'{n}-baby', type=t, killer='player', baby=1, weapon='minecraft:iron_sword;looting:3', kills=3)
add(f'{n}-luck', type=t, killer='player', luck=rng.choice([1, 2, 5]), kills=3)
add(f'{n}-arrow', type=t, killer='player', source='arrow', weapon='minecraft:bow;looting:3', kills=2)
head = 'body' if n in BODY else 'head'
armour = dict(ARMOUR)
if n in BODY:
armour['body'] = armour.pop('head').replace('helmet', 'horse_armor')
add(f'{n}-gear', type=t, killer='player', weapon='minecraft:iron_sword;looting:3', kills=6, **armour)
add(f'{n}-gear-plain', type=t, killer='player', kills=6, mainhand='minecraft:stone_axe', chance_mainhand=0.5,
**{head: 'minecraft:leather_helmet', f'chance_{head}': 2.0})
add(f'{n}-gear-nokill', type=t, source='generic', kills=4, feet='minecraft:iron_boots', chance_feet=1.0,
**{head: 'minecraft:carved_pumpkin', f'chance_{head}': 2.0})
add(f'{n}-gear-mob', type=t, killer='minecraft:skeleton', source='arrow', kills=4, feet='minecraft:iron_boots', chance_feet=1.0,
weapon='minecraft:bow;looting:3')
for color in DYES:
add(f'sheep-{color}', type='minecraft:sheep', color=color, killer='player', kills=3)
add(f'sheep-{color}-sheared', type='minecraft:sheep', color=color, sheared=1, killer='player', kills=2)
for cube in ['minecraft:slime', 'minecraft:magma_cube', 'minecraft:sulfur_cube']:
for size in [1, 2, 3, 4]:
add(f'{cube[10:]}-size{size}', type=cube, size=size, killer='player', weapon='minecraft:iron_sword;looting:2', kills=4)
for frog in ['temperate', 'warm', 'cold']:
for size in [1, 2, 4]:
add(f'magma_cube-frog-{frog}-{size}', type='minecraft:magma_cube', size=size, killer='minecraft:frog', frog='minecraft:' + frog,
pkill=rng.choice([0, 1]), kills=3)
add('creeper-skeleton', type='minecraft:creeper', killer='minecraft:skeleton', source='arrow', pkill=1, kills=3)
add('creeper-stray', type='minecraft:creeper', killer='minecraft:stray', source='arrow', kills=2)
for victim in ['zombie', 'skeleton', 'creeper', 'wither_skeleton', 'piglin', 'zombie_villager', 'cow']:
add(f'charged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', charged=1, source='explosion', kills=2)
add(f'uncharged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', source='explosion', kills=2)
add('ghast-fireball', type='minecraft:ghast', killer='player', source='fireball', kills=4)
add('ghast-fireball-ghast', type='minecraft:ghast', killer='minecraft:ghast', source='fireball', kills=2)
add('turtle-lightning', type='minecraft:turtle', source='lightning', kills=3)
add('turtle-lightning-player', type='minecraft:turtle', source='lightning', pkill=1, kills=3)
add('pillager-captain', type='minecraft:pillager', captain=1, leader=1, killer='player', kills=3)
add('pillager-captain-none', type='minecraft:pillager', captain=1, leader=1, source='generic', kills=2)
add('pillager-captain-looting', type='minecraft:pillager', captain=1, leader=1, killer='player',
weapon='minecraft:iron_sword;looting:3', kills=4, chance_head=2.0)
add('pillager-banner-only', type='minecraft:pillager', captain=1, killer='player', kills=3)
add('pillager-leader-only', type='minecraft:pillager', leader=1, killer='player', kills=2)
add('vindicator-captain', type='minecraft:vindicator', captain=1, leader=1, killer='player', kills=2)
for animal in ['pig', 'strider', 'horse', 'camel', 'donkey']:
add(f'{animal}-saddle', type='minecraft:' + animal, saddle='minecraft:saddle', chance_saddle=2.0, killer='player', kills=2)
add(f'{animal}-saddle-default', type='minecraft:' + animal, saddle='minecraft:saddle', killer='player', kills=6)
add('zombie-horse', type='minecraft:zombie', vehicle='minecraft:zombie_horse', killer='player', kills=4)
add('zombie-baby-chicken', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', killer='player', kills=3)
add('zombie-baby-chicken-none', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', source='generic', kills=2)
add('husk-camel', type='minecraft:husk', vehicle='minecraft:camel_husk', killer='player', kills=3)
for weapon in WEAPONS:
add('wither-' + weapon.split(';')[-1].replace(':', ''), type='minecraft:wither', killer='player', weapon=weapon, kills=2)
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-entity-death-loot-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
tables = resources / 'data/minecraft/loot_table/entities'
types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus(types)
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
try:
matched = base.compare(build / 'server.txt', build / 'rust.txt')
except AssertionError as error:
raise SystemExit(str(error) + explain(build)) from None
base.ensure_sources_unchanged(sources, tested)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'types': len(types), 'skipped': sorted(SKIPPED), 'matched_output_lines': matched, 'sources_sha256': tested,
'scope': 'LivingEntity.dropAllDeathLoot after the killer\'s killedEntity hook: entity loot tables under the world random '
'sequence, Mob.dropCustomDeathLoot equipment drops and durability, species death loot, experience orbs.'})
print(f'{len(cases):,} death-drop cases over {len(types)} entity types match vanilla ({matched:,} lines)')
def explain(build):
def sections(path):
out, name = {}, None
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
if line.startswith('== '):
name = line[3:]
out[name] = []
elif name is not None:
out[name].append(line)
return out
left, right = sections(build / 'server.txt'), sections(build / 'rust.txt')
bad = [n for n in left if left[n] != right.get(n)]
report = f'\n{len(bad)} differing cases'
for name in bad[:30]:
a, b = left[name], right.get(name, [])
diffs = [(x, y) for x, y in zip(a, b) if x != y][:3]
if len(a) != len(b):
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
report += f'\n {name}: {diffs}'
return report
if __name__ == '__main__':
main()
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Compare the frame limiter with the pinned client: the real
FramerateLimiter.limitDisplayFPS bytecode, its clock calls rewritten to a
scripted virtual clock, against the Rust limiter with the same script, frame
by frame: sleep requests, spin-waits, overshoot averaging and its reset on a
limit change, interrupted sleeps, oversleep and early wake-ups, the "below
260" condition of Minecraft.runTick, and the limits FramerateLimitTracker
hands it (option values, 60 in menus, 10 when minimised or idle)."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
LIMITS = [10, 30, 60, 60, 120, 144, 165, 240, 250, 259, 260, 1, 2, 7, 1000, 2**31 - 1]
def cases(rng):
for limit in LIMITS:
for overshoot in ([0], [50_000], [3_000_000], [30_000_000], [-200_000], [100_000, 2_500_000, 0, 24_999_999, 25_000_000]):
for spin in (1_000, 50_000, 7_919):
frames = [[rng.choice([0, 1_000_000, 4_000_000, 16_000_000]), limit] for _ in range(12)]
yield dict(now=10**12, call=rng.choice([0, 25]), spin=spin, overshoot=overshoot, interrupts=[False],
last=10**12, average=0, last_limit=0, frames=frames)
for n in range(5000):
frames = []
limit = rng.choice(LIMITS)
for _ in range(rng.randrange(1, 40)):
if rng.random() < 0.15:
limit = rng.choice(LIMITS)
work = rng.choice([0, 100_000, 2_000_000, 5_000_000, 16_666_666, 30_000_000, 120_000_000, rng.randrange(0, 50_000_000)])
frames.append([work, limit])
start = rng.choice([0, 10**9, 10**15, rng.randrange(0, 10**16)])
yield dict(now=start, call=rng.choice([1, 30, 400, 20_000]), spin=rng.choice([100, 1_000, 70_000, 600_000]),
overshoot=[rng.choice([0, 30_000, 80_000, 1_200_000, 2_100_000, 24_000_000, 26_000_000, -300_000, rng.randrange(-1_000_000, 4_000_000)])
for _ in range(rng.randrange(1, 8))],
interrupts=[False] + [rng.random() < 0.3 for _ in range(rng.randrange(0, 5))],
last=start - rng.choice([0, 1, 5_000_000, 200_000_000]),
average=rng.choice([0, 0, 1, 500_000, 2_000_000]), last_limit=rng.choice([0, 60, limit]), frames=frames)
def make_cases(build):
rng = random.Random(0x46505331)
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(rng):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The actual FramerateLimiter.limitDisplayFPS bytecode from the client jar, loaded through a ClassFile '
'rewrite that redirects System.nanoTime, LockSupport.parkNanos, Thread.interrupted and Thread.onSpinWait '
'to a scripted virtual clock (query cost, oversleep/early wake per park, spin cost, interrupt pattern), '
'with its static state seeded per case and the Minecraft.runTick "limit < 260" gate. Compares every '
'frame\'s park requests, spin count, clock queries, lastFrameTime, averageOvershootNs and '
'lastFramerateLimit. The limits themselves (FramerateLimitTracker) are compared by the game loop harness; '
'real OS sleep accuracy is outside the comparison.')
harness.differential(
'rust-frame-limiter-parity', 'VanillaFrameLimiterOracle', 'frame_limiter_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/window.rs'])
if __name__ == '__main__':
main()
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Compare the in-game HUD decorations with the vanilla 26.3 client's Hud.
The Java oracle (VanillaHudOracle) runs vanilla's own Hud.extractCrosshair,
extractItemHotbar, extractPlayerHealth, extractVehicleHealth, ExperienceBar
and ContextualBar.extractExperienceLevel on a stand-in client whose player
answers from the case, and records every blit (sprite, position, size,
partial region), text call (string, position, colour, shadow) and hotbar
item (slot, position, seed, pose). `examples/hud_fixture` lays out the same
state with `horizon_client::hud_layout`; the ordered call lists must agree.
test_hud_parity.py [--count N] [--detail N]
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
def cases(count):
rng = random.Random(0x485544)
out = []
for n in range(count):
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
air_max = 300
under = rng.random() < 0.3
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
case = {
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
'crosshair': rng.random() < 0.7,
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
'health': health, 'maxHealth': max_health,
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
'saturation': rng.choice([0.0, 5.0, 0.0]),
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
'air': air, 'maxAir': air_max, 'underWater': under,
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
'experienceBar': rng.random() < 0.8,
}
if case['damageCooldown'] and rng.random() < 0.5:
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
if rng.random() < 0.15:
case['vehicleMaxHealth'] = rng.choice([15.0, 30.0, 53.0, 100.0])
case['vehicleHealth'] = round(rng.uniform(0, case['vehicleMaxHealth']), 1)
out.append(case)
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=600)
parser.add_argument('--detail', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-hud-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
chosen = cases(args.count)
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
classes = build / 'classes'; classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java')
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'hud_fixture', '--',
resources, inputs, build / 'rust.jsonl'], 'rust')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust)
errors, bad = [], []
for v, r in zip(vanilla, rust):
if 'error' in v:
errors.append(v['error']); continue
a = [{k: x for k, x in d.items() if k != 'color' or d['type'] == 'text'} for d in v['draws']]
for d in a:
if d['type'] == 'sprite':
d.setdefault('region', None)
b = r['draws']
def same(x, y):
if x.keys() != y.keys():
return False
return all(
(all(abs(p - q) <= 1e-4 * (1 + abs(p)) for p, q in zip(x[k], y[k])) if k == 'matrix' else x[k] == y[k]) for k in x)
if len(a) != len(b) or not all(same(x, y) for x, y in zip(a, b)):
first = next((i for i, (x, y) in enumerate(zip(a, b)) if not same(x, y)), min(len(a), len(b)))
bad.append((v['case'], first, a[first:first + 2], b[first:first + 2], len(a), len(b)))
for e in sorted(set(errors))[:5]:
print('ORACLE ERROR', e)
for case, i, a, b, la, lb in bad[:args.detail]:
print('MISMATCH', json.dumps(case))
print(f' at call {i} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}')
print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} HUD states match; {len(errors)} oracle errors')
if bad or errors:
sys.exit(1)
print('hud parity ok')
if __name__ == '__main__':
main()
+53 -18
View File
@@ -26,7 +26,8 @@ TRIM_MATERIALS = ['quartz', 'iron', 'netherite', 'redstone', 'copper', 'gold', '
'amethyst', 'resin']
NEEDED = ('assets/minecraft/items/', 'assets/minecraft/models/', 'assets/minecraft/textures/item/',
'assets/minecraft/textures/block/', 'assets/minecraft/textures/trims/',
'assets/minecraft/textures/colormap/')
'assets/minecraft/textures/colormap/', 'assets/minecraft/textures/palettes/',
'assets/minecraft/atlases/')
def extract(jar, destination):
@@ -293,6 +294,12 @@ def matrix(bits):
return [0 if b == 0x80000000 else b for b in bits]
def rows_of(path):
with path.open('rb') as rows:
for line in rows:
yield json.loads(line)
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / 'item-model-parity'; build.mkdir(parents=True, exist_ok=True)
@@ -324,8 +331,11 @@ def main():
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaItemModelOracle',
resources, inputs, build / 'client.jsonl', prototypes_path], 'client')
# The host inputs vanilla derives from the stack (use duration, charge time).
client = [json.loads(line) for line in (build / 'client.jsonl').read_text().splitlines()]
derived = {r['id']: r['derived'] for r in client if r.get('row') == 'case' and 'derived' in r}
# Both outputs are gigabytes of quads, so rows are streamed one at a time.
derived = {}
for r in rows_of(build / 'client.jsonl'):
if r.get('row') == 'case' and 'derived' in r:
derived[r['id']] = r['derived']
rust_cases = []
for case in cases:
case = dict(case)
@@ -335,35 +345,60 @@ def main():
rust_inputs.write_text(''.join(json.dumps(c) + '\n' for c in rust_cases))
(build / 'rust-cases.jsonl.definitions').write_text((build / 'cases.jsonl.definitions').read_text())
run([binary, resources, prototypes_path, rust_inputs, build / 'rust.jsonl'], 'rust')
rust = [json.loads(line) for line in (build / 'rust.jsonl').read_text().splitlines()]
mismatches, compared, skipped, decoded = [], 0, 0, 0
vanilla_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in client if r['row'] in ('case', 'decode', 'components')}
rust_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in rust}
assert vanilla_by_key.keys() == rust_by_key.keys(), 'The two sides produced different rows'
assert vanilla_by_key[('components', None)]['names'] == rust_by_key[('components', None)]['names'], 'Data component registry differs'
unbaked = [r['name'] for r in client if r['row'] == 'unbaked']
for key, left in vanilla_by_key.items():
right = rust_by_key[key]
if key[0] == 'components': continue
mismatches, mismatch_count, compared, skipped, decoded = [], 0, 0, 0, 0
rust_offsets = {}
with (build / 'rust.jsonl').open('rb') as rust_file:
offset = 0
for line in rust_file:
r = json.loads(line)
rust_offsets[(r['row'], r.get('id') or r.get('name'))] = offset
offset += len(line)
vanilla_keys, unbaked = set(), []
rust_file = (build / 'rust.jsonl').open('rb')
def rust_row(key):
rust_file.seek(rust_offsets[key])
return json.loads(rust_file.readline())
for left in rows_of(build / 'client.jsonl'):
if left['row'] == 'unbaked':
unbaked.append(left['name'])
if left['row'] not in ('case', 'decode', 'components'):
continue
key = (left['row'], left.get('id') or left.get('name'))
vanilla_keys.add(key)
assert key in rust_offsets, f'Horizon produced no row for {key}'
right = rust_row(key)
if key[0] == 'components':
assert left['names'] == right['names'], 'Data component registry differs'
continue
if key[0] == 'decode':
decoded += 1
if left['ok'] != right['ok']: mismatches.append(('decode', key[1], left, right))
if left['ok'] != right['ok']:
mismatch_count += 1
if len(mismatches) < 5:
mismatches.append(('decode', key[1], left, right))
continue
if 'error' in left:
skipped += 1
continue
compared += 1
left.pop('derived', None) # an input Horizon received, not an output
for side in (left, right):
for layer in side['layers']:
layer['matrix'] = matrix(layer['matrix'])
layer.pop('has_transform', None)
if layer.get('quads') is not None: layer['quads'] = canonical_quads(layer['quads'])
if left != right:
mismatches.append(('case', key[1], left, right))
if mismatches:
for kind, name, left, right in mismatches[:5]:
mismatch_count += 1
if len(mismatches) < 5:
mismatches.append(('case', key[1], left, right))
rust_file.close()
assert vanilla_keys == rust_offsets.keys(), 'The two sides produced different rows'
if mismatch_count:
for kind, name, left, right in mismatches:
print(kind, name, '\nvanilla:', json.dumps(left)[:1500], '\nrust: ', json.dumps(right)[:1500])
raise AssertionError(f'{len(mismatches)} item model mismatches')
raise AssertionError(f'{mismatch_count} item model mismatches')
base.ensure_sources_unchanged(sources, tested)
assert compared > 1000, 'Too few cases compared'
assert skipped * 20 < len(cases), f'Too many cases rejected by vanilla: {skipped}'
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""Differential mob AI harness.
The Java oracle (VanillaMobAiOracle) runs vanilla mobs in a real, headless, flat vanilla server
level: each scenario builds a scene, places a target player and mobs with seeded random sources
and ticks the mobs the way ServerLevel.tick does. The Rust probe (mob_ai_probe) replays the same
scenarios on Horizon's mob AI. Both print every mob's AI-visible state after every tick (position,
motion, rotations, running goals and target goals, attack target, navigation path, move and look
controls, movement input, brain activities and memories) and the sounds played; this harness
reports, per scenario and mob, how many ticks match before the first divergence and what differs.
python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--strict]
"""
import argparse
import os
import struct
import subprocess
import sys
from pathlib import Path
try:
from . import lab, oracle_harness, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab
import oracle_harness
import test_rust_parity as base
import test_model_baking_parity as baking
FLOOR = -60 # top of the flat preset's grass layer + 1
def ring(x0, z0, size, state, y=FLOOR):
return [f'fill {x0 - size} {y} {z0 - size} {x0 + size} {y} {z0 + size} {state}']
# Each scenario is (name, ticks, options, lines); positions are relative to the scenario origin
# and translated by the generator so scenarios never share chunks.
def scenarios():
s = []
def add(name, ticks, lines, opts=''):
s.append((name, ticks, opts, lines))
# Passive and hostile land mobs on open grass with a survival player nearby.
for species, seed in [('zombie', 1), ('skeleton', 2), ('creeper', 3), ('spider', 4), ('husk', 5),
('cow', 6), ('pig', 7), ('chicken', 8), ('sheep', 9), ('wandering_trader', 10),
('villager', 11), ('drowned', 12), ('enderman', 13), ('witch', 14)]:
add(f'{species}_player', 200, [
'player 6.5 -60 0.5',
f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent',
])
add(f'{species}_alone', 200, [
f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent',
])
# Drowned in a pool with the player on the shore and in the water.
add('drowned_pool', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
'player 9.5 -60 0.5',
'mob minecraft:drowned 0.5 -63 0.5 0 21 persistent'])
add('drowned_pool_swimmer', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
'player 3.5 -62 0.5',
'mob minecraft:drowned -3.5 -63 0.5 0 22 persistent'])
# Night: undead do not burn, monsters seek darkness.
add('zombie_night', 200, ['player 10.5 -60 0.5', 'mob minecraft:zombie 0.5 -60 0.5 0 31 persistent'], 'time=18000')
add('skeleton_day_burn', 120, ['mob minecraft:skeleton 0.5 -60 0.5 0 32 persistent'])
# The wither (summoned, not built: no invulnerable spawn phase).
add('wither_player', 200, ['player 10.5 -60 0.5', 'mob minecraft:wither 0.5 -58 0.5 0 41 persistent'])
# A villager with a job site, a bed and a bell.
add('villager_village', 300, [
'block 4 -60 0 minecraft:composter',
'block -4 -60 2 minecraft:red_bed[facing=north,part=foot]',
'block -4 -60 1 minecraft:red_bed[facing=north,part=head]',
'block 0 -60 -6 minecraft:bell',
'player 12.5 -60 0.5',
'mob minecraft:villager 0.5 -60 0.5 0 51 persistent',
])
return s
def write_scenarios(path, chosen):
lines = []
for i, (name, ticks, opts, body) in chosen:
ox, oz = 512 * (i + 1), 0
lines.append(f'scenario {name} ticks={ticks} {opts}'.rstrip())
lines.append(f'origin {ox} {oz}')
for line in body:
f = line.split()
if f[0] == 'player':
f[1] = repr(float(f[1]) + ox)
f[3] = repr(float(f[3]) + oz)
elif f[0] == 'mob':
f[2] = repr(float(f[2]) + ox)
f[4] = repr(float(f[4]) + oz)
elif f[0] == 'block':
f[1] = str(int(f[1]) + ox)
f[3] = str(int(f[3]) + oz)
elif f[0] == 'fill':
for k in (1, 4):
f[k] = str(int(f[k]) + ox)
for k in (3, 6):
f[k] = str(int(f[k]) + oz)
lines.append(' '.join(f))
lines.append('end')
path.write_text('\n'.join(lines) + '\n')
def parse(path):
"""{scenario: {tick: {mob: {field: value}}, sounds: {tick: [..]}}}"""
result, cur = {}, None
for line in path.read_text().splitlines():
if line.startswith('== '):
cur = result.setdefault(line[3:], {'ticks': {}, 'sounds': {}})
continue
head, *fields = line.split('\t')
parts = head.split(' ', 2)
t = int(parts[0])
if parts[1] == 'sound':
cur['sounds'].setdefault(t, []).append(parts[2])
continue
if parts[1] == 'trace':
cur.setdefault('trace', {}).setdefault(t, []).append(parts[2])
continue
mob = int(parts[1])
row = {}
if len(parts) > 2:
row['removed'] = parts[2]
for f in fields:
k, _, v = f.partition(' ')
row[k] = v
cur['ticks'].setdefault(t, {})[mob] = row
return result
def decode(value):
"""Hex float/double fields made readable."""
def one(x):
try:
if len(x) > 8:
return f'{struct.unpack(">d", int(x, 16).to_bytes(8, "big"))[0]!r}'
return f'{struct.unpack(">f", int(x, 16).to_bytes(4, "big"))[0]:.9g}'
except ValueError:
return x
out = []
for word in value.split(' '):
out.append(','.join(one(p) if all(c in '0123456789abcdef' for c in p) and len(p) >= 5 else p for p in word.split(',')))
return ' '.join(out)
MULT, MASK = 0x5DEECE66D, (1 << 48) - 1
def draws(before, after, limit=20000):
"""How many LegacyRandomSource steps lead from one state to the next."""
try:
s, goal = int(before, 16), int(after, 16)
except (TypeError, ValueError):
return '?'
for n in range(limit):
if s == goal:
return n
s = (s * MULT + 11) & MASK
return f'>{limit}'
def compare(vanilla, rust, fields=None):
"""Returns (report lines, totals)."""
report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0}
for name, v in vanilla.items():
r = rust.get(name)
totals['scenarios'] += 1
if r is None:
report.append(f'{name}: missing from Horizon')
continue
mobs = sorted({m for t in v['ticks'].values() for m in t})
clean = True
for mob in mobs:
ticks = sorted(v['ticks'])
first = None
for t in ticks:
a = v['ticks'][t].get(mob)
b = r['ticks'].get(t, {}).get(mob)
totals['mob_ticks'] += 1
if a == b or (b is not None and fields and all(a.get(k) == b.get(k) for k in fields)):
if first is None:
totals['matched'] += 1
continue
if first is None:
first = t
diffs = []
for k in (a or {}):
if b is None or a.get(k) != b.get(k):
show = (lambda x: x) if k == 'rng' else decode
diffs.append(f'{k}: vanilla {show(a.get(k, "?"))} | horizon {show((b or {}).get(k, "?"))}')
for k in (b or {}):
if a is None or k not in a:
diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}')
prev_v = v['ticks'].get(t - 1, {}).get(mob, {}).get('rng')
prev_r = r['ticks'].get(t - 1, {}).get(mob, {}).get('rng')
report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)} '
f'(random draws this tick: vanilla {draws(prev_v, (a or {}).get("rng"))}, '
f'horizon {draws(prev_r, (b or {}).get("rng"))})')
for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]:
report.append(' vanilla ' + line)
report.extend(' ' + d for d in diffs[:12])
if first is not None:
clean = False
# Sounds: first differing tick.
for t in sorted(set(v['sounds']) | set(r['sounds'])):
if v['sounds'].get(t, []) != r['sounds'].get(t, []):
report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}')
clean = False
break
totals['clean'] += clean
if clean:
report.append(f'{name}: all {len(v["ticks"])} ticks match')
return report, totals
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--only', nargs='*')
parser.add_argument('--java-only', action='store_true')
parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output')
parser.add_argument('--strict', action='store_true', help='fail on any divergence')
args = parser.parse_args()
build = lab.LOCAL / 'mob-ai-parity'
build.mkdir(parents=True, exist_ok=True)
chosen = [(i, s) for i, s in enumerate(scenarios()) if not args.only or any(o in s[0] for o in args.only)]
inputs = build / 'scenarios.txt'
write_scenarios(inputs, chosen)
lock, jars, _ = base.verify_artifacts()
if not args.rust_only:
classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(),
lock['minecraft']['java_major'])
oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'],
build, 'vanilla', timeout=3600)
if not args.java_only:
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'],
build, 'compile-rust')
binary = lab.ROOT / 'target/release/examples/mob_ai_probe'
oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon')
if args.java_only:
return
names = {s[0] for _, s in chosen}
vanilla = {k: v for k, v in parse(build / 'vanilla.txt').items() if k in names}
report, totals = compare(vanilla, parse(build / 'horizon.txt'))
(build / 'report.txt').write_text('\n'.join(report) + '\n')
print('\n'.join(report))
print(f"{totals['clean']}/{totals['scenarios']} scenarios match entirely; "
f"{totals['matched']}/{totals['mob_ticks']} mob-ticks match before each mob's first divergence")
if args.strict and totals['clean'] != totals['scenarios']:
raise SystemExit(1)
if __name__ == '__main__':
main()
+167
View File
@@ -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()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Compare the situational music choice with the vanilla 26.3 client.
The oracle calls the real `Minecraft.getSituationalMusic` and
`getMusicVolume` with the open screen (none or the credits), the boss
overlay's bars (none, darkening, music), the player (absent, or in a dimension
with creative abilities and an underwater state) and a real camera
`EnvironmentAttributeProbe` over the dimension and biome attribute layers of
the vanilla data pack. Horizon's `Situation` with `MusicTables` answers the
same, for every dimension type x biome and every combination of the rest.
"""
import itertools
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
data = h.RESOURCES / 'data/minecraft'
biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json'))
dimensions = ['minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end']
lines = []
for screen, boss in itertools.product(['none', 'win'], ['none', 'dark', 'music', 'dark+music']):
lines.append(f'{screen} 0 minecraft:overworld minecraft:plains {boss} 0 0 0')
for d, b in itertools.product(dimensions, biomes):
for screen, boss, instabuild, mayfly, water in itertools.product(['none', 'win'], ['none', 'dark', 'music'], '01', '01', '01'):
lines.append(f'{screen} 1 {d} {b} {boss} {instabuild} {mayfly} {water}')
return lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'situational-music', 'VanillaSituationalMusicOracle', 'situational_music_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs'], rust_args=[h.RESOURCES],
scope='Real Minecraft.getSituationalMusic/getMusicVolume: screen music (credits), menu without a player, End boss music from '
'the boss overlay, BACKGROUND_MUSIC and MUSIC_VOLUME through a real camera EnvironmentAttributeProbe, creative abilities '
'(instabuild && mayfly) and underwater selection, for every dimension x biome.')
print(f'{matched:,} situational music lines match the pinned client: {report}', flush=True)
if __name__ == '__main__':
main()
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""Compare the sound engine's bookkeeping with the vanilla 26.3 client.
The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No
Output" device (see VanillaSoundRig) and replays scripts of plays (simple,
biome loop, underwater loop and sub-sound instances), stops (by instance, by
sound and/or source, all), category gains, source volume options and
refreshes, channel ends, delayed and queued sounds, pauses and client ticks.
After every step it prints each instance's `isActive` and the AL source the
engine configured (state, gain, pitch, position, relative, looping, distance
model, max distance, rolloff, reference distance), the subtitle notifications
and the channel pool counts. Horizon's `SoundEngine` replays the scripts
against a backend that records the same AL source fields.
"""
import json
import random
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def dbits(v):
import struct
return struct.pack('>d', v).hex()
class Script:
def __init__(self, events, streams):
self.lines = []
self.events, self.streams = events, streams
def add(self, *parts):
self.lines.append(' '.join(map(str, parts)))
def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'):
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay,
'linear' if linear else 'none', relative, seed)
def tick(self, n=1, paused=0):
for _ in range(n):
self.add('tick', paused)
def reset(self):
self.add('stopmatch', '-', '-')
for source in range(11):
self.add('volume', source, h.bits(1.0))
self.tick()
def scripted(s):
stone, cave, click = 'minecraft:block.stone.break', 'minecraft:ambient.cave', 'minecraft:ui.button.click'
music, loop, uloop = 'minecraft:music.game', 'minecraft:ambient.crimson_forest.loop', 'minecraft:ambient.underwater.loop'
# Positional and relative sounds, lifetimes and channel ends.
s.play('a', stone, 4, 1.0, 0.8, (10.5, 64.0, -3.25), seed=5)
s.play('b', click, 10, 0.25, 1.0, linear=False, relative=1, seed=6)
s.play('c', cave, 8, 4.0, 1.0, (100.0, 20.0, 100.0), seed=7)
s.play('d', stone, 4, 1.5, 3.0, (0.5, 0.5, 0.5), seed=8)
s.play('e', stone, 4, 0.5, 0.1, (1.0, 2.0, 3.0), seed=9)
s.tick(3)
s.add('finish', 'a')
s.tick(25)
s.add('finish', 'b')
s.add('stop', 'c')
s.tick(2)
s.reset()
# Volumes: options, category gains, refreshes, silent starts.
s.add('volume', 4, h.bits(0.5))
s.add('volume', 0, h.bits(0.75))
s.play('a', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=1)
s.add('volume', 4, h.bits(0.0))
s.play('b', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=2)
s.add('volume', 1, h.bits(0.0))
s.play('m', music, 1, 1.0, 1.0, linear=False, relative=1, seed=3)
s.add('refresh', 4)
s.add('volume', 4, h.bits(0.3))
s.add('refresh', 0)
s.add('gain', 1, h.bits(0.5))
s.add('gain', 1, h.bits(1.5))
s.add('gain', 4, h.bits(-0.2))
s.add('volume', 1, h.bits(1.0))
s.add('refresh', 1)
s.tick(2)
s.add('volume', 0, h.bits(2.0))
s.add('refresh', 0)
s.reset()
# Biome loops: fades, crossfade, stopping, removal.
s.play('l1', loop, kind='loop', seed=11)
s.add('fade', 'l1', 'in')
s.tick(45)
s.play('l2', 'minecraft:ambient.warped_forest.loop', kind='loop', seed=12)
s.add('fade', 'l1', 'out')
s.add('fade', 'l2', 'in')
s.tick(50)
s.add('fade', 'l2', 'out')
s.tick(10)
s.add('fade', 'l2', 'in')
s.tick(60)
s.add('volume', 8, h.bits(0.0))
s.play('l3', loop, kind='loop', seed=13)
s.tick(3)
s.reset()
# Underwater loop and sub-sounds.
s.add('player', 1, 0)
s.play('u', uloop, kind='uloop', seed=21)
s.play('v', 'minecraft:ambient.underwater.loop.additions.rare', kind='usub', seed=22)
s.tick(50)
s.add('player', 0, 0)
s.tick(5)
s.add('player', 1, 0)
s.tick(5)
s.add('player', 0, 0)
s.tick(30)
s.add('player', 1, 1)
s.play('u2', uloop, kind='uloop', seed=23)
s.tick(3)
s.add('player', 0, 0)
s.reset()
# Queued tickables, delayed and manually looped sounds.
s.play('q', loop, kind='loop', seed=31)
s.add('stop', 'q')
s.tick(25)
s.add('queue', 'q')
s.add('fade', 'q', 'in')
s.tick(3)
s.play('w', stone, 4, 1.0, 1.0, (2.0, 2.0, 2.0), seed=32)
s.add('delayed', 'w', 5)
s.tick(7)
s.play('r', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, delay=4, seed=33)
s.tick(22)
s.add('finish', 'r')
s.tick(8)
s.add('finish', 'r')
s.tick(6)
s.play('n', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, seed=34)
s.tick(2)
s.reset()
# Stopping by source and sound, pauses.
s.play('a', stone, 4, seed=41)
s.play('b', stone, 5, seed=42)
s.play('c', cave, 8, seed=43)
s.play('m', music, 1, linear=False, relative=1, seed=44)
s.play('u', click, 10, linear=False, relative=1, seed=45)
s.add('pause')
s.tick(1, paused=1)
s.add('stop', 'm')
s.tick(1, paused=1)
s.add('resume')
s.add('stopmatch', stone, '-')
s.tick(25)
s.add('stopmatch', '-', 8)
s.add('stopmatch', click, 4)
s.add('stopmatch', click, 10)
s.tick(2)
s.reset()
# Unknown, empty and intentionally empty events; replaying an instance.
for i, event in enumerate(['minecraft:not.a.sound', 'minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:entity.generic.eat']):
s.play(f'x{i}', event, 6, seed=50 + i)
s.add('replay', 'x3')
s.tick(25)
s.reset()
# Channel pools.
for i in range(252):
s.play('p', stone, 4, 1.0, 1.0, (float(i), 0.0, 0.0), seed=i)
for i in range(10):
s.play('s', music, 1, linear=False, relative=1, seed=i)
s.tick(2)
s.add('stopmatch', '-', '-')
s.tick(1)
def fuzz(s, rng, steps):
names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5']
live = set()
for _ in range(steps):
op = rng.random()
name = rng.choice(names)
if op < 0.25:
kind = rng.choice(['simple', 'simple', 'simple', 'loop', 'uloop', 'usub'])
event = rng.choice(s.streams if kind != 'simple' and rng.random() < 0.5 else s.events)
at = tuple(rng.choice([0.0, rng.uniform(-200, 200)]) for _ in range(3))
s.play(name, event, rng.randrange(11), rng.choice([1.0, 0.5, 2.0, 0.0, 4.0, rng.uniform(0, 3)]), rng.choice([1.0, 0.5, 2.5, rng.uniform(0.2, 3)]),
at, int(rng.random() < 0.2), rng.choice([0, 0, 0, 3]), rng.random() < 0.7, int(rng.random() < 0.3), rng.getrandbits(63), kind)
live.add(name)
elif not live:
s.tick()
elif op < 0.32:
s.add('finish', rng.choice(sorted(live)))
elif op < 0.36:
s.add('stop', rng.choice(sorted(live)))
elif op < 0.40:
s.add('fade', rng.choice(sorted(live)), rng.choice(['in', 'out']))
elif op < 0.42:
s.add('stopmatch', rng.choice(['-', rng.choice(s.events)]), rng.choice(['-', rng.randrange(11)]))
elif op < 0.45:
s.add('volume', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.5, rng.random()])))
elif op < 0.48:
s.add('refresh', rng.randrange(11))
elif op < 0.51:
s.add('gain', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.3, 1.2])))
elif op < 0.53:
s.add('player', int(rng.random() < 0.6), int(rng.random() < 0.05))
elif op < 0.55:
s.add('replay', rng.choice(sorted(live)))
elif op < 0.56:
s.add('pause')
s.tick(rng.randrange(1, 4), paused=1)
s.add('resume')
elif op < 0.57:
s.add('forget', name)
live.discard(name)
else:
s.tick(rng.randrange(1, 6))
def fixtures():
sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text())
names = sorted(sounds)
streams = sorted('minecraft:' + n for n in names if any(isinstance(e, dict) and e.get('stream') for e in sounds[n].get('sounds', [])))
rng = random.Random(0x454e47494e45)
events = sorted(set(['minecraft:' + rng.choice(names) for _ in range(60)] + ['minecraft:ambient.cave', 'minecraft:block.stone.break']))
s = Script(events, streams)
scripted(s)
for _ in range(40):
s.reset()
fuzz(s, rng, 150)
return s.lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'sound-engine', 'VanillaSoundEngineOracle', 'sound_engine_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java'],
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real SoundEngine (OpenAL Soft null device, inline executor, silent static buffers, never-ready streams): play results, '
'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear '
'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, '
'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, '
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. '
'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.')
print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Compare sound event resolution with the vanilla 26.3 client.
The oracle builds the real `SoundManager` registry from the client asset root
(`SoundManager.prepare` + `Preparations.apply`: sounds.json, `replace`,
subtitles, file validation against the listed .ogg resources, event references
weighing as much as their event) and resolves seeded `SimpleSoundInstance`s:
`getOrResolve`, `getVolume`, `getPitch`, `Sound.getAttenuationDistance`, the
stream/preload/type fields and the instance random's next draw. Horizon's
`SoundRegistry` + `SoundEngine::resolve` replay the same inputs.
"""
import json
import random
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text())
rng = random.Random(0x534f554e44)
volumes = [1.0, 0.5, 0.25, 2.0, 4.0, 0.0, 1e-3, 16.0]
pitches = [1.0, 0.5, 2.0, 0.8, 1.2, 3.0, 0.1]
lines = []
for name in sorted(sounds):
event = 'minecraft:' + name
count = len(sounds[name].get('sounds', []))
seeds = [0, 1, -1, 42] + [rng.getrandbits(64) - (1 << 63) for _ in range(max(4, 2 * count))]
for seed in seeds:
lines.append(f'{event} {seed} {h.bits(rng.choice(volumes))} {h.bits(rng.choice(pitches))}')
for event in ['minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:not.a.sound', 'horizon:missing', 'block.stone.break', 'music.game']:
for seed in [0, 7, -99]:
lines.append(f'{event} {seed} {h.bits(1.0)} {h.bits(1.0)}')
return lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'sound-events', 'VanillaSoundEventOracle', 'sound_event_fixture', ''.join(l + '\n' for l in lines),
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real SoundManager.prepare/Preparations.apply over the client asset root and SimpleSoundInstance.getOrResolve/getVolume/getPitch '
'for every sounds.json event with seeded randoms (weighted choice, nested event references, MultipliedFloats volume/pitch, '
'stream/preload/attenuation fields, EMPTY and INTENTIONALLY_EMPTY sentinels, draw counts) and the full registered event list.')
print(f'{matched:,} sound event lines match the pinned client ({len(lines):,} resolutions): {report}', flush=True)
if __name__ == '__main__':
main()
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Compare spawn placement checks and spawn predicates with vanilla.
Java (VanillaSpawnRulesOracle) runs SpawnPlacements.isSpawnPositionOk and
checkSpawnRules on a stand-in ServerLevel holding one column of blocks with
uniform light; Rust (spawn_rules_fixture) runs horizon_client::mobs::spawn_rules
on the same column. Every mob type is tried on surfaces, caves, water, lava,
the nether and the end, dangerous blocks, light levels, thunder, difficulty,
biomes, slime chunks, nearby players and several spawn reasons; each case
also prints the next draw of its random, pinning the number of draws.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# Living types that are not Horizon mob types or not mobs at all.
SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'}
SCENARIOS = {
'grass-day': dict(b=dict(m1='minecraft:grass_block'), sky=15, surface=64),
'grass-night': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, surface=64),
'grass-dusk': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=7, surface=64),
'grass-thunder': dict(b=dict(m1='minecraft:grass_block'), sky=15, thunder=1, surface=64),
'grass-peaceful': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, difficulty='peaceful', surface=64),
'grass-torch': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, light=9, surface=64),
'cave-dark': dict(b=dict(m1='minecraft:stone'), sky=0, y=20, surface=80),
'cave-lit1': dict(b=dict(m1='minecraft:stone'), sky=0, light=1, y=20, surface=80),
'cave-lit8': dict(b=dict(m1='minecraft:deepslate'), sky=0, light=8, y=-20, surface=80),
'cave-lit12': dict(b=dict(m1='minecraft:stone'), sky=0, light=12, y=20, surface=80),
'cave-dim': dict(b=dict(m1='minecraft:stone'), sky=3, y=40, surface=80),
'water-surface': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=60, surface=64, biome='minecraft:ocean'),
'water-warm': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=58, surface=64, biome='minecraft:warm_ocean'),
'water-deep': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=25, surface=64, biome='minecraft:deep_ocean'),
'water-deep-lit': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, light=3, y=25, surface=64, biome='minecraft:lukewarm_ocean'),
'water-mid': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=45, surface=64, biome='minecraft:cold_ocean'),
'water-roofed': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water', p3='minecraft:stone'), sky=0, y=50, surface=64, biome='minecraft:ocean'),
'water-river': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=50, surface=64, biome='minecraft:river', darken=11),
'water-conductor': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:stone'), sky=15, y=60, surface=64),
'water-seagrass': dict(b=dict(m1='minecraft:sand', p0='minecraft:water', p1='minecraft:water'), sky=15, y=55, surface=64, biome='minecraft:ocean'),
'water-clay': dict(b=dict(m1='minecraft:clay', p0='minecraft:water', p1='minecraft:water'), sky=0, y=10, surface=64, biome='minecraft:lush_caves'),
'lava-nether': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava', p1='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'lava-open': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-dark': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-lit7': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=7, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-lit8': dict(b=dict(m1='minecraft:crimson_nylium'), sky=0, light=8, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-wart': dict(b=dict(m1='minecraft:nether_wart_block'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-soul': dict(b=dict(m1='minecraft:soul_sand'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'nether-magma': dict(b=dict(m1='minecraft:magma_block'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'end': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=0, y=60, dim='minecraft:the_end', biome='minecraft:the_end'),
'end-lit': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=14, y=60, dim='minecraft:the_end', biome='minecraft:end_highlands'),
'ice-frozen': dict(b=dict(m1='minecraft:ice'), sky=15, y=63, surface=64, biome='minecraft:frozen_ocean'),
'ice-plains': dict(b=dict(m1='minecraft:packed_ice'), sky=15, y=64, surface=64, biome='minecraft:snowy_plains'),
'snow-block': dict(b=dict(m1='minecraft:snow_block'), sky=15, darken=11, y=70, surface=70, biome='minecraft:snowy_plains'),
'snow-layer': dict(b=dict(m1='minecraft:grass_block[snowy=true]', p0='minecraft:snow'), sky=15, y=70, surface=71, biome='minecraft:snowy_taiga'),
'powder-snow-stray': dict(b=dict(m1='minecraft:snow_block', p1='minecraft:powder_snow', p2='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=93, biome='minecraft:frozen_peaks'),
'sand-beach': dict(b=dict(m1='minecraft:sand'), sky=15, y=63, surface=64, biome='minecraft:beach'),
'sand-desert': dict(b=dict(m1='minecraft:sand'), sky=15, darken=11, y=70, surface=70, biome='minecraft:desert'),
'red-sand': dict(b=dict(m1='minecraft:red_sand'), sky=15, y=80, surface=80, biome='minecraft:badlands'),
'leaves-jungle': dict(b=dict(m1='minecraft:jungle_leaves'), sky=15, y=90, surface=90, biome='minecraft:jungle'),
'grass-jungle': dict(b=dict(m1='minecraft:grass_block'), sky=15, y=70, surface=70, biome='minecraft:jungle'),
'mycelium': dict(b=dict(m1='minecraft:mycelium'), sky=15, y=70, surface=70, biome='minecraft:mushroom_fields'),
'podzol': dict(b=dict(m1='minecraft:podzol'), sky=15, y=70, surface=70, biome='minecraft:old_growth_pine_taiga'),
'mud-swamp': dict(b=dict(m1='minecraft:mud'), sky=15, y=62, surface=62, biome='minecraft:mangrove_swamp'),
'stone-peaks': dict(b=dict(m1='minecraft:stone'), sky=15, y=160, surface=160, biome='minecraft:jagged_peaks'),
'coarse-savanna': dict(b=dict(m1='minecraft:coarse_dirt'), sky=15, y=70, surface=70, biome='minecraft:savanna'),
'slab-bottom': dict(b=dict(m1='minecraft:oak_slab[type=bottom]'), sky=0, y=40, surface=80),
'slab-top': dict(b=dict(m1='minecraft:oak_slab[type=top]'), sky=0, y=40, surface=80),
'glass': dict(b=dict(m1='minecraft:glass'), sky=0, y=40, surface=80),
'glowstone': dict(b=dict(m1='minecraft:glowstone'), sky=0, light=15, y=40, surface=80),
'fire': dict(b=dict(m1='minecraft:netherrack', p0='minecraft:fire'), sky=0, light=15, y=40, surface=80),
'soul-fire': dict(b=dict(m1='minecraft:soul_soil', p0='minecraft:soul_fire'), sky=0, light=10, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'wither-rose': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:wither_rose'), sky=0, y=40, surface=80),
'berry-bush': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:sweet_berry_bush'), sky=15, y=70, surface=70, biome='minecraft:taiga'),
'cactus': dict(b=dict(m1='minecraft:sand', p0='minecraft:cactus'), sky=0, y=70, surface=72, biome='minecraft:desert'),
'powder-snow-feet': dict(b=dict(m1='minecraft:snow_block', p0='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=91, biome='minecraft:snowy_slopes'),
'campfire': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=true]'), sky=0, light=15, y=40, surface=80),
'campfire-out': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=false]'), sky=0, y=40, surface=80),
'rail': dict(b=dict(m1='minecraft:stone', p0='minecraft:rail'), sky=0, y=40, surface=80),
'redstone-torch': dict(b=dict(m1='minecraft:stone', p0='minecraft:redstone_torch'), sky=0, light=7, y=40, surface=80),
'tall-grass': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:short_grass', p1='minecraft:air'), sky=15, darken=11, y=70, surface=70),
'low-ceiling': dict(b=dict(m1='minecraft:stone', p1='minecraft:stone'), sky=0, y=40, surface=80),
'swamp-surface': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=62, surface=63, biome='minecraft:swamp', slime=0.5),
'swamp-full-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=4, y=64, surface=65, biome='minecraft:swamp', slime=0.5),
'swamp-new-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=63, surface=64, biome='minecraft:swamp', slime=0.0),
'bat-cave': dict(b=dict(m1='minecraft:stone'), sky=0, y=10, surface=80),
'bat-surface': dict(b=dict(m1='minecraft:stone'), sky=0, y=79, surface=79),
}
REASONS = ['natural', 'natural', 'natural', 'chunk_generation', 'spawner', 'trial_spawner', 'reinforcement', 'patrol']
def corpus(types):
rng = random.Random(0x5350574E)
cases = []
for t in types:
n = t.split(':')[1]
for name, s in SCENARIOS.items():
for k in range(3):
kv = {k2: v for k2, v in s.items() if k2 != 'b'}
kv.setdefault('y', 64)
for key, block in s['b'].items():
kv['at' + ('-' if key[0] == 'm' else '') + key[1:]] = block
kv['reason'] = REASONS[k] if k == 0 else rng.choice(REASONS)
kv['seed'] = rng.randrange(-2**47, 2**47)
cases.append(f'{n}/{name}/{k} type={t} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
# Slime chunks: deep caves at many chunk positions and world seeds.
if n in ('slime', 'zombie'):
for k in range(600 if n == 'slime' else 60):
cases.append(f'{n}/slime-chunk/{k} type={t} at-1=minecraft:stone sky=0 y={rng.randrange(-60, 45)} '
f'x={rng.randrange(-4000, 4000)} z={rng.randrange(-4000, 4000)} wseed={rng.randrange(-2**63, 2**63)} '
f'seed={rng.randrange(-2**47, 2**47)} reason=natural surface=80')
# Nearby players (silverfish and endermite refuse to spawn next to a targetable one).
for k, player in enumerate(['1,0,1,survival', '1,0,1,creative', '4,0,4,survival', '3,1,3,adventure', '0,4.4,0,survival',
'2,2,2,spectator']):
cases.append(f'{n}/player/{k} type={t} at-1=minecraft:stone sky=0 y=20 surface=80 player={player} '
f'seed={rng.randrange(-2**47, 2**47)} reason={rng.choice(REASONS)}')
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-spawn-rules-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
entity_types = json.loads((resources / 'entity-types.json').read_text())
types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus(types)
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a}\n rust {b}' for a, b in bad[:40])
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged(sources, tested)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'types': len(types), 'scenarios': sorted(SCENARIOS), 'sources_sha256': tested,
'scope': 'SpawnPlacements.isSpawnPositionOk (placement types, isValidSpawn, isValidEmptySpawnBlock with per-type '
'dangerous blocks) and checkSpawnRules (every registered predicate, peaceful, spawn reasons) with the '
'random draw count.'})
print(f'{len(cases):,} spawn rule cases over {len(types)} entity types match vanilla')
if __name__ == '__main__':
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Compare toggle sprint/sneak (and toggle attack/use) with the pinned client:
the real Options ToggleKeyMappings driven by the real static KeyMapping
functions as keyboard presses, SDL key repeats and releases, mouse buttons,
screens opening and closing over the game (releaseAll and
restoreToggleStatesOnScreenClosed), respawning (resetToggleKeys) and toggle
options changing mid-sequence, event by event."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def op(rng, screen):
kind = rng.choice(['key', 'key', 'key', 'key', 'button', 'button', 'open', 'close', 'option', 'option', 'respawn'])
if kind == 'key':
return ['key', rng.choice([0, 1]), rng.choice([1, 1, 0, 0, -1]), screen]
if kind == 'button':
return ['button', rng.choice([2, 3]), rng.random() < 0.5, screen]
if kind == 'option':
return ['option', rng.randrange(4), rng.random() < 0.6]
return [kind]
def cases(rng):
# Every short sequence of the main events for sneak with toggle off and on.
events = [['key', 0, 1, False], ['key', 0, 0, False], ['key', 0, -1, False], ['key', 0, 1, True], ['key', 0, 0, True],
['open'], ['close'], ['respawn'], ['option', 0, True], ['option', 0, False]]
for a in events:
for b in events:
for c in events:
for toggled in (False, True):
yield dict(ops=[['option', 0, toggled], a, b, c, ['key', 0, 1, False], ['open'], ['close']])
for _ in range(6000):
screen = False
ops = [['option', i, rng.random() < 0.5] for i in range(4)]
for _ in range(rng.randrange(1, 60)):
o = op(rng, screen)
if o[0] == 'open':
screen = True
elif o[0] == 'close':
screen = False
elif o[0] in ('key', 'button'):
o[3] = screen
ops.append(o)
yield dict(ops=ops)
def make_cases(build):
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(random.Random(0x544f474c)):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The real Options keyShift/keySprint/keyAttack/keyUse ToggleKeyMappings with their real toggle options and '
'shouldRestore flags, driven through the real static KeyMapping.set/click (every mapping bound to the key), '
'releaseAll, restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as KeyboardHandler.keyPress '
'(release always; press and SDL repeat only without a screen), MouseHandler.onButton (only without a screen), '
'Gui.setScreen and LocalPlayer.respawn call them. Compares down state and pending clicks after every event. '
'The screen-consumed keyPressed/keyReleased branches and KeyMapping.setAll (an InputQuirks platform quirk) are '
'not exercised; KeyboardInput then reads isDown as the sprint and local input harnesses compare.')
harness.differential(
'rust-toggle-keys-parity', 'VanillaToggleKeysOracle', 'toggle_keys_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/keymapping.rs'])
if __name__ == '__main__':
main()
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Launch the vanilla 26.3 client offline (no Microsoft account, no auth
servers: --offlineDeveloperMode) and optionally join a server straight away
(--quickPlayMultiplayer). Meant to run on a virtual screen:
vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565
Sound goes to OpenAL's null backend. The game directory gets an options.txt
that skips the first-run screens, keeps the game running unfocused and
renders few chunks, so a harness can drive it with vscreen keys.
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
import uuid
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
GAME = ROOT / ".local/minecraft/26.3"
OPTIONS = {
"onboardAccessibility": "false",
"skipMultiplayerWarning": "true",
"joinedFirstServer": "true",
"tutorialStep": "none",
"pauseOnLostFocus": "false",
"renderDistance": "6",
"simulationDistance": "6",
"maxFps": "30",
"narrator": "0",
"soundCategory_master": "0.0",
"realmsNotifications": "false",
"hideServerAddress": "false",
"autoJump": "false",
"chatLinksPrompt": "false",
"onlyShowSecureChat": "false",
"rawMouseInput": "false",
}
def offline_uuid(name):
digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest())
digest[6] = (digest[6] & 0x0F) | 0x30
digest[8] = (digest[8] & 0x3F) | 0x80
return uuid.UUID(bytes=bytes(digest))
def linux_library(path):
name = Path(path).name
if "natives-" in name:
return name.endswith("natives-linux.jar")
if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name):
return False
return "java-objc-bridge" not in name
def classpath():
prepared = json.loads((GAME / "prepared.json").read_text())
jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)]
return [GAME / "jars/client.jar", *jars]
def extract_natives(jars, target):
target.mkdir(parents=True, exist_ok=True)
for jar in jars:
if not jar.name.endswith("natives-linux.jar"):
continue
with zipfile.ZipFile(jar) as archive:
for name in archive.namelist():
if name.endswith(".so") and "arm" not in name and "aarch" not in name:
out = target / Path(name).name
if not out.exists():
out.write_bytes(archive.read(name))
def write_options(game_dir, extra):
path = game_dir / "options.txt"
current = {}
if path.exists():
for line in path.read_text().splitlines():
if ":" in line:
k, v = line.split(":", 1)
current[k] = v
current.update(OPTIONS)
current.update(extra)
path.write_text("".join(f"{k}:{v}\n" for k, v in current.items()))
def environment():
env = dict(os.environ)
libs = [p for p in (os.environ.get("NIX_LD_LIBRARY_PATH", ""), "/run/opengl-driver/lib",
"/run/current-system/sw/share/nix-ld/lib") if p]
env["LD_LIBRARY_PATH"] = ":".join(libs + [env.get("LD_LIBRARY_PATH", "")]).strip(":")
env["ALSOFT_DRIVERS"] = "null"
return env
def command(args):
jars = classpath()
natives = args.game_dir / "natives"
extract_natives(jars, natives)
assets = args.assets or (args.game_dir / "assets")
(assets / "indexes").mkdir(parents=True, exist_ok=True)
cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32",
"--enable-native-access=ALL-UNNAMED",
"--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
f"-Dio.netty.native.workdir={natives}",
"-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main",
"--username", args.name, "--uuid", offline_uuid(args.name).hex,
"--accessToken", "0", "--offlineDeveloperMode",
"--version", "26.3", "--gameDir", str(args.game_dir),
"--assetsDir", str(assets), "--assetIndex", "34",
"--width", str(args.width), "--height", str(args.height)]
if args.join:
cmd += ["--quickPlayMultiplayer", args.join]
if args.world:
cmd += ["--quickPlaySingleplayer", args.world]
if args.lan_port is not None:
# The vanilla client as reference LAN host (OfflineLanHost).
cp = cmd.index("-cp") + 1
cmd[cp] = os.pathsep.join([str(args.classes), cmd[cp]])
main = cmd.index("net.minecraft.client.main.Main")
cmd[main:main + 1] = [f"-Dhorizon.lanPort={args.lan_port}", "dev.horizonlab.parity.OfflineLanHost"]
if args.backend:
cmd += ["--graphicsBackend", args.backend]
return cmd
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--name", default="Guest")
parser.add_argument("--join", help="HOST:PORT to join on start")
parser.add_argument("--world", help="open this saves/ folder in singleplayer on start")
parser.add_argument("--game-dir", type=Path, default=ROOT / ".local/vanilla-client")
parser.add_argument("--assets", type=Path)
parser.add_argument("--heap", default="3G")
parser.add_argument("--width", type=int, default=1280)
parser.add_argument("--height", type=int, default=800)
parser.add_argument("--lan-port", type=int,
help="open the --world to LAN on this port without authentication (needs --classes)")
parser.add_argument("--classes", type=Path, default=ROOT / ".local/mp/oracle",
help="compiled OfflineLanHost (mods/horizon/src/test/java)")
parser.add_argument("--backend", help="graphics backend (opengl or vulkan)")
parser.add_argument("--option", action="append", default=[], help="KEY:VALUE for options.txt")
parser.add_argument("--print", action="store_true", help="print the command and exit")
args = parser.parse_args()
args.game_dir = args.game_dir.resolve()
args.game_dir.mkdir(parents=True, exist_ok=True)
write_options(args.game_dir, dict(o.split(":", 1) for o in args.option))
cmd = command(args)
if args.print:
print(" ".join(cmd))
return
sys.exit(subprocess.run(cmd, cwd=args.game_dir, env=environment()).returncode)
if __name__ == "__main__":
main()