diff --git a/crates/horizon-world/examples/level_shape_fixture.rs b/crates/horizon-world/examples/level_shape_fixture.rs new file mode 100644 index 000000000..24bdfad73 --- /dev/null +++ b/crates/horizon-world/examples/level_shape_fixture.rs @@ -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, + 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 { + 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> { + 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(®istry, 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 = 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 = 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 = scheduled.into_iter().collect(); + writeln!(out, "shape {} ticks {} survive {survive}", shape.0, scheduled.join(" "))?; + } + Ok(()) +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 725bb511c..5eb0da78b 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -110,7 +110,7 @@ pub struct ShapeInfo { pub wall_cover: u8, } -fn analyse_shape(shape: &VoxelShape) -> io::Result { +pub(crate) fn analyse_shape(shape: &VoxelShape) -> io::Result { 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 io::Result, items: HashMap, liquid_blocks: FluidBlockBindings, + /// Uncached (position- or block-entity-dependent) collision shapes. + dynamic: HashMap, occlusion_cache: Mutex>, } @@ -454,6 +456,22 @@ impl Behaviours { pub fn can_survive(&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( + &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(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> BlockStateId { self.sim(level, ticks).update_from_neighbour_shapes(state, pos) diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index 4e1064cb4..ab568e449 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -876,7 +876,8 @@ impl 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, }) } diff --git a/crates/horizon-world/src/level/query.rs b/crates/horizon-world/src/level/query.rs index 79788f4e7..580b6276f 100644 --- a/crates/horizon-world/src/level/query.rs +++ b/crates/horizon-world/src/level/query.rs @@ -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, Self::Error> { + Ok(None) + } + fn moving_piston_shape(&mut self, _position: [i32; 3]) -> Result, Self::Error> { + Ok(None) + } +} +impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities { + fn shulker_collision_state(&mut self, _position: [i32; 3]) -> Result, Self::Error> { + Ok(None) + } +} + impl 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) } diff --git a/crates/horizon-world/src/level/shapes.rs b/crates/horizon-world/src/level/shapes.rs index 702891af3..7acbff205 100644 --- a/crates/horizon-world/src/level/shapes.rs +++ b/crates/horizon-world/src/level/shapes.rs @@ -653,13 +653,40 @@ impl 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 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() { diff --git a/crates/horizon-world/src/level/survive.rs b/crates/horizon-world/src/level/survive.rs index f7c6ff672..75fef433c 100644 --- a/crates/horizon-world/src/level/survive.rs +++ b/crates/horizon-world/src/level/survive.rs @@ -257,7 +257,7 @@ impl 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 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) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java new file mode 100644 index 000000000..e0555a4b0 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java @@ -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>((id, required) -> registry.get(id).map(value -> (Holder) value), "tags/fluid"); + var definitions = new HashMap>(); + try (var files = Files.list(dir)) { + for (var file : (Iterable) 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(); + for (var entry : parsed.entries()) entries.add(new TagLoader.EntryWithSource(entry, "vanilla")); + definitions.put(Identifier.parse("minecraft:" + name), entries); + } + } + var tags = new HashMap, List>>(); + 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) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + var cells = new HashMap(); + 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(); + 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); + } + } + } +} diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py new file mode 100644 index 000000000..2817d4681 --- /dev/null +++ b/tools/test_level_shape_parity.py @@ -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()