Add section mesh parity gate against the client's block and fluid renderers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:13:16 +02:00
parent 1b38d82aac
commit 2940b5ac90
3 changed files with 897 additions and 0 deletions
@@ -0,0 +1,154 @@
//! Headless transport for the section-mesh parity gate: builds the requested
//! scenes in real client chunks and writes the vertices `Mesher::mesh` emits in
//! the oracle's canonical form (vanilla ARGB colours and packed light coords).
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
biome::{Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, Vertex},
models,
};
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
fs,
io::{BufRead, BufReader, BufWriter, Write},
path::PathBuf,
sync::Arc,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn int(value: &Value) -> Result<i32> {
Ok(i32::try_from(value.as_i64().ok_or("expected integer")?)?)
}
/// Horizon packs RGBA little endian (red in the low byte); vanilla uses ARGB.
fn argb(color: u32) -> i32 {
let [r, g, b, a] = color.to_le_bytes();
i32::from_be_bytes([a, r, g, b])
}
/// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light
/// coords keep block in the low half-word and sky in the high one.
fn light_coords(light: u32) -> i32 {
((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32
}
/// Scenes cover the 3x3 chunk region around chunk (0, 0).
fn chunk_index(x: i32, z: i32) -> Result<usize> {
let (cx, cz) = (x.div_euclid(16), z.div_euclid(16));
if !(-1..=1).contains(&cx) || !(-1..=1).contains(&cz) {
return Err("scene block outside the 3x3 chunk region".into());
}
Ok(((cz + 1) * 3 + cx + 1) as usize)
}
fn scene(
row: &Value,
assets: &Assets,
tables: &MeshTables,
biomes: &mut Biomes,
names: &BTreeMap<u32, &str>,
) -> Result<Value> {
let colors = &row["colors"];
let color = |k: &str| -> Result<u32> { Ok(int(&colors[k])? as u32 & 0xFF_FFFF) };
for biome in &mut biomes.list {
biome.grass = color("grass")?;
biome.modifier = GrassModifier::None;
biome.foliage = color("foliage")?;
biome.dry_foliage = color("dry_foliage")?;
biome.water = color("water")?;
}
let default = row["light"].as_array().ok_or("missing default light")?;
let packed = |sky: i32, block: i32| (sky << 4 | block) as u8;
let default = packed(int(&default[0])?, int(&default[1])?);
let mut chunks: Vec<Chunk> = (0..9)
.map(|i| {
let mut chunk = Chunk::empty(i % 3 - 1, i / 3 - 1);
for section in &mut chunk.sections {
Arc::make_mut(section).light = Light::Uniform(default);
}
chunk
})
.collect();
for block in row["blocks"].as_array().ok_or("missing blocks")? {
let (x, y, z) = (int(&block[0])?, int(&block[1])?, int(&block[2])?);
let i = chunk_index(x, z)?;
chunks[i].set(x & 15, y, z & 15, u16::try_from(int(&block[3])?)?);
}
for cell in row["lights"].as_array().ok_or("missing lights")? {
let (x, y, z) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?);
let i = chunk_index(x, z)?;
let s = ((y - MIN_Y) >> 4) as usize;
let section = Arc::make_mut(&mut chunks[i].sections[s]);
if let Light::Uniform(v) = section.light {
section.light = Light::Full(Box::new([v; 4096]));
}
if let Light::Full(values) = &mut section.light {
values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?);
}
}
let region: [[Option<&Chunk>; 3]; 3] =
std::array::from_fn(|z| std::array::from_fn(|x| Some(&chunks[z * 3 + x])));
let mut mesher = Mesher {
nether_shading: row["nether"].as_bool().unwrap_or(false),
assets,
tables,
biomes: &*biomes,
visibility: tables.visibility.clone(),
};
let section_y = int(&row["section_y"])?;
let mesh = mesher.mesh(&region, (section_y * 16 - MIN_Y) / 16);
let mut quads = Vec::new();
for (layer, vertices) in [("opaque", &mesh.solid), ("translucent", &mesh.translucent)] {
if vertices.len() % 4 != 0 {
return Err("partial quad".into());
}
for quad in vertices.chunks_exact(4) {
let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?;
if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) {
return Err("quad mixes sprite layers".into());
}
let vertices: Vec<Value> = quad
.iter()
.map(|v| {
json!([
v.pos[0],
v.pos[1],
v.pos[2],
v.uv[0],
v.uv[1],
argb(v.color),
light_coords(v.light)
])
})
.collect();
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
}
}
Ok(json!({"name": row["name"], "quads": quads}))
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
if args.len() != 3 {
return Err("usage: section_mesh_fixture RESOURCES INPUT.jsonl OUTPUT.jsonl".into());
}
let root = PathBuf::from(&args[0]);
let assets = Assets::load(&root)?;
let facts = BlockFacts::load(&root, assets.registry)?;
let mut biomes = Biomes::load(&root)?;
let visibility = models::load_visibility(&root, assets.registry)?;
let tables = MeshTables::new(&assets, &facts, visibility)?;
let names: BTreeMap<u32, &str> = assets
.sprite_layers
.iter()
.map(|(name, layer)| (*layer, name.as_str()))
.collect();
let mut output = BufWriter::new(fs::File::create(&args[2])?);
for line in BufReader::new(fs::File::open(&args[1])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let result = scene(&row, &assets, &tables, &mut biomes, &names)?;
serde_json::to_writer(&mut output, &result)?;
output.write_all(b"\n")?;
}
output.flush()?;
Ok(())
}
@@ -0,0 +1,293 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.vertex.QuadInstance;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.serialization.JsonOps;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.client.renderer.block.*;
import net.minecraft.client.renderer.block.dispatch.*;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.resources.model.*;
import net.minecraft.client.resources.model.cuboid.*;
import net.minecraft.client.resources.model.geometry.BakedQuad;
import net.minecraft.client.resources.model.sprite.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.util.StrictJsonParser;
import net.minecraft.world.level.CardinalLighting;
import net.minecraft.world.level.ColorResolver;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.lighting.LevelLightEngine;
import net.minecraft.world.level.material.FluidState;
import org.joml.Vector3fc;
import static dev.horizonlab.parity.VanillaCuboidModelOracle.map;
/** Runs the client's own ModelBlockRenderer (smooth lighting on) and FluidRenderer
* over small fixed scenes, the way SectionCompiler visits one section, and
* records every emitted vertex. Block models are baked from the jar's own
* blockstate and model resources; every texture becomes a real sprite alone in
* a unit atlas so UVs stay in sprite-local [0,1] space. Fluid sprites share one
* strip with gaps so their vertex stream still identifies the sprite. */
public final class VanillaSectionMeshOracle {
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
private static final String[] FLUID_SPRITES = {"minecraft:block/water_still", "minecraft:block/water_flow",
"minecraft:block/water_overlay", "minecraft:block/lava_still", "minecraft:block/lava_flow"};
private static final int STRIP = 2 * FLUID_SPRITES.length;
private static final class Sprite extends TextureAtlasSprite {
Sprite(SpriteContents contents, int slots, int slot) {
super(TextureAtlas.LOCATION_BLOCKS, contents, contents.width() * slots, contents.height(), contents.width() * slot, 0, 0);
}
}
private static final Map<Identifier, TextureAtlasSprite> SPRITES = new HashMap<>();
private static SpriteContents contents(Identifier id) throws IOException {
var path = "/assets/" + id.getNamespace() + "/textures/" + id.getPath() + ".png";
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) {
NativeImage image = input == null ? new NativeImage(16, 16, true) : NativeImage.read(input);
int size = Math.min(image.getWidth(), image.getHeight());
return new SpriteContents(id, new FrameSize(image.getWidth(), size), image);
}
}
private static TextureAtlasSprite sprite(Identifier id) {
return SPRITES.computeIfAbsent(id, key -> {
try {
int slot = Arrays.asList(FLUID_SPRITES).indexOf(key.toString());
return slot < 0 ? new Sprite(contents(key), 1, 0) : new Sprite(contents(key), STRIP, 2 * slot);
} catch (IOException error) { throw new UncheckedIOException(error); }
});
}
/** Hands out the unit-atlas sprite named by each material. */
private static final class Materials extends MaterialBaker {
Materials(SpriteLoader.Preparations atlas) { super(atlas, atlas); }
@Override public Material.Baked get(Material material, ModelDebugName name) {
return new Material.Baked(sprite(material.sprite()), material.forceTranslucent());
}
}
private static final class Baker implements ModelBaker {
final Map<Identifier, ResolvedModel> resolved; final ResolvedModel missing; final MaterialBaker materials;
final Map<SharedOperationKey<?>, Object> cache = new HashMap<>();
Baker(Map<Identifier, ResolvedModel> resolved, ResolvedModel missing, MaterialBaker materials) {
this.resolved = resolved; this.missing = missing; this.materials = materials;
}
public ResolvedModel getModel(Identifier id) { return resolved.getOrDefault(id, missing); }
public BlockStateModelPart missingBlockModelPart() { throw new AssertionError("missing block model part"); }
public MaterialBaker materials() { return materials; }
public ModelBaker.Interner interner() {
return new ModelBaker.Interner() {
public Vector3fc vector(Vector3fc vector) { return vector; }
public BakedQuad.MaterialInfo materialInfo(BakedQuad.MaterialInfo value) { return value; }
};
}
@SuppressWarnings("unchecked")
public <T> T compute(SharedOperationKey<T> key) {
var value = cache.get(key);
if (value == null) { value = key.compute(this); cache.put(key, value); }
return (T) value;
}
}
private static String resource(String path) throws IOException {
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) {
return input == null ? null : new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
}
/** Real blockstate definitions and models for the requested blocks. */
private static final class Models {
final Map<BlockState, BlockStateModel.UnbakedRoot> roots = new HashMap<>();
final Map<BlockState, BlockStateModel> baked = new HashMap<>();
final Baker baker;
Models(Set<Block> blocks, MaterialBaker materials) throws IOException {
var unbaked = new HashMap<Identifier, UnbakedModel>();
for (var block : blocks) {
var id = BuiltInRegistries.BLOCK.getKey(block);
var raw = resource("/assets/" + id.getNamespace() + "/blockstates/" + id.getPath() + ".json");
if (raw == null) continue;
var definition = BlockStateModelDispatcher.CODEC.parse(JsonOps.INSTANCE, StrictJsonParser.parse(raw)).getOrThrow();
roots.putAll(definition.instantiate(block.getStateDefinition(), id::toString));
}
var pending = new ArrayList<Identifier>();
for (var root : new HashSet<>(roots.values())) root.resolveDependencies(pending::add);
for (int i = 0; i < pending.size(); i++) {
var id = pending.get(i);
if (unbaked.containsKey(id)) continue;
var raw = resource("/assets/" + id.getNamespace() + "/models/" + id.getPath() + ".json");
if (raw == null) continue;
var model = CuboidModel.fromStream(new StringReader(raw));
unbaked.put(id, model);
if (model.parent() != null) pending.add(model.parent());
}
var discovery = new ModelDiscovery(unbaked, MissingCuboidModel.missingModel());
discovery.addRoot(resolver -> { for (var id : unbaked.keySet()) resolver.markDependency(id); });
var resolved = discovery.resolve();
baker = new Baker(resolved, discovery.missingModel(), materials);
}
BlockStateModel get(BlockState state) {
return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker));
}
}
private static long key(int x, int y, int z) { return BlockPos.asLong(x, y, z); }
/** A fixed region: listed blocks over air, listed light over a default. */
private static final class Scene implements BlockAndTintGetter {
final Map<Long, BlockState> blocks = new HashMap<>();
final Map<Long, int[]> light = new HashMap<>();
int[] defaultLight; boolean nether; int grass, foliage, dry, water;
public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; }
public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; }
public int getBrightness(LightLayer layer, BlockPos pos) {
var value = light.getOrDefault(pos.asLong(), defaultLight);
return layer == LightLayer.SKY ? value[0] : value[1];
}
public int getBlockTint(BlockPos pos, ColorResolver resolver) {
int rgb = resolver == BiomeColors.GRASS_COLOR_RESOLVER ? grass : resolver == BiomeColors.FOLIAGE_COLOR_RESOLVER ? foliage
: resolver == BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER ? dry : resolver == BiomeColors.WATER_COLOR_RESOLVER ? water : -1;
if (rgb == -1) throw new AssertionError("unexpected colour resolver");
return 0xFF000000 | rgb;
}
public BlockEntity getBlockEntity(BlockPos pos) { return null; }
public BlockState getBlockState(BlockPos pos) { return blocks.getOrDefault(pos.asLong(), Blocks.AIR.defaultBlockState()); }
public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
public int getHeight() { return 384; }
public int getMinY() { return -64; }
}
private static final class Recorder {
final List<Object> quads = new ArrayList<>();
List<Object> pending; BlockPos block; String kind, layer, sprite;
void vertex(float x, float y, float z, int color, float u, float v, int light) {
if (pending == null) pending = new ArrayList<>();
pending.add(new Object[]{x, y, z, u, v, color, light});
if (pending.size() == 4) {
quads.add(map("block", new int[]{block.getX(), block.getY(), block.getZ()}, "kind", kind, "layer", layer, "sprite", sprite, "vertices", pending));
pending = null;
}
}
}
private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); }
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) {
var scene = new Scene();
var light = row.getAsJsonArray("light");
scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()};
scene.nether = row.get("nether").getAsBoolean();
var colors = row.getAsJsonObject("colors");
scene.grass = colors.get("grass").getAsInt(); scene.foliage = colors.get("foliage").getAsInt();
scene.dry = colors.get("dry_foliage").getAsInt(); scene.water = colors.get("water").getAsInt();
for (var item : row.getAsJsonArray("blocks")) {
var b = item.getAsJsonArray();
scene.blocks.put(key(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()), Block.stateById(b.get(3).getAsInt()));
}
for (var item : row.getAsJsonArray("lights")) {
var l = item.getAsJsonArray();
scene.light.put(key(l.get(0).getAsInt(), l.get(1).getAsInt(), l.get(2).getAsInt()), new int[]{l.get(3).getAsInt(), l.get(4).getAsInt()});
}
var recorder = new Recorder();
BlockModelLighter.enableCaching();
var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault());
var fluidRenderer = new FluidRenderer(fluids);
BlockQuadOutput output = (x, y, z, quad, instance) -> {
recorder.kind = "model"; recorder.layer = layer(quad.materialInfo().layer());
recorder.sprite = quad.materialInfo().sprite().contents().name().toString();
int emission = quad.materialInfo().lightEmission();
for (int i = 0; i < 4; i++) {
var p = quad.position(i); long uv = quad.packedUV(i);
recorder.vertex(p.x() + x, p.y() + y, p.z() + z, instance.getColor(i),
Float.intBitsToFloat((int) (uv >>> 32)), Float.intBitsToFloat((int) uv), instance.getLightCoordsWithEmission(i, emission));
}
};
int baseY = row.get("section_y").getAsInt() * 16;
for (var pos : BlockPos.betweenClosed(0, baseY, 0, 15, baseY + 15, 15)) {
var state = scene.getBlockState(pos);
if (state.isAir()) continue;
recorder.block = pos.immutable();
var fluid = state.getFluidState();
if (!fluid.isEmpty()) {
fluidRenderer.tesselate(scene, pos, sectionLayer -> new VertexConsumer() {
public void addVertex(float x, float y, float z, int color, float u, float v, int overlay, int light, float nx, float ny, float nz) {
int slot = (int) Math.floor(u * STRIP / 2.0f);
recorder.kind = "fluid"; recorder.layer = layer(sectionLayer); recorder.sprite = FLUID_SPRITES[slot];
recorder.vertex(x, y, z, color, u * STRIP - 2 * slot, v, light);
}
public VertexConsumer addVertex(float x, float y, float z) { throw new AssertionError(); }
public VertexConsumer setColor(int r, int g, int b, int a) { throw new AssertionError(); }
public VertexConsumer setColor(int color) { throw new AssertionError(); }
public VertexConsumer setUv(float u, float v) { throw new AssertionError(); }
public VertexConsumer setUv1(int u, int v) { throw new AssertionError(); }
public VertexConsumer setUv2(int u, int v) { throw new AssertionError(); }
public VertexConsumer setUv3(float u, float v) { throw new AssertionError(); }
public VertexConsumer setNormal(float x, float y, float z) { throw new AssertionError(); }
public VertexConsumer setLineWidth(float width) { throw new AssertionError(); }
}, state, fluid);
}
if (state.getRenderShape() == RenderShape.MODEL) {
renderer.tesselateBlock(ModelBlockRenderer.forceOpaque(true, state) ? (x, y, z, quad, instance) -> {
throw new AssertionError("cutout leaves are enabled");
} : output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()),
scene, pos, state, models.get(state), state.getSeed(pos));
}
}
BlockModelLighter.clearCache();
if (recorder.pending != null) throw new AssertionError("partial quad");
return map("name", row.get("name").getAsString(), "quads", recorder.quads);
}
/** Per-state facts the Rust mesher derives from prepared resources. */
private static Object facts(BlockState state, int id) {
var level = EmptyBlockGetter.INSTANCE;
var offsets = new ArrayList<Object>();
if (state.hasOffsetFunction()) {
for (var p : new BlockPos[]{new BlockPos(0, 0, 0), new BlockPos(5, 7, -3), new BlockPos(-17, 70, 31), new BlockPos(123, -40, -456), new BlockPos(9, 1, 2)}) {
var o = state.getOffset(p);
offsets.add(new double[]{o.x, o.y, o.z});
}
}
var block = state.getBlock();
return map("id", id, "shade", state.getShadeBrightness(level, BlockPos.ZERO), "emissive", state.emissiveRendering(),
"legacy_solid", state.isSolid(), "light_permeable", state.isLightPermeable(), "solid_render", state.isSolidRender(),
"full_collision", state.isCollisionShapeFullBlock(level, BlockPos.ZERO), "emission", state.getLightEmission(),
"half_transparent", block instanceof HalfTransparentBlock, "leaves", block instanceof LeavesBlock,
"tint_sources", BlockColors.createDefault().getTintSources(state).size(), "offsets", offsets);
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
LeavesBlock.setCutoutLeaves(true);
if (args[0].equals("facts")) {
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
int id = 0;
for (var state : Block.BLOCK_STATE_REGISTRY) {
if (Block.getId(state) != id) throw new AssertionError("state registry order");
output.write(JSON.toJson(facts(state, id++))); output.newLine();
}
}
return;
}
var rows = new ArrayList<JsonObject>();
try (var input = Files.newBufferedReader(Path.of(args[0]))) {
for (String line; (line = input.readLine()) != null; ) rows.add(JsonParser.parseString(line).getAsJsonObject());
}
var blocks = new HashSet<Block>();
for (var row : rows) for (var item : row.getAsJsonArray("blocks")) blocks.add(Block.stateById(item.getAsJsonArray().get(3).getAsInt()).getBlock());
var missingContents = new SpriteContents(Identifier.parse("minecraft:missingno"), new FrameSize(16, 16), new NativeImage(16, 16, true));
var missing = new Sprite(missingContents, 1, 0);
var atlas = new SpriteLoader.Preparations(16, 16, 0, missing, Map.of(), CompletableFuture.completedFuture(null));
var materials = new Materials(atlas);
var models = new Models(blocks, materials);
var fluidModels = FluidStateModelSet.bake(materials);
var fluids = new FluidStateModelSet(fluidModels, fluidModels.values().iterator().next());
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids))); output.newLine(); }
}
}
}
+450
View File
@@ -0,0 +1,450 @@
#!/usr/bin/env python3
"""Compare Horizon's section mesher with the client's own ModelBlockRenderer and FluidRenderer.
Both sides mesh the same scenes (block states by registry ID, per-cell sky/block
light, constant biome colours, overworld or Nether cardinal lighting). The Java
oracle runs vanilla smooth lighting (AO on, cutout leaves) block by block the way
SectionCompiler visits a section; the Rust fixture runs ``Mesher::mesh`` on real
client chunks. Quads are compared as multisets keyed by sprite, render layer class
and rounded geometry; matched quads then compare UVs, ARGB colours and light
coordinates per vertex. A second gate compares the per-state facts the Rust mesher
derives (shade brightness, emissive rendering, legacy solidity, offsets, ...)
with the client's own state accessors for every registry state.
"""
import argparse
from collections import Counter, defaultdict
import json
import math
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab
import test_rust_parity as base
import test_model_baking_parity as baking
BUILD = lab.ROOT / 'target/section-mesh-parity'
SECTION_Y = 0
COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4}
POSITION_TOLERANCE = 1e-4
UV_TOLERANCE = 1e-4
class States:
"""Registry state IDs by name and properties, from the prepared registry facts."""
def __init__(self, resources):
facts = json.loads((resources / 'facts.json').read_text())
self.defaults = facts['defaults']
self.properties = [entry[4].get('properties', {}) for entry in facts['states']]
self.names = [entry[0] for entry in facts['states']]
self.by_name = defaultdict(list)
for index, name in enumerate(self.names):
self.by_name[name].append(index)
gameplay = json.loads((resources / 'gameplay-facts.json').read_text())['states']
self.dampening = [s['dampening'] for s in gameplay]
self.emission = [s['emission'] for s in gameplay]
self.opaque = [s['solid_render'] for s in gameplay]
self.render_shape = [s['render_shape'] for s in gameplay]
def __call__(self, name, **properties):
name = name if ':' in name else 'minecraft:' + name
wanted = dict(self.properties[self.defaults[name]])
for key, value in properties.items():
key = key.rstrip('_')
if key not in wanted:
raise KeyError(f'{name} has no property {key}')
wanted[key] = str(value).lower()
for index in self.by_name[name]:
if self.properties[index] == wanted:
return index
raise KeyError(f'no state {name} {wanted}')
class Scene:
def __init__(self, states, name, nether=False):
self.states, self.name, self.nether = states, name, nether
self.blocks = {}
self.light_override = {}
self.noise = None
def put(self, x, y, z, name, **properties):
self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties)
def fill(self, x0, y0, z0, x1, y1, z1, name, **properties):
state = self.states(name, **properties)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
for z in range(z0, z1 + 1):
self.blocks[(x, y, z)] = state
def floor(self, y=3, name='stone'):
self.fill(-1, y, -1, 16, y, 16, name)
def lights(self):
"""Simple deterministic propagation: straight-down skylight, -1 per step
sideways, dampening per cell; emitters spread block light the same way."""
lo, hi = -2, 17
base = SECTION_Y * 16
cells = [(x, y, z) for x in range(lo, hi + 1) for y in range(base + lo, base + hi + 1) for z in range(lo, hi + 1)]
damp = {c: self.states.dampening[self.blocks.get(c, 0)] for c in cells}
opaque = {c: self.states.opaque[self.blocks.get(c, 0)] and damp[c] > 0 for c in cells}
def spread(seeds, straight_down):
level = {c: 0 for c in cells}
queue = []
for c, v in seeds:
if v > level[c]:
level[c] = v
queue.append(c)
while queue:
nxt = []
for c in queue:
v = level[c]
for d in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]:
n = (c[0] + d[0], c[1] + d[1], c[2] + d[2])
if n not in level or opaque[n]:
continue
loss = 0 if straight_down and d == (0, -1, 0) and v == 15 and damp[n] == 0 else 1
w = v - loss - damp[n]
if w > level[n]:
level[n] = w
nxt.append(n)
queue = nxt
return level
top = base + hi
sky = spread([((x, top, z), 15) for x in range(lo, hi + 1) for z in range(lo, hi + 1) if not opaque[(x, top, z)]], True)
block = spread([(c, self.states.emission[self.blocks.get(c, 0)]) for c in cells], False)
rng = random.Random(self.noise) if self.noise is not None else None
result = []
for c in cells:
s, b = sky[c], block[c]
if rng is not None:
s, b = rng.randrange(16), rng.randrange(16)
s, b = self.light_override.get(c, (s, b))
if (s, b) != (15, 0):
result.append([*c, s, b])
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()}
def corpus(states):
scenes = []
def scene(name, **kwargs):
s = Scene(states, name, **kwargs)
scenes.append(s)
return s
# Full cubes: open air, corners, cavities, overhangs and steps for AO.
s = scene('cubes_open')
s.put(8, 8, 8, 'stone')
s.put(3, 3, 3, 'grass_block')
s = scene('cubes_corners')
s.floor(3)
s.fill(0, 4, 0, 15, 7, 0, 'stone')
s.fill(0, 4, 0, 0, 7, 15, 'cobblestone')
s.fill(4, 4, 4, 6, 4, 6, 'oak_planks')
s.put(5, 5, 5, 'stone')
s.fill(9, 4, 9, 12, 6, 12, 'stone')
s.put(10, 6, 10, 'air')
s.put(11, 5, 10, 'air')
s.put(10, 5, 10, 'air')
s.fill(2, 8, 2, 6, 8, 6, 'stone')
s.put(13, 4, 2, 'glass')
s.put(13, 4, 3, 'stone')
s.put(14, 4, 2, 'oak_leaves')
s.put(14, 5, 2, 'grass_block')
s.put(12, 4, 14, 'soul_sand')
s.put(13, 4, 14, 'mud')
s.put(14, 4, 14, 'barrier')
s.put(12, 5, 14, 'grass_block')
s.put(13, 5, 14, 'grass_block')
s.put(14, 5, 14, 'snow', layers=8)
s.put(15, 5, 14, 'snow', layers=4)
s = scene('cave')
s.fill(-1, 0, -1, 16, 15, 16, 'stone')
s.fill(2, 3, 2, 13, 9, 13, 'air')
s.fill(5, 3, 5, 9, 3, 9, 'water')
s.put(4, 4, 4, 'torch')
s.put(12, 3, 12, 'glowstone')
s.put(3, 3, 12, 'magma_block')
s.put(12, 3, 3, 'sea_lantern')
s.put(7, 9, 7, 'shroomlight')
s.put(10, 4, 4, 'lantern')
s.put(2, 5, 7, 'wall_torch', facing='east')
s.put(6, 4, 11, 'redstone_wire', power=15)
s.put(7, 4, 11, 'redstone_wire', power=7)
s.put(8, 4, 11, 'redstone_wire', power=0)
s.put(6, 3, 11, 'stone')
s.put(9, 4, 12, 'sculk_sensor', sculk_sensor_phase='active')
s.put(10, 4, 12, 'sculk_sensor')
s.put(11, 4, 12, 'glow_lichen', down=True)
# Shapes on a floor, against walls and in the open.
s = scene('shapes')
s.floor(3)
s.fill(-1, 4, 15, 16, 7, 16, 'stone')
x = 0
for name, props in [('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}),
('oak_stairs', {}), ('oak_stairs', {'facing': 'east', 'half': 'top'}), ('oak_stairs', {'shape': 'inner_left'}),
('oak_stairs', {'facing': 'south', 'shape': 'outer_right'}), ('cobblestone_wall', {'north': 'low', 'up': True}),
('oak_fence', {'north': True, 'east': True}), ('glass_pane', {'north': True, 'south': True}),
('iron_bars', {'east': True, 'west': True}), ('torch', {}), ('poppy', {}), ('dandelion', {}),
('short_grass', {}), ('fern', {})]:
s.put(x, 4, 7, name, **props)
s.put(x, 4, 14, name, **props)
x += 1
x = 0
for name, props in [('tall_grass', {'half': 'lower'}), ('large_fern', {'half': 'lower'}), ('sunflower', {'half': 'lower'}),
('grass_block', {}), ('oak_leaves', {}), ('spruce_leaves', {}), ('birch_leaves', {}), ('snow', {'layers': 1}),
('snow', {'layers': 7}), ('white_carpet', {}), ('farmland', {}), ('dirt_path', {}), ('cauldron', {}),
('water_cauldron', {'level': 3}), ('hopper', {}), ('anvil', {})]:
s.put(x, 4, 4, name, **props)
if name in ('tall_grass', 'large_fern', 'sunflower'):
s.put(x, 5, 4, name, half='upper')
x += 1
x = 0
for name, props in [('iron_chain', {}), ('iron_chain', {'axis': 'x'}), ('lantern', {}), ('lantern', {'hanging': True}),
('soul_lantern', {}), ('lily_pad', {}), ('vine', {'north': True}), ('sugar_cane', {}), ('pink_petals', {'flower_amount': 4}),
('melon_stem', {'age': 5}), ('attached_pumpkin_stem', {}), ('leaf_litter', {'segment_amount': 3}),
('small_dripleaf', {}), ('pointed_dripstone', {}), ('bamboo', {}), ('brewing_stand', {})]:
s.put(x, 4, 10, name, **props)
x += 1
s.put(15, 8, 10, 'stone')
s.put(3, 7, 10, 'stone')
s.put(2, 5, 10, 'stone')
s.put(15, 4, 1, 'scaffolding')
# Fluids: sources, flowing levels, falling columns, mixed neighbours, waterlogging.
s = scene('fluids')
s.floor(2)
s.fill(0, 3, 0, 4, 3, 4, 'water')
for i, level in enumerate([1, 2, 3, 4, 5, 6, 7]):
s.put(5 + i, 3, 2, 'water', level=level)
s.put(5 + i, 3, 3, 'water', level=8 - level)
s.put(5 + i, 3, 6, 'lava', level=level)
s.put(2, 4, 2, 'water', level=8)
s.put(2, 5, 2, 'water', level=8)
s.put(13, 3, 3, 'glass')
s.put(12, 4, 3, 'oak_leaves')
s.put(4, 4, 4, 'stone_slab', type='bottom', waterlogged=True)
s.put(4, 4, 3, 'oak_stairs', waterlogged=True)
s.put(3, 4, 4, 'oak_fence', waterlogged=True)
s.put(1, 4, 1, 'ice')
s.fill(0, 3, 8, 3, 3, 11, 'lava')
s.put(1, 4, 9, 'lava', level=8)
s.put(2, 4, 10, 'stone')
s.fill(8, 3, 9, 12, 5, 13, 'water')
s.put(10, 6, 11, 'water', level=3)
s.put(9, 6, 11, 'oak_slab', type='top')
s.put(11, 6, 11, 'glass')
s.put(10, 6, 12, 'stone')
s.put(13, 4, 11, 'kelp')
s.put(14, 3, 11, 'seagrass')
s.put(15, 3, 13, 'water', level=2)
s.put(15, 4, 14, 'water', level=9)
s.put(15, 3, 15, 'stone_slab', type='top')
# Section edges with neighbours in other chunks and sections.
s = scene('edges')
for x in [0, 15]:
for y in [0, 15]:
for z in [0, 15]:
s.put(x, y, z, 'stone')
s.put(x + (-1 if x == 0 else 1), y, z, 'stone')
s.put(x, y + (-1 if y == 0 else 1), z, 'dirt')
s.put(7, 15, 7, 'water')
s.put(7, 16, 7, 'water')
s.put(8, 0, 8, 'water', level=3)
s.put(8, -1, 8, 'stone')
s.put(-1, 7, 7, 'water')
s.put(0, 7, 7, 'water', level=2)
s.put(16, 7, 7, 'oak_leaves')
s.put(15, 7, 7, 'oak_leaves')
# Every block with a model, default state, on a sparse grid.
model_blocks = sorted(name for name, default in states.defaults.items() if states.render_shape[default] == 'MODEL'
and name not in ('minecraft:air', 'minecraft:cave_air', 'minecraft:void_air'))
per_scene = 8 * 8 * 8
for chunk in range(0, len(model_blocks), per_scene):
s = scene(f'catalog_{chunk // per_scene}')
for i, name in enumerate(model_blocks[chunk:chunk + per_scene]):
s.put(i % 8 * 2, i // 64 * 2, i // 8 % 8 * 2, states.defaults[name])
# Random dense scenes over a palette, with structured and noisy light.
palette = ['stone', 'glass', 'oak_leaves', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy',
'short_grass', 'glowstone', 'oak_fence', 'snow', 'white_carpet', 'magma_block', 'soul_sand', 'ice', 'farmland', 'dirt_path']
for seed in range(8):
rng = random.Random(0x4D455348 + seed)
s = scene(f'random_{seed}', nether=seed % 4 == 3)
for _ in range(900):
name = rng.choice(palette)
ids = states.by_name['minecraft:' + name]
s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids))
if seed % 2:
s.noise = seed
s = scene('cubes_nether', nether=True)
s.floor(3, 'netherrack')
s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks')
s.fill(8, 4, 8, 10, 4, 10, 'lava')
s.put(12, 4, 12, 'glowstone')
return scenes
def quad_key(quad):
vertices = quad['vertices']
rounded = [tuple(round(v[i] * 1000) for i in range(3)) for v in vertices]
rotation = min(range(4), key=lambda r: rounded[r:] + rounded[:r])
layer = 'translucent' if quad['layer'] == 'translucent' else 'opaque'
return (quad['sprite'], layer, tuple(rounded[rotation:] + rounded[:rotation])), rotation
def channels(color):
color &= 0xFFFFFFFF
return [color >> 16 & 255, color >> 8 & 255, color & 255, color >> 24]
def light(coords):
return [coords >> 16 & 0xFFFF, coords & 0xFFFF]
def compare(scene, client, rust, states, report, limit):
blocks = {tuple(b[:3]): b[3] for b in scene['blocks']}
def describe(quad, rotation):
v = quad['vertices']
centre = [sum(p[i] for p in v) / 4 for i in range(3)]
block = quad.get('block') or [math.floor(c + 1e-4 if i != 1 else c - 1e-3) for i, c in enumerate(centre)]
state = blocks.get(tuple(block), 0)
return {'block': block, 'state': f"{states.names[state]}{states.properties[state] or ''}",
'sprite': quad['sprite'], 'kind': quad.get('kind', 'rust'),
'vertices': [list(x) for x in (v[rotation:] + v[:rotation])]}
groups = defaultdict(lambda: ([], []))
for side, quads in [(0, client), (1, rust)]:
for quad in quads:
key, rotation = quad_key(quad)
groups[key][side].append((quad, rotation))
counts = Counter()
def add(category, *examples):
counts[category] += 1
report['categories'][category] = report['categories'].get(category, 0) + 1
bucket = report['examples'].setdefault(category, [])
if len(bucket) < limit:
bucket.append({'scene': scene['name'], 'quads': list(examples)})
for key, (left, right) in groups.items():
def attributes(entry):
quad, rotation = entry
v = quad['vertices']
return [(round(x[3], 3), round(x[4], 3), channels(x[5]), light(x[6])) for x in v[rotation:] + v[:rotation]]
left.sort(key=lambda e: str(attributes(e)))
right.sort(key=lambda e: str(attributes(e)))
for a, b in zip(left, right):
report['matched_quads'] += 1
va = [x for x in attributes(a)]
ca = a[0]['vertices'][a[1]:] + a[0]['vertices'][:a[1]]
cb = b[0]['vertices'][b[1]:] + b[0]['vertices'][:b[1]]
problems = set()
for p, q in zip(ca, cb):
if any(abs(p[i] - q[i]) > POSITION_TOLERANCE for i in range(3)):
problems.add('position')
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 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]):
lp, lq = light(p[6]), light(q[6])
problems.add('light_sky' if lp[0] != lq[0] else 'light_block')
del va
if not problems:
report['identical_quads'] += 1
for problem in sorted(problems):
add(f"{problem}:{a[0].get('kind', 'model')}", describe(*a), describe(*b))
for entry in left[len(right):]:
add(f"missing:{entry[0]['kind']}", describe(*entry))
for entry in right[len(left):]:
add('extra', describe(*entry))
report['client_quads'] += len(client)
report['rust_quads'] += len(rust)
return counts
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--strict', action='store_true', help='fail when any quad or fact differs')
parser.add_argument('--examples', type=int, default=12, help='examples kept per mismatch category')
parser.add_argument('--only', help='only scenes whose name contains this text')
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
BUILD.mkdir(parents=True, exist_ok=True)
report_path = BUILD / 'report.json'
report_path.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java'
helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']]
sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers,
lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs']
for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']:
sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))]
tested = base.source_hashes(sources)
states = States(resources)
scenes = [s for s in corpus(states) if not args.only or args.only in s.name]
rows = [s.row() for s in scenes]
inputs = BUILD / 'inputs.jsonl'
inputs.write_text(''.join(json.dumps(row) + '\n' for row in rows))
def run(command, name):
with (BUILD / (name + '.log')).open('w') as log:
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
classes = BUILD / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java')
env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3')
run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_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' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture')
java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle']
run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust')
run([*java, inputs, BUILD / 'client.jsonl', resources], 'client')
run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts')
run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts')
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(),
'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0,
'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}}
client = [json.loads(line) for line in (BUILD / 'client.jsonl').read_text().splitlines()]
rust = [json.loads(line) for line in (BUILD / 'rust.jsonl').read_text().splitlines()]
for row, a, b in zip(rows, client, rust):
assert row['name'] == a['name'] == b['name']
counts = compare(row, a['quads'], b['quads'], states, report, args.examples)
report['per_scene'][row['name']] = {'client': len(a['quads']), 'rust': len(b['quads']), **counts}
client_facts = [json.loads(line) for line in (BUILD / 'client-facts.jsonl').read_text().splitlines()]
rust_facts = [json.loads(line) for line in (BUILD / 'rust-facts.jsonl').read_text().splitlines()]
fact_mismatches = Counter()
for a, b in zip(client_facts, rust_facts):
for key in a:
if key == 'offsets':
same = len(a[key]) == len(b.get(key, [])) and all(abs(x - y) < 1e-6 for p, q in zip(a[key], b[key]) for x, y in zip(p, q))
else:
same = a[key] == b.get(key)
if not same:
fact_mismatches[key] += 1
examples = report['facts'].setdefault(key, [])
if len(examples) < args.examples:
examples.append({'state': f"{states.names[a['id']]}{states.properties[a['id']]}", 'client': a[key], 'rust': b.get(key)})
report['fact_mismatches'] = dict(fact_mismatches)
report['fact_states'] = len(client_facts)
base.ensure_sources_unchanged(sources, tested)
report['sources_sha256'] = tested
lab.write_json(report_path, report)
total = report['client_quads']
print(f"Section mesh parity: {len(rows)} scenes, client {total:,} quads, Rust {report['rust_quads']:,} quads, "
f"{report['matched_quads']:,} geometry matches, {report['identical_quads']:,} identical "
f"({100.0 * report['identical_quads'] / max(total, 1):.2f}% of client quads)")
for category, count in sorted(report['categories'].items(), key=lambda kv: -kv[1]):
print(f' {category:<28} {count:,}')
print(f"Mesh facts: {len(client_facts):,} states, mismatches: {dict(fact_mismatches) or 'none'}")
print(f'Report: {report_path}')
if args.strict and (report['categories'] or fact_mismatches):
raise SystemExit(1)
if __name__ == '__main__':
main()