Merge main into agent branch

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 09:57:55 +02:00
98 changed files with 13539 additions and 1293 deletions
@@ -0,0 +1,132 @@
package dev.horizonlab.parity;
import java.lang.reflect.Field;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.*;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.RegistryOps;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
/**
* Shared set-up for the interaction/inventory parity oracles: the vanilla data
* pack loaded into registries (as the server does), an NBT registry ops, a
* stand-in ServerLevel that only answers registryAccess, and canonical text
* for item stacks and NBT so both sides print comparable lines.
*/
public final class ParityData {
public static HolderLookup.Provider lookup;
public static RegistryAccess access;
public static RegistryOps<Tag> ops;
public static ServerLevel level;
public static void init() throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
access = loaded.layers().compositeAccess();
ops = RegistryOps.create(NbtOps.INSTANCE, lookup);
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafe = unsafeField.get(null);
level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class);
Field registryAccess = Level.class.getDeclaredField("registryAccess");
registryAccess.setAccessible(true);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess);
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access);
}
/** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */
public static ItemStack stack(String snbt) throws Exception {
if (snbt.equals("-")) return ItemStack.EMPTY;
Tag tag = TagParser.parseCompoundFully(snbt);
return ItemStack.CODEC.parse(ops, tag).getOrThrow();
}
public static String canon(ItemStack stack) {
if (stack == null || stack.isEmpty()) return "-";
Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow();
return canon(tag);
}
/** Sorted-key, type-annotated text of an NBT tag. */
public static String canon(Tag tag) {
StringBuilder out = new StringBuilder();
canon(tag, out);
return out.toString();
}
private static void canon(Tag tag, StringBuilder out) {
switch (tag) {
case ByteTag t -> out.append(t.value()).append('b');
case ShortTag t -> out.append(t.value()).append('s');
case IntTag t -> out.append(t.value());
case LongTag t -> out.append(t.value()).append('L');
case FloatTag t -> out.append(t.value()).append('f');
case DoubleTag t -> out.append(t.value()).append('d');
case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"');
case ByteArrayTag t -> {
out.append("[B;");
byte[] a = t.getAsByteArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case IntArrayTag t -> {
out.append("[I;");
int[] a = t.getAsIntArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case LongArrayTag t -> {
out.append("[L;");
long[] a = t.getAsLongArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case ListTag t -> {
out.append('[');
for (int i = 0; i < t.size(); i++) {
if (i > 0) out.append(',');
canon(t.get(i), out);
}
out.append(']');
}
case CompoundTag t -> {
out.append('{');
boolean first = true;
for (String key : new TreeSet<>(t.keySet())) {
if (!first) out.append(',');
first = false;
out.append(key).append(':');
canon(t.get(key), out);
}
out.append('}');
}
default -> throw new IllegalStateException(tag.toString());
}
}
}
@@ -0,0 +1,118 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.core.component.BlockTransformer;
/**
* Original oracle: the data-driven axe/hoe/shovel BlockTransformer entries.
* "dump" lists every block state; a case line "transformer TAB face TAB
* clicked TAB above" (states as "name|prop=value,...") prints the first
* transform that yields a state and its settings, as BlockTransformer.transformBlock
* would pick it.
*/
public final class VanillaBlockTransformerOracle {
static String describe(BlockState state) {
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
List<Property<?>> props = new ArrayList<>(state.getProperties());
props.sort(Comparator.comparing(Property::getName));
boolean first = true;
for (Property<?> p : props) {
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
first = false;
}
return out.toString();
}
@SuppressWarnings({"unchecked", "rawtypes"})
static String name(BlockState state, Property p) {
return p.getName(state.getValue(p));
}
@SuppressWarnings({"unchecked", "rawtypes"})
static BlockState parse(String text) {
String[] parts = text.split("\\|", -1);
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
BlockState state = block.defaultBlockState();
if (!parts[1].isEmpty()) {
for (String kv : parts[1].split(",")) {
String[] pair = kv.split("=");
Property p = block.getStateDefinition().getProperty(pair[0]);
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
}
}
return state;
}
static LevelAccessor level(BlockState clicked, BlockState above) {
return (LevelAccessor) Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(), new Class<?>[]{LevelAccessor.class}, (proxy, method, args) -> {
if (method.getName().equals("getBlockState")) {
BlockPos pos = (BlockPos) args[0];
return pos.getY() == 0 ? clicked : pos.getY() == 1 && pos.getX() == 0 && pos.getZ() == 0 ? above : net.minecraft.world.level.block.Blocks.STONE.defaultBlockState();
}
throw new UnsupportedOperationException(method.getName());
});
}
public static void main(String[] args) throws Exception {
ParityData.init();
if (args[0].equals("dump")) {
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
for (Block block : BuiltInRegistries.BLOCK) {
for (BlockState state : block.getStateDefinition().getPossibleStates()) out.println(describe(state));
}
}
return;
}
var registry = ParityData.access.lookupOrThrow(Registries.BLOCK_TRANSFORMER);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
String[] f = line.split("\t", -1);
try {
if (f[0].equals("honeycomb")) {
out.println(net.minecraft.world.item.HoneycombItem.getWaxed(parse(f[2])).map(VanillaBlockTransformerOracle::describe).orElse("none"));
continue;
}
var transformer = registry.getOrThrow(ResourceKey.create(Registries.BLOCK_TRANSFORMER, Identifier.parse(f[0]))).value();
Direction face = Direction.byName(f[1]);
BlockState clicked = parse(f[2]);
LevelAccessor level = level(clicked, parse(f[3]));
String result = "none";
int index = 0;
for (var data : transformer.transforms()) {
if (!data.disallowedFaces().contains(face)) {
BlockState state = data.blockStateProvider().value().getOptionalState(level, RandomSource.create(0L), BlockPos.ZERO);
if (state != null) {
result = index + "\t" + describe(state) + "\t" + BuiltInRegistries.SOUND_EVENT.getKey(data.sound().value())
+ "\t" + data.particle().name().toLowerCase() + "\t"
+ data.loot().map(k -> k.identifier().toString()).orElse("-") + "\t" + data.dropStrategy().name().toLowerCase()
+ "\t" + data.updateFromNeighbors() + "\t" + data.transformType().name().toLowerCase() + "\t" + data.consumeOnUse()
+ "\t" + data.itemDamagePerUse();
break;
}
}
index++;
}
out.println(result);
} catch (Throwable e) {
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
}
}
}
}
}
@@ -0,0 +1,168 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntityEquipment;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.AbstractCauldronBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
/**
* Original oracle: a cauldron's useItemOn (CauldronInteractions) with a
* recording stand-in level and player. Each case line is JSON: cauldron state
* ("name|prop=value"), the held stack, creative, whether water is above. The
* output line lists the result, block writes, sounds, the final inventory and
* drops.
*/
public final class VanillaCauldronOracle {
static Object unsafe;
static java.lang.reflect.Method allocate;
static final List<String> events = new ArrayList<>();
static boolean underWater;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) {
try {
return (T) allocate.invoke(unsafe, type);
} catch (Exception e) {
throw new AssertionError(e);
}
}
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
f.set(target, value);
}
static String describe(BlockState state) {
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
List<Property<?>> props = new ArrayList<>(state.getProperties());
props.sort(Comparator.comparing(Property::getName));
boolean first = true;
for (Property<?> p : props) {
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
first = false;
}
return out.toString();
}
@SuppressWarnings({"unchecked", "rawtypes"})
static String name(BlockState state, Property p) {
return p.getName(state.getValue(p));
}
@SuppressWarnings({"unchecked", "rawtypes"})
static BlockState parse(String text) {
String[] parts = text.split("\\|", -1);
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
BlockState state = block.defaultBlockState();
if (!parts[1].isEmpty()) {
for (String kv : parts[1].split(",")) {
String[] pair = kv.split("=");
Property p = block.getStateDefinition().getProperty(pair[0]);
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
}
}
return state;
}
static final class World extends ServerLevel {
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public boolean isClientSide() { return false; }
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; }
@Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); }
@Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) {
events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s));
}
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
}
static final class FakePlayer extends ServerPlayer {
boolean creative;
Inventory inv;
FakePlayer() {
super(null, null, null, null);
}
@Override public Inventory getInventory() { return inv; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); }
@Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); }
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack));
return null;
}
}
public static void main(String[] args) throws Exception {
ParityData.init();
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
try {
events.clear();
underWater = f.get("under_water").getAsBoolean();
var world = make(World.class);
var player = make(FakePlayer.class);
player.creative = f.get("creative").getAsBoolean();
player.inv = new Inventory(player, new EntityEquipment());
for (var other : f.getAsJsonArray("inventory")) {
var pair = other.getAsJsonArray();
player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString()));
}
ItemStack held = ParityData.stack(f.get("held").getAsString());
player.inv.setItem(0, held);
BlockState state = parse(f.get("state").getAsString());
var cauldron = (AbstractCauldronBlock) state.getBlock();
var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class,
net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class);
use.setAccessible(true);
InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null);
String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume"
: result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString();
StringBuilder inventory = new StringBuilder();
for (int i = 0; i < 41; i++) {
ItemStack s = player.inv.getItem(i);
if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' ');
}
out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim());
} catch (Throwable e) {
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace();
}
}
}
}
}
@@ -0,0 +1,377 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.FramerateLimitTracker;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.platform.Window;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.*;
import net.minecraft.client.*;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.tutorial.Tutorial;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerTickRateManager;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.entity.player.Input;
import net.minecraft.world.entity.player.Inventory;
/**
* Drives the real DeltaTracker.Timer, ServerTickRateManager, Window.calculateScale,
* FramerateLimitTracker, MouseHandler (move, scroll, turnPlayer), Entity.turn and
* ToggleKeyMapping with the input sequences in a JSON-lines file and prints
* every observable bit-exactly. Hosts are uninitialised shells (Unsafe) that
* carry only the fields the exercised code reads.
*/
public final class VanillaGameLoopOracle {
static Object unsafe;
static Method allocate;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) throws Exception {
return (T) allocate.invoke(unsafe, type);
}
static Field field(Class<?> type, String name) throws Exception {
Field f = type.getDeclaredField(name);
f.setAccessible(true);
return f;
}
static float f(JsonElement v) {
return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16));
}
static double d(JsonElement v) {
return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16));
}
static String fb(float v) {
return String.format("%08x", Float.floatToRawIntBits(v) == 0x7fc00000 || Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v));
}
static String db(double v) {
return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v));
}
// ---- stubs for the server tick manager -------------------------------------------------
static final List<String> reports = new ArrayList<>();
static final class StubStack extends CommandSourceStack {
StubStack() {
super(null, null, null, null, null, (Component) null, null);
}
@Override
public void sendSuccess(Supplier<Component> message, boolean broadcast) {
var contents = (TranslatableContents) message.get().getContents();
reports.add(contents.getArgs()[0] + " " + contents.getArgs()[1]);
}
}
static final class StubPlayers extends PlayerList {
StubPlayers() {
super(null, null, null, (net.minecraft.server.notifications.NotificationService) null);
}
@Override
public void broadcastAll(net.minecraft.network.protocol.Packet<?> packet) {
}
}
static StubStack stubStack;
static StubPlayers stubPlayers;
static final class StubServer extends MinecraftServer {
StubServer() {
super(null, null, null, null, null, null, null, null, null, false, null);
}
@Override public PlayerList getPlayerList() { return stubPlayers; }
@Override public CommandSourceStack createCommandSourceStack() { return stubStack; }
@Override public void onTickRateChanged() { }
@Override protected boolean initServer() { return false; }
@Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; }
@Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; }
@Override public boolean shouldRconBroadcast() { return false; }
@Override protected net.minecraft.util.debugchart.SampleLogger getTickTimeLogger() { return null; }
@Override public boolean isTickTimeLoggingEnabled() { return false; }
@Override public net.minecraft.SystemReport fillServerSystemReport(net.minecraft.SystemReport r) { return r; }
@Override public boolean isDedicatedServer() { return false; }
@Override public int getRateLimitPacketsPerSecond() { return 0; }
@Override public int getCommandSpamThresholdSeconds() { return 0; }
@Override public int getChatSpamThresholdSeconds() { return 0; }
@Override public boolean useNativeTransport() { return false; }
@Override public boolean isPublished() { return false; }
@Override public int getMaxPlayers() { return 0; }
@Override public boolean shouldInformAdmins() { return false; }
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
}
static final class StubPlayer extends LocalPlayer {
boolean scoping;
StubPlayer() {
super(null, null, null, null, null, Input.EMPTY, false, null, null);
}
@Override public boolean isScoping() { return scoping; }
@Override public boolean isSpectator() { return false; }
}
static Minecraft shell;
static Options options;
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
var u = Class.forName("sun.misc.Unsafe");
unsafe = field(u, "theUnsafe").get(null);
allocate = u.getMethod("allocateInstance", Class.class);
shell = make(Minecraft.class);
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
field(Minecraft.class, "instance").set(null, shell);
options = new Options(shell, Files.createTempDirectory("opts").toFile());
stubStack = make(StubStack.class);
stubPlayers = make(StubPlayers.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (var line : (Iterable<String>) lines::iterator) {
var c = JsonParser.parseString(line).getAsJsonObject();
switch (c.get("t").getAsString()) {
case "timer" -> timer(c, out);
case "rate" -> rate(c, out);
case "scale" -> scale(c, out);
case "limit" -> limit(c, out);
case "mouse" -> mouse(c, out);
case "scroll" -> scroll(c, out);
case "key" -> key(c, out);
default -> throw new IllegalArgumentException(line);
}
}
}
System.exit(0);
}
static void timer(JsonObject c, PrintWriter out) {
float[] mspt = {0};
var timer = new DeltaTracker.Timer(f(c.get("tps")), c.get("start").getAsLong(),
d -> mspt[0] == 0 ? d : Math.max(d, mspt[0]));
out.println("timer");
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
String name = op.get(0).getAsString();
String result = "";
switch (name) {
case "adv" -> {
mspt[0] = op.get(2).isJsonNull() ? 0 : f(op.get(2));
result = " " + timer.advanceGameTime(op.get(1).getAsLong());
}
case "real" -> timer.advanceRealTime(op.get(1).getAsLong());
case "pause" -> timer.updatePauseState(op.get(1).getAsBoolean());
case "frozen" -> timer.updateFrozenState(op.get(1).getAsBoolean());
default -> throw new IllegalArgumentException(name);
}
out.println(name + result + " " + fb(timer.getGameTimeDeltaTicks()) + " " + fb(timer.getGameTimeDeltaPartialTick(false))
+ " " + fb(timer.getGameTimeDeltaPartialTick(true)) + " " + fb(timer.getRealtimeDeltaTicks()));
}
}
static void rate(JsonObject c, PrintWriter out) throws Exception {
var m = make(ServerTickRateManager.class);
field(ServerTickRateManager.class, "server").set(m, make(StubServer.class));
// Field initialisers do not run on a shell.
field(net.minecraft.world.TickRateManager.class, "tickrate").setFloat(m, 20.0F);
field(net.minecraft.world.TickRateManager.class, "nanosecondsPerTick").setLong(m, 50_000_000L);
field(net.minecraft.world.TickRateManager.class, "runGameElements").setBoolean(m, true);
var startTime = field(ServerTickRateManager.class, "sprintTickStartTime");
var spend = field(ServerTickRateManager.class, "sprintTimeSpend");
out.println("rate");
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
String name = op.get(0).getAsString();
reports.clear();
String result = "";
switch (name) {
case "rate" -> m.setTickRate(f(op.get(1)));
case "freeze" -> m.setFrozen(op.get(1).getAsBoolean());
case "step" -> result = " " + m.stepGameIfPaused(op.get(1).getAsInt());
case "stopstep" -> result = " " + m.stopStepping();
case "sprint" -> result = " " + m.requestGameToSprint(op.get(1).getAsInt());
case "check" -> {
result = " " + m.checkShouldSprintThisTick();
if (m.runsNormally() && result.equals(" true")) {
startTime.setLong(m, op.get(1).getAsLong());
} else if (m.runsNormally() && reports.isEmpty()) {
// unreachable: the else branch always reports
}
}
case "end" -> {
long before = spend.getLong(m);
m.endTickWork();
spend.setLong(m, before + (op.get(1).getAsLong() - startTime.getLong(m)));
}
case "stopsprint" -> result = " " + m.stopSprinting();
case "tick" -> m.tick();
default -> throw new IllegalArgumentException(name);
}
out.println(name + result + " | " + fb(m.tickrate()) + " " + m.nanosecondsPerTick() + " " + fb(m.millisecondsPerTick())
+ " " + m.runsNormally() + " " + m.isSteppingForward() + " " + m.frozenTicksToRun() + " " + m.isFrozen()
+ " " + m.isSprinting() + (reports.isEmpty() ? "" : " report " + reports.get(0)));
}
}
static Window window(int w, int h, int sw, int sh) throws Exception {
Window window = make(Window.class);
field(Window.class, "framebufferWidth").setInt(window, w);
field(Window.class, "framebufferHeight").setInt(window, h);
field(Window.class, "width").setInt(window, sw);
field(Window.class, "height").setInt(window, sh);
return window;
}
static void scale(JsonObject c, PrintWriter out) throws Exception {
Window window = window(c.get("w").getAsInt(), c.get("h").getAsInt(), c.get("sw").getAsInt(), c.get("sh").getAsInt());
int scale = window.calculateScale(c.get("max").getAsInt(), c.get("uni").getAsBoolean());
window.setGuiScale(scale);
out.println("scale " + scale + " " + window.getGuiScaledWidth() + " " + window.getGuiScaledHeight() + " "
+ db(MouseHandler.getScaledXPos(window, d(c.get("x")))) + " " + db(MouseHandler.getScaledYPos(window, d(c.get("y")))));
}
static void limit(JsonObject c, PrintWriter out) throws Exception {
Window window = window(1, 1, 1, 1);
field(Window.class, "iconified").setBoolean(window, c.get("iconified").getAsBoolean());
field(Window.class, "focused").setBoolean(window, c.get("focused").getAsBoolean());
Minecraft mc = make(Minecraft.class);
field(Minecraft.class, "window").set(mc, window);
Gui gui = make(Gui.class);
field(Gui.class, "screen").set(gui, c.get("screen").getAsBoolean() ? make(net.minecraft.client.gui.screens.PauseScreen.class) : null);
field(Gui.class, "overlay").set(gui, c.get("overlay").getAsBoolean() ? make(net.minecraft.client.gui.screens.LoadingOverlay.class) : null);
field(Minecraft.class, "gui").set(mc, gui);
field(Minecraft.class, "level").set(mc, c.get("level").getAsBoolean() ? make(net.minecraft.client.multiplayer.ClientLevel.class) : null);
options.framerateLimit().set(c.get("opt").getAsInt());
options.inactivityFpsLimit().set(c.get("afk").getAsBoolean() ? InactivityFpsLimit.AFK : InactivityFpsLimit.MINIMIZED);
var tracker = new FramerateLimitTracker(options, mc);
field(FramerateLimitTracker.class, "latestInputTime").setLong(tracker, net.minecraft.util.Util.getMillis() - c.get("ago").getAsLong());
out.println("limit " + tracker.getThrottleReason() + " " + tracker.getFramerateLimit() + " " + tracker.isHeavilyThrottled());
}
static MouseHandler handler(Minecraft mc) throws Exception {
MouseHandler h = new MouseHandler(mc);
return h;
}
static void mouse(JsonObject c, PrintWriter out) throws Exception {
Window window = window(1, 1, 1, 1);
field(Window.class, "handle").setLong(window, 1L);
field(Window.class, "focused").setBoolean(window, c.get("active").getAsBoolean());
Minecraft mc = make(Minecraft.class);
field(Minecraft.class, "window").set(mc, window);
field(Minecraft.class, "options").set(mc, options);
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
field(Minecraft.class, "tutorial").set(mc, make(Tutorial.class));
StubPlayer player = make(StubPlayer.class);
player.scoping = c.get("scoping").getAsBoolean();
mc.player = player;
options.sensitivity().set(d(c.get("sens")));
options.smoothCamera = c.get("smooth").getAsBoolean();
options.invertMouseX().set(c.get("ix").getAsBoolean());
options.invertMouseY().set(c.get("iy").getAsBoolean());
MouseHandler h = handler(mc);
field(MouseHandler.class, "mouseGrabbed").setBoolean(h, c.get("grabbed").getAsBoolean());
var turn = MouseHandler.class.getDeclaredMethod("turnPlayer", double.class);
turn.setAccessible(true);
var dx = field(MouseHandler.class, "accumulatedDX");
var dy = field(MouseHandler.class, "accumulatedDY");
double last = Double.MIN_VALUE;
out.println("mouse");
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
switch (op.get(0).getAsString()) {
case "move" -> h.onMove(1L, d(op.get(1)), d(op.get(2)), d(op.get(3)), d(op.get(4)));
case "ignore" -> h.setIgnoreFirstMove();
case "frame" -> {
double time = d(op.get(1));
double mousea = time - last;
last = time;
// MouseHandler.handleAccumulatedMovement without the SDL clock and screens.
if (mc.isWindowActive() && h.isMouseGrabbed() && mc.player != null) {
turn.invoke(h, mousea);
}
dx.setDouble(h, 0.0);
dy.setDouble(h, 0.0);
out.println("frame " + fb(player.getXRot()) + " " + fb(player.getYRot()) + " "
+ fb(player.xRotO) + " " + fb(player.yRotO));
}
default -> throw new IllegalArgumentException(op.toString());
}
}
}
static void scroll(JsonObject c, PrintWriter out) throws Exception {
Window window = window(1, 1, 1, 1);
field(Window.class, "handle").setLong(window, 1L);
Minecraft mc = make(Minecraft.class);
field(Minecraft.class, "window").set(mc, window);
field(Minecraft.class, "options").set(mc, options);
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
field(Minecraft.class, "gui").set(mc, make(Gui.class));
StubPlayer player = make(StubPlayer.class);
Inventory inventory = make(Inventory.class);
inventory.setSelectedSlot(c.get("slot").getAsInt());
field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory);
mc.player = player;
options.discreteMouseScroll().set(c.get("discrete").getAsBoolean());
options.mouseWheelSensitivity().set(d(c.get("sens")));
MouseHandler h = handler(mc);
out.println("scroll");
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
h.onScroll(1L, d(op.get(0)), d(op.get(1)));
out.println(inventory.getSelectedSlot());
}
}
static int keys = 0;
static void key(JsonObject c, PrintWriter out) throws Exception {
AtomicBoolean option = new AtomicBoolean();
int value = 10000 + keys++;
KeyMapping mapping = c.get("toggle").getAsBoolean()
? new ToggleKeyMapping("key.test" + value, c.get("keyboard").getAsBoolean() ? InputConstants.Type.KEYBOARD : InputConstants.Type.MOUSE,
value, KeyMapping.Category.MISC, option::get, c.get("restore").getAsBoolean())
: new KeyMapping("key.test" + value, InputConstants.Type.KEYBOARD, value, KeyMapping.Category.MISC);
var release = KeyMapping.class.getDeclaredMethod("release");
release.setAccessible(true);
var key = c.get("toggle").getAsBoolean() && !c.get("keyboard").getAsBoolean()
? InputConstants.Type.MOUSE.getOrCreate(value) : InputConstants.Type.KEYBOARD.getOrCreate(value);
out.println("key");
for (var e : c.getAsJsonArray("ops")) {
var op = e.getAsJsonArray();
String result = "";
switch (op.get(0).getAsString()) {
case "option" -> option.set(op.get(1).getAsBoolean());
case "down" -> mapping.setDown(op.get(1).getAsBoolean());
case "release" -> release.invoke(mapping);
case "restore" -> result = mapping instanceof ToggleKeyMapping t ? " " + t.shouldRestoreStateOnScreenClosed() : " false";
case "click" -> KeyMapping.click(key);
case "consume" -> result = " " + mapping.consumeClick();
case "ingame" -> {
var m = KeyMapping.class.getDeclaredMethod("shouldSetOnIngameFocus");
m.setAccessible(true);
result = " " + m.invoke(mapping);
}
default -> throw new IllegalArgumentException(op.toString());
}
out.println(op.get(0).getAsString() + result + " " + mapping.isDown());
}
}
}
@@ -0,0 +1,205 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.Container;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.EntityEquipment;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeManager;
/**
* Original oracle: AbstractContainerMenu.clicked over vanilla's real menu
* classes. A stand-in player (inventory, drops recorded) and a stand-in server
* level (real RecipeManager, no networking) run each case's clicks; after
* every click the slots, carried stack, data slots, drops and player state
* are printed as canonical NBT.
*/
public final class VanillaMenuOracle {
static Object unsafe;
static java.lang.reflect.Method allocate;
static RecipeManager recipes;
static final List<String> drops = new ArrayList<>();
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) {
try {
return (T) allocate.invoke(unsafe, type);
} catch (Exception e) {
throw new AssertionError(e);
}
}
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
f.set(target, value);
}
static final class Server extends net.minecraft.server.dedicated.DedicatedServer {
Server() {
super(null, null, null, null, null, null, null, null, null, null);
}
@Override public RecipeManager getRecipeManager() { return recipes; }
}
static final class Connection extends ServerGamePacketListenerImpl {
Connection() {
super(null, null, null, null);
}
@Override public void send(net.minecraft.network.protocol.Packet<?> packet) { }
}
static final class World extends ServerLevel {
Server server;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@Override public RecipeManager recipeAccess() { return recipes; }
@Override public boolean isClientSide() { return false; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
@Override public net.minecraft.world.level.gamerules.GameRules getGameRules() { return new net.minecraft.world.level.gamerules.GameRules(FeatureFlags.DEFAULT_FLAGS); }
@Override public void levelEvent(net.minecraft.world.entity.Entity p, int type, BlockPos pos, int data) { }
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { }
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; }
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
}
static final class FakePlayer extends ServerPlayer {
World world;
boolean creative;
Inventory inv;
FakePlayer() {
super(null, null, null, null);
}
@Override public Inventory getInventory() { return inv; }
@Override public ServerLevel level() { return world; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public boolean isSpectator() { return false; }
@Override public EntityType<?> getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public boolean canUseSlot(EquipmentSlot slot) { return true; }
@Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { }
@Override public boolean hasDisconnected() { return false; }
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
if (!stack.isEmpty()) drops.add(ParityData.canon(stack));
return null;
}
@Override public void triggerRecipeCrafted(net.minecraft.world.item.crafting.RecipeHolder<?> recipe, java.util.List<ItemStack> items) { }
@Override public int awardRecipes(java.util.Collection<net.minecraft.world.item.crafting.RecipeHolder<?>> recipes) { return 0; }
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
@Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); }
@Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); }
}
static AbstractContainerMenu menu(String kind, FakePlayer player, Inventory inv) {
var access = ContainerLevelAccess.create(player.world, BlockPos.ZERO);
if (kind.startsWith("chest")) {
int rows = Integer.parseInt(kind.substring(5));
MenuType<?> type = new MenuType[]{MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6}[rows - 1];
return new ChestMenu(type, 0, inv, new SimpleContainer(9 * rows), rows);
}
return switch (kind) {
case "inventory" -> new InventoryMenu(inv, true, player);
case "crafting" -> new CraftingMenu(0, inv, access);
case "hopper" -> new HopperMenu(0, inv);
case "dispenser" -> new DispenserMenu(0, inv);
case "shulker" -> new ShulkerBoxMenu(0, inv);
case "furnace" -> new FurnaceMenu(0, inv);
case "blast_furnace" -> new BlastFurnaceMenu(0, inv);
case "smoker" -> new SmokerMenu(0, inv);
case "brewing" -> new BrewingStandMenu(0, inv);
case "crafter" -> new CrafterMenu(0, inv);
default -> throw new IllegalArgumentException(kind);
};
}
static String state(AbstractContainerMenu menu, Inventory inv) throws Exception {
StringBuilder out = new StringBuilder();
for (int i = 0; i < menu.slots.size(); i++) {
out.append(i > 0 ? " " : "").append(ParityData.canon(menu.getSlot(i).getItem()));
}
out.append(" | ").append(ParityData.canon(menu.getCarried()));
Field dataSlots = AbstractContainerMenu.class.getDeclaredField("dataSlots");
dataSlots.setAccessible(true);
List<DataSlot> data = (List<DataSlot>) dataSlots.get(menu);
out.append(" |");
for (DataSlot d : data) out.append(' ').append(d.get());
out.append(" | ").append(String.join(";", drops));
return out.toString();
}
public static void main(String[] args) throws Exception {
ParityData.init();
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
try {
drops.clear();
var world = make(World.class);
world.server = make(Server.class);
var player = make(FakePlayer.class);
player.world = world;
player.creative = f.get("creative").getAsBoolean();
set(player, ServerPlayer.class, "connection", make(Connection.class));
var inv = new Inventory(player, new EntityEquipment());
player.inv = inv;
AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv);
set(player, Player.class, "containerMenu", menu);
if (menu instanceof InventoryMenu im) set(player, Player.class, "inventoryMenu", im);
var slotsJson = f.getAsJsonArray("slots");
for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString()));
menu.setCarried(ParityData.stack(f.get("carried").getAsString()));
var dataJson = f.getAsJsonArray("data");
for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt());
drops.clear();
out.println("init " + state(menu, inv));
for (var opJson : f.getAsJsonArray("ops")) {
var op = opJson.getAsJsonArray();
int slot = op.get(0).getAsInt();
int button = op.get(1).getAsInt();
var input = ContainerInput.valueOf(op.get(2).getAsString());
try {
menu.clicked(slot, button, input, player);
} catch (RuntimeException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
out.println("error " + cause.getClass().getSimpleName());
if (System.getenv("MENU_TRACE") != null) cause.printStackTrace();
continue;
}
out.println(state(menu, inv));
}
out.println("end");
} catch (Throwable e) {
out.println("error-case " + e.getClass().getSimpleName());
if (System.getenv("MENU_TRACE") != null) e.printStackTrace();
}
}
}
}
}
@@ -0,0 +1,63 @@
package dev.horizonlab.parity;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.*;
import net.minecraft.util.datafix.DataFixers;
/**
* Loads each options.txt case through the real Options.load and writes it back
* with Options.save, then dumps the key mapping table (order, defaults,
* categories). The Minecraft instance is an uninitialised shell that only
* supplies the data fixer.
*/
public final class VanillaOptionsOracle {
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
var u = Class.forName("sun.misc.Unsafe");
var uf = u.getDeclaredField("theUnsafe");
uf.setAccessible(true);
Object unsafe = uf.get(null);
var allocate = u.getMethod("allocateInstance", Class.class);
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
Field fixer = Minecraft.class.getDeclaredField("fixerUpper");
fixer.setAccessible(true);
fixer.set(shell, DataFixers.getDataFixer());
Field instance = Minecraft.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, shell);
Path cases = Path.of(args[0]);
Path work = Files.createTempDirectory("opts");
List<Path> files = new ArrayList<>();
try (var s = Files.list(cases)) {
s.sorted().forEach(files::add);
}
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
boolean first = true;
for (Path file : files) {
Path target = work.resolve("options.txt");
Files.deleteIfExists(target);
if (!file.getFileName().toString().equals("absent.txt")) {
Files.copy(file, target);
}
Options options = new Options(shell, work.toFile());
options.save();
out.print("== " + file.getFileName() + "\n");
out.print(Files.readString(target, StandardCharsets.UTF_8));
if (first) {
first = false;
out.print("== keys\n");
for (KeyMapping k : options.keyMappings) {
out.print(k.getName() + " " + k.getDefaultKey().getName() + " " + k.getCategory().id().getPath() + " "
+ (k instanceof ToggleKeyMapping) + "\n");
}
}
}
}
System.exit(0);
}
}
@@ -0,0 +1,119 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
import net.minecraft.client.*;
import net.minecraft.util.datafix.DataFixers;
/**
* Dumps Options.processOptions as a table: key, kind and default in processing
* order. Used to (re)generate the Rust options table; the differential harness
* then proves the Rust port agrees on loading and saving.
*/
public final class VanillaOptionsTableExporter {
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
var u = Class.forName("sun.misc.Unsafe");
var uf = u.getDeclaredField("theUnsafe");
uf.setAccessible(true);
Object unsafe = uf.get(null);
var allocate = u.getMethod("allocateInstance", Class.class);
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
Field instance = Minecraft.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, shell);
Path work = Files.createTempDirectory("opts");
Options options = new Options(shell, work.toFile());
Method process = Options.class.getDeclaredMethod("processOptions", Class.forName("net.minecraft.client.Options$FieldAccess"));
process.setAccessible(true);
Field valuesField = OptionInstance.class.getDeclaredField("values");
valuesField.setAccessible(true);
Gson gson = new Gson();
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) {
Class<?> fa = Class.forName("net.minecraft.client.Options$FieldAccess");
Object access = Proxy.newProxyInstance(fa.getClassLoader(), new Class<?>[]{fa}, (proxy, method, a) -> {
String name = (String) a[0];
Class<?> rt = method.getReturnType();
if (a.length == 2 && a[1] instanceof OptionInstance<?> oi) {
Object vs = valuesField.get(oi);
var encoded = ((OptionInstance<Object>) oi).codec().encodeStart(JsonOps.INSTANCE, oi.get()).result().orElse(null);
if (vs instanceof OptionInstance.Enum<?> en) {
StringBuilder sb = new StringBuilder();
for (Object v : en.values()) {
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
}
out.println("enum " + name + " " + sb);
}
if (vs instanceof OptionInstance.SliderableEnum<?> en) {
StringBuilder sb = new StringBuilder();
for (Object v : en.values()) {
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
}
out.println("enum " + name + " " + sb);
}
out.println("option " + name + " " + vs.getClass().getSimpleName() + " " + describe(vs) + " => " + gson.toJson(encoded));
return null;
}
if (a.length == 2) {
out.println("plain " + name + " " + rt.getSimpleName() + " => " + a[1]);
return a[1];
}
if (a.length == 4) {
Object conv = ((Function<Object, String>) a[3]).apply(a[1]);
out.println("custom " + name + " => " + conv);
return a[1];
}
return null;
});
process.invoke(options, access);
}
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
Field map = com.mojang.blaze3d.platform.InputConstants.Type.class.getDeclaredField("map");
map.setAccessible(true);
for (var type : com.mojang.blaze3d.platform.InputConstants.Type.values()) {
var m = (it.unimi.dsi.fastutil.ints.Int2ObjectMap<com.mojang.blaze3d.platform.InputConstants.Key>) map.get(type);
var entries = new TreeMap<Integer, String>();
for (var e : m.int2ObjectEntrySet()) {
entries.put(e.getIntKey(), e.getValue().getName());
}
for (var e : entries.entrySet()) {
out.println(type.name().toLowerCase() + " " + e.getKey() + " " + e.getValue());
}
}
}
System.exit(0);
}
static String describe(Object vs) throws Exception {
if (vs instanceof Record r) {
StringBuilder sb = new StringBuilder("{");
for (var c : r.getClass().getRecordComponents()) {
Object v = c.getAccessor().invoke(r);
String s = String.valueOf(v);
if (v instanceof List<?> l) {
s = l.toString();
} else if (v != null && s.contains("$$Lambda")) {
s = "<fn>";
}
if (c.getName().equals("codec") || c.getName().equals("valueSetter") || c.getName().equals("altCondition")
|| c.getName().equals("validateValue") || c.getName().equals("maxSupplier") || c.getName().equals("values") && !(v instanceof List)) {
if (c.getName().equals("maxSupplier")) {
s = "<supplier " + ((java.util.function.IntSupplier) v).getAsInt() + ">";
} else if (!c.getName().equals("values")) {
s = "<fn>";
}
}
sb.append(c.getName()).append('=').append(s).append(' ');
}
return sb.append('}').toString();
}
return vs.toString();
}
}
@@ -0,0 +1,103 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.file.*;
import java.util.*;
import java.util.stream.LongStream;
import net.minecraft.core.IdMap;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.PalettedContainerRO;
import net.minecraft.world.level.chunk.Strategy;
/** Runs the real PalettedContainer (single-value, linear, hash-map and global palettes, resize,
* network write/read, pack/unpack) over scripted edits and records hashes of everything
* observable: set results, the serialized container after every few edits, the saved form and
* the containers read back from both. */
public final class VanillaPalettedContainerOracle {
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
/** The palettes compare entries by identity, as registry objects allow: intern the boxes. */
private static final Map<Integer, Integer> INTERNED = new HashMap<>();
private static Integer intern(int value) { return INTERNED.computeIfAbsent(value, v -> new Integer(v)); }
private static final class Ids implements IdMap<Integer> {
final int size;
Ids(int size) { this.size = size; }
public int getId(Integer value) { return value < size ? value : -1; }
public Integer byId(int id) { return id >= 0 && id < size ? intern(id) : null; }
public int size() { return size; }
public Iterator<Integer> iterator() { return java.util.stream.IntStream.range(0, size).boxed().iterator(); }
}
private static long fnv(long h, int b) { return (h ^ (b & 0xFF)) * 0x100000001b3L; }
private static final long BASIS = 0xcbf29ce484222325L;
private static long hashBytes(byte[] bytes) {
long h = BASIS;
for (byte b : bytes) h = fnv(h, b);
return h;
}
private static long hashValues(PalettedContainer<Integer> c, int bits) {
long h = BASIS;
int n = 1 << (3 * bits);
for (int i = 0; i < n; i++) {
int v = c.get(i & (n - 1) & ((1 << bits) - 1), i >> (2 * bits), (i >> bits) & ((1 << bits) - 1));
for (int k = 0; k < 4; k++) h = fnv(h, v >> (8 * k));
}
return h;
}
private static byte[] write(PalettedContainer<Integer> c) {
var buffer = new FriendlyByteBuf(Unpooled.buffer());
c.write(buffer);
byte[] bytes = new byte[buffer.readableBytes()];
buffer.readBytes(bytes);
return bytes;
}
private static String wire(PalettedContainer<Integer> c) {
byte[] bytes = write(c);
return bytes.length + ":" + hashBytes(bytes);
}
/** Input line: name kind initial every i v i v ...; output: one line of fields. */
private static String scenario(String line) {
var t = line.trim().split(" ");
boolean blocks = t[1].equals("blocks");
int bits = blocks ? 4 : 2;
Strategy<Integer> strategy = blocks ? Strategy.createForBlockStates(new Ids(35723)) : Strategy.createForBiomes(new Ids(67));
var c = new PalettedContainer<>(intern(Integer.parseInt(t[2])), strategy);
int every = Integer.parseInt(t[3]);
var checkpoints = new StringJoiner(",");
long oldsHash = BASIS;
int n = 0, mask = (1 << bits) - 1;
for (int k = 4; k + 1 < t.length; k += 2) {
int i = Integer.parseInt(t[k]);
int old = c.getAndSetUnchecked(i & mask, i >> (2 * bits), (i >> bits) & mask, intern(Integer.parseInt(t[k + 1])));
for (int j = 0; j < 4; j++) oldsHash = fnv(oldsHash, old >> (8 * j));
if (++n % every == 0) checkpoints.add(wire(c));
}
var out = new StringJoiner(" ");
out.add(t[0]).add(Long.toString(oldsHash)).add("cp=" + checkpoints).add("bits=" + c.bitsPerEntry());
out.add("final=" + wire(c)).add("values=" + hashValues(c, bits));
var read = new PalettedContainer<>(intern(0), strategy);
read.read(new FriendlyByteBuf(Unpooled.wrappedBuffer(write(c))));
out.add("read=" + hashValues(read, bits) + "/" + wire(read));
var packed = c.pack(strategy);
long[] storage = packed.storage().map(LongStream::toArray).orElse(null);
long storageHash = BASIS;
if (storage != null) for (long word : storage) for (int j = 0; j < 8; j++) storageHash = fnv(storageHash, (int) (word >> (8 * j)));
var palette = new StringJoiner(",");
for (int v : packed.paletteEntries()) palette.add(Integer.toString(v));
out.add("packed=" + packed.bitsPerEntry() + "/" + storageHash + "/" + palette);
var loaded = PalettedContainer.unpack(strategy, new PalettedContainerRO.PackedData<>(packed.paletteEntries(),
Optional.ofNullable(storage).map(LongStream::of), -1)).getOrThrow();
out.add("loaded=" + hashValues(loaded, bits) + "/" + wire(loaded));
return out.toString();
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
try (var input = Files.newBufferedReader(Path.of(args[0])); var output = Files.newBufferedWriter(Path.of(args[1]))) {
for (String line; (line = input.readLine()) != null; ) {
output.write(scenario(line));
output.newLine();
}
}
}
}
@@ -0,0 +1,140 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
/**
* Original oracle: vanilla's RecipeManager over the data pack's recipes.
* Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty):
* craft N cells..., cook TYPE stack, stonecut stack, smith template base addition.
* "dump" prints every crafting recipe's ingredient item lists for the generator.
*/
public final class VanillaRecipeOracle {
static RecipeManager recipes;
public static void main(String[] args) throws Exception {
ParityData.init();
recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
if (args[0].equals("dump")) {
dump(Path.of(args[1]));
return;
}
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
String result;
try {
result = run(line.split("\t", -1));
} catch (Exception e) {
result = "error";
}
out.println(result);
}
}
}
static String run(String[] f) throws Exception {
switch (f[0]) {
case "craft": {
int n = Integer.parseInt(f[1]);
List<ItemStack> items = new ArrayList<>();
for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i]));
var positioned = CraftingInput.ofPositioned(n, n, items);
var input = positioned.input();
if (input.isEmpty()) return "none";
var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
var result = recipe.assemble(input);
var rest = recipe.getRemainingItems(input);
StringJoiner joiner = new StringJoiner(";");
for (int i = 0; i < rest.size(); i++) {
if (rest.get(i).isEmpty()) continue;
int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width();
joiner.add(at + "=" + ParityData.canon(rest.get(i)));
}
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner;
}
case "cook": {
RecipeType<? extends AbstractCookingRecipe> type = switch (f[1]) {
case "smelting" -> RecipeType.SMELTING;
case "blasting" -> RecipeType.BLASTING;
case "smoking" -> RecipeType.SMOKING;
default -> RecipeType.CAMPFIRE_COOKING;
};
return cook(type, ParityData.stack(f[2]));
}
case "stonecut": {
var stack = ParityData.stack(f[1]);
StringJoiner joiner = new StringJoiner(";");
for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) {
var holder = entry.recipe().recipe().get();
joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack))));
}
return joiner.toString();
}
case "smith": {
var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3]));
var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null);
if (found.isEmpty()) return "none";
return ParityData.canon(found.get().value().assemble(input));
}
default:
throw new IllegalArgumentException(f[0]);
}
}
static <T extends AbstractCookingRecipe> String cook(RecipeType<T> type, ItemStack stack) {
if (stack.isEmpty()) return "none";
var input = new SingleRecipeInput(stack);
var found = recipes.getRecipeFor(type, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime();
}
static String items(Ingredient ingredient) {
if (ingredient == null) return "[]";
StringBuilder row = new StringBuilder("[");
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
return row.append(']').toString();
}
static void dump(Path path) throws Exception {
try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
for (var holder : recipes.getRecipes()) {
var recipe = holder.value();
if (recipe instanceof SmithingRecipe smithing) {
out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName()
+ "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient())
+ ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}");
continue;
}
if (recipe.getType() != RecipeType.CRAFTING) continue;
var info = recipe.placementInfo();
StringBuilder row = new StringBuilder();
row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":[");
for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i));
row.append("],\"ingredients\":[");
boolean firstIngredient = true;
for (var ingredient : info.ingredients()) {
row.append(firstIngredient ? "" : ",").append('[');
firstIngredient = false;
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
row.append(']');
}
row.append("]}");
out.println(row);
}
}
}
}
@@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.client.renderer.block.*;
@@ -29,6 +30,14 @@ 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.DryFoliageColor;
import net.minecraft.world.level.FoliageColor;
import net.minecraft.world.level.GrassColor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.ARGB;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
@@ -100,6 +109,12 @@ public final class VanillaSectionMeshOracle {
return (T) value;
}
}
private static int[] colormap(String name) throws IOException {
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream("/assets/minecraft/textures/colormap/" + name + ".png");
var image = NativeImage.read(input)) {
return image.makePixelArray();
}
}
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);
@@ -139,12 +154,47 @@ public final class VanillaSectionMeshOracle {
return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker));
}
}
/** ClientLevel.calculateBlockTint over a BiomeManager with a fixed noise-biome map:
* quart cells listed in the scene, a default elsewhere in the 3x3 chunk region and
* plains outside it (chunks that are not loaded). */
private static final class TintBiomes {
final BiomeManager manager; final int radius;
final Map<Long, Holder<Biome>> cells = new HashMap<>();
final Holder<Biome> dflt, plains;
TintBiomes(JsonObject o, HolderLookup.RegistryLookup<Biome> lookup) {
radius = o.get("radius").getAsInt();
Function<String, Holder<Biome>> named = name -> lookup.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(name)));
plains = named.apply("minecraft:plains");
dflt = named.apply(o.get("default").getAsString());
for (var item : o.getAsJsonArray("cells")) {
var c = item.getAsJsonArray();
cells.put(BlockPos.asLong(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), named.apply(c.get(3).getAsString()));
}
manager = new BiomeManager((qx, qy, qz) -> {
if (qx < -4 || qx >= 8 || qz < -4 || qz >= 8) return plains;
return cells.getOrDefault(BlockPos.asLong(qx, Math.max(-16, Math.min(79, qy)), qz), dflt);
}, o.get("seed").getAsLong());
}
int tint(BlockPos pos, ColorResolver resolver) {
if (radius == 0) return resolver.getColor(manager.getBiome(pos).value(), pos.getX(), pos.getZ());
int count = (radius * 2 + 1) * (radius * 2 + 1);
int red = 0, green = 0, blue = 0;
var cursor = new Cursor3D(pos.getX() - radius, pos.getY(), pos.getZ() - radius, pos.getX() + radius, pos.getY(), pos.getZ() + radius);
var next = new BlockPos.MutableBlockPos();
while (cursor.advance()) {
next.set(cursor.nextX(), cursor.nextY(), cursor.nextZ());
int color = resolver.getColor(manager.getBiome(next).value(), next.getX(), next.getZ());
red += ARGB.red(color); green += ARGB.green(color); blue += ARGB.blue(color);
}
return ARGB.color(red / count, green / count, blue / count);
}
}
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;
int[] defaultLight; boolean nether; int grass, foliage, dry, water; TintBiomes biomes;
public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; }
public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; }
public int getBrightness(LightLayer layer, BlockPos pos) {
@@ -152,6 +202,7 @@ public final class VanillaSectionMeshOracle {
return layer == LightLayer.SKY ? value[0] : value[1];
}
public int getBlockTint(BlockPos pos, ColorResolver resolver) {
if (biomes != null) return biomes.tint(pos, 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");
@@ -165,7 +216,7 @@ public final class VanillaSectionMeshOracle {
}
private static final class Recorder {
final List<Object> quads = new ArrayList<>();
List<Object> pending; BlockPos block; String kind, layer, sprite;
List<Object> pending; boolean forceSolid; 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});
@@ -176,7 +227,7 @@ public final class VanillaSectionMeshOracle {
}
}
private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); }
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) {
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids, HolderLookup.RegistryLookup<Biome> biomeLookup) {
var scene = new Scene();
var light = row.getAsJsonArray("light");
scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()};
@@ -184,6 +235,7 @@ public final class VanillaSectionMeshOracle {
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();
if (row.has("biomes")) scene.biomes = new TintBiomes(row.getAsJsonObject("biomes"), biomeLookup);
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()));
@@ -194,10 +246,13 @@ public final class VanillaSectionMeshOracle {
}
var recorder = new Recorder();
BlockModelLighter.enableCaching();
var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault());
boolean smooth = !row.has("smooth") || row.get("smooth").getAsBoolean();
boolean cutoutLeaves = !row.has("cutout_leaves") || row.get("cutout_leaves").getAsBoolean();
LeavesBlock.setCutoutLeaves(cutoutLeaves);
var renderer = new ModelBlockRenderer(smooth, 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.kind = "model"; recorder.layer = recorder.forceSolid ? "solid" : layer(quad.materialInfo().layer());
recorder.sprite = quad.materialInfo().sprite().contents().name().toString();
int emission = quad.materialInfo().lightEmission();
int slot = Arrays.asList(FLUID_SPRITES).indexOf(recorder.sprite);
@@ -233,9 +288,8 @@ public final class VanillaSectionMeshOracle {
}, 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()),
recorder.forceSolid = ModelBlockRenderer.forceOpaque(cutoutLeaves, state);
renderer.tesselateBlock(output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()),
scene, pos, state, models.get(state), state.getSeed(pos));
}
}
@@ -244,6 +298,7 @@ public final class VanillaSectionMeshOracle {
return map("name", row.get("name").getAsString(), "quads", recorder.quads);
}
private static BlockColors COLORS;
private static HolderLookup.RegistryLookup<Biome> biomeLookup;
/** Per-state facts the Rust mesher derives from prepared resources. */
private static Object facts(BlockState state, int id) {
var level = EmptyBlockGetter.INSTANCE;
@@ -266,6 +321,7 @@ public final class VanillaSectionMeshOracle {
net.minecraft.server.Bootstrap.bootStrap();
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
LeavesBlock.setCutoutLeaves(true);
GrassColor.init(colormap("grass")); FoliageColor.init(colormap("foliage")); DryFoliageColor.init(colormap("dry_foliage"));
COLORS = BlockColors.createDefault();
if (args[0].equals("facts")) {
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
@@ -288,10 +344,11 @@ public final class VanillaSectionMeshOracle {
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);
biomeLookup = net.minecraft.data.registries.VanillaRegistries.createWorldLookup().lookupOrThrow(Registries.BIOME);
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(); }
for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids, biomeLookup))); output.newLine(); }
}
}
}