Merge worktree-agent-aa7f8206a004fc51a

This commit is contained in:
Ludovic Marie
2026-10-10 08:46:17 +02:00
24 changed files with 1955 additions and 311 deletions
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Compare Horizon's resident PalettedContainer with the client's own.
Scripted edits run through vanilla's PalettedContainer (block-state and biome
strategies: single-value, linear, hash-map and global palettes, resizing, network
write and read, pack and unpack) and through horizon_core::paletted. Both sides
print the set results, the serialized container after every few edits, the
container read back from the wire, the saved form (palette, bit width, storage)
and the container loaded from it, as hashes.
"""
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
BUILD = lab.ROOT / 'target/paletted-container-parity'
LIMITS = {'blocks': (4096, 35723), 'biomes': (64, 67)}
def corpus():
rng = random.Random(0x50414C45545445)
counts = [1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 31, 32, 33, 64, 100, 128, 129, 200, 256, 257, 300, 700, 2000]
for kind, (entries, ids) in LIMITS.items():
for count in counts:
if kind == 'biomes' and count > 70:
continue
for trial in range(6):
pool = rng.sample(range(ids), min(count, ids))
initial = rng.choice(pool) if trial % 2 else rng.randrange(ids)
ops = []
for _ in range(rng.choice([entries // 4, entries, entries * 3])):
ops.append((rng.randrange(entries), rng.choice(pool)))
if trial == 5:
# Every position written once, in order, then half of them reset.
ops = [(i, pool[i % len(pool)]) for i in range(entries)] + [(i, initial) for i in range(0, entries, 2)]
yield f'{kind}_{count}_{trial}', kind, initial, rng.choice([1, 7, 37, 211]), ops
# A few edits at a time: the palette grows one value at a time from a single value.
for trial in range(20):
ops = [(rng.randrange(entries), rng.randrange(ids)) for _ in range(rng.randrange(1, 40))]
yield f'{kind}_sparse_{trial}', kind, rng.randrange(ids), 1, ops
# Overwriting with the value already there, and filling a section with one value.
yield f'{kind}_fill', kind, 3, 500, [(i, 9) for i in range(entries)] + [(i, 3) for i in range(entries)]
yield f'{kind}_same', kind, 3, 1, [(i, 3) for i in range(0, entries, 5)]
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
BUILD.mkdir(parents=True, exist_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java'
sources = [Path(__file__), oracle, lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-core/examples/paletted_fixture.rs',
*sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs'))]
tested = base.source_hashes(sources)
scenarios = list(corpus())
inputs = BUILD / 'inputs.txt'
inputs.write_text(''.join(f'{name} {kind} {initial} {every} ' + ' '.join(f'{i} {v}' for i, v in ops) + '\n'
for name, kind, initial, every, ops in scenarios))
def run(command, name):
with (BUILD / (name + '.log')).open('w') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
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', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', os.environ.get('CARGO_BUILD_JOBS', '3'), '-p', 'horizon-core', '--example', 'paletted_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory']) / 'fast/examples/paletted_fixture'
run([binary, inputs, BUILD / 'rust.txt'], 'rust')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPalettedContainerOracle', inputs, BUILD / 'client.txt'], 'client')
client = (BUILD / 'client.txt').read_text().splitlines()
rust = (BUILD / 'rust.txt').read_text().splitlines()
assert len(client) == len(rust) == len(scenarios), (len(client), len(rust), len(scenarios))
bad = [(a, b) for a, b in zip(client, rust) if a != b]
base.ensure_sources_unchanged(sources, tested)
for a, b in bad[:5]:
print('client', a[:600])
print('rust ', b[:600])
if bad:
raise SystemExit(f'{len(bad)} of {len(scenarios)} scenarios differ')
edits = sum(len(s[4]) for s in scenarios)
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenarios': len(scenarios), 'edits': edits,
'sources_sha256': tested}
lab.write_json(BUILD / 'report.json', report)
print(f'PalettedContainer parity: {len(scenarios)} scenarios, {edits:,} edits, all hashes identical')
if __name__ == '__main__':
main()
+73 -2
View File
@@ -29,6 +29,7 @@ except ImportError:
import test_model_baking_parity as baking
BUILD = lab.ROOT / 'target/section-mesh-parity'
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
SECTION_Y = 0
COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4}
POSITION_TOLERANCE = 1e-4
@@ -71,6 +72,8 @@ class Scene:
self.blocks = {}
self.light_override = {}
self.noise = None
self.biomes = None
self.options = {}
def put(self, x, y, z, name, **properties):
self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties)
@@ -130,8 +133,38 @@ class Scene:
return result
def row(self):
return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
row = {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
if self.biomes is not None:
row['biomes'] = self.biomes
row.update(self.options)
return row
def tinted_columns(self):
"""Every tint source at several heights over the section's 16x16 footprint."""
names = [('grass_block', {}), ('short_grass', {}), ('oak_leaves', {}), ('water', {}), ('leaf_litter', {'segment_amount': 2}),
('sugar_cane', {}), ('fern', {}), ('vine', {'north': True}), ('mangrove_leaves', {}), ('jungle_leaves', {})]
for x in range(16):
for z in range(16):
for layer, y in enumerate((1, 5, 9, 13)):
name, properties = names[(x * 5 + z * 3 + layer) % len(names)]
self.put(x, y, z, 'stone')
self.put(x, y + 1, z, name, **properties)
if name == 'water':
self.put(x, y + 2, z, 'water')
def biome_field(self, seed, radius, names, default='plains'):
"""Noise-biome quart cells: a Voronoi patchwork that shifts with height."""
rng = random.Random(seed)
sites = [[(rng.uniform(-4, 8), rng.uniform(-4, 8), rng.choice(names)) for _ in range(9)] for _ in range(10)]
cells = []
for qy in range(-3, 8):
layer = sites[(qy + 3) // 2 % len(sites)]
for qx in range(-4, 8):
for qz in range(-4, 8):
best = min(layer, key=lambda site: (site[0] - qx) ** 2 + (site[1] - qz) ** 2)
cells.append([qx, qy, qz, 'minecraft:' + best[2]])
self.biomes = {'seed': rng.randrange(-2 ** 63, 2 ** 63), 'radius': radius, 'default': 'minecraft:' + default, 'cells': cells}
def corpus(states, full=True):
@@ -306,6 +339,38 @@ def corpus(states, full=True):
s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids))
if seed % 2:
s.noise = seed
# Biome tint blending: BiomeManager's zoomed biome at each block's own height, averaged
# over the blend radius, for real biome colours (colormaps, overrides, modifiers).
biome_names = sorted(path.stem for path in (RESOURCES / 'data/minecraft/worldgen/biome').glob('*.json'))
common = ['plains', 'swamp', 'dark_forest', 'desert', 'jungle', 'badlands', 'mangrove_swamp', 'warm_ocean', 'snowy_plains',
'birch_forest', 'cherry_grove', 'pale_garden', 'savanna', 'taiga', 'old_growth_pine_taiga', 'lush_caves']
for i, radius in enumerate((2, 0, 1, 3, 5, 7)):
s = scene(f'biome_blend_r{radius}')
s.floor(0)
s.tinted_columns()
s.biome_field(0x42494F4D + i, radius, common)
for i in range(0, len(biome_names), 8):
s = scene(f'biome_each_{i // 8}')
s.tinted_columns()
s.biome_field(0x45414348 + i, 2, biome_names[i:i + 8], biome_names[i])
# Options: flat lighting (ao off) and opaque leaves (cutoutLeaves off) alone and together.
leaves = ['oak_leaves', 'spruce_leaves', 'birch_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves',
'azalea_leaves', 'flowering_azalea_leaves', 'mangrove_leaves', 'cherry_leaves', 'pale_oak_leaves']
option_palette = ['stone', 'glass', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy', 'short_grass',
'glowstone', 'oak_fence', 'ice', 'oak_log', 'tinted_glass', 'slime_block', 'honey_block'] + leaves * 2
for i, options in enumerate(({'smooth': False}, {'cutout_leaves': False}, {'smooth': False, 'cutout_leaves': False})):
rng = random.Random(0x4F505453 + i)
s = scene(f'options_{i}', nether=i == 2)
s.options = options
s.floor(0)
for x in range(-1, 17):
for y in range(1, 17):
for z in range(-1, 17):
if rng.random() < 0.5:
name = rng.choice(option_palette)
s.put(x, y, z, rng.choice(states.by_name['minecraft:' + name]))
if i:
s.noise = i
s = scene('cubes_nether', nether=True)
s.floor(3, 'netherrack')
s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks')
@@ -337,6 +402,7 @@ def light(coords):
def compare(scene, client, rust, states, report, limit):
blend_zero = scene.get('biomes', {}).get('radius') == 0
blocks = {tuple(b[:3]): b[3] for b in scene['blocks']}
def describe(quad, rotation):
v = quad['vertices']
@@ -377,6 +443,11 @@ def compare(scene, client, rust, states, report, limit):
if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)):
problems.add('uv')
cp, cq = channels(p[5]), channels(q[5])
if blend_zero and cp[3] == 0 and cq[3] == 255:
# With biomeBlendRadius 0 the client uses the resolver's colour as is,
# and biome colours given as plain RGB have alpha 0: tinted vertices come
# out fully transparent. Horizon keeps them opaque; RGB is compared.
cp[3] = 255
if cp != cq:
problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding')
if light(p[6]) != light(q[6]):