Add native updateShape/canSurvive parity harness; port potent sulfur states

VanillaLevelShapeOracle evaluates BlockState.updateShape and canSurvive over
generated 5x5x5 neighbourhoods with a reflective LevelReader and records the
ticks requested through ScheduledTickAccess; level_shape_fixture does the same
through Behaviours. 40000/40000 random cases match. Walls, snow layers and sea
pickles now read position-dependent collision shapes (bamboo, speleothems,
shulker boxes) through DynamicSupport.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 03:04:21 +02:00
parent 6c2bf5c138
commit 244d2e95cf
10 changed files with 447 additions and 8 deletions
@@ -0,0 +1,102 @@
//! Rust side of `tools/test_level_shape_parity.py`: evaluates
//! `Behaviours::update_shape` and `can_survive` for generated neighbourhoods.
use horizon_core::{
geometry::Direction,
position::{BlockPos, ChunkPos},
random::LegacyRandom,
};
use horizon_world::{
level::{Behaviours, LevelAccess, Ticks, data::load_registry},
registry::BlockStateId,
};
use serde_json::Value;
use std::{
collections::{BTreeSet, HashMap},
io::{BufRead, Write},
path::Path,
};
struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
light: i32,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.cells.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, _pos: BlockPos, _state: BlockStateId) -> Option<BlockStateId> {
None
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
fn sky_light(&self, _pos: BlockPos) -> i32 {
self.light
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let resources = args.next().expect("resource directory");
let cases = args.next().expect("case file");
let output = args.next().expect("output file");
let resources = Path::new(&resources);
let registry = load_registry(resources)?;
let behaviours = Behaviours::load(&registry, resources)?;
let air = registry.default_state("minecraft:air").unwrap();
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for line in std::io::BufReader::new(std::fs::File::open(cases)?).lines() {
let case: Value = serde_json::from_str(&line?)?;
let mut cells = HashMap::new();
for cell in case["cells"].as_array().unwrap() {
let c: Vec<i64> = cell.as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect();
cells.insert(BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32), BlockStateId(c[3] as u32));
}
let mut level = Cells {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
light: case["light"].as_i64().unwrap() as i32,
};
let mut ticks = Ticks::new(0);
for x in -2..=2 {
for z in -2..=2 {
ticks.add_empty_chunk(ChunkPos::new(x, z))?;
}
}
let p: Vec<i32> = case["pos"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap() as i32).collect();
let pos = BlockPos::new(p[0], p[1], p[2]);
let direction = Direction::ALL[case["dir"].as_u64().unwrap() as usize];
let [dx, dy, dz] = direction.normal();
let neighbour_pos = pos.offset(dx, dy, dz);
let state = level.block_state(pos);
let neighbour = level.block_state(neighbour_pos);
let shape = behaviours.update_shape(&mut level, &mut ticks, state, pos, direction, neighbour_pos, neighbour);
let mut scheduled = BTreeSet::new();
for x in -2..=2 {
for z in -2..=2 {
let chunk = ChunkPos::new(x, z);
for tick in ticks.blocks.chunk(chunk).map(|c| c.queued()).unwrap_or_default() {
let name = &behaviours.table.info(horizon_world::level::BlockId(tick.kind.0 as u16)).name;
scheduled.insert(format!("{name}@{},{},{}+{}p{}", tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32));
}
for tick in ticks.fluids.chunk(chunk).map(|c| c.queued()).unwrap_or_default() {
let name = horizon_world::fluid::FluidKind::ALL[tick.kind.0 as usize].name();
scheduled.insert(format!("{name}@{},{},{}+{}p{}", tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32));
}
}
}
let survive = behaviours.can_survive(&mut level, &mut ticks, pos, state);
let scheduled: Vec<String> = scheduled.into_iter().collect();
writeln!(out, "shape {} ticks {} survive {survive}", shape.0, scheduled.join(" "))?;
}
Ok(())
}
+12 -1
View File
@@ -110,7 +110,7 @@ pub struct ShapeInfo {
pub wall_cover: u8,
}
fn analyse_shape(shape: &VoxelShape) -> io::Result<ShapeInfo> {
pub(crate) fn analyse_shape(shape: &VoxelShape) -> io::Result<ShapeInfo> {
let err = |e: horizon_core::geometry::ShapeError| invalid(e.to_string());
let mut info = ShapeInfo::default();
let block = VoxelShape::block();
@@ -551,6 +551,7 @@ props! {
side_chain = "side_chain",
copper_golem_pose = "copper_golem_pose",
sculk_sensor_phase = "sculk_sensor_phase",
potent_sulfur_state = "potent_sulfur_state",
}
fn fail(message: &str) -> io::Error {
@@ -932,6 +933,15 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviou
}
let liquid_blocks = FluidBlockBindings::new(registry)?;
let mut dynamic = HashMap::new();
for (id, fact) in facts.iter().enumerate() {
if fact.shape < 0 {
let state = BlockStateId(id as u32);
if let Some(support) = crate::dynamic_support::DynamicSupport::from_state(registry.state(state).unwrap())? {
dynamic.insert(state, support);
}
}
}
Ok(Behaviours {
table,
props,
@@ -945,6 +955,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviou
blocks,
items,
liquid_blocks,
dynamic,
occlusion_cache: Default::default(),
})
}
+14 -1
View File
@@ -72,7 +72,20 @@ impl Behaviours {
return Landing::Continue;
}
let concrete = self.instance_of(state, Class::ConcretePowder);
let may_replace = self.is_replaceable(current);
// DirectionalPlaceContext(level, pos, DOWN, ItemStack.EMPTY, UP).
let ctx = super::place::Ctx {
pos,
hit_pos: pos,
face: Direction::Up,
hit: horizon_core::geometry::Vec3::new(f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5),
inside: false,
yaw: 0.0,
pitch: 90.0,
sneaking: false,
item: String::new(),
replace_clicked: true,
};
let may_replace = sim.can_be_replaced(current, &ctx);
let would_continue = sim.is_free(sim.below_state(pos)) && (!concrete || !stuck_in_water);
let would_survive = sim.can_survive(state, pos) && !would_continue;
if !(may_replace && would_survive) {
+18
View File
@@ -348,6 +348,8 @@ pub struct Behaviours {
blocks: Vec<BlockData>,
items: HashMap<String, ItemBinding>,
liquid_blocks: FluidBlockBindings,
/// Uncached (position- or block-entity-dependent) collision shapes.
dynamic: HashMap<BlockStateId, crate::dynamic_support::DynamicSupport>,
occlusion_cache: Mutex<HashMap<(i32, i32, u8), bool>>,
}
@@ -454,6 +456,22 @@ impl Behaviours {
pub fn can_survive<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> bool {
self.sim(level, ticks).can_survive(state, pos)
}
/// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos,
/// neighbourState, random)`: the state `state` at `pos` would take after its
/// neighbour in `direction` became `neighbour` (ticks it requests are queued).
#[allow(clippy::too_many_arguments)]
pub fn update_shape<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
neighbour_pos: BlockPos,
neighbour: BlockStateId,
) -> BlockStateId {
self.sim(level, ticks).update_shape(state, pos, direction, neighbour_pos, neighbour)
}
/// `Block.updateFromNeighbourShapes`: a state adjusted to its neighbours.
pub fn update_from_neighbour_shapes<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> BlockStateId {
self.sim(level, ticks).update_from_neighbour_shapes(state, pos)
+2 -1
View File
@@ -876,7 +876,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
if clicked_vine { Some(result) } else { None }
}
Class::PotentSulfur | Class::Nylium => sup!(),
Class::PotentSulfur => Some(self.potent_sulfur_state(default, pos)),
Class::Nylium => sup!(),
_ => return None,
})
}
+33
View File
@@ -131,7 +131,40 @@ impl Behaviours {
}
}
/// Block-entity lookups for dynamic shapes: Horizon's level keeps no shulker
/// box animation state, so boxes read as closed (a full cube).
struct NoBlockEntities;
impl crate::dynamic_support::DynamicSupportWorld for NoBlockEntities {
type Error = std::convert::Infallible;
fn shulker_is_closed(&mut self, _position: [i32; 3]) -> Result<Option<bool>, Self::Error> {
Ok(None)
}
fn moving_piston_shape(&mut self, _position: [i32; 3]) -> Result<Option<horizon_core::geometry::VoxelShape>, Self::Error> {
Ok(None)
}
}
impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities {
fn shulker_collision_state(&mut self, _position: [i32; 3]) -> Result<Option<crate::block_collision::ShulkerCollisionState>, Self::Error> {
Ok(None)
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// Shape queries over `getCollisionShape(level, pos)`, including the
/// position-dependent shapes (bamboo, speleothems, shulker boxes).
pub(crate) fn shape_info_at(&self, state: BlockStateId, pos: BlockPos) -> super::data::ShapeInfo {
if self.b.facts(state).shape >= 0 {
return self.b.shape_info(state);
}
match self.b.dynamic.get(&state) {
Some(support) => support
.collision_shape(&mut NoBlockEntities, [pos.x, pos.y, pos.z])
.ok()
.and_then(|shape| super::data::analyse_shape(&shape).ok())
.unwrap_or_default(),
None => super::data::ShapeInfo::default(),
}
}
pub fn sturdy(&self, pos: BlockPos, direction: Direction) -> bool {
self.b.is_face_sturdy(self.state(pos), direction)
}
+30 -3
View File
@@ -653,13 +653,40 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::WallHangingSign => {
survive_or_air!(axis_of(dir) == axis_of(clockwise(b.facing(state))))
}
Class::NetherPortal | Class::PotentSulfur => sup!(),
Class::PotentSulfur => self.potent_sulfur_state(state, pos),
Class::NetherPortal => sup!(),
_ => return None,
})
}
// ---- family helpers ----
/// `PotentSulfurBlock.validBlockState` (the geyser block-entity countdown
/// reset is the caller's).
pub(crate) fn potent_sulfur_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId {
let b = self.b;
let key = b.props.potent_sulfur_state;
if self.fluid_at(above(pos)).kind() != FluidKind::Water {
return b.table.set_text(state, key, "dry");
}
let below_state = self.below_state(pos);
let fluid = b.fluid(below_state);
let source_if_fluid = fluid.kind() == FluidKind::Empty || fluid.is_source();
let tagged = |name: &str| b.tag(name).is_some_and(|tag| b.in_set(below_state, tag));
if tagged("minecraft:causes_continuous_geyser_eruptions") && source_if_fluid {
return b.table.set_text(state, key, "continuous");
}
if tagged("minecraft:causes_periodic_geyser_eruptions") && source_if_fluid {
if b.table.text(state, key) == "erupting" {
state
} else {
b.table.set_text(state, key, "dormant")
}
} else {
b.table.set_text(state, key, "wet")
}
}
fn bed_neighbour_direction(&self, state: BlockStateId) -> Direction {
let facing = self.b.facing(state);
if self.b.table.text(state, self.b.props.part) == "foot" { facing } else { facing.opposite() }
@@ -697,10 +724,10 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
b.in_set(state, &b.tags.walls) || (!b.is_exception_for_connection(state) && face_solid) || b.instance_of(state, Class::IronBars) || gate
}
/// `WallBlock.updateShape(level, state, topPos, topNeighbour, n, e, s, w)`.
pub(crate) fn wall_shape(&self, state: BlockStateId, _top_pos: BlockPos, top: BlockStateId, sides: [bool; 4]) -> BlockStateId {
pub(crate) fn wall_shape(&self, state: BlockStateId, top_pos: BlockPos, top: BlockStateId, sides: [bool; 4]) -> BlockStateId {
let b = self.b;
let table = &b.table;
let cover = b.shape_info(top).wall_cover;
let cover = self.shape_info_at(top, top_pos).wall_cover;
let mut result = state;
let directions = [Direction::North, Direction::East, Direction::South, Direction::West];
for (i, direction) in directions.into_iter().enumerate() {
+2 -2
View File
@@ -257,7 +257,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
} else if b.in_set(below_state, &t.support_override_snow_layer) {
true
} else {
b.collision_face_full(below_state, Direction::Up)
self.shape_info_at(below_state, below(pos)).full_faces & (1 << Direction::Up as u8) != 0
|| (b.is_block(below_state, block) && b.table.int(below_state, p.layers) == 8)
}
}
@@ -330,7 +330,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::NetherSprouts => b.in_set(ground, &t.supports_nether_sprouts),
Class::NetherWart => b.in_set(ground, &t.supports_nether_wart),
Class::SeaPickle => {
b.shape_info(ground).nonempty_faces & (1 << Direction::Up as u8) != 0 || b.is_face_sturdy(ground, Direction::Up)
self.shape_info_at(ground, ground_pos).nonempty_faces & (1 << Direction::Up as u8) != 0 || b.is_face_sturdy(ground, Direction::Up)
}
Class::Seagrass | Class::TallSeagrass => {
b.is_face_sturdy(ground, Direction::Up) && !b.in_set(ground, &t.cannot_support_seagrass)
@@ -0,0 +1,133 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.*;
import net.minecraft.util.RandomSource;
import net.minecraft.world.attribute.EnvironmentAttributeReader;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.ticks.LevelTickAccess;
import net.minecraft.world.ticks.TickPriority;
/**
* Native BlockState.updateShape and canSurvive over small generated neighbourhoods.
* The level is a reflective LevelReader over the case cells; scheduled ticks requested
* through ScheduledTickAccess are recorded instead of queued.
*/
public final class VanillaLevelShapeOracle {
private static void bindFluidTags(Path dir) throws Exception {
var registry = BuiltInRegistries.FLUID;
var loader = new TagLoader<Holder<Fluid>>((id, required) -> registry.get(id).map(value -> (Holder<Fluid>) value), "tags/fluid");
var definitions = new HashMap<Identifier, List<TagLoader.EntryWithSource>>();
try (var files = Files.list(dir)) {
for (var file : (Iterable<Path>) files::iterator) {
var name = file.getFileName().toString().replace(".json", "");
var parsed = TagFile.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseString(Files.readString(file))).getOrThrow();
var entries = new ArrayList<TagLoader.EntryWithSource>();
for (var entry : parsed.entries()) entries.add(new TagLoader.EntryWithSource(entry, "vanilla"));
definitions.put(Identifier.parse("minecraft:" + name), entries);
}
}
var tags = new HashMap<TagKey<Fluid>, List<Holder<Fluid>>>();
loader.build(definitions).forEach((id, values) -> tags.put(TagKey.create(Registries.FLUID, id), List.copyOf(values)));
registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.FLUID, tags)).apply();
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
Path resources = Path.of(args[0]);
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject());
bindFluidTags(resources.resolve("data/minecraft/tags/fluid"));
var registryAccess = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY);
var air = net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
for (var line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
var cells = new HashMap<BlockPos, BlockState>();
for (var cell : f.getAsJsonArray("cells")) {
var c = cell.getAsJsonArray();
cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt()));
}
int light = f.get("light").getAsInt();
var noTicks = (LevelTickAccess<?>) Proxy.newProxyInstance(LevelTickAccess.class.getClassLoader(), new Class<?>[]{LevelTickAccess.class}, (proxy, method, values) -> {
if (method.getReturnType() == boolean.class) return false;
if (method.getReturnType() == int.class) return 0;
return null;
});
var level = (LevelReader) Proxy.newProxyInstance(LevelReader.class.getClassLoader(), new Class<?>[]{LevelReader.class}, (proxy, method, values) -> {
switch (method.getName()) {
case "getBlockState": return cells.getOrDefault((BlockPos) values[0], air);
case "getFluidState": return cells.getOrDefault((BlockPos) values[0], air).getFluidState();
case "getBlockEntity": return null;
case "getRawBrightness": return Math.max(0, light - (int) values[1]);
case "getMaxLocalRawBrightness": return light;
case "getBrightness": return light;
case "isClientSide": return false;
case "registryAccess": return registryAccess;
case "enabledFeatures": return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS;
case "environmentAttributes": return EnvironmentAttributeReader.EMPTY;
case "getMinY": return -64;
case "getHeight": return values == null || values.length == 0 ? 384 : null;
case "getSkyDarken": return 0;
case "hashCode": return System.identityHashCode(proxy);
case "equals": return proxy == values[0];
default:
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, values);
throw new AssertionError(method.toString());
}
});
var scheduled = new TreeSet<String>();
var ticks = (ScheduledTickAccess) Proxy.newProxyInstance(ScheduledTickAccess.class.getClassLoader(), new Class<?>[]{ScheduledTickAccess.class}, (proxy, method, values) -> {
switch (method.getName()) {
case "scheduleTick": {
var pos = (BlockPos) values[0];
String type = values[1] instanceof Block block ? BuiltInRegistries.BLOCK.getKey(block).toString() : BuiltInRegistries.FLUID.getKey((Fluid) values[1]).toString();
int priority = values.length > 3 ? ((TickPriority) values[3]).getValue() : 0;
scheduled.add(type + "@" + pos.getX() + "," + pos.getY() + "," + pos.getZ() + "+" + values[2] + "p" + priority);
return null;
}
case "getBlockTicks":
case "getFluidTicks":
return noTicks;
default:
throw new AssertionError(method.toString());
}
});
RandomSource random = new LegacyRandomSource(f.get("seed").getAsLong());
var p = f.getAsJsonArray("pos");
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
var state = cells.getOrDefault(pos, air);
var direction = Direction.from3DDataValue(f.get("dir").getAsInt());
var neighbourPos = pos.relative(direction);
String shape;
try {
var result = state.updateShape(level, ticks, pos, direction, neighbourPos, level.getBlockState(neighbourPos), random);
shape = Integer.toString(Block.getId(result));
} catch (RuntimeException | AssertionError e) {
shape = "error " + e.getClass().getSimpleName();
}
String survive;
try {
survive = Boolean.toString(state.canSurvive(level, pos));
} catch (RuntimeException | AssertionError e) {
survive = "error";
}
out.println("shape " + shape + " ticks " + String.join(" ", scheduled) + " survive " + survive);
}
}
}
}
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Compare horizon-world's level updateShape/canSurvive port with pinned vanilla.
Generates random 5x5x5 neighbourhoods around a random block state, evaluates
BlockState.updateShape towards one neighbour and canSurvive with the native
oracle (VanillaLevelShapeOracle) and with Behaviours (level_shape_fixture),
and reports every differing case.
"""
import argparse
import json
import os
import random
import subprocess
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# Blocks whose updateShape needs a full level (portal frames) are skipped.
SKIP = {'minecraft:nether_portal', 'minecraft:moving_piston'}
def generate(resources, count, seed):
facts = json.loads((resources / 'facts.json').read_text())
states = facts['states']
by_block = {}
for index, state in enumerate(states):
by_block.setdefault(state[0], []).append(index)
names = [name for name in by_block if name not in SKIP]
common = [by_block[name][0] for name in ['minecraft:stone', 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:water',
'minecraft:oak_planks', 'minecraft:glass', 'minecraft:sand', 'minecraft:farmland']]
rng = random.Random(seed)
cases = []
for _ in range(count):
block = rng.choice(names)
center = rng.choice(by_block[block])
related = by_block[block]
cells = []
for x in range(-2, 3):
for y in range(-2, 3):
for z in range(-2, 3):
if (x, y, z) == (0, 0, 0):
cells.append([0, 0, 0, center])
continue
roll = rng.random()
if roll < 0.35:
continue
if roll < 0.55:
cells.append([x, y, z, rng.choice(common)])
elif roll < 0.75:
cells.append([x, y, z, rng.choice(related)])
else:
other = rng.choice(names)
cells.append([x, y, z, rng.choice(by_block[other])])
cases.append({'seed': rng.randrange(1 << 40), 'light': rng.randrange(16), 'pos': [0, 0, 0],
'dir': rng.randrange(6), 'cells': cells, 'block': block})
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=20000)
parser.add_argument('--seed', type=int, default=1)
args = parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'level-shape-parity'
work.mkdir(parents=True, exist_ok=True)
cases = generate(resources, args.count, args.seed)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
sources = [parity / 'VanillaLevelShapeOracle.java', parity / 'VanillaHeightmapOracle.java']
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), *map(str, sources)], check=True)
subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'),
str(work / 'native.txt')], check=True)
subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_fixture', '--',
str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT)
native = (work / 'native.txt').read_text().splitlines()
rust = (work / 'rust.txt').read_text().splitlines()
differences = {}
for case, a, b in zip(cases, native, rust):
if a != b:
differences.setdefault(case['block'], []).append((case, a, b))
total = sum(len(v) for v in differences.values())
for block, items in sorted(differences.items(), key=lambda item: -len(item[1])):
case, a, b = items[0]
print(f'{block}: {len(items)} differing; e.g. dir={case["dir"]}\n native {a}\n rust {b}')
print(f'{len(cases) - total}/{len(cases)} cases match')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in differences.items()}))
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()