Merge branch 'parity-base' into parity/saves
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.server.IntegratedServer;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* The vanilla client as the reference LAN host for the multiplayer harness
|
||||
* (tools/test_lan_vanilla_client.py): it runs net.minecraft.client.main.Main
|
||||
* unchanged, and once the singleplayer world is up it turns off the
|
||||
* integrated server's authentication (it always authenticates guests against
|
||||
* Mojang's session servers, which offline test clients cannot pass) and opens
|
||||
* the world to LAN on the port in -Dhorizon.lanPort, with commands allowed,
|
||||
* as the "Open to LAN" screen does.
|
||||
*/
|
||||
public final class OfflineLanHost {
|
||||
public static void main(String[] args) throws Exception {
|
||||
int port = Integer.getInteger("horizon.lanPort", 0);
|
||||
Thread watcher = new Thread(() -> {
|
||||
boolean published = false;
|
||||
while (!published) {
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
IntegratedServer server = mc == null ? null : mc.getSingleplayerServer();
|
||||
if (server == null || mc.player == null || !server.isReady()) continue;
|
||||
server.setUsesAuthentication(false);
|
||||
mc.execute(() -> {
|
||||
boolean ok = server.publishServer(MinecraftServer.MultiplayerScope.LAN, true, port);
|
||||
System.out.println("[OfflineLanHost] published=" + ok + " port=" + server.getPort());
|
||||
});
|
||||
published = true;
|
||||
} catch (Throwable t) {
|
||||
// The game is still starting.
|
||||
}
|
||||
}
|
||||
}, "horizon-offline-lan");
|
||||
watcher.setDaemon(true);
|
||||
watcher.start();
|
||||
net.minecraft.client.main.Main.main(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.blaze3d.font.GlyphInfo;
|
||||
import com.mojang.blaze3d.font.GlyphProvider;
|
||||
import com.mojang.blaze3d.font.UnbakedGlyph;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GlyphSource;
|
||||
import net.minecraft.client.gui.font.glyphs.BakedGlyph;
|
||||
import net.minecraft.client.gui.font.providers.GlyphProviderDefinition;
|
||||
import net.minecraft.client.gui.font.TextRenderable;
|
||||
import net.minecraft.network.chat.FontDescription;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.util.RandomSource;
|
||||
|
||||
/**
|
||||
* The vanilla default font's glyph metrics without a GPU: the `space` and
|
||||
* `include/default` providers of the client jar loaded by vanilla's own
|
||||
* provider definitions (BitmapProvider scans ascii.png etc. for advances).
|
||||
* Glyphs carry metrics only; nothing is stitched.
|
||||
*/
|
||||
public final class ParityFont {
|
||||
public static ResourceManager resources() throws Exception {
|
||||
var method = net.minecraft.client.resources.ClientPackSource.class.getDeclaredMethod("createVanillaPackSource", Path.class);
|
||||
method.setAccessible(true);
|
||||
var pack = (net.minecraft.server.packs.VanillaPackResources) method.invoke(null, Path.of("/nonexistent-horizon-assets"));
|
||||
return pack.asResourceManager();
|
||||
}
|
||||
|
||||
public static Font create(ResourceManager resources) throws Exception {
|
||||
List<GlyphProvider> providers = new ArrayList<>();
|
||||
for (String include : new String[] {"space", "default"}) {
|
||||
var id = Identifier.withDefaultNamespace("font/include/" + include + ".json");
|
||||
try (var reader = new InputStreamReader(resources.open(id), StandardCharsets.UTF_8)) {
|
||||
var json = JsonParser.parseReader(reader).getAsJsonObject();
|
||||
for (var element : json.getAsJsonArray("providers")) {
|
||||
var conditional = GlyphProviderDefinition.Conditional.CODEC.parse(JsonOps.INSTANCE, element).getOrThrow();
|
||||
var loader = conditional.definition().unpack().left().orElseThrow();
|
||||
providers.add(loader.load(resources));
|
||||
}
|
||||
}
|
||||
}
|
||||
GlyphSource source = new GlyphSource() {
|
||||
@Override
|
||||
public BakedGlyph getGlyph(int codepoint) {
|
||||
for (GlyphProvider provider : providers) {
|
||||
UnbakedGlyph glyph = provider.getGlyph(codepoint);
|
||||
if (glyph != null) return baked(glyph.info());
|
||||
}
|
||||
return baked(GlyphInfo.simple(6.0F));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakedGlyph getRandomGlyph(RandomSource random, int width) {
|
||||
return getGlyph('?');
|
||||
}
|
||||
};
|
||||
return new Font(new Font.Provider() {
|
||||
@Override
|
||||
public GlyphSource glyphs(FontDescription font) {
|
||||
return source;
|
||||
}
|
||||
|
||||
@Override
|
||||
public net.minecraft.client.gui.font.glyphs.EffectGlyph effect() {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static BakedGlyph baked(GlyphInfo info) {
|
||||
return new BakedGlyph() {
|
||||
@Override
|
||||
public GlyphInfo info() {
|
||||
return info;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextRenderable.Styled createGlyph(float x, float y, int color, int shadowColor, Style style, float boldOffset, float shadowOffset) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.client.sounds.ChannelAccess;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.tags.FluidTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.BubbleColumnBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Runs the local player's real ambient sound path over the real SoundEngine
|
||||
* (VanillaSoundRig): LocalPlayer.updateIsUnderwater (enter/exit sounds through
|
||||
* ClientLevel.playLocalSound and the UnderLiquidAmbientSoundInstance), the
|
||||
* UnderwaterAmbientSoundHandler and the BiomeAmbientSoundsHandler, then
|
||||
* SoundManager.tick, once per client tick. Inputs: the AMBIENT_SOUNDS value
|
||||
* (a constant attribute layer), the player's position, eye height, whether
|
||||
* its eyes are in water, spectator and removed flags, and the level's sky and
|
||||
* block brightness (a hash of the position). Prints the level random's next
|
||||
* long (without drawing it), the handlers' state and every playing instance.
|
||||
*/
|
||||
public final class VanillaAmbientOracle {
|
||||
public static final class Actor extends LocalPlayer {
|
||||
boolean eyeInWater, spectator;
|
||||
|
||||
Actor() {
|
||||
super(null, null, null, null, null, null, false, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEyeInFluid(final TagKey<Fluid> type) {
|
||||
return type == FluidTags.WATER && eyeInWater;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSpectator() {
|
||||
return spectator;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Lvl extends ClientLevel {
|
||||
int mode;
|
||||
final Map<BlockPos, Boolean> columns = new HashMap<>();
|
||||
|
||||
Lvl() {
|
||||
super(null, null, null, null, 0, 0, null, false, 0L, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBrightness(final LightLayer layer, final BlockPos pos) {
|
||||
return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getBlockState(final BlockPos pos) {
|
||||
Boolean drag = columns.get(pos);
|
||||
return drag == null ? Blocks.AIR.defaultBlockState() : Blocks.BUBBLE_COLUMN.defaultBlockState().setValue(BubbleColumnBlock.DRAG_DOWN, drag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasChunksAt(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The scripted brightness: (sky, block) for a light mode and block. */
|
||||
static int[] light(int mode, int x, int y, int z) {
|
||||
int h = x * 73856093 ^ y * 19349663 ^ z * 83492791;
|
||||
return switch (mode) {
|
||||
case 0 -> new int[]{15, 0};
|
||||
case 1 -> new int[]{0, 0};
|
||||
case 2 -> new int[]{0, (h >>> 4) & 15};
|
||||
default -> new int[]{(h & 3) == 0 ? (h >>> 8) & 15 : 0, (h >>> 12) & 15};
|
||||
};
|
||||
}
|
||||
|
||||
/** The player's box (EntityDimensions.makeBoundingBox, width 0.6F). */
|
||||
static AABB box(Vec3 at, float height) {
|
||||
return new AABB(at.x - 0.3F, at.y, at.z - 0.3F, at.x + 0.3F, at.y + height, at.z + 0.3F);
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
static double d(String hex) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16));
|
||||
}
|
||||
|
||||
static Holder<SoundEvent> event(String id) {
|
||||
return Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(id)));
|
||||
}
|
||||
|
||||
/** "loop|- mood|- addition..." with mood "sound,delay,extent,offsetbits" and additions "sound,chancebits". */
|
||||
static AmbientSounds sounds(String[] a) {
|
||||
Optional<Holder<SoundEvent>> loop = a[1].equals("-") ? Optional.empty() : Optional.of(event(a[1]));
|
||||
Optional<AmbientMoodSettings> mood = Optional.empty();
|
||||
if (!a[2].equals("-")) {
|
||||
String[] m = a[2].split(",");
|
||||
mood = Optional.of(new AmbientMoodSettings(event(m[0]), Integer.parseInt(m[1]), Integer.parseInt(m[2]), d(m[3])));
|
||||
}
|
||||
var additions = new ArrayList<AmbientAdditionsSettings>();
|
||||
for (int i = 3; i < a.length; i++) {
|
||||
String[] p = a[i].split(",");
|
||||
additions.add(new AmbientAdditionsSettings(event(p[0]), d(p[1])));
|
||||
}
|
||||
return new AmbientSounds(loop, mood, additions);
|
||||
}
|
||||
|
||||
/** LegacyRandomSource's next nextLong(), read from its state. */
|
||||
static long peek(RandomSource random) throws Exception {
|
||||
long s = ((java.util.concurrent.atomic.AtomicLong) VanillaSoundRig.get(random,
|
||||
Class.forName("net.minecraft.world.level.levelgen.LegacyRandomSource"), "seed")).get();
|
||||
long m = 0x5DEECE66DL, mask = (1L << 48) - 1;
|
||||
long s1 = (s * m + 0xBL) & mask;
|
||||
long s2 = (s1 * m + 0xBL) & mask;
|
||||
return ((long) (int) (s1 >>> 16) << 32) + (int) (s2 >>> 16);
|
||||
}
|
||||
|
||||
static String bits(double v) {
|
||||
return String.format("%016x", Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
var mc = VanillaSoundRig.make(Minecraft.class);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager);
|
||||
var renderer = VanillaSoundRig.make(GameRenderer.class);
|
||||
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", VanillaSoundRig.make(Camera.class));
|
||||
VanillaSoundRig.set(VanillaSoundRig.get(renderer, GameRenderer.class, "mainCamera"), Camera.class, "position", Vec3.ZERO);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
|
||||
Method update = LocalPlayer.class.getDeclaredMethod("updateIsUnderwater");
|
||||
update.setAccessible(true);
|
||||
var instanceToChannel = VanillaSoundRig.field(SoundEngine.class, "instanceToChannel");
|
||||
Lvl level = null;
|
||||
Actor actor = null;
|
||||
UnderwaterAmbientSoundHandler underwater = null;
|
||||
BiomeAmbientSoundsHandler biome = null;
|
||||
BubbleColumnAmbientSoundHandler bubble = null;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "start" -> {
|
||||
// A new level and player: fresh handlers on a seeded level random.
|
||||
rig.manager.stop();
|
||||
level = VanillaSoundRig.make(Lvl.class);
|
||||
VanillaSoundRig.set(level, Level.class, "random", RandomSource.create(Long.parseLong(a[1])));
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "minecraft", mc);
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", EnvironmentAttributeSystem.builder().build());
|
||||
actor = VanillaSoundRig.make(Actor.class);
|
||||
VanillaSoundRig.set(actor, Entity.class, "level", level);
|
||||
VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO);
|
||||
VanillaSoundRig.set(actor, Entity.class, "bb", box(Vec3.ZERO, 1.8F));
|
||||
VanillaSoundRig.set(level, Lvl.class, "columns", new HashMap<BlockPos, Boolean>());
|
||||
VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc);
|
||||
underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager);
|
||||
bubble = new BubbleColumnAmbientSoundHandler(actor);
|
||||
biome = new BiomeAmbientSoundsHandler(actor, rig.manager);
|
||||
}
|
||||
case "sounds" -> {
|
||||
AmbientSounds value = sounds(a);
|
||||
var system = EnvironmentAttributeSystem.builder()
|
||||
.addConstantLayer(EnvironmentAttributes.AMBIENT_SOUNDS, base -> value)
|
||||
.build();
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", system);
|
||||
}
|
||||
case "player" -> {
|
||||
// player x y z eyeHeight eyeInWater spectator removed lightMode
|
||||
VanillaSoundRig.set(actor, Entity.class, "position", new Vec3(d(a[1]), d(a[2]), d(a[3])));
|
||||
VanillaSoundRig.set(actor, Entity.class, "eyeHeight", f(a[4]));
|
||||
actor.eyeInWater = a[5].equals("1");
|
||||
actor.spectator = a[6].equals("1");
|
||||
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[7].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
level.mode = Integer.parseInt(a[8]);
|
||||
var at = new Vec3(d(a[1]), d(a[2]), d(a[3]));
|
||||
VanillaSoundRig.set(actor, Entity.class, "bb", box(at, f(a[9])));
|
||||
level.columns.clear();
|
||||
for (int i = 10; i < a.length; i++) {
|
||||
String[] c = a[i].split(",");
|
||||
level.columns.put(new BlockPos(Integer.parseInt(c[0]), Integer.parseInt(c[1]), Integer.parseInt(c[2])), c[3].equals("1"));
|
||||
}
|
||||
}
|
||||
case "volume" -> {
|
||||
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
}
|
||||
case "tick" -> {
|
||||
update.invoke(actor);
|
||||
underwater.tick();
|
||||
bubble.tick();
|
||||
biome.tick();
|
||||
rig.manager.tick(false);
|
||||
}
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
out.printf(" rand=%d mood=%08x underwater=%s delay=%d%n", peek(level.getRandom()), Float.floatToRawIntBits(biome.getMoodiness()),
|
||||
actor.isUnderWater(), (int) VanillaSoundRig.get(underwater, UnderwaterAmbientSoundHandler.class, "tickDelay"));
|
||||
var loops = (Map<Holder<SoundEvent>, BiomeAmbientSoundsHandler.LoopSoundInstance>) VanillaSoundRig.get(biome,
|
||||
BiomeAmbientSoundsHandler.class, "loopSounds");
|
||||
for (var e : loops.entrySet()) {
|
||||
var loop = e.getValue();
|
||||
out.printf(" loop %s fade=%d direction=%d stopped=%s active=%s%n", e.getKey().value().location(),
|
||||
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fade"),
|
||||
(int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fadeDirection"), loop.isStopped(),
|
||||
rig.manager.isActive(loop));
|
||||
}
|
||||
var playing = new ArrayList<String>();
|
||||
for (SoundInstance i : ((Map<SoundInstance, ChannelAccess.ChannelHandle>) instanceToChannel.get(rig.engine)).keySet()) {
|
||||
float volume = (float) VanillaSoundRig.get(i, AbstractSoundInstance.class, "volume");
|
||||
playing.add(String.format(" playing %s volume=%08x looping=%s relative=%s at=%s,%s,%s stopped=%s", i.getIdentifier(),
|
||||
Float.floatToRawIntBits(volume), i.isLooping(), i.isRelative(), bits(i.getX()), bits(i.getY()), bits(i.getZ()),
|
||||
i instanceof TickableSoundInstance t && t.isStopped()));
|
||||
}
|
||||
Collections.sort(playing);
|
||||
for (String p : playing) out.println(p);
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.sounds.Musics;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.clock.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* The audio environment attributes as the vanilla EnvironmentAttributeSystem
|
||||
* evaluates them from the vanilla data pack (dimension layer, the biome's
|
||||
* positional layer, the dimension timelines and weather layers):
|
||||
* BACKGROUND_MUSIC with BackgroundMusic.select for every creative/underwater
|
||||
* combination, MUSIC_VOLUME and AMBIENT_SOUNDS, for lines "dimension biome
|
||||
* ticks"; plus the Musics constants.
|
||||
*/
|
||||
public final class VanillaAudioAttributesOracle {
|
||||
static String music(Music m) {
|
||||
return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
|
||||
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
|
||||
}
|
||||
|
||||
public static void main(String[] args) 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();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var biomes = world.lookupOrThrow(Registries.BIOME);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
w.println("MENU " + music(Musics.MENU));
|
||||
w.println("CREDITS " + music(Musics.CREDITS));
|
||||
w.println("END_BOSS " + music(Musics.END_BOSS));
|
||||
w.println("CREATIVE " + music(Musics.CREATIVE));
|
||||
w.println("END " + music(Musics.END));
|
||||
w.println("UNDER_WATER " + music(Musics.UNDER_WATER));
|
||||
w.println("GAME " + music(Musics.GAME));
|
||||
for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) {
|
||||
String[] f = line.split(" ");
|
||||
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[0]))).value();
|
||||
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[1]))).value();
|
||||
long ticks = Long.parseLong(f[2]);
|
||||
ClockManager clocks = h -> new ClockInstance() {
|
||||
public long totalTicks() { return ticks; }
|
||||
public float partialTick() { return 0.0F; }
|
||||
public float rate() { return 1.0F; }
|
||||
public boolean isPaused() { return false; }
|
||||
};
|
||||
var b = EnvironmentAttributeSystem.builder();
|
||||
b.addConstantLayer(dim.attributes());
|
||||
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
|
||||
dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks));
|
||||
if (dim.hasSkyLight() && !dim.hasCeiling()) {
|
||||
WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() {
|
||||
public float rainLevel() { return 0.0F; }
|
||||
public float thunderLevel() { return 0.0F; }
|
||||
});
|
||||
}
|
||||
var system = b.build();
|
||||
BackgroundMusic bg = system.getValue(EnvironmentAttributes.BACKGROUND_MUSIC, Vec3.ZERO);
|
||||
StringBuilder sb = new StringBuilder(line);
|
||||
sb.append(" default=").append(music(bg.defaultMusic().orElse(null)))
|
||||
.append(" creative=").append(music(bg.creativeMusic().orElse(null)))
|
||||
.append(" underwater=").append(music(bg.underwaterMusic().orElse(null)));
|
||||
for (boolean creative : new boolean[]{false, true}) {
|
||||
for (boolean underwater : new boolean[]{false, true}) {
|
||||
sb.append(" select=").append(music(bg.select(creative, underwater).orElse(null)));
|
||||
}
|
||||
}
|
||||
sb.append(String.format(" volume=%08x", Float.floatToRawIntBits(system.getValue(EnvironmentAttributes.MUSIC_VOLUME, Vec3.ZERO))));
|
||||
AmbientSounds ambient = system.getValue(EnvironmentAttributes.AMBIENT_SOUNDS, Vec3.ZERO);
|
||||
sb.append(" loop=").append(ambient.loop().map(s -> s.value().location().toString()).orElse("-"));
|
||||
sb.append(" mood=").append(ambient.mood().map(m -> m.soundEvent().value().location() + "," + m.tickDelay() + ","
|
||||
+ m.blockSearchExtent() + "," + String.format("%016x", Double.doubleToRawLongBits(m.soundPositionOffset()))).orElse("-"));
|
||||
for (AmbientAdditionsSettings a : ambient.additions()) {
|
||||
sb.append(" addition=").append(a.soundEvent().value().location()).append(String.format(",%016x", Double.doubleToRawLongBits(a.tickChance())));
|
||||
}
|
||||
w.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.player.ClientInput;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.world.effect.*;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.Input;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
|
||||
/**
|
||||
* Runs the real LocalPlayer.updateAutoJump (with canAutoJump, getBlockJumpFactor,
|
||||
* CollisionGetter.getCollisions/BlockCollisions and the player's collision
|
||||
* context) on a LocalPlayer shell standing in an independently constructed copy
|
||||
* of the client's resident test scene, with each case's blocks placed.
|
||||
*/
|
||||
public final class VanillaAutoJumpOracle {
|
||||
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 Map<Long, Chunk> chunks;
|
||||
|
||||
static final class AutoLevel extends net.minecraft.server.level.ServerLevel {
|
||||
AutoLevel() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
|
||||
@Override public BlockState getBlockState(BlockPos p) { return chunks.get(key(p.getX() >> 4, p.getZ() >> 4)).getBlockState(p); }
|
||||
@Override public BlockGetter getChunkForCollisions(int x, int z) { return chunks.get(key(x, z)); }
|
||||
@Override public List<VoxelShape> getEntityCollisions(Entity entity, AABB bounds) { return List.of(); }
|
||||
}
|
||||
|
||||
static final class Jumper extends LocalPlayer {
|
||||
boolean ground;
|
||||
net.minecraft.world.entity.ai.attributes.AttributeMap attributes;
|
||||
|
||||
Jumper() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public boolean onGround() { return ground; }
|
||||
@Override public net.minecraft.world.entity.ai.attributes.AttributeMap getAttributes() { return attributes; }
|
||||
@Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; }
|
||||
@Override public ItemStack getItemBySlot(EquipmentSlot slot) { return ItemStack.EMPTY; }
|
||||
}
|
||||
|
||||
static <T extends Comparable<T>> BlockState with(BlockState state, Property<T> key, String value) {
|
||||
return state.setValue(key, key.getValue(value).orElseThrow());
|
||||
}
|
||||
|
||||
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);
|
||||
Path resources = Path.of(args[2]);
|
||||
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject());
|
||||
var description = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject();
|
||||
var trace = new Trace();
|
||||
trace.out = new PrintWriter(OutputStream.nullOutputStream());
|
||||
trace.fail = -1;
|
||||
chunks = VanillaSceneCollisionOracle.scene(description, trace);
|
||||
AutoLevel level = make(AutoLevel.class);
|
||||
var update = LocalPlayer.class.getDeclaredMethod("updateAutoJump", float.class, float.class);
|
||||
update.setAccessible(true);
|
||||
var enabled = field(LocalPlayer.class, "autoJumpEnabled");
|
||||
var time = field(LocalPlayer.class, "autoJumpTime");
|
||||
var moveVector = field(ClientInput.class, "moveVector");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
var restore = new ArrayList<Object[]>();
|
||||
for (var e : c.getAsJsonArray("blocks")) {
|
||||
var b = e.getAsJsonArray();
|
||||
var pos = new BlockPos(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt());
|
||||
BlockState state = VanillaSceneCollisionOracle.state(b.get(3).getAsString());
|
||||
for (var p : b.get(4).getAsJsonObject().entrySet()) {
|
||||
state = with(state, Objects.requireNonNull(state.getBlock().getStateDefinition().getProperty(p.getKey())), p.getValue().getAsString());
|
||||
}
|
||||
restore.add(new Object[] {pos, level.getBlockState(pos)});
|
||||
VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), state);
|
||||
}
|
||||
var p = c.getAsJsonObject("player");
|
||||
Jumper player = make(Jumper.class);
|
||||
field(Entity.class, "level").set(player, level);
|
||||
var position = new Vec3(d(p.getAsJsonArray("pos").get(0)), d(p.getAsJsonArray("pos").get(1)), d(p.getAsJsonArray("pos").get(2)));
|
||||
field(Entity.class, "position").set(player, position);
|
||||
field(Entity.class, "blockPosition").set(player, BlockPos.containing(position));
|
||||
player.mainSupportingBlockPos = Optional.empty();
|
||||
var dimensions = EntityDimensions.scalable(f(p.get("width")), f(p.get("height")));
|
||||
field(Entity.class, "dimensions").set(player, dimensions);
|
||||
player.setBoundingBox(dimensions.makeBoundingBox(position));
|
||||
player.ground = p.get("ground").getAsBoolean();
|
||||
field(Entity.class, "yRot").setFloat(player, f(p.get("yr")));
|
||||
field(Entity.class, "xRot").setFloat(player, f(p.get("xr")));
|
||||
// Player.getSpeed reads the movement speed attribute.
|
||||
player.attributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(Player.createAttributes().build());
|
||||
player.attributes.getInstance(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED).setBaseValue(f(p.get("speed")));
|
||||
var input = new ClientInput();
|
||||
boolean shift = p.get("shift").getAsBoolean();
|
||||
input.keyPresses = new Input(false, false, false, false, false, shift, false);
|
||||
var move = p.getAsJsonArray("move");
|
||||
moveVector.set(input, new Vec2(f(move.get(0)), f(move.get(1))));
|
||||
player.input = input;
|
||||
var effects = new HashMap<net.minecraft.core.Holder<MobEffect>, MobEffectInstance>();
|
||||
if (!p.get("boost").isJsonNull()) {
|
||||
effects.put(MobEffects.JUMP_BOOST, new MobEffectInstance(MobEffects.JUMP_BOOST, 100, p.get("boost").getAsInt()));
|
||||
}
|
||||
field(LivingEntity.class, "activeEffects").set(player, effects);
|
||||
enabled.setBoolean(player, p.get("enabled").getAsBoolean());
|
||||
time.setInt(player, p.get("time").getAsInt());
|
||||
update.invoke(player, f(c.get("xa")), f(c.get("za")));
|
||||
out.println("jump " + time.getInt(player));
|
||||
Collections.reverse(restore);
|
||||
for (var r : restore) {
|
||||
var pos = (BlockPos) r[0];
|
||||
VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), (BlockState) r[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.model.Model;
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
import net.minecraft.client.model.geom.LayerDefinitions;
|
||||
import net.minecraft.client.renderer.SubmitNodeCollector;
|
||||
import net.minecraft.client.renderer.blockentity.*;
|
||||
import net.minecraft.client.renderer.blockentity.state.*;
|
||||
import net.minecraft.client.renderer.rendertype.RenderType;
|
||||
import net.minecraft.client.renderer.state.level.CameraRenderState;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.UvMapping;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteGetter;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteId;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
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.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.minecraft.world.item.DyeColor;
|
||||
import net.minecraft.world.item.ItemStackTemplate;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.entity.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.ChestType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
/**
|
||||
* Original oracle for block-entity rendering: each case builds a vanilla block
|
||||
* entity for a block state, sets its animation fields, runs the real
|
||||
* renderer's extractRenderState and submit, and captures every submitted
|
||||
* model (vertices after setupAnim and the pose stack, sprite-local UVs, tint,
|
||||
* light), text call and item. Level-backed inputs (light, chest lid
|
||||
* openness, pot wobble) come from the case because the entity has no level.
|
||||
*
|
||||
* Input lines: case JSON. Output lines: {case, submits:[...]} or {case, error}.
|
||||
*/
|
||||
public final class VanillaBlockEntityRenderOracle {
|
||||
private static final Map<TextureAtlasSprite, SpriteId> SPRITES = new IdentityHashMap<>();
|
||||
private static Object unsafe;
|
||||
private static Method allocate;
|
||||
|
||||
static String textureName(Identifier id) {
|
||||
String path = id.getPath();
|
||||
if (path.startsWith("textures/")) path = path.substring(9);
|
||||
if (path.endsWith(".png")) path = path.substring(0, path.length() - 4);
|
||||
return id.getNamespace().equals("minecraft") ? path : id.getNamespace() + ":" + path;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Identifier renderTypeTexture(RenderType type) throws Exception {
|
||||
Field state = RenderType.class.getDeclaredField("state");
|
||||
state.setAccessible(true);
|
||||
Object setup = state.get(type);
|
||||
Field textures = setup.getClass().getDeclaredField("textures");
|
||||
textures.setAccessible(true);
|
||||
var map = (Map<String, Object>) textures.get(setup);
|
||||
Object binding = map.get("Sampler0");
|
||||
if (binding == null) return null;
|
||||
Method location = binding.getClass().getDeclaredMethod("location");
|
||||
location.setAccessible(true);
|
||||
return (Identifier) location.invoke(binding);
|
||||
}
|
||||
|
||||
static JsonArray matrix(Matrix4f m) {
|
||||
var a = new JsonArray();
|
||||
float[] f = new float[16];
|
||||
m.get(f);
|
||||
for (float x : f) a.add(x);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** A vertex consumer recording [x,y,z,color,u,v,overlay,light,nx,ny,nz]. */
|
||||
static VertexConsumer recorder(List<float[]> out) {
|
||||
InvocationHandler handler = new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args);
|
||||
float[] v = out.isEmpty() ? null : out.get(out.size() - 1);
|
||||
switch (method.getName()) {
|
||||
case "addVertex" -> out.add(new float[] {(float) args[0], (float) args[1], (float) args[2], 0, 0, 0, 0, 0, 0, 0, 0});
|
||||
case "setColor" -> v[3] = Float.intBitsToFloat(args.length == 1 ? (int) args[0]
|
||||
: ((int) args[3] << 24) | ((int) args[0] << 16) | ((int) args[1] << 8) | (int) args[2]);
|
||||
case "setUv" -> { v[4] = (float) args[0]; v[5] = (float) args[1]; }
|
||||
case "setUv1" -> v[6] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16));
|
||||
case "setUv2" -> v[7] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16));
|
||||
case "setNormal" -> { v[8] = (float) args[0]; v[9] = (float) args[1]; v[10] = (float) args[2]; }
|
||||
default -> { }
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
};
|
||||
return (VertexConsumer) Proxy.newProxyInstance(VertexConsumer.class.getClassLoader(), new Class<?>[] {VertexConsumer.class}, handler);
|
||||
}
|
||||
|
||||
static JsonArray vertices(List<float[]> verts) {
|
||||
var out = new JsonArray();
|
||||
for (float[] v : verts) {
|
||||
var a = new JsonArray();
|
||||
a.add(v[0]); a.add(v[1]); a.add(v[2]);
|
||||
a.add(Float.floatToRawIntBits(v[3]));
|
||||
a.add(v[4]); a.add(v[5]);
|
||||
a.add(Float.floatToRawIntBits(v[6])); a.add(Float.floatToRawIntBits(v[7]));
|
||||
a.add(v[8]); a.add(v[9]); a.add(v[10]);
|
||||
out.add(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String text(FormattedCharSequence sequence) {
|
||||
var sb = new StringBuilder();
|
||||
sequence.accept((index, style, codepoint) -> {
|
||||
sb.appendCodePoint(codepoint);
|
||||
return true;
|
||||
});
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static SubmitNodeCollector collector(JsonArray submits) {
|
||||
InvocationHandler handler = new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
String name = method.getName();
|
||||
if (name.equals("order")) return proxy;
|
||||
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args);
|
||||
var submit = new JsonObject();
|
||||
submit.addProperty("type", name);
|
||||
switch (name) {
|
||||
case "submitModel" -> {
|
||||
var model = (Model) args[0];
|
||||
var pose = (PoseStack) args[2];
|
||||
var renderType = (RenderType) args[3];
|
||||
var uv = (UvMapping) args[7];
|
||||
String texture;
|
||||
if (uv instanceof TextureAtlasSprite sprite && SPRITES.containsKey(sprite))
|
||||
texture = textureName(SPRITES.get(sprite).texture());
|
||||
else {
|
||||
Identifier t = renderTypeTexture(renderType);
|
||||
texture = t == null ? "?" : textureName(t);
|
||||
}
|
||||
submit.addProperty("texture", texture);
|
||||
submit.addProperty("renderType", renderType.toString().split("\\[")[0]);
|
||||
submit.addProperty("light", (int) args[4]);
|
||||
submit.addProperty("overlay", (int) args[5]);
|
||||
submit.addProperty("tint", (int) args[6]);
|
||||
model.setupAnim(args[1]);
|
||||
List<float[]> verts = new ArrayList<>();
|
||||
model.renderToBuffer(pose, recorder(verts), (int) args[4], (int) args[5], (int) args[6]);
|
||||
submit.add("vertices", vertices(verts));
|
||||
}
|
||||
case "submitText" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
submit.addProperty("x", (float) args[1]);
|
||||
submit.addProperty("y", (float) args[2]);
|
||||
submit.addProperty("text", text((FormattedCharSequence) args[3]));
|
||||
submit.addProperty("shadow", (boolean) args[4]);
|
||||
submit.addProperty("mode", args[5].toString());
|
||||
submit.addProperty("light", (int) args[6]);
|
||||
submit.addProperty("color", (int) args[7]);
|
||||
submit.addProperty("background", (int) args[8]);
|
||||
submit.addProperty("outline", (int) args[9]);
|
||||
}
|
||||
case "submitCustomGeometry" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
var renderType = (RenderType) args[1];
|
||||
Identifier t = renderTypeTexture(renderType);
|
||||
submit.addProperty("texture", t == null ? "?" : textureName(t));
|
||||
submit.addProperty("renderType", renderType.toString().split("\\[")[0]);
|
||||
List<float[]> verts = new ArrayList<>();
|
||||
((SubmitNodeCollector.CustomGeometryRenderer) args[2]).render(pose.last(), recorder(verts));
|
||||
submit.add("vertices", vertices(verts));
|
||||
}
|
||||
case "submitItem" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
submit.addProperty("context", args[1].toString());
|
||||
submit.addProperty("light", (int) args[2]);
|
||||
}
|
||||
case "submitMovingBlock", "submitBlockModel" -> {
|
||||
var pose = (PoseStack) args[0];
|
||||
submit.add("matrix", matrix(pose.last().pose()));
|
||||
}
|
||||
case "submitCrumblingOverlay" -> { return null; }
|
||||
default -> { }
|
||||
}
|
||||
submits.add(submit);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return (SubmitNodeCollector) Proxy.newProxyInstance(SubmitNodeCollector.class.getClassLoader(), new Class<?>[] {SubmitNodeCollector.class}, handler);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws NoSuchFieldException {
|
||||
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
|
||||
try {
|
||||
Field f = c.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
} catch (NoSuchFieldException e) {
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name + " on " + type);
|
||||
}
|
||||
|
||||
static DyeColor dye(String name) {
|
||||
return DyeColor.byName(name, DyeColor.BLACK);
|
||||
}
|
||||
|
||||
static SignText signText(JsonObject side) {
|
||||
var lines = side.getAsJsonArray("lines");
|
||||
var messages = new ArrayList<Component>();
|
||||
for (int i = 0; i < 4; i++) messages.add(Component.literal(i < lines.size() ? lines.get(i).getAsString() : ""));
|
||||
return new SignText(messages, messages, dye(side.get("color").getAsString()), side.get("glowing").getAsBoolean());
|
||||
}
|
||||
|
||||
/** Block-entity fields that vanilla ticks; set from the case before extraction. */
|
||||
static void apply(BlockEntity be, JsonObject c) throws Exception {
|
||||
if (be instanceof BellBlockEntity bell) {
|
||||
bell.ticks = c.has("bellTicks") ? c.get("bellTicks").getAsInt() : 0;
|
||||
bell.shaking = c.has("shake");
|
||||
if (bell.shaking) bell.clickDirection = Direction.byName(c.get("shake").getAsString());
|
||||
} else if (be instanceof ShulkerBoxBlockEntity) {
|
||||
field(ShulkerBoxBlockEntity.class, "progressOld").setFloat(be, c.has("progressOld") ? c.get("progressOld").getAsFloat() : 0.0F);
|
||||
field(ShulkerBoxBlockEntity.class, "progress").setFloat(be, c.has("progress") ? c.get("progress").getAsFloat() : 0.0F);
|
||||
} else if (be instanceof ConduitBlockEntity conduit && c.has("conduit")) {
|
||||
var k = c.getAsJsonObject("conduit");
|
||||
conduit.tickCount = k.get("tickCount").getAsInt();
|
||||
field(ConduitBlockEntity.class, "isActive").setBoolean(be, k.get("active").getAsBoolean());
|
||||
field(ConduitBlockEntity.class, "isHunting").setBoolean(be, k.get("hunting").getAsBoolean());
|
||||
field(ConduitBlockEntity.class, "activeRotation").setFloat(be, k.get("activeRotation").getAsFloat());
|
||||
} else if (be instanceof EnchantingTableBlockEntity table && c.has("book")) {
|
||||
var b = c.getAsJsonObject("book");
|
||||
table.time = b.get("time").getAsInt();
|
||||
table.flip = b.get("flip").getAsFloat(); table.oFlip = b.get("oFlip").getAsFloat();
|
||||
table.open = b.get("open").getAsFloat(); table.oOpen = b.get("oOpen").getAsFloat();
|
||||
table.rot = b.get("rot").getAsFloat(); table.oRot = b.get("oRot").getAsFloat();
|
||||
} else if (be instanceof SkullBlockEntity && c.has("skullAnimation")) {
|
||||
var a = c.getAsJsonArray("skullAnimation");
|
||||
field(SkullBlockEntity.class, "isAnimating").setBoolean(be, a.get(0).getAsBoolean());
|
||||
field(SkullBlockEntity.class, "animationTickCount").setInt(be, a.get(1).getAsInt());
|
||||
} else if (be instanceof DecoratedPotBlockEntity && c.has("sherds")) {
|
||||
var s = c.getAsJsonArray("sherds");
|
||||
var items = new ArrayList<Optional<ItemStackTemplate>>();
|
||||
for (var e : s) {
|
||||
var id = e.getAsString();
|
||||
items.add(id.isEmpty() ? Optional.empty()
|
||||
: Optional.of(new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(id)))));
|
||||
}
|
||||
field(DecoratedPotBlockEntity.class, "decorations").set(be, new PotDecorations(items.get(0), items.get(1), items.get(2), items.get(3)));
|
||||
} else if (be instanceof BannerBlockEntity && c.has("patterns")) {
|
||||
var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder();
|
||||
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
|
||||
for (var e : c.getAsJsonArray("patterns")) {
|
||||
var p = e.getAsJsonArray();
|
||||
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
|
||||
builder.add(holder, dye(p.get(1).getAsString()));
|
||||
}
|
||||
field(BannerBlockEntity.class, "patterns").set(be, builder.build());
|
||||
}
|
||||
}
|
||||
|
||||
/** Render-state values vanilla reads from the level (absent here). */
|
||||
static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) {
|
||||
if (rs instanceof ChestRenderState chest) {
|
||||
chest.type = state.hasProperty(net.minecraft.world.level.block.ChestBlock.TYPE)
|
||||
? state.getValue(net.minecraft.world.level.block.ChestBlock.TYPE) : ChestType.SINGLE;
|
||||
chest.facing = state.getValue(net.minecraft.world.level.block.ChestBlock.FACING);
|
||||
chest.open = c.has("open") ? c.get("open").getAsFloat() : 0.0F;
|
||||
} else if (rs instanceof DecoratedPotRenderState pot && c.has("wobble")) {
|
||||
var w = c.getAsJsonArray("wobble");
|
||||
pot.wobbleStyle = DecoratedPotBlockEntity.WobbleStyle.valueOf(w.get(0).getAsString());
|
||||
pot.wobbleProgress = w.get(1).getAsFloat();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
Font font = ParityFont.create(ParityFont.resources());
|
||||
var models = new EntityModelSet(LayerDefinitions.createRoots());
|
||||
SpriteGetter sprites = id -> {
|
||||
try {
|
||||
var sprite = (TextureAtlasSprite) allocate.invoke(unsafe, TextureAtlasSprite.class);
|
||||
SPRITES.put(sprite, id);
|
||||
return sprite;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
};
|
||||
var context = new BlockEntityRendererProvider.Context(null, null, null, null, models, font, sprites, null);
|
||||
Map<Object, BlockEntityRenderer> renderers = (Map) BlockEntityRenderers.createEntityRenderers(context);
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
if (line.isBlank()) continue;
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
var result = new JsonObject();
|
||||
result.add("case", c);
|
||||
try {
|
||||
BlockState state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, c.get("block").getAsString(), false).blockState();
|
||||
var p = c.getAsJsonArray("pos");
|
||||
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
|
||||
var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
|
||||
if (be == null) throw new IllegalStateException("no block entity");
|
||||
apply(be, c);
|
||||
var renderer = renderers.get(be.getType());
|
||||
if (renderer == null) throw new IllegalStateException("no renderer");
|
||||
float partial = c.get("partial").getAsFloat();
|
||||
var cam = c.getAsJsonArray("camera");
|
||||
var cameraPos = new Vec3(cam.get(0).getAsDouble(), cam.get(1).getAsDouble(), cam.get(2).getAsDouble());
|
||||
var rs = (BlockEntityRenderState) renderer.createRenderState();
|
||||
if (rs instanceof BeaconRenderState beacon) {
|
||||
// BeaconRenderer.extract reads Minecraft.getInstance().player (scoping); its level-free part:
|
||||
BlockEntityRenderState.extractBase(be, rs, null);
|
||||
beacon.animationTime = Math.floorMod(c.get("gameTime").getAsLong(), 40) + partial;
|
||||
var sections = new ArrayList<BeaconRenderState.Section>();
|
||||
for (var e : c.getAsJsonArray("beam")) sections.add(new BeaconRenderState.Section(e.getAsJsonArray().get(0).getAsInt(), e.getAsJsonArray().get(1).getAsInt()));
|
||||
beacon.sections = sections;
|
||||
float distance = (float) cameraPos.subtract(Vec3.atCenterOf(pos)).horizontalDistance();
|
||||
beacon.beamRadiusScale = Math.max(1.0F, distance / 96.0F);
|
||||
} else
|
||||
if (rs instanceof SignRenderState sign) {
|
||||
// AbstractSignRenderer.extractRenderState reads Minecraft.getInstance(); its level-free part:
|
||||
var signBe = (SignBlockEntity) be;
|
||||
BlockEntityRenderState.extractBase(be, rs, null);
|
||||
sign.maxTextLineWidth = signBe.getMaxTextLineWidth();
|
||||
sign.textLineHeight = signBe.getTextLineHeight();
|
||||
var s = c.getAsJsonObject("sign");
|
||||
sign.frontText = signText(s.getAsJsonObject("front"));
|
||||
sign.backText = signText(s.getAsJsonObject("back"));
|
||||
sign.drawOutline = s.get("near").getAsBoolean();
|
||||
if (rs instanceof StandingSignRenderState standing) {
|
||||
standing.attachmentType = net.minecraft.world.level.block.PlainSignBlock.getAttachmentPoint(state);
|
||||
sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallSignBlock
|
||||
? StandingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallSignBlock.FACING))
|
||||
: StandingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.StandingSignBlock.ROTATION));
|
||||
} else {
|
||||
((HangingSignRenderState) rs).attachmentType = net.minecraft.world.level.block.HangingSignBlock.getAttachmentPoint(state);
|
||||
sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallHangingSignBlock
|
||||
? HangingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallHangingSignBlock.FACING))
|
||||
: HangingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.CeilingHangingSignBlock.ROTATION));
|
||||
}
|
||||
} else {
|
||||
renderer.extractRenderState(be, rs, partial, cameraPos, null);
|
||||
}
|
||||
var light = c.getAsJsonArray("light");
|
||||
rs.lightCoords = light.get(1).getAsInt() << 4 | light.get(0).getAsInt() << 20;
|
||||
patch(rs, state, c);
|
||||
var camera = new CameraRenderState();
|
||||
camera.pos = cameraPos;
|
||||
float yaw = c.has("yaw") ? c.get("yaw").getAsFloat() : 0.0F, pitch = c.has("pitch") ? c.get("pitch").getAsFloat() : 0.0F;
|
||||
// Camera.setRotation.
|
||||
camera.orientation = new Quaternionf().rotationYXZ((float) Math.PI - yaw * (float) (Math.PI / 180.0), -pitch * (float) (Math.PI / 180.0), 0.0F);
|
||||
var submits = new JsonArray();
|
||||
renderer.submit(rs, new PoseStack(), collector(submits), camera);
|
||||
result.add("submits", submits);
|
||||
} catch (Throwable error) {
|
||||
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result.addProperty("error", sw.toString().lines().limit(6).reduce("", (a, b) -> a + b + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
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.client.entity.ClientAvatarState;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.client.renderer.state.GameRenderState;
|
||||
import net.minecraft.client.renderer.state.level.CameraRenderState;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeProbe;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.*;
|
||||
import net.minecraft.world.entity.player.*;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.*;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.*;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/**
|
||||
* Drives the real Camera (tick, tickFov, alignWithEntity with getMaxZoom over
|
||||
* Level.clip, calculateFov, calculateHudFov), AbstractClientPlayer
|
||||
* .getFieldOfViewModifier and updateBob, ClientAvatarState and
|
||||
* GameRenderer.bobHurt/bobView with scripted entity states, and prints every
|
||||
* observable bit-exactly. Entities, the level and the renderer are
|
||||
* uninitialised shells (Unsafe) with controlled queries; block visual shapes
|
||||
* come from the case.
|
||||
*/
|
||||
public final class VanillaCameraOracle {
|
||||
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 Method method(Class<?> type, String name, Class<?>... args) throws Exception {
|
||||
Method m = type.getDeclaredMethod(name, args);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
|
||||
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.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String db(double v) {
|
||||
return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
static Vec3 vec(JsonElement v) {
|
||||
var a = v.getAsJsonArray();
|
||||
return new Vec3(d(a.get(0)), d(a.get(1)), d(a.get(2)));
|
||||
}
|
||||
|
||||
// ---- level with controlled visual shapes ----------------------------------------------
|
||||
static final class State extends BlockState {
|
||||
VoxelShape visual;
|
||||
|
||||
State() {
|
||||
super(null, null, null);
|
||||
}
|
||||
|
||||
@Override public VoxelShape getVisualShape(BlockGetter w, BlockPos p, CollisionContext c) { return visual; }
|
||||
@Override public VoxelShape getInteractionShape(BlockGetter w, BlockPos p) { return Shapes.empty(); }
|
||||
}
|
||||
|
||||
static final class Level extends net.minecraft.server.level.ServerLevel {
|
||||
Map<BlockPos, State> cells = new HashMap<>();
|
||||
State air;
|
||||
|
||||
Level() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
|
||||
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, air); }
|
||||
@Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); }
|
||||
}
|
||||
|
||||
static final class NoProbe extends EnvironmentAttributeProbe {
|
||||
@Override public void tick(net.minecraft.world.level.Level level, Vec3 position) { }
|
||||
}
|
||||
|
||||
static final class StubCamera extends Camera {
|
||||
net.minecraft.world.level.material.FogType fluid = net.minecraft.world.level.material.FogType.NONE;
|
||||
|
||||
@Override public net.minecraft.world.level.material.FogType getFluidInCamera() { return fluid; }
|
||||
}
|
||||
|
||||
// ---- camera entities ----------------------------------------------------------------
|
||||
static final class StubPlayer extends LocalPlayer {
|
||||
AttributeMap attributes;
|
||||
boolean using, dead, sleeping, swimming, ground;
|
||||
ItemStack useItem = ItemStack.EMPTY;
|
||||
int useTicks;
|
||||
Direction bed;
|
||||
Vec3 motion = Vec3.ZERO;
|
||||
|
||||
StubPlayer() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public AttributeMap getAttributes() { return attributes; }
|
||||
@Override public boolean isUsingItem() { return using; }
|
||||
@Override public ItemStack getUseItem() { return useItem; }
|
||||
@Override public int getTicksUsingItem() { return useTicks; }
|
||||
@Override public boolean isDeadOrDying() { return dead; }
|
||||
@Override public boolean isSleeping() { return sleeping; }
|
||||
@Override public Direction getBedOrientation() { return bed; }
|
||||
@Override public boolean isDescending() { return false; }
|
||||
@Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; }
|
||||
@Override public boolean isSwimming() { return swimming; }
|
||||
@Override public boolean onGround() { return ground; }
|
||||
@Override public Vec3 getDeltaMovement() { return motion; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
}
|
||||
|
||||
static final class StubMarker extends Marker {
|
||||
StubMarker() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override public boolean isDescending() { return false; }
|
||||
}
|
||||
|
||||
static Minecraft shell;
|
||||
static Options options;
|
||||
static Field position, xRot, yRot, eyeHeight, vehicle, abilities;
|
||||
static Constructor<ItemStack> stack;
|
||||
|
||||
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());
|
||||
field(Minecraft.class, "options").set(shell, options);
|
||||
position = field(Entity.class, "position");
|
||||
xRot = field(Entity.class, "xRot");
|
||||
yRot = field(Entity.class, "yRot");
|
||||
eyeHeight = field(Entity.class, "eyeHeight");
|
||||
vehicle = field(Entity.class, "vehicle");
|
||||
abilities = field(Player.class, "abilities");
|
||||
stack = ItemStack.class.getDeclaredConstructor(Holder.class, int.class, net.minecraft.core.component.PatchedDataComponentMap.class);
|
||||
stack.setAccessible(true);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
switch (c.get("t").getAsString()) {
|
||||
case "fov" -> out.println(fb(player(c).getFieldOfViewModifier(c.get("fp").getAsBoolean(), f(c.get("scale")))));
|
||||
case "camera" -> camera(c, out);
|
||||
case "bob" -> bob(c, out);
|
||||
case "avatar" -> avatar(c, out);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static AttributeMap attributes(double scale, double distance, double speed) {
|
||||
var map = new AttributeMap(Player.createAttributes().build());
|
||||
map.getInstance(Attributes.SCALE).setBaseValue(scale);
|
||||
map.getInstance(Attributes.CAMERA_DISTANCE).setBaseValue(distance);
|
||||
map.getInstance(Attributes.MOVEMENT_SPEED).setBaseValue(speed);
|
||||
return map;
|
||||
}
|
||||
|
||||
/** A player shell from the "fov" fields of a case or an entity op. */
|
||||
static StubPlayer player(JsonObject c) throws Exception {
|
||||
StubPlayer p = make(StubPlayer.class);
|
||||
fill(p, c);
|
||||
return p;
|
||||
}
|
||||
|
||||
static void fill(StubPlayer p, JsonObject c) throws Exception {
|
||||
var a = new Abilities();
|
||||
a.flying = c.get("flying").getAsBoolean();
|
||||
a.setWalkingSpeed(f(c.get("ws")));
|
||||
abilities.set(p, a);
|
||||
double scale = c.has("scale_attr") ? d(c.get("scale_attr")) : 1.0;
|
||||
double distance = c.has("dist") ? d(c.get("dist")) : 4.0;
|
||||
p.attributes = attributes(scale, distance, d(c.get("speed")));
|
||||
var use = c.get("use");
|
||||
p.using = !use.isJsonNull();
|
||||
if (p.using) {
|
||||
var u = use.getAsJsonArray();
|
||||
Item item = switch (u.get(0).getAsString()) {
|
||||
case "bow" -> Items.BOW;
|
||||
case "spyglass" -> Items.SPYGLASS;
|
||||
default -> Items.STICK;
|
||||
};
|
||||
p.useItem = stack.newInstance(Holder.direct(item), 1,
|
||||
new net.minecraft.core.component.PatchedDataComponentMap(net.minecraft.core.component.DataComponentMap.EMPTY));
|
||||
p.useTicks = u.get(1).getAsInt();
|
||||
}
|
||||
}
|
||||
|
||||
static void camera(JsonObject c, PrintWriter out) throws Exception {
|
||||
var level = make(Level.class);
|
||||
level.cells = new HashMap<>();
|
||||
level.air = make(State.class);
|
||||
level.air.visual = Shapes.empty();
|
||||
for (var e : c.getAsJsonObject("cells").entrySet()) {
|
||||
var at = e.getKey().split(" ");
|
||||
var s = make(State.class);
|
||||
VoxelShape shape = Shapes.empty();
|
||||
for (var b : e.getValue().getAsJsonArray()) {
|
||||
var a = b.getAsJsonArray();
|
||||
shape = Shapes.or(shape, Shapes.box(d(a.get(0)), d(a.get(1)), d(a.get(2)), d(a.get(3)), d(a.get(4)), d(a.get(5))));
|
||||
}
|
||||
s.visual = shape;
|
||||
level.cells.put(new BlockPos(Integer.parseInt(at[0]), Integer.parseInt(at[1]), Integer.parseInt(at[2])), s);
|
||||
}
|
||||
options.fov().set(c.get("fov").getAsInt());
|
||||
options.fovEffectScale().set(d(c.get("effect")));
|
||||
options.setCameraType(CameraType.values()[c.get("type").getAsInt()]);
|
||||
var camera = new StubCamera();
|
||||
field(Camera.class, "attributeProbe").set(camera, new NoProbe());
|
||||
field(Camera.class, "level").set(camera, level);
|
||||
GameRenderer renderer = make(GameRenderer.class);
|
||||
field(GameRenderer.class, "mainCamera").set(renderer, camera);
|
||||
field(Minecraft.class, "gameRenderer").set(shell, renderer);
|
||||
var align = method(Camera.class, "alignWithEntity", float.class);
|
||||
var fov = method(Camera.class, "calculateFov", float.class);
|
||||
var hud = method(Camera.class, "calculateHudFov", float.class);
|
||||
var panoramic = field(Camera.class, "isPanoramicMode");
|
||||
var eye = field(Camera.class, "eyeHeight");
|
||||
var eyeOld = field(Camera.class, "eyeHeightOld");
|
||||
var mod = field(Camera.class, "fovModifier");
|
||||
var modOld = field(Camera.class, "oldFovModifier");
|
||||
Entity entity = null;
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "entity" -> {
|
||||
var s = op.get(1).getAsJsonObject();
|
||||
entity = entity(s, entity);
|
||||
camera.setEntity(entity);
|
||||
out.println("entity");
|
||||
}
|
||||
case "type" -> {
|
||||
options.setCameraType(CameraType.values()[op.get(1).getAsInt()]);
|
||||
out.println("type");
|
||||
}
|
||||
case "tick" -> {
|
||||
camera.tick();
|
||||
out.println("tick " + fb(eye.getFloat(camera)) + " " + fb(eyeOld.getFloat(camera)) + " "
|
||||
+ fb(mod.getFloat(camera)) + " " + fb(modOld.getFloat(camera)));
|
||||
}
|
||||
case "frame" -> {
|
||||
float pt = f(op.get(1));
|
||||
camera.fluid = net.minecraft.world.level.material.FogType.valueOf(
|
||||
new String[] {"NONE", "WATER", "LAVA", "POWDER_SNOW"}[op.get(2).getAsInt()]);
|
||||
panoramic.setBoolean(camera, op.get(3).getAsBoolean());
|
||||
align.invoke(camera, pt);
|
||||
float fv = (float) fov.invoke(camera, pt);
|
||||
float hv = (float) hud.invoke(camera, pt);
|
||||
var p = camera.position();
|
||||
var q = camera.rotation();
|
||||
var fw = camera.forwardVector();
|
||||
var up = camera.upVector();
|
||||
var left = camera.leftVector();
|
||||
out.println("frame " + db(p.x) + " " + db(p.y) + " " + db(p.z) + " " + fb(camera.xRot()) + " " + fb(camera.yRot())
|
||||
+ " " + fb(q.x) + " " + fb(q.y) + " " + fb(q.z) + " " + fb(q.w)
|
||||
+ " " + fb(fw.x()) + " " + fb(fw.y()) + " " + fb(fw.z())
|
||||
+ " " + fb(up.x()) + " " + fb(up.y()) + " " + fb(up.z())
|
||||
+ " " + fb(left.x()) + " " + fb(left.y()) + " " + fb(left.z())
|
||||
+ " " + camera.isDetached() + " " + fb(fv) + " " + fb(hv));
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies an entity op: a player (with fov fields) or a non-living marker. */
|
||||
static Entity entity(JsonObject s, Entity previous) throws Exception {
|
||||
Entity entity;
|
||||
if (s.get("kind").getAsString().equals("player")) {
|
||||
StubPlayer p = previous instanceof StubPlayer old ? old : make(StubPlayer.class);
|
||||
fill(p, s);
|
||||
p.dead = !s.get("dead").isJsonNull();
|
||||
if (p.dead) {
|
||||
p.deathTime = s.get("dead").getAsInt();
|
||||
}
|
||||
p.sleeping = !s.get("sleeping").isJsonNull();
|
||||
p.bed = null;
|
||||
if (p.sleeping && !s.get("sleeping").getAsJsonArray().get(0).isJsonNull()) {
|
||||
p.bed = Direction.from2DDataValue(s.get("sleeping").getAsJsonArray().get(0).getAsInt());
|
||||
}
|
||||
var mount = s.get("mount");
|
||||
if (mount.isJsonNull()) {
|
||||
vehicle.set(p, null);
|
||||
} else {
|
||||
StubPlayer m = make(StubPlayer.class);
|
||||
var a = mount.getAsJsonArray();
|
||||
m.attributes = attributes(d(a.get(0)), d(a.get(1)), 0.1);
|
||||
vehicle.set(p, m);
|
||||
}
|
||||
entity = p;
|
||||
} else {
|
||||
entity = previous instanceof StubMarker old ? old : make(StubMarker.class);
|
||||
}
|
||||
position.set(entity, vec(s.get("pos")));
|
||||
var prev = vec(s.get("prev"));
|
||||
entity.xo = prev.x;
|
||||
entity.yo = prev.y;
|
||||
entity.zo = prev.z;
|
||||
xRot.setFloat(entity, f(s.get("xr")));
|
||||
yRot.setFloat(entity, f(s.get("yr")));
|
||||
entity.xRotO = f(s.get("xro"));
|
||||
entity.yRotO = f(s.get("yro"));
|
||||
eyeHeight.setFloat(entity, f(s.get("eye")));
|
||||
return entity;
|
||||
}
|
||||
|
||||
static void bob(JsonObject c, PrintWriter out) throws Exception {
|
||||
GameRenderer renderer = make(GameRenderer.class);
|
||||
var state = new GameRenderState();
|
||||
field(GameRenderer.class, "gameRenderState").set(renderer, state);
|
||||
state.optionsRenderState.damageTiltStrength = d(c.get("tilt"));
|
||||
state.optionsRenderState.bobView = c.get("view").getAsBoolean();
|
||||
var camera = new CameraRenderState();
|
||||
var es = camera.entityRenderState;
|
||||
var living = c.get("living");
|
||||
es.isLiving = !living.isJsonNull();
|
||||
if (es.isLiving) {
|
||||
var l = living.getAsJsonObject();
|
||||
es.hurtTime = f(l.get("hurt"));
|
||||
es.hurtDuration = l.get("duration").getAsInt();
|
||||
es.hurtDir = f(l.get("dir"));
|
||||
es.isDeadOrDying = !l.get("death").isJsonNull();
|
||||
if (es.isDeadOrDying) {
|
||||
es.deathTime = f(l.get("death"));
|
||||
}
|
||||
}
|
||||
var player = c.get("player");
|
||||
es.isPlayer = !player.isJsonNull();
|
||||
if (es.isPlayer) {
|
||||
es.backwardsInterpolatedWalkDistance = f(player.getAsJsonArray().get(0));
|
||||
es.bob = f(player.getAsJsonArray().get(1));
|
||||
}
|
||||
var stack = new PoseStack();
|
||||
method(GameRenderer.class, "bobHurt", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack);
|
||||
if (state.optionsRenderState.bobView) {
|
||||
method(GameRenderer.class, "bobView", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack);
|
||||
}
|
||||
Matrix4f m = stack.last().pose();
|
||||
var sb = new StringBuilder("bob");
|
||||
for (int col = 0; col < 4; col++) {
|
||||
for (int row = 0; row < 4; row++) {
|
||||
sb.append(' ').append(fb(m.get(col, row)));
|
||||
}
|
||||
}
|
||||
sb.append(' ').append(m.properties());
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static void avatar(JsonObject c, PrintWriter out) throws Exception {
|
||||
StubPlayer p = make(StubPlayer.class);
|
||||
var state = new ClientAvatarState();
|
||||
field(net.minecraft.client.player.AbstractClientPlayer.class, "clientAvatarState").set(p, state);
|
||||
var updateBob = method(net.minecraft.client.player.AbstractClientPlayer.class, "updateBob");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "tick" -> state.tick(Vec3.ZERO, Vec3.ZERO);
|
||||
case "move" -> state.addWalkDistance(Mth.length(f(op.get(1)), f(op.get(2))) * 0.6F);
|
||||
case "bob" -> {
|
||||
p.ground = op.get(1).getAsBoolean();
|
||||
p.dead = op.get(2).getAsBoolean();
|
||||
p.swimming = op.get(3).getAsBoolean();
|
||||
p.motion = vec(op.get(4));
|
||||
updateBob.invoke(p);
|
||||
}
|
||||
case "reset" -> state.resetBob();
|
||||
case "frame" -> {
|
||||
float pt = f(op.get(1));
|
||||
out.println("frame " + fb(state.getInterpolatedBob(pt)) + " " + fb(state.getBackwardsInterpolatedWalkDistance(pt)));
|
||||
continue;
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
out.println(op.get(0).getAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,9 +411,17 @@ public final class VanillaChunkGenerationOracle {
|
||||
var tag = target.getBlockEntityNbtForSaving(pos, registry);
|
||||
if (tag == null) continue;
|
||||
var st = target.getBlockState(pos);
|
||||
var fresh = ((net.minecraft.world.level.block.EntityBlock) st.getBlock()).newBlockEntity(pos, st).saveWithFullMetadata(registry);
|
||||
if ("DUMMY".equals(tag.getStringOr("id", ""))) tag = fresh;
|
||||
w.println("be " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\t" + canonicalOf(tag) + "\t" + canonicalOf(fresh));
|
||||
var block = (net.minecraft.world.level.block.EntityBlock) st.getBlock();
|
||||
var fresh = block.newBlockEntity(pos, st).saveWithFullMetadata(registry);
|
||||
// The value of each key Horizon leaves out: what loading a tag without
|
||||
// it gives (BrewingStandBlockEntity reads a missing total_brew_time as 400).
|
||||
var empty = block.newBlockEntity(pos, st);
|
||||
empty.loadWithComponents(net.minecraft.world.level.storage.TagValueInput.create(
|
||||
net.minecraft.util.ProblemReporter.DISCARDING, registry, new net.minecraft.nbt.CompoundTag()));
|
||||
var absent = empty.saveWithFullMetadata(registry);
|
||||
// A DUMMY pending entry becomes a fresh block entity, not a loaded one.
|
||||
if ("DUMMY".equals(tag.getStringOr("id", ""))) tag = absent = fresh;
|
||||
w.println("be " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\t" + canonicalOf(tag) + "\t" + canonicalOf(absent));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.brigadier.tree.ArgumentCommandNode;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
|
||||
/**
|
||||
* Lists the argument nodes of vanilla's full command tree (Commands with
|
||||
* CommandSelection.ALL, the tree the commands report shows) that carry a
|
||||
* custom suggestion provider, with the provider's network name
|
||||
* (SuggestionProviders.getName: ask_server unless it is one of the named
|
||||
* client-side providers). ClientboundCommandsPacket sends that name; the
|
||||
* report does not include it. One line per node: the path of node names
|
||||
* from the root, space separated, a tab, the provider id.
|
||||
*/
|
||||
public final class VanillaCommandSuggestionsExporter {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
Commands commands = new Commands(Commands.CommandSelection.ALL, Commands.createValidationContext(ParityData.lookup));
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) {
|
||||
walk(commands.getDispatcher().getRoot(), "", out);
|
||||
}
|
||||
}
|
||||
|
||||
static void walk(CommandNode<CommandSourceStack> node, String path, PrintWriter out) {
|
||||
for (CommandNode<CommandSourceStack> child : node.getChildren()) {
|
||||
String childPath = path.isEmpty() ? child.getName() : path + " " + child.getName();
|
||||
if (child instanceof ArgumentCommandNode<CommandSourceStack, ?> arg && arg.getCustomSuggestions() != null) {
|
||||
out.println(childPath + "\t" + SuggestionProviders.getName(arg.getCustomSuggestions()));
|
||||
}
|
||||
walk(child, childPath, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.ReloadableServerRegistries;
|
||||
import net.minecraft.server.ReloadableServerResources;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
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.util.RandomSource;
|
||||
import net.minecraft.world.DifficultyInstance;
|
||||
import net.minecraft.world.RandomSequences;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.damagesource.DamageSources;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.DyeColor;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.entity.EntityTypeTest;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldOptions;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
|
||||
/**
|
||||
* Original oracle: entity death drops. Each input line describes a victim, its
|
||||
* equipment and state, a killer and a damage source; the oracle creates the
|
||||
* real entities on a stand-in ServerLevel (whose addFreshEntity records the
|
||||
* spawned item entities and experience orbs) and runs LivingEntity.die's drop
|
||||
* step: the source entity's killedEntity hook, then dropAllDeathLoot (loot
|
||||
* table with the world's random sequence, dropCustomDeathLoot with the entity
|
||||
* random, dropEquipment, dropExperience). Loot table randoms come from a fresh
|
||||
* RandomSequences per case; each case kills `kills` identical victims in turn.
|
||||
*/
|
||||
public final class VanillaEntityDeathLootOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate, putObject, objectFieldOffset;
|
||||
|
||||
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
|
||||
|
||||
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
long offset = (long) objectFieldOffset.invoke(unsafe, f);
|
||||
putObject.invoke(unsafe, target, offset, value);
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
MinecraftServer fake;
|
||||
RegistryAccess registries;
|
||||
GameRules rules;
|
||||
List<String> out;
|
||||
int next = 1;
|
||||
@Override public MinecraftServer getServer() { return fake; }
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public GameRules getGameRules() { return rules; }
|
||||
@Override public boolean addFreshEntity(Entity entity) {
|
||||
if (entity instanceof ItemEntity item) out.add("drop " + stack(item.getItem()));
|
||||
else if (entity instanceof ExperienceOrb orb) out.add("orb " + orb.getValue());
|
||||
else out.add("entity " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()));
|
||||
return true;
|
||||
}
|
||||
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) { return new ArrayList<>(); }
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public int getSeaLevel() { return 63; }
|
||||
@Override public net.minecraft.world.entity.raid.Raid getRaidAt(BlockPos pos) { return null; }
|
||||
@Override public net.minecraft.world.level.BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return null; }
|
||||
@Override public List<net.minecraft.world.phys.shapes.VoxelShape> getEntityCollisions(Entity source, AABB area) { return List.of(); }
|
||||
@Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); }
|
||||
}
|
||||
|
||||
static final class OraclePlayer extends Player {
|
||||
OraclePlayer(Level level) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); }
|
||||
@Override public GameType gameMode() { return GameType.SURVIVAL; }
|
||||
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); }
|
||||
}
|
||||
|
||||
static String stack(ItemStack stack) {
|
||||
StringBuilder line = new StringBuilder(BuiltInRegistries.ITEM.getKey(stack.getItem()) + " " + stack.getCount());
|
||||
if (stack.getDamageValue() != 0) line.append(" damage=").append(stack.getDamageValue());
|
||||
var enchantments = stack.getOrDefault(DataComponents.ENCHANTMENTS, net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY);
|
||||
for (var e : enchantments.entrySet()) line.append(" ench=").append(e.getKey().unwrapKey().get().identifier()).append(':').append(e.getIntValue());
|
||||
var potion = stack.get(DataComponents.POTION_CONTENTS);
|
||||
if (potion != null && potion.potion().isPresent()) line.append(" potion=").append(potion.potion().get().unwrapKey().get().identifier());
|
||||
var ominous = stack.get(DataComponents.OMINOUS_BOTTLE_AMPLIFIER);
|
||||
if (ominous != null) line.append(" ominous=").append(ominous.value());
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
static Map<String, String> parse(String line) {
|
||||
Map<String, String> m = new LinkedHashMap<>();
|
||||
for (String token : line.trim().split("\\s+")) {
|
||||
int eq = token.indexOf('=');
|
||||
if (eq < 0) m.put("name", token); else m.put(token.substring(0, eq), token.substring(eq + 1));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
|
||||
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
|
||||
|
||||
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();
|
||||
HolderLookup.Provider 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);
|
||||
RegistryAccess access = loaded.layers().compositeAccess();
|
||||
|
||||
// A server that only answers reloadableRegistries, getRandomSequence and debug subscribers.
|
||||
MinecraftServer server = (MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
put(server, MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
ReloadableServerResources managers = (ReloadableServerResources) alloc(ReloadableServerResources.class);
|
||||
put(managers, ReloadableServerResources.class, "fullRegistryHolder", new ReloadableServerRegistries.Holder(lookup));
|
||||
Class<?> holderRecord = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources");
|
||||
Constructor<?> rr = holderRecord.getDeclaredConstructors()[0];
|
||||
rr.setAccessible(true);
|
||||
put(server, MinecraftServer.class, "resources", rr.newInstance(null, managers));
|
||||
var recipes = new net.minecraft.world.item.crafting.RecipeManager(lookup);
|
||||
recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
put(managers, ReloadableServerResources.class, "recipes", recipes);
|
||||
put(server, MinecraftServer.class, "scoreboard", new net.minecraft.server.ServerScoreboard(server));
|
||||
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
level.registries = access;
|
||||
put(level, ServerLevel.class, "server", server);
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
|
||||
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
put(level, Level.class, "damageSources", new DamageSources(access));
|
||||
put(level, Level.class, "random", RandomSource.create(0L));
|
||||
Method dropAll = LivingEntity.class.getDeclaredMethod("dropAllDeathLoot", ServerLevel.class, DamageSource.class);
|
||||
dropAll.setAccessible(true);
|
||||
var enchantments = access.lookupOrThrow(Registries.ENCHANTMENT);
|
||||
|
||||
if (args.length > 2 && args[2].equals("facts")) {
|
||||
// Per-type facts the death step reads (a debugging aid, not compared).
|
||||
Field xp = Mob.class.getDeclaredField("xpReward");
|
||||
xp.setAccessible(true);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE) {
|
||||
Entity e;
|
||||
try { e = type.create(level, EntitySpawnReason.LOAD); } catch (Throwable t) { continue; }
|
||||
if (!(e instanceof Mob mob)) continue;
|
||||
StringBuilder sb = new StringBuilder(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString());
|
||||
sb.append(" monster=").append(e instanceof net.minecraft.world.entity.monster.Monster).append(" xp=").append(xp.get(mob))
|
||||
.append(" baby=").append(mob.isBaby()).append(" class=").append(e.getClass().getSimpleName())
|
||||
.append(" animal=").append(e instanceof net.minecraft.world.entity.animal.Animal)
|
||||
.append(" agwater=").append(e instanceof net.minecraft.world.entity.animal.AgeableWaterCreature)
|
||||
.append(" water=").append(e instanceof net.minecraft.world.entity.animal.fish.WaterAnimal)
|
||||
.append(" ageable=").append(e instanceof AgeableMob);
|
||||
mob.setBaby(true);
|
||||
sb.append(" canbaby=").append(mob.isBaby());
|
||||
for (EquipmentSlot slot : EquipmentSlot.VALUES) if (mob.getDropChances().byEquipment(slot) != 0.085F) sb.append(' ').append(slot.getName()).append('=').append(mob.getDropChances().byEquipment(slot));
|
||||
w.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String raw : lines) {
|
||||
if (raw.isBlank() || raw.startsWith("#")) continue;
|
||||
Map<String, String> c = parse(raw);
|
||||
w.println("== " + c.get("name"));
|
||||
List<String> out = new ArrayList<>();
|
||||
level.out = out;
|
||||
try {
|
||||
long worldSeed = Long.parseLong(c.getOrDefault("seed", "0"));
|
||||
put(server, MinecraftServer.class, "worldGenSettings", new WorldGenSettings(new WorldOptions(worldSeed, false, false), null));
|
||||
put(server, MinecraftServer.class, "randomSequences", new RandomSequences());
|
||||
int kills = Integer.parseInt(c.getOrDefault("kills", "1"));
|
||||
long rand = Long.parseLong(c.getOrDefault("rand", "0"));
|
||||
for (int k = 0; k < kills; k++) {
|
||||
out.add("kill " + k);
|
||||
run(level, access, enchantments, c, rand + k, dropAll);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t;
|
||||
StringBuilder trace = new StringBuilder("error " + cause);
|
||||
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) trace.append("\n at ").append(frame);
|
||||
out.add(trace.toString());
|
||||
}
|
||||
out.forEach(w::println);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static ItemStack item(HolderLookup.RegistryLookup<net.minecraft.world.item.enchantment.Enchantment> enchantments, String spec) {
|
||||
// id[;enchantment:level...]
|
||||
String[] parts = spec.split(";");
|
||||
ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(parts[0])));
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
int colon = parts[i].lastIndexOf(':');
|
||||
String name = parts[i].substring(0, colon);
|
||||
if (!name.contains(":")) name = "minecraft:" + name;
|
||||
stack.enchant(enchantments.getOrThrow(ResourceKey.create(Registries.ENCHANTMENT, Identifier.parse(name))), Integer.parseInt(parts[i].substring(colon + 1)));
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
static Entity create(Lvl level, String id) {
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(id));
|
||||
return type.create(level, EntitySpawnReason.LOAD);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static void run(Lvl level, RegistryAccess access, HolderLookup.RegistryLookup<net.minecraft.world.item.enchantment.Enchantment> enchantments,
|
||||
Map<String, String> c, long rand, Method dropAll) throws Exception {
|
||||
LivingEntity victim = (LivingEntity) create(level, c.get("type"));
|
||||
victim.setPos(0.5, 64.0, 0.5);
|
||||
if (c.containsKey("baby") && victim instanceof Mob mob) mob.setBaby(c.get("baby").equals("1"));
|
||||
if (c.getOrDefault("fire", "0").equals("1")) victim.setRemainingFireTicks(100);
|
||||
if (c.containsKey("size")) victim.getClass().getMethod("setSize", int.class, boolean.class).invoke(victim, Integer.parseInt(c.get("size")), true);
|
||||
if (c.containsKey("color") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setColor(DyeColor.byName(c.get("color"), DyeColor.WHITE));
|
||||
if (c.getOrDefault("sheared", "0").equals("1") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true);
|
||||
if (c.getOrDefault("leader", "0").equals("1")) ((net.minecraft.world.entity.monster.PatrollingMonster) victim).setPatrolLeader(true);
|
||||
if (c.getOrDefault("captain", "0").equals("1"))
|
||||
victim.setItemSlot(EquipmentSlot.HEAD, net.minecraft.world.entity.raid.Raid.getOminousBannerInstance(access.lookupOrThrow(Registries.BANNER_PATTERN)));
|
||||
for (EquipmentSlot slot : EquipmentSlot.VALUES) {
|
||||
String spec = c.get(slot.getName());
|
||||
if (spec != null) victim.setItemSlot(slot, item(enchantments, spec));
|
||||
String chance = c.get("chance_" + slot.getName());
|
||||
if (chance != null && victim instanceof Mob mob) mob.setDropChance(slot, Float.parseFloat(chance));
|
||||
}
|
||||
if (c.containsKey("vehicle")) {
|
||||
Entity vehicle = create(level, c.get("vehicle"));
|
||||
vehicle.setPos(0.5, 64.0, 0.5);
|
||||
if (!victim.startRiding(vehicle, true, false)) throw new IllegalStateException("could not ride");
|
||||
}
|
||||
// Killer and damage source.
|
||||
Player player = null;
|
||||
LivingEntity killer = null;
|
||||
String killerId = c.getOrDefault("killer", "none");
|
||||
if (killerId.equals("player") || c.getOrDefault("pkill", "0").equals("1")) {
|
||||
player = new OraclePlayer(level);
|
||||
player.setPos(2.5, 64.0, 0.5);
|
||||
if (c.containsKey("luck")) player.getAttribute(Attributes.LUCK).setBaseValue(Double.parseDouble(c.get("luck")));
|
||||
if (killerId.equals("player") && c.containsKey("weapon")) player.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon")));
|
||||
}
|
||||
if (killerId.equals("player")) killer = player;
|
||||
else if (!killerId.equals("none")) {
|
||||
killer = (LivingEntity) create(level, killerId);
|
||||
killer.setPos(2.5, 64.0, 0.5);
|
||||
if (c.containsKey("weapon")) killer.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon")));
|
||||
if (c.containsKey("frog")) killer.setComponent(DataComponents.FROG_VARIANT,
|
||||
access.lookupOrThrow(Registries.FROG_VARIANT).getOrThrow(ResourceKey.create(Registries.FROG_VARIANT, Identifier.parse(c.get("frog")))));
|
||||
if (c.getOrDefault("charged", "0").equals("1")) {
|
||||
Field powered = net.minecraft.world.entity.monster.Creeper.class.getDeclaredField("DATA_IS_POWERED");
|
||||
powered.setAccessible(true);
|
||||
killer.getEntityData().set((net.minecraft.network.syncher.EntityDataAccessor<Boolean>) powered.get(null), true);
|
||||
}
|
||||
}
|
||||
if (player != null && c.getOrDefault("pkill", killerId.equals("player") ? "1" : "0").equals("1")) victim.setLastHurtByPlayer(player, 100);
|
||||
DamageSources sources = level.damageSources();
|
||||
DamageSource source = switch (c.getOrDefault("source", "attack")) {
|
||||
case "attack" -> killer == null ? sources.generic() : killer instanceof Player p ? sources.playerAttack(p) : sources.mobAttack(killer);
|
||||
case "arrow" -> {
|
||||
var arrow = new net.minecraft.world.entity.projectile.arrow.Arrow(EntityTypes.ARROW, level);
|
||||
arrow.setPos(1.5, 64.0, 0.5);
|
||||
yield sources.arrow(arrow, killer);
|
||||
}
|
||||
case "fireball" -> {
|
||||
var fireball = new net.minecraft.world.entity.projectile.hurtingprojectile.LargeFireball(EntityTypes.FIREBALL, level);
|
||||
fireball.setPos(1.5, 64.0, 0.5);
|
||||
yield sources.fireball(fireball, killer);
|
||||
}
|
||||
case "explosion" -> sources.explosion(killer, killer);
|
||||
case "lightning" -> sources.lightningBolt();
|
||||
case "fire" -> sources.onFire();
|
||||
default -> sources.generic();
|
||||
};
|
||||
victim.getRandom().setSeed(rand);
|
||||
Entity sourceEntity = source.getEntity();
|
||||
if (sourceEntity == null || sourceEntity.killedEntity(level, victim, source)) dropAll.invoke(victim, level, source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.classfile.*;
|
||||
import java.lang.classfile.instruction.InvokeInstruction;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Runs the real FramerateLimiter.limitDisplayFPS from the client jar with its
|
||||
* clock calls (System.nanoTime, LockSupport.parkNanos, Thread.interrupted,
|
||||
* Thread.onSpinWait) redirected by a ClassFile rewrite to a scripted virtual
|
||||
* clock, and the Minecraft.runTick condition (limits below 260), printing the
|
||||
* limiter state and clock interaction of every frame.
|
||||
*/
|
||||
public final class VanillaFrameLimiterOracle {
|
||||
/** The scripted clock the rewritten limiter calls. */
|
||||
public static final class Clock {
|
||||
static long now, call, spin;
|
||||
static long[] overshoot;
|
||||
static int nextOvershoot;
|
||||
static boolean[] interrupts;
|
||||
static int nextInterrupt;
|
||||
static List<Long> parks = new ArrayList<>();
|
||||
static long spins, queries;
|
||||
|
||||
public static long nanoTime() {
|
||||
queries++;
|
||||
long t = now;
|
||||
now += call;
|
||||
return t;
|
||||
}
|
||||
|
||||
public static void parkNanos(long nanos) {
|
||||
parks.add(nanos);
|
||||
long o = overshoot[nextOvershoot++ % overshoot.length];
|
||||
now += Math.max(Math.max(nanos, 0) + o, 1);
|
||||
}
|
||||
|
||||
public static void onSpinWait() {
|
||||
spins++;
|
||||
now += spin;
|
||||
}
|
||||
|
||||
public static boolean interrupted() {
|
||||
return interrupts[nextInterrupt++ % interrupts.length];
|
||||
}
|
||||
}
|
||||
|
||||
static final ClassDesc CLOCK = ClassDesc.of(Clock.class.getName());
|
||||
|
||||
/** Loads FramerateLimiter itself, rewritten; everything else from the parent. */
|
||||
static final class Rewriting extends ClassLoader {
|
||||
Rewriting(ClassLoader parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
if (!name.equals("net.minecraft.client.FramerateLimiter")) {
|
||||
return super.loadClass(name, resolve);
|
||||
}
|
||||
synchronized (getClassLoadingLock(name)) {
|
||||
Class<?> loaded = findLoadedClass(name);
|
||||
if (loaded == null) {
|
||||
try (var in = getParent().getResourceAsStream("net/minecraft/client/FramerateLimiter.class")) {
|
||||
byte[] bytes = rewrite(in.readAllBytes());
|
||||
loaded = defineClass(name, bytes, 0, bytes.length);
|
||||
} catch (IOException e) {
|
||||
throw new ClassNotFoundException(name, e);
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int rewrites;
|
||||
|
||||
static byte[] rewrite(byte[] bytes) {
|
||||
var cf = ClassFile.of();
|
||||
ClassModel model = cf.parse(bytes);
|
||||
return cf.transformClass(model, ClassTransform.transformingMethodBodies((builder, element) -> {
|
||||
if (element instanceof InvokeInstruction call && call.opcode() == Opcode.INVOKESTATIC) {
|
||||
String owner = call.owner().asInternalName();
|
||||
String name = call.name().stringValue();
|
||||
String target = switch (owner + "." + name) {
|
||||
case "java/lang/System.nanoTime" -> "nanoTime";
|
||||
case "java/util/concurrent/locks/LockSupport.parkNanos" -> "parkNanos";
|
||||
case "java/lang/Thread.interrupted" -> "interrupted";
|
||||
case "java/lang/Thread.onSpinWait" -> "onSpinWait";
|
||||
default -> null;
|
||||
};
|
||||
if (target != null) {
|
||||
rewrites++;
|
||||
builder.invokestatic(CLOCK, target, MethodTypeDesc.ofDescriptor(call.type().stringValue()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
builder.with(element);
|
||||
}));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Clock.overshoot = new long[] {0};
|
||||
Clock.interrupts = new boolean[] {false};
|
||||
Class<?> limiter = Class.forName("net.minecraft.client.FramerateLimiter", true,
|
||||
new Rewriting(VanillaFrameLimiterOracle.class.getClassLoader()));
|
||||
// System.nanoTime x4 (and once in the static initialiser), parkNanos, interrupted, onSpinWait.
|
||||
if (rewrites != 8) {
|
||||
throw new AssertionError("unexpected clock calls in FramerateLimiter: " + rewrites);
|
||||
}
|
||||
Method limit = limiter.getMethod("limitDisplayFPS", int.class);
|
||||
Field last = limiter.getDeclaredField("lastFrameTime");
|
||||
Field average = limiter.getDeclaredField("averageOvershootNs");
|
||||
Field lastLimit = limiter.getDeclaredField("lastFramerateLimit");
|
||||
for (Field f : List.of(last, average, lastLimit)) {
|
||||
f.setAccessible(true);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
Clock.now = c.get("now").getAsLong();
|
||||
Clock.call = c.get("call").getAsLong();
|
||||
Clock.spin = c.get("spin").getAsLong();
|
||||
var o = c.getAsJsonArray("overshoot");
|
||||
Clock.overshoot = new long[o.size()];
|
||||
for (int i = 0; i < o.size(); i++) {
|
||||
Clock.overshoot[i] = o.get(i).getAsLong();
|
||||
}
|
||||
var in = c.getAsJsonArray("interrupts");
|
||||
Clock.interrupts = new boolean[in.size()];
|
||||
for (int i = 0; i < in.size(); i++) {
|
||||
Clock.interrupts[i] = in.get(i).getAsBoolean();
|
||||
}
|
||||
Clock.nextOvershoot = 0;
|
||||
Clock.nextInterrupt = 0;
|
||||
last.setLong(null, c.get("last").getAsLong());
|
||||
average.setLong(null, c.get("average").getAsLong());
|
||||
lastLimit.setInt(null, c.get("last_limit").getAsInt());
|
||||
for (var e : c.getAsJsonArray("frames")) {
|
||||
var frame = e.getAsJsonArray();
|
||||
Clock.now += frame.get(0).getAsLong();
|
||||
Clock.parks.clear();
|
||||
Clock.spins = 0;
|
||||
Clock.queries = 0;
|
||||
int framerateLimit = frame.get(1).getAsInt();
|
||||
// Minecraft.runTick: "if (framerateLimit < 260) FramerateLimiter.limitDisplayFPS(framerateLimit)".
|
||||
if (framerateLimit < 260) {
|
||||
limit.invoke(null, framerateLimit);
|
||||
}
|
||||
var parks = new StringJoiner(",");
|
||||
for (long p : Clock.parks) {
|
||||
parks.add(Long.toString(p));
|
||||
}
|
||||
out.println("frame " + Clock.now + " " + last.getLong(null) + " " + average.getLong(null) + " "
|
||||
+ lastLimit.getInt(null) + " queries " + Clock.queries + " spins " + Clock.spins + " parks [" + parks + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.AttackIndicatorStatus;
|
||||
import net.minecraft.client.DeltaTracker;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.OptionInstance;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.Hud;
|
||||
import net.minecraft.client.gui.contextualbar.ExperienceBar;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.tags.FluidTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityEquipment;
|
||||
import net.minecraft.world.entity.HumanoidArm;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.food.FoodData;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import org.joml.Matrix3x2f;
|
||||
import org.joml.Matrix3x2fStack;
|
||||
|
||||
/**
|
||||
* Original oracle for the in-game HUD decorations: runs vanilla's own Hud
|
||||
* methods (extractItemHotbar, extractPlayerHealth, extractVehicleHealth,
|
||||
* extractCrosshair) and ExperienceBar / ContextualBar on a stand-in client
|
||||
* (Unsafe-allocated Minecraft, options, game mode, window and level) and a
|
||||
* player whose state getters answer from the case, and records every
|
||||
* GuiGraphicsExtractor blit, text and item call.
|
||||
*
|
||||
* Input lines: case JSON. Output lines: {case, draws:[...]} or {case, error}.
|
||||
*/
|
||||
public final class VanillaHudOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
static JsonObject c;
|
||||
static IdentityHashMap<ItemStack, Integer> slots = new IdentityHashMap<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T alloc(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws NoSuchFieldException {
|
||||
for (Class<?> k = type; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Field f = k.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
} catch (NoSuchFieldException e) {
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name + " on " + type);
|
||||
}
|
||||
|
||||
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
Field f = field(owner, name);
|
||||
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
|
||||
Class<?> t = f.getType();
|
||||
String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject";
|
||||
Class<?> param = t.isPrimitive() ? t : Object.class;
|
||||
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
|
||||
}
|
||||
|
||||
static float f(String k, float d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsFloat() : d; }
|
||||
static int i(String k, int d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsInt() : d; }
|
||||
static boolean b(String k) { return c.has(k) && c.get(k).getAsBoolean(); }
|
||||
|
||||
/** A player whose HUD-facing getters answer from the case. */
|
||||
public static final class Actor extends LocalPlayer {
|
||||
Level level;
|
||||
Entity vehicle;
|
||||
FoodData food;
|
||||
ItemStack offhand = ItemStack.EMPTY;
|
||||
private Actor() { super(null, null, null, null, null, null, false, null, null); }
|
||||
@Override public float getHealth() { return f("health", 20); }
|
||||
@Override public double getAttributeValue(Holder<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("maxHealth", 20) : 0.0; }
|
||||
@Override public float getAbsorptionAmount() { return f("absorption", 0); }
|
||||
@Override public int getArmorValue() { return i("armor", 0); }
|
||||
@Override public FoodData getFoodData() { return food; }
|
||||
@Override public boolean hasEffect(Holder<MobEffect> effect) {
|
||||
for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true;
|
||||
return false;
|
||||
}
|
||||
@Override public boolean isFullyFrozen() { return b("frozen"); }
|
||||
@Override public int getAirSupply() { return i("air", 300); }
|
||||
@Override public int getMaxAirSupply() { return i("maxAir", 300); }
|
||||
@Override public boolean isEyeInFluid(TagKey<Fluid> tag) { return tag == FluidTags.WATER && b("underWater"); }
|
||||
@Override public Entity getVehicle() { return vehicle; }
|
||||
@Override public ItemStack getOffhandItem() { return offhand; }
|
||||
@Override public HumanoidArm getMainArm() { return b("rightHanded") ? HumanoidArm.RIGHT : HumanoidArm.LEFT; }
|
||||
@Override public float getAttackStrengthScale(float a) { return f("attackScale", 1); }
|
||||
@Override public Level level() { return level; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
@Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { }
|
||||
}
|
||||
|
||||
/** A ridden mount answering health from the case. */
|
||||
public static final class Mount extends net.minecraft.world.entity.animal.equine.Horse {
|
||||
private Mount() { super(null, null); }
|
||||
@Override public float getHealth() { return f("vehicleHealth", 0); }
|
||||
@Override public double getAttributeValue(Holder<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("vehicleMaxHealth", 0) : 0.0; }
|
||||
@Override public boolean showVehicleHealth() { return true; }
|
||||
}
|
||||
|
||||
/** Records GuiGraphicsExtractor calls. */
|
||||
public static final class Capture extends GuiGraphicsExtractor {
|
||||
JsonArray draws;
|
||||
Matrix3x2fStack stack;
|
||||
private Capture() { super(null, null, 0, 0); }
|
||||
@Override public int guiWidth() { return i("width", 0); }
|
||||
@Override public int guiHeight() { return i("height", 0); }
|
||||
@Override public Matrix3x2fStack pose() { return stack; }
|
||||
@Override public void nextStratum() { }
|
||||
void sprite(Identifier id, int x, int y, int w, int h, int[] region, int color) {
|
||||
var o = new JsonObject();
|
||||
o.addProperty("type", "sprite");
|
||||
o.addProperty("sprite", id.getPath());
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
|
||||
if (region != null) {
|
||||
var r = new JsonArray();
|
||||
for (int v : region) r.add(v);
|
||||
o.add("region", r);
|
||||
}
|
||||
o.addProperty("color", color);
|
||||
draws.add(o);
|
||||
}
|
||||
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(id, x, y, w, h, null, color); }
|
||||
@Override public void blitSprite(RenderPipeline p, Identifier id, int sw, int sh, int u, int v, int x, int y, int w, int h, int color) {
|
||||
sprite(id, x, y, w, h, new int[] {sw, sh, u, v}, color);
|
||||
}
|
||||
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
|
||||
var o = new JsonObject();
|
||||
o.addProperty("type", "text");
|
||||
var sb = new StringBuilder();
|
||||
str.accept((index, style, cp) -> { sb.appendCodePoint(cp); return true; });
|
||||
o.addProperty("text", sb.toString());
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
|
||||
draws.add(o);
|
||||
}
|
||||
@Override public void item(LivingEntity owner, ItemStack stack, int x, int y, int seed) {
|
||||
var o = new JsonObject();
|
||||
o.addProperty("type", "item");
|
||||
o.addProperty("slot", slots.getOrDefault(stack, -1));
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("seed", seed);
|
||||
var m = new Matrix3x2f(stack.isEmpty() ? new Matrix3x2f() : this.stack);
|
||||
var a = new JsonArray();
|
||||
for (float v : new float[] {m.m00, m.m01, m.m10, m.m11, m.m20, m.m21}) a.add(v);
|
||||
o.add("matrix", a);
|
||||
draws.add(o);
|
||||
}
|
||||
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) { }
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
Font font = ParityFont.create(ParityFont.resources());
|
||||
Method hotbar = Hud.class.getDeclaredMethod("extractItemHotbar", GuiGraphicsExtractor.class, DeltaTracker.class);
|
||||
Method health = Hud.class.getDeclaredMethod("extractPlayerHealth", GuiGraphicsExtractor.class);
|
||||
Method vehicle = Hud.class.getDeclaredMethod("extractVehicleHealth", GuiGraphicsExtractor.class);
|
||||
Method crosshair = Hud.class.getDeclaredMethod("extractCrosshair", GuiGraphicsExtractor.class, DeltaTracker.class);
|
||||
crosshair.setAccessible(true);
|
||||
for (Method m : new Method[] {hotbar, health, vehicle}) m.setAccessible(true);
|
||||
Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar")
|
||||
.getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class);
|
||||
level.setAccessible(true);
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
if (line.isBlank()) continue;
|
||||
c = JsonParser.parseString(line).getAsJsonObject();
|
||||
var result = new JsonObject();
|
||||
result.add("case", c);
|
||||
try {
|
||||
slots.clear();
|
||||
var mc = alloc(Minecraft.class);
|
||||
var actor = alloc(Actor.class);
|
||||
var clientLevel = alloc(ClientLevel.class);
|
||||
var levelData = alloc(ClientLevel.ClientLevelData.class);
|
||||
put(levelData, ClientLevel.ClientLevelData.class, "hardcore", b("hardcore"));
|
||||
put(clientLevel, ClientLevel.class, "clientLevelData", levelData);
|
||||
actor.level = clientLevel;
|
||||
actor.offhand = ItemStack.EMPTY;
|
||||
actor.food = new FoodData();
|
||||
actor.food.setFoodLevel(i("food", 20));
|
||||
actor.food.setSaturation(f("saturation", 5));
|
||||
actor.damageCooldownTime = i("damageCooldown", 0);
|
||||
actor.experienceProgress = f("xpProgress", 0);
|
||||
actor.experienceLevel = i("xpLevel", 0);
|
||||
var inventory = new Inventory(actor, new EntityEquipment());
|
||||
put(actor, net.minecraft.world.entity.player.Player.class, "inventory", inventory);
|
||||
inventory.setSelectedSlot(i("selected", 0));
|
||||
var stacks = c.getAsJsonArray("slots");
|
||||
var items = new net.minecraft.world.item.Item[] {Items.STONE, Items.DIAMOND_SWORD, Items.APPLE, Items.TORCH, Items.BOW,
|
||||
Items.OAK_LOG, Items.BREAD, Items.SHIELD, Items.COMPASS};
|
||||
for (int n = 0; n < 9; n++) {
|
||||
if (stacks.get(n).isJsonNull()) continue;
|
||||
var stack = new ItemStack(items[n]);
|
||||
stack.setPopTime(stacks.get(n).getAsInt());
|
||||
inventory.setItem(n, stack);
|
||||
slots.put(stack, n);
|
||||
}
|
||||
if (c.has("offhand") && !c.get("offhand").isJsonNull()) {
|
||||
actor.offhand = new ItemStack(Items.TOTEM_OF_UNDYING);
|
||||
actor.offhand.setPopTime(c.get("offhand").getAsInt());
|
||||
slots.put(actor.offhand, 40);
|
||||
}
|
||||
if (c.has("vehicleMaxHealth")) actor.vehicle = alloc(Mount.class);
|
||||
put(mc, Minecraft.class, "player", actor);
|
||||
var camera = alloc(net.minecraft.client.Camera.class);
|
||||
put(camera, net.minecraft.client.Camera.class, "entity", actor);
|
||||
var renderer = alloc(net.minecraft.client.renderer.GameRenderer.class);
|
||||
put(renderer, net.minecraft.client.renderer.GameRenderer.class, "mainCamera", camera);
|
||||
put(mc, Minecraft.class, "gameRenderer", renderer);
|
||||
put(mc, Minecraft.class, "font", font);
|
||||
var gameMode = alloc(MultiPlayerGameMode.class);
|
||||
put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.get("gameMode").getAsString()));
|
||||
put(mc, Minecraft.class, "gameMode", gameMode);
|
||||
var options = alloc(Options.class);
|
||||
var indicator = alloc(OptionInstance.class);
|
||||
put(indicator, OptionInstance.class, "value", AttackIndicatorStatus.valueOf(c.get("attackIndicator").getAsString()));
|
||||
put(options, Options.class, "attackIndicator", indicator);
|
||||
put(mc, Minecraft.class, "options", options);
|
||||
var window = alloc(com.mojang.blaze3d.platform.Window.class);
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", i("width", 0));
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", i("height", 0));
|
||||
put(mc, Minecraft.class, "window", window);
|
||||
var hud = alloc(Hud.class);
|
||||
put(hud, Hud.class, "minecraft", mc);
|
||||
put(hud, Hud.class, "random", net.minecraft.util.RandomSource.create());
|
||||
put(hud, Hud.class, "tickCount", i("tick", 0));
|
||||
put(hud, Hud.class, "lastHealth", i("lastHealth", 0));
|
||||
put(hud, Hud.class, "displayHealth", i("displayHealth", 0));
|
||||
put(hud, Hud.class, "lastHealthTime", Util.getMillis() - (long) i("lastHealthAgo", 0));
|
||||
put(hud, Hud.class, "healthBlinkTime", (long) i("healthBlinkTime", 0));
|
||||
var capture = alloc(Capture.class);
|
||||
capture.draws = new JsonArray();
|
||||
capture.stack = new Matrix3x2fStack(16);
|
||||
float partial = f("partial", 0);
|
||||
DeltaTracker delta = (DeltaTracker) Proxy.newProxyInstance(DeltaTracker.class.getClassLoader(), new Class<?>[] {DeltaTracker.class},
|
||||
(proxy, method, a) -> method.getReturnType() == float.class ? partial : null);
|
||||
var mode = GameType.byName(c.get("gameMode").getAsString());
|
||||
if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) {
|
||||
put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON);
|
||||
var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class);
|
||||
put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList<Identifier>());
|
||||
put(mc, Minecraft.class, "debugEntries", debug);
|
||||
crosshair.invoke(hud, capture, delta);
|
||||
}
|
||||
if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta);
|
||||
if (mode.isSurvival()) health.invoke(hud, capture);
|
||||
vehicle.invoke(hud, capture);
|
||||
if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta);
|
||||
if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel);
|
||||
result.add("draws", capture.draws);
|
||||
} catch (Throwable error) {
|
||||
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result.addProperty("error", sw.toString().lines().limit(8).reduce("", (x, y) -> x + y + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,11 @@ public final class VanillaItemModelOracle {
|
||||
static TextureAtlasSprite load(Identifier id, Identifier atlas) {
|
||||
try {
|
||||
var png = root.resolve("assets").resolve(id.getNamespace()).resolve("textures").resolve(id.getPath() + ".png");
|
||||
if (!Files.isRegularFile(png)) return null;
|
||||
if (!Files.isRegularFile(png)) {
|
||||
// Armour trim textures come from the atlas's paletted_permutations source.
|
||||
var generated = generatedSprites(atlas).get(id);
|
||||
return generated == null ? null : new Sprite(atlas, generated.get(null));
|
||||
}
|
||||
NativeImage image;
|
||||
try (var in = Files.newInputStream(png)) { image = NativeImage.read(in); }
|
||||
var mcmeta = png.resolveSibling(png.getFileName() + ".mcmeta");
|
||||
@@ -100,6 +104,40 @@ public final class VanillaItemModelOracle {
|
||||
} catch (IOException e) { throw new UncheckedIOException(e); }
|
||||
}
|
||||
|
||||
static final Map<Identifier, Map<Identifier, net.minecraft.client.renderer.texture.atlas.SpriteSource.DiscardableLoader>> GENERATED = new HashMap<>();
|
||||
/** The atlas's paletted_permutations sprites, run by vanilla's own source over the extracted resources. */
|
||||
static Map<Identifier, net.minecraft.client.renderer.texture.atlas.SpriteSource.DiscardableLoader> generatedSprites(Identifier atlas) {
|
||||
return GENERATED.computeIfAbsent(atlas, a -> {
|
||||
Map<Identifier, net.minecraft.client.renderer.texture.atlas.SpriteSource.DiscardableLoader> out = new HashMap<>();
|
||||
var file = "/assets/" + a.getNamespace() + "/atlases/" + a.getPath().replaceFirst("^textures/atlas/", "").replaceFirst("\\.png$", "") + ".json";
|
||||
try (var in = VanillaItemModelOracle.class.getResourceAsStream(file)) {
|
||||
if (in == null) return out;
|
||||
var json = JsonParser.parseString(new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8));
|
||||
var sources = net.minecraft.client.renderer.texture.atlas.SpriteSources.FILE_CODEC.parse(JsonOps.INSTANCE, json).getOrThrow();
|
||||
var output = new net.minecraft.client.renderer.texture.atlas.SpriteSource.Output() {
|
||||
@Override public void add(Identifier id, net.minecraft.client.renderer.texture.atlas.SpriteSource.DiscardableLoader sprite) { out.put(id, sprite); }
|
||||
@Override public void removeAll(java.util.function.Predicate<Identifier> predicate) { out.keySet().removeIf(predicate); }
|
||||
};
|
||||
for (var source : sources)
|
||||
if (source instanceof net.minecraft.client.renderer.texture.atlas.sources.PalettedPermutations) source.run(FILES, output);
|
||||
} catch (IOException e) { throw new UncheckedIOException(e); }
|
||||
return out;
|
||||
});
|
||||
}
|
||||
/** The extracted resources as a single-pack resource manager. */
|
||||
static final net.minecraft.server.packs.resources.ResourceManager FILES = new net.minecraft.server.packs.resources.ResourceManager() {
|
||||
Path path(Identifier id) { return root.resolve("assets").resolve(id.getNamespace()).resolve(id.getPath()); }
|
||||
@Override public Optional<net.minecraft.server.packs.resources.Resource> getResource(Identifier id) {
|
||||
var file = path(id);
|
||||
return Files.isRegularFile(file) ? Optional.of(new net.minecraft.server.packs.resources.Resource(null, () -> Files.newInputStream(file))) : Optional.empty();
|
||||
}
|
||||
@Override public java.util.Set<String> getNamespaces() { return java.util.Set.of("minecraft"); }
|
||||
@Override public List<net.minecraft.server.packs.resources.Resource> getResourceStack(Identifier id) { return getResource(id).stream().toList(); }
|
||||
@Override public Map<Identifier, net.minecraft.server.packs.resources.Resource> listResources(String directory, net.minecraft.server.packs.resources.ResourceManager.Selector selector) { throw new UnsupportedOperationException(); }
|
||||
@Override public Map<Identifier, List<net.minecraft.server.packs.resources.Resource>> listResourceStacks(String directory, net.minecraft.server.packs.resources.ResourceManager.Selector selector) { throw new UnsupportedOperationException(); }
|
||||
@Override public java.util.stream.Stream<net.minecraft.server.packs.PackResources> listPacks() { return java.util.stream.Stream.empty(); }
|
||||
};
|
||||
|
||||
// --- Tagging of special renderers so the layer carries its codec form. ---
|
||||
static final class Tagged implements SpecialModelRenderer.Unbaked<Object> {
|
||||
final SpecialModelRenderer.Unbaked<?> delegate;
|
||||
@@ -196,6 +234,15 @@ public final class VanillaItemModelOracle {
|
||||
models.getOrDefault(id, missing).update(output, item, this, context, level instanceof ClientLevel c ? c : null, owner, seed);
|
||||
}
|
||||
}
|
||||
// ModelManager.getItemProperties, from the same baked properties.
|
||||
@Override public boolean shouldPlaySwapAnimation(ItemStack stack) {
|
||||
Identifier id = stack.get(DataComponents.ITEM_MODEL);
|
||||
return id == null || properties.getOrDefault(id, ClientItem.Properties.DEFAULT).handAnimationOnSwap();
|
||||
}
|
||||
@Override public float swapAnimationScale(ItemStack stack) {
|
||||
Identifier id = stack.get(DataComponents.ITEM_MODEL);
|
||||
return id == null ? 1.0F : properties.getOrDefault(id, ClientItem.Properties.DEFAULT).swapAnimationScale();
|
||||
}
|
||||
}
|
||||
|
||||
static Object field(Object target, Class<?> type, String name) throws Exception {
|
||||
@@ -251,12 +298,22 @@ public final class VanillaItemModelOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
// Item tags (compasses get the special foil) come from the vanilla data pack.
|
||||
var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
try (var data = new net.minecraft.server.packs.resources.MultiPackResourceManager(net.minecraft.server.packs.PackType.SERVER_DATA, repo.openAllSelected())) {
|
||||
var layers = net.minecraft.server.RegistryLayer.createRegistryAccess();
|
||||
net.minecraft.tags.TagLoader.loadTagsForExistingRegistries(data, layers.getLayer(net.minecraft.server.RegistryLayer.STATIC))
|
||||
.forEach(net.minecraft.core.Registry.PendingTags::apply);
|
||||
}
|
||||
ItemModels.bootstrap();
|
||||
SpecialModelRenderers.bootstrap();
|
||||
net.minecraft.client.color.item.ItemTintSources.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.select.SelectItemModelProperties.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperties.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.numeric.RangeSelectItemModelProperties.bootstrap();
|
||||
net.minecraft.client.renderer.texture.atlas.SpriteSources.bootstrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe"); uf.setAccessible(true); unsafe = uf.get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
|
||||
@@ -0,0 +1,604 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.SystemReport;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.gametest.framework.GameTestServer;
|
||||
import net.minecraft.gizmos.GizmoCollector;
|
||||
import net.minecraft.gizmos.Gizmos;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.Services;
|
||||
import net.minecraft.server.WorldLoader;
|
||||
import net.minecraft.server.WorldStem;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.progress.LoggingLevelLoadListener;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.notifications.EmptyNotificationService;
|
||||
import net.minecraft.server.notifications.NotificationManager;
|
||||
import net.minecraft.server.packs.repository.PackRepository;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.server.permissions.PermissionSet;
|
||||
import net.minecraft.server.players.NameAndId;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
import net.minecraft.util.debugchart.LocalSampleLogger;
|
||||
import net.minecraft.util.debugchart.SampleLogger;
|
||||
import net.minecraft.world.clock.WorldClocks;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySpawnReason;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.AgeableMob;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.behavior.BlockPosTracker;
|
||||
import net.minecraft.world.entity.ai.behavior.EntityTracker;
|
||||
import net.minecraft.world.entity.ai.control.LookControl;
|
||||
import net.minecraft.world.entity.ai.control.MoveControl;
|
||||
import net.minecraft.world.entity.ai.goal.GoalSelector;
|
||||
import net.minecraft.world.entity.ai.goal.WrappedGoal;
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
||||
import net.minecraft.world.entity.ai.memory.WalkTarget;
|
||||
import net.minecraft.world.entity.ai.navigation.PathNavigation;
|
||||
import net.minecraft.world.entity.ai.sensing.Sensor;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelSettings;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.WorldDimensions;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldOptions;
|
||||
import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
||||
import net.minecraft.world.level.storage.LevelDataAndDimensions;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Mob AI oracle: a real (headless, flat, structure-free) vanilla server level. Each scenario
|
||||
* builds blocks, places a target player and mobs with seeded random sources, then ticks the
|
||||
* mobs exactly as ServerLevel.tick does (despawn check, then tickNonPassenger) while the rest of
|
||||
* the level stands still (no block ticks, weather, spawning or random ticks), printing the
|
||||
* AI-visible state of every mob after each tick: position, motion, rotations, running goals,
|
||||
* targets, navigation, move/look/jump controls, brain activities and memories, and sounds.
|
||||
*/
|
||||
public final class VanillaMobAiOracle {
|
||||
static final List<Scenario> SCENARIOS = new ArrayList<>();
|
||||
static PrintWriter out;
|
||||
static final List<String> SOUNDS = new ArrayList<>();
|
||||
|
||||
/** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */
|
||||
static final class TracingRandom extends net.minecraft.world.level.levelgen.LegacyRandomSource {
|
||||
static int tick;
|
||||
static boolean on;
|
||||
final List<String> log;
|
||||
final int who;
|
||||
TracingRandom(long seed, List<String> log, int who) { super(seed); this.log = log; this.who = who; }
|
||||
@Override
|
||||
public int next(int bits) {
|
||||
int v = super.next(bits);
|
||||
if (on) {
|
||||
StringBuilder sb = new StringBuilder(tick + " trace " + who + " " + bits + "=" + Integer.toHexString(v) + ":");
|
||||
int n = 0;
|
||||
for (StackTraceElement e : new Throwable().getStackTrace()) {
|
||||
String c = e.getClassName();
|
||||
if (c.contains("RandomSource") || c.contains("TracingRandom") || c.contains("Mth")) continue;
|
||||
sb.append(' ').append(c.substring(c.lastIndexOf('.') + 1)).append('.').append(e.getMethodName()).append(':').append(e.getLineNumber());
|
||||
if (++n == 7) break;
|
||||
}
|
||||
log.add(sb.toString());
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
static final List<String> TRACE = new ArrayList<>();
|
||||
|
||||
static final class MobSpec {
|
||||
String type;
|
||||
double x, y, z;
|
||||
float yaw;
|
||||
long seed;
|
||||
boolean baby;
|
||||
List<String> flags = new ArrayList<>();
|
||||
}
|
||||
|
||||
static final class Scenario {
|
||||
String name;
|
||||
int ticks;
|
||||
long time = 6000;
|
||||
boolean rain, thunder;
|
||||
int originX, originZ;
|
||||
List<String[]> blocks = new ArrayList<>();
|
||||
double[] player;
|
||||
boolean creative;
|
||||
List<MobSpec> mobs = new ArrayList<>();
|
||||
long levelSeed = 0;
|
||||
}
|
||||
|
||||
static void parse(Path path) throws Exception {
|
||||
Scenario s = null;
|
||||
for (String raw : Files.readAllLines(path)) {
|
||||
String line = raw.strip();
|
||||
if (line.isEmpty() || line.startsWith("#")) continue;
|
||||
String[] f = line.split("\\s+");
|
||||
switch (f[0]) {
|
||||
case "scenario" -> {
|
||||
s = new Scenario();
|
||||
s.name = f[1];
|
||||
for (int i = 2; i < f.length; i++) {
|
||||
String[] kv = f[i].split("=", 2);
|
||||
switch (kv[0]) {
|
||||
case "ticks" -> s.ticks = Integer.parseInt(kv[1]);
|
||||
case "time" -> s.time = Long.parseLong(kv[1]);
|
||||
case "rain" -> s.rain = true;
|
||||
case "thunder" -> s.thunder = true;
|
||||
case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); }
|
||||
case "fill", "block" -> s.blocks.add(f);
|
||||
case "player" -> {
|
||||
s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])};
|
||||
s.creative = f.length > 4 && f[4].equals("creative");
|
||||
}
|
||||
case "mob" -> {
|
||||
MobSpec m = new MobSpec();
|
||||
m.type = f[1];
|
||||
m.x = Double.parseDouble(f[2]);
|
||||
m.y = Double.parseDouble(f[3]);
|
||||
m.z = Double.parseDouble(f[4]);
|
||||
m.yaw = Float.parseFloat(f[5]);
|
||||
m.seed = Long.parseLong(f[6]);
|
||||
for (int i = 7; i < f.length; i++) {
|
||||
if (f[i].equals("baby")) m.baby = true; else m.flags.add(f[i]);
|
||||
}
|
||||
s.mobs.add(m);
|
||||
}
|
||||
case "end" -> { SCENARIOS.add(s); s = null; }
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
parse(Path.of(args[0]));
|
||||
out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
Util.startTimerHackThread();
|
||||
Path universe = Files.createTempDirectory("horizon-mob-ai");
|
||||
LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld");
|
||||
PackRepository packs = ServerPacksSource.createPackRepository(access);
|
||||
MinecraftServer.spin(thread -> Server.create(thread, access, packs));
|
||||
}
|
||||
|
||||
static String traceSpec() { String v = System.getenv("AI_TRACE"); return v == null ? "" : v; }
|
||||
// Every mob random is traced unless AI_TRACE=0.
|
||||
static boolean tracing(Scenario s) { return !traceSpec().equals("0"); }
|
||||
static int traceFrom() { return 0; }
|
||||
static int traceTo() { return Integer.MAX_VALUE; }
|
||||
|
||||
static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
|
||||
static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
static Field field(Class<?> c, String name) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Field fl = k.getDeclaredField(name);
|
||||
fl.setAccessible(true);
|
||||
return fl;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name);
|
||||
}
|
||||
|
||||
static Method method(Class<?> c, String name, Class<?>... types) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Method m = k.getDeclaredMethod(name, types);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
} catch (NoSuchMethodException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchMethodException(name);
|
||||
}
|
||||
|
||||
static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); }
|
||||
|
||||
static final class Server extends MinecraftServer {
|
||||
static final FeatureFlagSet FEATURES = FeatureFlags.REGISTRY
|
||||
.allFlags()
|
||||
.subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS));
|
||||
final LocalSampleLogger sampleLogger = new LocalSampleLogger(4);
|
||||
int scenario = 0;
|
||||
int phase = 0;
|
||||
int wait = 0;
|
||||
ServerPlayer player;
|
||||
int failures = 0;
|
||||
|
||||
static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) {
|
||||
try {
|
||||
packs.reload();
|
||||
ArrayList<String> enabled = new ArrayList<>(packs.getAvailableIds());
|
||||
enabled.remove("vanilla");
|
||||
enabled.addFirst("vanilla");
|
||||
WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES);
|
||||
LevelSettings settings = new LevelSettings("AI Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config);
|
||||
WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true);
|
||||
WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER);
|
||||
WorldStem stem = Util.<WorldStem>blockUntilDone(executor -> WorldLoader.load(init, context -> {
|
||||
Registry<LevelStem> none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
|
||||
WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET)
|
||||
.getOrThrow(WorldPresets.FLAT).value().createWorldDimensions();
|
||||
WorldDimensions.Complete complete = dims.bake(none);
|
||||
PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle());
|
||||
return new WorldLoader.DataLoadOutput<>(
|
||||
new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)),
|
||||
complete.dimensionsRegistryAccess());
|
||||
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
|
||||
GameRules rules = new GameRules(FEATURES);
|
||||
rules.set(GameRules.SPAWN_MOBS, false, null);
|
||||
rules.set(GameRules.SPAWN_MONSTERS, false, null);
|
||||
rules.set(GameRules.SPAWN_PATROLS, false, null);
|
||||
rules.set(GameRules.SPAWN_PHANTOMS, false, null);
|
||||
rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null);
|
||||
rules.set(GameRules.SPAWN_WARDENS, false, null);
|
||||
rules.set(GameRules.ADVANCE_TIME, false, null);
|
||||
rules.set(GameRules.ADVANCE_WEATHER, false, null);
|
||||
rules.set(GameRules.RAIDS, false, null);
|
||||
Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES");
|
||||
nf.setAccessible(true);
|
||||
return new Server(thread, access, packs, stem, rules, (Services) nf.get(null));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) {
|
||||
super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services,
|
||||
LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean initServer() {
|
||||
this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {
|
||||
@Override
|
||||
public void broadcast(Player except, double x, double y, double z, double range, ResourceKey<Level> dim, Packet<?> packet) {
|
||||
capture(packet);
|
||||
}
|
||||
});
|
||||
Gizmos.withCollector(GizmoCollector.NOOP);
|
||||
this.loadLevel();
|
||||
return true;
|
||||
}
|
||||
|
||||
static void capture(Packet<?> packet) {
|
||||
if (packet instanceof ClientboundSoundPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
} else if (packet instanceof ClientboundSoundEntityPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tickServer(BooleanSupplier haveTime) {
|
||||
try {
|
||||
step(haveTime);
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
out.flush();
|
||||
System.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
ServerLevel level() { return this.overworld(); }
|
||||
|
||||
void step(BooleanSupplier haveTime) throws Exception {
|
||||
if (scenario >= SCENARIOS.size()) {
|
||||
out.close();
|
||||
// Nothing to save: skip the shutdown.
|
||||
Runtime.getRuntime().halt(0);
|
||||
return;
|
||||
}
|
||||
Scenario s = SCENARIOS.get(scenario);
|
||||
ServerLevel level = level();
|
||||
int cx = s.originX >> 4, cz = s.originZ >> 4;
|
||||
switch (phase) {
|
||||
case 0 -> {
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, true);
|
||||
phase = 1;
|
||||
super.tickServer(haveTime);
|
||||
}
|
||||
case 1 -> {
|
||||
super.tickServer(haveTime);
|
||||
boolean ready = true;
|
||||
for (int dx = -4; dx <= 4 && ready; dx++)
|
||||
for (int dz = -4; dz <= 4 && ready; dz++)
|
||||
ready = level.isPositionEntityTicking(new BlockPos((cx + dx) * 16, -60, (cz + dz) * 16));
|
||||
if (ready) {
|
||||
build(s, level);
|
||||
phase = 2;
|
||||
wait = 0;
|
||||
}
|
||||
}
|
||||
case 2 -> {
|
||||
super.tickServer(haveTime);
|
||||
if (!level.getChunkSource().getLightEngine().hasLightWork() && ++wait > 5) {
|
||||
run(s, level);
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, false);
|
||||
scenario++;
|
||||
phase = 0;
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
void build(Scenario s, ServerLevel level) throws Exception {
|
||||
var blocks = level.holderLookup(Registries.BLOCK);
|
||||
for (String[] b : s.blocks) {
|
||||
if (b[0].equals("block")) {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState();
|
||||
level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16);
|
||||
} else {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState();
|
||||
int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]);
|
||||
int x1 = Integer.parseInt(b[4]), y1 = Integer.parseInt(b[5]), z1 = Integer.parseInt(b[6]);
|
||||
for (int x = Math.min(x0, x1); x <= Math.max(x0, x1); x++)
|
||||
for (int y = Math.min(y0, y1); y <= Math.max(y0, y1); y++)
|
||||
for (int z = Math.min(z0, z1); z <= Math.max(z0, z1); z++)
|
||||
level.setBlock(new BlockPos(x, y, z), state, 2 | 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void run(Scenario s, ServerLevel level) throws Exception {
|
||||
out.println("== " + s.name);
|
||||
var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD);
|
||||
this.clockManager().setTotalTicks(clock, s.time);
|
||||
// Every scenario starts at game time 1000.
|
||||
this.getWorldData().overworldData().setGameTime(1000L);
|
||||
// isRaining/isThundering read the rain and thunder levels only.
|
||||
level.setRainLevel(s.rain ? 1.0F : 0.0F);
|
||||
level.setThunderLevel(s.thunder ? 1.0F : 0.0F);
|
||||
if (s.player != null) {
|
||||
if (player == null) {
|
||||
CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-ai"), false);
|
||||
player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation());
|
||||
Connection connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
new EmbeddedChannel(connection);
|
||||
this.getPlayerList().placeNewPlayer(connection, player, cookie);
|
||||
}
|
||||
player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL);
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
} else if (player != null) {
|
||||
player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F);
|
||||
}
|
||||
List<Mob> mobs = new ArrayList<>();
|
||||
int id = 100000;
|
||||
for (MobSpec spec : s.mobs) {
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
|
||||
Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND);
|
||||
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, mobs.size()));
|
||||
mob.setId(id++);
|
||||
mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F);
|
||||
mob.setYHeadRot(spec.yaw);
|
||||
mob.setYBodyRot(spec.yaw);
|
||||
if (spec.baby) {
|
||||
if (mob instanceof AgeableMob a) a.setBaby(true);
|
||||
else mob.setBaby(true);
|
||||
}
|
||||
for (String flag : spec.flags) {
|
||||
if (flag.equals("persistent")) mob.setPersistenceRequired();
|
||||
else if (flag.equals("noai")) mob.setNoAi(true);
|
||||
else throw new IllegalArgumentException(flag);
|
||||
}
|
||||
level.addFreshEntity(mob);
|
||||
mob.getRandom().setSeed(spec.seed);
|
||||
Brain<?> brain = mob.getBrain();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(brain, "sensors");
|
||||
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
|
||||
mobs.add(mob);
|
||||
}
|
||||
level.getRandom().setSeed(s.levelSeed);
|
||||
SOUNDS.clear();
|
||||
Method tickTime = method(ServerLevel.class, "tickTime");
|
||||
Object manager = get(level, "entityManager");
|
||||
Method managerTick = method(manager.getClass(), "tick");
|
||||
for (int i = 0; i < mobs.size(); i++) print(0, i, mobs.get(i));
|
||||
for (int t = 1; t <= s.ticks; t++) {
|
||||
level.environmentAttributes().invalidateTickCache();
|
||||
level.updateSkyBrightness();
|
||||
tickTime.invoke(level);
|
||||
if (player != null && s.player != null) {
|
||||
player.setHealth(player.getMaxHealth());
|
||||
player.setInvulnerableTime(0);
|
||||
player.hurtTime = 0;
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
}
|
||||
TracingRandom.tick = t;
|
||||
TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo();
|
||||
SOUNDS.clear();
|
||||
for (Mob mob : mobs) {
|
||||
if (mob.isRemoved()) continue;
|
||||
mob.checkDespawn();
|
||||
if (mob.isRemoved()) continue;
|
||||
level.tickNonPassenger(mob);
|
||||
}
|
||||
managerTick.invoke(manager);
|
||||
for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i));
|
||||
for (String sound : SOUNDS) out.println(t + " sound " + sound);
|
||||
for (String line : TRACE) out.println(line);
|
||||
TRACE.clear();
|
||||
}
|
||||
for (Mob mob : mobs) mob.discard();
|
||||
managerTick.invoke(manager);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
static String who(Entity e) {
|
||||
if (e == null) return "none";
|
||||
if (e instanceof ServerPlayer) return "player";
|
||||
return "e" + e.getId();
|
||||
}
|
||||
|
||||
static String goals(GoalSelector selector) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (WrappedGoal g : selector.getAvailableGoals()) {
|
||||
if (!g.isRunning()) continue;
|
||||
if (sb.length() > 0) sb.append('|');
|
||||
Class<?> c = g.getGoal().getClass();
|
||||
String name = c.getSimpleName();
|
||||
if (name.isEmpty()) name = c.getName().substring(c.getName().lastIndexOf('.') + 1);
|
||||
sb.append(name);
|
||||
}
|
||||
return sb.length() == 0 ? "-" : sb.toString();
|
||||
}
|
||||
|
||||
static String pos(BlockPos p) { return p.getX() + "," + p.getY() + "," + p.getZ(); }
|
||||
|
||||
static String value(Object v) {
|
||||
if (v == null) return "null";
|
||||
if (v instanceof Entity e) return who(e);
|
||||
if (v instanceof BlockPos p) return pos(p);
|
||||
if (v instanceof GlobalPos g) return pos(g.pos());
|
||||
if (v instanceof WalkTarget w) return value(w.getTarget()) + "/" + f(w.getSpeedModifier()) + "/" + w.getCloseEnoughDist();
|
||||
if (v instanceof EntityTracker e) return who(e.getEntity());
|
||||
if (v instanceof BlockPosTracker b) return pos(b.currentBlockPosition());
|
||||
if (v instanceof Boolean || v instanceof Integer || v instanceof Long) return v.toString();
|
||||
if (v instanceof net.minecraft.util.Unit) return "u";
|
||||
if (v instanceof Collection<?> c) return "n" + c.size();
|
||||
if (v instanceof net.minecraft.world.level.pathfinder.Path p) return "path" + pos(p.getTarget());
|
||||
return v.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
void print(int t, int i, Mob m) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(t).append(' ').append(i);
|
||||
if (m.isRemoved()) {
|
||||
out.println(sb.append(" removed ").append(m.getRemovalReason()));
|
||||
return;
|
||||
}
|
||||
sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ()));
|
||||
Vec3 v = m.getDeltaMovement();
|
||||
sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z));
|
||||
sb.append("\tr ").append(f(m.getYRot())).append(',').append(f(m.getXRot())).append(',').append(f(m.getYHeadRot())).append(',').append(f(m.yBodyRot));
|
||||
sb.append("\tg ").append(m.onGround() ? 1 : 0).append(m.horizontalCollision ? 1 : 0);
|
||||
sb.append("\thp ").append(f(m.getHealth()));
|
||||
sb.append("\tgoals ").append(goals((GoalSelector) get(m, "goalSelector")));
|
||||
sb.append("\ttargets ").append(goals((GoalSelector) get(m, "targetSelector")));
|
||||
sb.append("\ttarget ").append(who(m.getTarget()));
|
||||
PathNavigation nav = m.getNavigation();
|
||||
var path = nav.getPath();
|
||||
sb.append("\tnav ");
|
||||
if (path == null) sb.append("none");
|
||||
else sb.append(pos(path.getTarget())).append(' ').append(path.getNextNodeIndex()).append('/').append(path.getNodeCount())
|
||||
.append(path.isDone() ? " done" : "");
|
||||
MoveControl mc = m.getMoveControl();
|
||||
sb.append("\tmove ").append(get(mc, "operation")).append(' ').append(d((double) get(mc, "wantedX"))).append(',')
|
||||
.append(d((double) get(mc, "wantedY"))).append(',').append(d((double) get(mc, "wantedZ"))).append(' ')
|
||||
.append(d((double) get(mc, "speedModifier")));
|
||||
LookControl lc = m.getLookControl();
|
||||
sb.append("\tlook ").append(get(lc, "lookAtCooldown")).append(' ').append(d((double) get(lc, "wantedX"))).append(',')
|
||||
.append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ")));
|
||||
sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',')
|
||||
.append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0);
|
||||
sb.append("\trng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(m.getRandom())).get()));
|
||||
Brain<?> brain = m.getBrain();
|
||||
if (!brain.getActiveActivities().isEmpty() && !((Map<?, ?>) get(brain, "sensors")).isEmpty()) {
|
||||
List<String> acts = new ArrayList<>();
|
||||
for (var a : brain.getActiveActivities()) acts.add(a.getName());
|
||||
acts.sort(null);
|
||||
sb.append("\tact ").append(String.join("|", acts));
|
||||
List<String> mem = new ArrayList<>();
|
||||
brain.forEach(new Brain.Visitor() {
|
||||
@Override public <U> void acceptEmpty(MemoryModuleType<U> type) {}
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value) { mem.add(name(type) + "=" + value(value)); }
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value, long ttl) { mem.add(name(type) + "=" + value(value) + "@" + ttl); }
|
||||
});
|
||||
mem.sort(null);
|
||||
sb.append("\tmem ").append(String.join(" ", mem));
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static String name(MemoryModuleType<?> type) {
|
||||
return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath();
|
||||
}
|
||||
|
||||
@Override protected SampleLogger getTickTimeLogger() { return sampleLogger; }
|
||||
@Override public boolean isTickTimeLoggingEnabled() { return false; }
|
||||
@Override protected void waitUntilNextTick() { this.runAllTasks(); }
|
||||
@Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Mob AI oracle"); return report; }
|
||||
@Override protected void onServerExit() { super.onServerExit(); System.exit(0); }
|
||||
@Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); }
|
||||
@Override public boolean isHardcore() { return false; }
|
||||
@Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; }
|
||||
@Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; }
|
||||
@Override public boolean shouldRconBroadcast() { return false; }
|
||||
@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 boolean shouldInformAdmins() { return false; }
|
||||
@Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; }
|
||||
@Override public int getMaxPlayers() { return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.components.toasts.ToastManager;
|
||||
import net.minecraft.client.gui.screens.LevelLoadingScreen;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.MusicManager;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import net.minecraft.client.sounds.SoundManager;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
|
||||
/**
|
||||
* Drives the real MusicManager over the real SoundEngine (VanillaSoundRig).
|
||||
* The situation, Minecraft.getSituationalMusic and getMusicVolume, is the
|
||||
* script's input; the loading screen is a LevelLoadingScreen in the Gui; the
|
||||
* toast manager records showNowPlayingToast/hideNowPlayingToast. Each client
|
||||
* tick is musicManager.tick() then soundManager.tick(pause), as Minecraft.tick
|
||||
* runs them. Prints the manager's state and the music channel every step.
|
||||
*/
|
||||
public final class VanillaMusicOracle {
|
||||
public static final class Mc extends Minecraft {
|
||||
Music music;
|
||||
float volume = 1.0F;
|
||||
|
||||
Mc() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Music getSituationalMusic() {
|
||||
return music;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getMusicVolume() {
|
||||
return volume;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Toasts extends ToastManager {
|
||||
final List<String> calls = new ArrayList<>();
|
||||
|
||||
Toasts() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showNowPlayingToast() {
|
||||
calls.add("show");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hideNowPlayingToast() {
|
||||
calls.add("hide");
|
||||
}
|
||||
}
|
||||
|
||||
static Music music(String spec) {
|
||||
if (spec.equals("-")) return null;
|
||||
String[] p = spec.split(",");
|
||||
return new Music(Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(p[0]))), Integer.parseInt(p[1]),
|
||||
Integer.parseInt(p[2]), p[3].equals("1"));
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
Mc mc = VanillaSoundRig.make(Mc.class);
|
||||
Gui gui = VanillaSoundRig.make(Gui.class);
|
||||
Toasts toasts = VanillaSoundRig.make(Toasts.class);
|
||||
VanillaSoundRig.set(toasts, Toasts.class, "calls", new ArrayList<String>());
|
||||
VanillaSoundRig.set(gui, Gui.class, "toastManager", toasts);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gui", gui);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager);
|
||||
var loading = VanillaSoundRig.make(LevelLoadingScreen.class);
|
||||
MusicManager manager = null;
|
||||
var gains = VanillaSoundRig.field(SoundEngine.class, "gainBySource");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "start" -> {
|
||||
// A fresh manager: MusicManager(minecraft) with a seeded random.
|
||||
manager = VanillaSoundRig.make(MusicManager.class);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "minecraft", mc);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "random", RandomSource.create(Long.parseLong(a[1])));
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "gameMusicFrequency", MusicManager.MusicFrequency.valueOf(a[2]));
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "currentGain", 1.0F);
|
||||
VanillaSoundRig.set(manager, MusicManager.class, "nextSongDelay", 100);
|
||||
rig.manager.stop();
|
||||
}
|
||||
case "situation" -> {
|
||||
mc.music = music(a[1]);
|
||||
mc.volume = f(a[2]);
|
||||
}
|
||||
case "tick" -> {
|
||||
VanillaSoundRig.set(gui, Gui.class, "screen", a[1].equals("1") ? loading : null);
|
||||
manager.tick();
|
||||
rig.manager.tick(a[2].equals("1"));
|
||||
}
|
||||
case "finish" -> {
|
||||
var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic");
|
||||
if (current != null) rig.finish(current);
|
||||
}
|
||||
case "stop" -> manager.stopPlaying();
|
||||
case "stopmusic" -> manager.stopPlaying(music(a[1]));
|
||||
case "freq" -> manager.setMinutesBetweenSongs(MusicManager.MusicFrequency.valueOf(a[1]));
|
||||
case "toast" -> manager.showNowPlayingToastIfNeeded();
|
||||
case "volume" -> {
|
||||
rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
}
|
||||
case "stopall" -> rig.manager.stop();
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic");
|
||||
out.printf(" current=%s delay=%d gain=%08x toastShown=%s musicGain=%08x%n", current == null ? "-" : current.getIdentifier(),
|
||||
(int) VanillaSoundRig.get(manager, MusicManager.class, "nextSongDelay"),
|
||||
Float.floatToRawIntBits((float) VanillaSoundRig.get(manager, MusicManager.class, "currentGain")),
|
||||
VanillaSoundRig.get(manager, MusicManager.class, "toastShown"),
|
||||
Float.floatToRawIntBits(((it.unimi.dsi.fastutil.objects.Object2FloatMap<SoundSource>) gains.get(rig.engine)).getFloat(SoundSource.MUSIC)));
|
||||
for (String call : toasts.calls) out.println(" toast " + call);
|
||||
toasts.calls.clear();
|
||||
if (current != null) out.println(rig.describe("music", current));
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.ProtocolInfo;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
|
||||
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
|
||||
import net.minecraft.network.protocol.game.GameProtocols;
|
||||
import net.minecraft.network.protocol.login.LoginProtocols;
|
||||
import net.minecraft.network.protocol.status.StatusProtocols;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
|
||||
/**
|
||||
* Checks a capture written by tools/net_capture.py against vanilla's own
|
||||
* packet codecs: every clientbound packet a server sent (login,
|
||||
* configuration and play) must decode with vanilla's StreamCodec, consume
|
||||
* its whole payload, and encode back to the same bytes, so the bytes are
|
||||
* exactly what vanilla would have written for that packet. Chunk data is
|
||||
* decoded section by section and the stored block counts are checked
|
||||
* against a recount. Prints one line per packet:
|
||||
* conn dir state name ok|ERROR|REENCODE|SECTIONS detail
|
||||
* and a summary per packet type at the end.
|
||||
*/
|
||||
public final class VanillaPacketCodecOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
Path capture = Path.of(args[0]);
|
||||
boolean verbose = args.length > 2 && args[2].equals("--verbose");
|
||||
var play = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
|
||||
var factory = PalettedContainerFactory.create(ParityData.access);
|
||||
Field nonEmpty = LevelChunkSection.class.getDeclaredField("nonEmptyBlockCount");
|
||||
Field fluids = LevelChunkSection.class.getDeclaredField("fluidCount");
|
||||
nonEmpty.setAccessible(true);
|
||||
fluids.setAccessible(true);
|
||||
Map<String, int[]> totals = new TreeMap<>();
|
||||
int failures = 0;
|
||||
try (BufferedReader in = Files.newBufferedReader(capture);
|
||||
PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) {
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
if (line.isBlank()) continue;
|
||||
JsonObject e = JsonParser.parseString(line).getAsJsonObject();
|
||||
if (!e.has("name") || !e.get("dir").getAsString().equals("s2c")) continue;
|
||||
String state = e.get("state").getAsString();
|
||||
String name = e.get("name").getAsString();
|
||||
String key = state + "/" + name;
|
||||
int[] t = totals.computeIfAbsent(key, k -> new int[2]);
|
||||
t[0]++;
|
||||
if (!e.has("data")) {
|
||||
out.println(e.get("conn") + " s2c " + key + " SKIPPED payload not captured");
|
||||
t[1]++;
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
byte[] payload = HexFormat.of().parseHex(e.get("data").getAsString());
|
||||
ProtocolInfo<?> protocol = switch (state) {
|
||||
case "status" -> StatusProtocols.CLIENTBOUND;
|
||||
case "login" -> LoginProtocols.CLIENTBOUND;
|
||||
case "configuration" -> ConfigurationProtocols.CLIENTBOUND;
|
||||
case "play" -> play;
|
||||
default -> null;
|
||||
};
|
||||
if (protocol == null) continue;
|
||||
ByteBuf original = Unpooled.buffer();
|
||||
new FriendlyByteBuf(original).writeVarInt(e.get("id").getAsInt());
|
||||
original.writeBytes(payload);
|
||||
byte[] framed = new byte[original.readableBytes()];
|
||||
original.getBytes(0, framed);
|
||||
String verdict;
|
||||
String detail = "";
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
var codec = (net.minecraft.network.codec.StreamCodec<ByteBuf, Packet<?>>) (Object) protocol.codec();
|
||||
Packet<?> packet = codec.decode(original);
|
||||
if (original.readableBytes() != 0) {
|
||||
verdict = "ERROR";
|
||||
detail = original.readableBytes() + " bytes left after decoding " + packet;
|
||||
} else {
|
||||
ByteBuf again = Unpooled.buffer();
|
||||
codec.encode(again, packet);
|
||||
byte[] encoded = new byte[again.readableBytes()];
|
||||
again.getBytes(0, encoded);
|
||||
if (!java.util.Arrays.equals(encoded, framed)) {
|
||||
verdict = "REENCODE";
|
||||
detail = firstDifference(framed, encoded) + " " + abbreviate(packet.toString());
|
||||
} else if (packet instanceof ClientboundLevelChunkWithLightPacket chunk) {
|
||||
String problem = checkSections(chunk, factory, nonEmpty, fluids);
|
||||
verdict = problem == null ? "ok" : "SECTIONS";
|
||||
detail = problem == null ? "" : problem;
|
||||
} else {
|
||||
verdict = "ok";
|
||||
if (verbose) detail = abbreviate(packet.toString());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
verdict = "ERROR";
|
||||
detail = ex.toString();
|
||||
}
|
||||
if (!verdict.equals("ok")) {
|
||||
t[1]++;
|
||||
failures++;
|
||||
}
|
||||
if (!verdict.equals("ok") || verbose) {
|
||||
out.println(e.get("conn") + " s2c " + key + " " + verdict + " " + detail);
|
||||
}
|
||||
}
|
||||
out.println("# packet type, count, failures");
|
||||
for (var entry : totals.entrySet()) {
|
||||
out.println("# " + entry.getKey() + " " + entry.getValue()[0] + " " + entry.getValue()[1]);
|
||||
}
|
||||
out.println("# failures " + failures);
|
||||
}
|
||||
System.exit(failures == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
static String checkSections(ClientboundLevelChunkWithLightPacket chunk, PalettedContainerFactory factory,
|
||||
Field nonEmpty, Field fluids) throws Exception {
|
||||
FriendlyByteBuf buf = chunk.chunkData().getReadBuffer();
|
||||
int index = 0;
|
||||
while (buf.isReadable()) {
|
||||
int start = buf.readerIndex();
|
||||
short storedBlocks = buf.getShort(start);
|
||||
short storedFluids = buf.getShort(start + 2);
|
||||
LevelChunkSection section = new LevelChunkSection(factory);
|
||||
section.read(buf);
|
||||
section.recalcBlockCounts();
|
||||
int blocks = (short) (int) nonEmpty.get(section);
|
||||
int fluidCount = (short) (int) fluids.get(section);
|
||||
if (blocks != storedBlocks || fluidCount != storedFluids) {
|
||||
return "section " + index + " of " + chunk.x() + "," + chunk.z() + " stores " + storedBlocks + " blocks/"
|
||||
+ storedFluids + " fluids, recount " + blocks + "/" + fluidCount;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
if (index != 24 && index != 16) return index + " sections in " + chunk.x() + "," + chunk.z();
|
||||
return null;
|
||||
}
|
||||
|
||||
static String firstDifference(byte[] a, byte[] b) {
|
||||
int n = Math.min(a.length, b.length);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (a[i] != b[i]) return "differs at byte " + i + " of " + a.length + " (vanilla writes " + b.length + ")";
|
||||
}
|
||||
return "lengths " + a.length + " vs vanilla " + b.length;
|
||||
}
|
||||
|
||||
static String abbreviate(String s) {
|
||||
s = s.replace('\n', ' ');
|
||||
return s.length() > 400 ? s.substring(0, 400) + "..." : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.Camera;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.gui.Hud;
|
||||
import net.minecraft.client.gui.components.BossHealthOverlay;
|
||||
import net.minecraft.client.gui.components.LerpingBossEvent;
|
||||
import net.minecraft.client.gui.screens.WinScreen;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.sounds.Music;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.BossEvent;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Abilities;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Calls the real Minecraft.getSituationalMusic and getMusicVolume on shells
|
||||
* holding the open screen (none or the credits' WinScreen), the boss overlay's
|
||||
* events, the player (its level's dimension, abilities and underwater state)
|
||||
* and a real camera EnvironmentAttributeProbe over the dimension and biome's
|
||||
* attribute layers from the vanilla data pack. Lines: "screen player
|
||||
* dimension biome boss instabuild mayfly underwater".
|
||||
*/
|
||||
public final class VanillaSituationalMusicOracle {
|
||||
static String music(Music m) {
|
||||
return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
|
||||
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
|
||||
}
|
||||
|
||||
static LerpingBossEvent bar(boolean darken, boolean music) {
|
||||
return new LerpingBossEvent(UUID.randomUUID(), Component.empty(), 1.0F, BossEvent.BossBarColor.PINK, BossEvent.BossBarOverlay.PROGRESS,
|
||||
darken, music, false);
|
||||
}
|
||||
|
||||
public static void main(String[] args) 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();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var biomes = world.lookupOrThrow(Registries.BIOME);
|
||||
|
||||
Minecraft mc = VanillaSoundRig.make(Minecraft.class);
|
||||
Gui gui = VanillaSoundRig.make(Gui.class);
|
||||
Hud hud = VanillaSoundRig.make(Hud.class);
|
||||
BossHealthOverlay overlay = VanillaSoundRig.make(BossHealthOverlay.class);
|
||||
Map<UUID, LerpingBossEvent> events = new LinkedHashMap<>();
|
||||
VanillaSoundRig.set(overlay, BossHealthOverlay.class, "events", events);
|
||||
VanillaSoundRig.set(hud, Hud.class, "bossOverlay", overlay);
|
||||
VanillaSoundRig.set(gui, Gui.class, "hud", hud);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gui", gui);
|
||||
GameRenderer renderer = VanillaSoundRig.make(GameRenderer.class);
|
||||
Camera camera = VanillaSoundRig.make(Camera.class);
|
||||
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", camera);
|
||||
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
|
||||
WinScreen credits = VanillaSoundRig.make(WinScreen.class);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) {
|
||||
String[] f = line.split(" ");
|
||||
VanillaSoundRig.set(gui, Gui.class, "screen", f[0].equals("win") ? credits : null);
|
||||
events.clear();
|
||||
if (f[4].contains("dark")) events.put(UUID.randomUUID(), bar(true, false));
|
||||
if (f[4].contains("music")) events.put(UUID.randomUUID(), bar(false, true));
|
||||
var probe = new EnvironmentAttributeProbe();
|
||||
VanillaSoundRig.set(camera, Camera.class, "attributeProbe", probe);
|
||||
if (f[1].equals("1")) {
|
||||
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[2]))).value();
|
||||
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[3]))).value();
|
||||
var b = EnvironmentAttributeSystem.builder();
|
||||
b.addConstantLayer(dim.attributes());
|
||||
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
|
||||
ClientLevel level = VanillaSoundRig.make(ClientLevel.class);
|
||||
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", b.build());
|
||||
VanillaSoundRig.set(level, Level.class, "dimension", f[2].equals("minecraft:the_end") ? Level.END
|
||||
: f[2].equals("minecraft:the_nether") ? Level.NETHER : Level.OVERWORLD);
|
||||
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "level", level);
|
||||
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "position", new Vec3(0.5, 64.0, 0.5));
|
||||
LocalPlayer player = VanillaSoundRig.make(LocalPlayer.class);
|
||||
VanillaSoundRig.set(player, Entity.class, "level", level);
|
||||
var abilities = new Abilities();
|
||||
abilities.instabuild = f[5].equals("1");
|
||||
abilities.mayfly = f[6].equals("1");
|
||||
VanillaSoundRig.set(player, Player.class, "abilities", abilities);
|
||||
VanillaSoundRig.set(player, Player.class, "wasUnderwater", f[7].equals("1"));
|
||||
mc.player = player;
|
||||
} else {
|
||||
mc.player = null;
|
||||
}
|
||||
w.printf("%s music=%s volume=%08x%n", line, music(mc.getSituationalMusic()), Float.floatToRawIntBits(mc.getMusicVolume()));
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
/**
|
||||
* Drives the real SoundEngine (see VanillaSoundRig) with a script of plays,
|
||||
* stops, category gains, option volumes, channel ends, pauses and ticks, and
|
||||
* prints after every step each instance's activity and AL source parameters,
|
||||
* the subtitle notifications and the channel pool counts.
|
||||
*/
|
||||
public final class VanillaSoundEngineOracle {
|
||||
/** The local player the underwater instances look at. */
|
||||
public static final class Actor extends LocalPlayer {
|
||||
boolean underwater;
|
||||
|
||||
Actor() {
|
||||
super(null, null, null, null, null, null, false, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderWater() {
|
||||
return underwater;
|
||||
}
|
||||
}
|
||||
|
||||
static float f(String hex) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
|
||||
}
|
||||
|
||||
static double d(String hex) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16));
|
||||
}
|
||||
|
||||
static void seed(SoundInstance instance, long seed) throws Exception {
|
||||
VanillaSoundRig.set(instance, AbstractSoundInstance.class, "random", RandomSource.create(seed));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var rig = new VanillaSoundRig(Path.of(args[0]));
|
||||
var actor = VanillaSoundRig.make(Actor.class);
|
||||
Constructor<UnderLiquidSubSound> sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class);
|
||||
sub.setAccessible(true);
|
||||
var instances = new TreeMap<String, SoundInstance>();
|
||||
var manager = rig.manager;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
out.println(line);
|
||||
String[] a = line.split(" ");
|
||||
switch (a[0]) {
|
||||
case "play" -> {
|
||||
// play name kind event source volume pitch x y z looping delay attenuation relative seed
|
||||
Identifier id = Identifier.parse(a[3]);
|
||||
SoundEvent event = SoundEvent.createVariableRangeEvent(id);
|
||||
long seed = Long.parseLong(a[14]);
|
||||
SoundInstance instance = switch (a[2]) {
|
||||
case "simple" -> new SimpleSoundInstance(id, SoundSource.values()[Integer.parseInt(a[4])], f(a[5]), f(a[6]),
|
||||
RandomSource.create(seed), a[10].equals("1"), Integer.parseInt(a[11]),
|
||||
a[12].equals("linear") ? SoundInstance.Attenuation.LINEAR : SoundInstance.Attenuation.NONE, d(a[7]), d(a[8]), d(a[9]),
|
||||
a[13].equals("1"));
|
||||
case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event);
|
||||
case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater);
|
||||
case "usub" -> sub.newInstance(actor, event);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
};
|
||||
if (!a[2].equals("simple")) seed(instance, seed);
|
||||
instances.put(a[1], instance);
|
||||
out.println(" result " + manager.play(instance));
|
||||
}
|
||||
case "replay" -> out.println(" result " + manager.play(instances.get(a[1])));
|
||||
case "queue" -> manager.queueTickingSound((TickableSoundInstance) instances.get(a[1]));
|
||||
case "delayed" -> manager.playDelayed(instances.get(a[1]), Integer.parseInt(a[2]));
|
||||
case "fade" -> {
|
||||
if (instances.get(a[1]) instanceof BiomeAmbientSoundsHandler.LoopSoundInstance loop) {
|
||||
if (a[2].equals("in")) loop.fadeIn(); else loop.fadeOut();
|
||||
}
|
||||
}
|
||||
case "stop" -> manager.stop(instances.get(a[1]));
|
||||
case "stopmatch" -> manager.stop(a[1].equals("-") ? null : Identifier.parse(a[1]),
|
||||
a[2].equals("-") ? null : SoundSource.values()[Integer.parseInt(a[2])]);
|
||||
case "finish" -> rig.finish(instances.get(a[1]));
|
||||
case "gain" -> manager.updateCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
case "volume" -> rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2]));
|
||||
case "refresh" -> manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]);
|
||||
case "pause" -> manager.pauseAllExcept(SoundSource.MUSIC, SoundSource.UI);
|
||||
case "resume" -> manager.resume();
|
||||
case "player" -> {
|
||||
actor.underwater = a[1].equals("1");
|
||||
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null);
|
||||
}
|
||||
case "tick" -> manager.tick(a[1].equals("1"));
|
||||
case "forget" -> instances.remove(a[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
for (var e : instances.entrySet()) out.println(rig.describe(e.getKey(), e.getValue()));
|
||||
rig.flush(out);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.resources.sounds.*;
|
||||
import net.minecraft.client.sounds.*;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.*;
|
||||
import net.minecraft.server.packs.repository.PackSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.util.profiling.InactiveProfiler;
|
||||
|
||||
/**
|
||||
* Builds vanilla's sound event registry with the real SoundManager.prepare
|
||||
* (sounds.json read through a resource manager over the client asset root,
|
||||
* files validated against the listed .ogg resources) and Preparations.apply,
|
||||
* then resolves SimpleSoundInstances: getOrResolve with a seeded random,
|
||||
* getVolume/getPitch, and the instance random's next draw (to fix the number
|
||||
* of draws). Lines: "event seed volume pitch".
|
||||
*/
|
||||
public final class VanillaSoundEventOracle {
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static String bits(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String sentinel(Sound sound) {
|
||||
if (sound == SoundManager.EMPTY_SOUND) return "empty";
|
||||
if (sound == SoundManager.INTENTIONALLY_EMPTY_SOUND) return "intentionally_empty";
|
||||
return "-";
|
||||
}
|
||||
|
||||
/** The real registry, prepared from an asset root. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static SoundManager load(Path root) throws Exception {
|
||||
var info = new PackLocationInfo("horizon", Component.literal("horizon"), PackSource.BUILT_IN, Optional.empty());
|
||||
ResourceManager resources = new MultiPackResourceManager(PackType.CLIENT_RESOURCES, List.of(new PathPackResources(info, root)));
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
Object unsafe = field(u, "theUnsafe").get(null);
|
||||
Options options = (Options) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Options.class);
|
||||
var manager = new SoundManager(options);
|
||||
Method prepare = SoundManager.class.getDeclaredMethod("prepare", ResourceManager.class, net.minecraft.util.profiling.ProfilerFiller.class);
|
||||
prepare.setAccessible(true);
|
||||
Object preparations = prepare.invoke(manager, resources, InactiveProfiler.INSTANCE);
|
||||
Method apply = preparations.getClass().getDeclaredMethod("apply", Map.class, Map.class, SoundEngine.class);
|
||||
apply.setAccessible(true);
|
||||
apply.invoke(preparations, field(SoundManager.class, "registry").get(manager), field(SoundManager.class, "soundCache").get(manager),
|
||||
field(SoundManager.class, "soundEngine").get(manager));
|
||||
return manager;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var manager = load(Path.of(args[0]));
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
|
||||
var names = new ArrayList<String>();
|
||||
for (var id : manager.getAvailableSounds()) names.add(id.toString());
|
||||
Collections.sort(names);
|
||||
for (String name : names) out.println("registered " + name);
|
||||
for (String line : Files.readAllLines(Path.of(args[1]))) {
|
||||
String[] f = line.split(" ");
|
||||
long seed = Long.parseLong(f[1]);
|
||||
float volume = Float.intBitsToFloat(Integer.parseUnsignedInt(f[2], 16));
|
||||
float pitch = Float.intBitsToFloat(Integer.parseUnsignedInt(f[3], 16));
|
||||
RandomSource random = RandomSource.create(seed);
|
||||
var instance = new SimpleSoundInstance(Identifier.parse(f[0]), SoundSource.MASTER, volume, pitch, random, false, 0,
|
||||
SoundInstance.Attenuation.LINEAR, 0.0, 0.0, 0.0, false);
|
||||
WeighedSoundEvents event = instance.getOrResolve(manager);
|
||||
Sound sound = instance.getSound();
|
||||
StringBuilder sb = new StringBuilder(line);
|
||||
if (event == null) {
|
||||
sb.append(" event=none");
|
||||
} else {
|
||||
String subtitle = "-";
|
||||
if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey();
|
||||
sb.append(" event weight=").append(event.getWeight()).append(" subtitle=").append(subtitle);
|
||||
}
|
||||
float v = instance.getVolume();
|
||||
float p = instance.getPitch();
|
||||
sb.append(" sound=").append(sound.getLocation()).append(" path=").append(sound.getPath())
|
||||
.append(" sentinel=").append(sentinel(sound))
|
||||
.append(" weight=").append(sound.getWeight())
|
||||
.append(" type=").append(sound.getType().name())
|
||||
.append(" stream=").append(sound.shouldStream())
|
||||
.append(" preload=").append(sound.shouldPreload())
|
||||
.append(" attenuation=").append(sound.getAttenuationDistance())
|
||||
.append(" volume=").append(bits(v))
|
||||
.append(" pitch=").append(bits(p))
|
||||
.append(" range=").append(bits(sound.getAttenuationDistance(v)))
|
||||
.append(" next=").append(random.nextLong());
|
||||
out.println(sb);
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.blaze3d.audio.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
import net.minecraft.client.OptionInstance;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.*;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import org.lwjgl.openal.AL10;
|
||||
|
||||
/**
|
||||
* A real vanilla SoundManager/SoundEngine running on OpenAL Soft's "No Output"
|
||||
* device (ALSOFT_DRIVERS=null), shared by the audio oracles.
|
||||
*
|
||||
* Determinism: the sound executor runs each task inline (the model where the
|
||||
* sound thread keeps up between client ticks); static sounds get one silent
|
||||
* hour-long buffer (they play until stopped or "finished" by the script) and
|
||||
* streams play endless silence. Everything else, the
|
||||
* channel pools, AL source parameters, lifetimes and bookkeeping, is the real
|
||||
* code and the real OpenAL implementation.
|
||||
*/
|
||||
public final class VanillaSoundRig {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
if (unsafe == null) {
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
}
|
||||
return type.cast(allocate.invoke(unsafe, type));
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static Object get(Object target, Class<?> type, String name) throws Exception {
|
||||
return field(type, name).get(target);
|
||||
}
|
||||
|
||||
static void set(Object target, Class<?> type, String name, Object value) throws Exception {
|
||||
field(type, name).set(target, value);
|
||||
}
|
||||
|
||||
/** Runs every task on the calling thread. */
|
||||
public static final class Inline extends SoundEngineExecutor {
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
command.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutDown() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startUp() {
|
||||
}
|
||||
}
|
||||
|
||||
static SoundBuffer silence;
|
||||
|
||||
/** Static sounds: a silent hour; streams: endless silence. */
|
||||
public static final class Buffers extends SoundBufferLibrary {
|
||||
Buffers() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SoundBuffer> getCompleteBuffer(final Identifier location) {
|
||||
return CompletableFuture.completedFuture(silence);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<AudioStream> getStream(final Identifier location, final boolean looping) {
|
||||
return CompletableFuture.completedFuture(new Silence());
|
||||
}
|
||||
}
|
||||
|
||||
/** An endless silent stream, a minute per read (it never runs dry between ticks). */
|
||||
public static final class Silence implements AudioStream {
|
||||
static final AudioFormat FORMAT = new AudioFormat(8000.0F, 8, 1, false, false);
|
||||
|
||||
@Override
|
||||
public AudioFormat getFormat() {
|
||||
return FORMAT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer read(final int expectedSize) {
|
||||
ByteBuffer data = ByteBuffer.allocateDirect(8000 * 60);
|
||||
for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80);
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
|
||||
public final SoundManager manager;
|
||||
public final SoundEngine engine;
|
||||
public final Options options;
|
||||
public final List<String> heard = new ArrayList<>();
|
||||
|
||||
public VanillaSoundRig(Path root) throws Exception {
|
||||
manager = VanillaSoundEventOracle.load(root);
|
||||
engine = (SoundEngine) get(manager, SoundManager.class, "soundEngine");
|
||||
options = (Options) get(engine, SoundEngine.class, "options");
|
||||
var inline = make(Inline.class);
|
||||
set(engine, SoundEngine.class, "executor", inline);
|
||||
set(get(engine, SoundEngine.class, "channelAccess"), ChannelAccess.class, "executor", inline);
|
||||
set(engine, SoundEngine.class, "soundBuffers", make(Buffers.class));
|
||||
Library library = (Library) get(engine, SoundEngine.class, "library");
|
||||
library.init(null, DeviceList.query(), false);
|
||||
ByteBuffer data = ByteBuffer.allocateDirect(8000 * 3600);
|
||||
for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80);
|
||||
silence = new SoundBuffer(data, new AudioFormat(8000.0F, 8, 1, false, false));
|
||||
set(engine, SoundEngine.class, "loaded", true);
|
||||
Method slider = Options.class.getDeclaredMethod("createSoundSliderOptionInstance", String.class, SoundSource.class);
|
||||
slider.setAccessible(true);
|
||||
var volumes = new EnumMap<SoundSource, OptionInstance<Double>>(SoundSource.class);
|
||||
for (SoundSource source : SoundSource.values()) {
|
||||
volumes.put(source, (OptionInstance<Double>) slider.invoke(options, "soundCategory." + source.getName(), source));
|
||||
}
|
||||
set(options, Options.class, "soundSourceVolumes", volumes);
|
||||
manager.addListener((sound, event, range) -> {
|
||||
String subtitle = "-";
|
||||
if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey();
|
||||
heard.add(String.format("notify %s %s %08x %s %016x %016x %016x", sound.getIdentifier(), subtitle, Float.floatToRawIntBits(range),
|
||||
sound.isLooping(), Double.doubleToRawLongBits(sound.getX()), Double.doubleToRawLongBits(sound.getY()),
|
||||
Double.doubleToRawLongBits(sound.getZ())));
|
||||
});
|
||||
}
|
||||
|
||||
/** Set a sound source volume option without its change callback. */
|
||||
public void volume(SoundSource source, double value) throws Exception {
|
||||
set(options.getSoundSourceOptionInstance(source), OptionInstance.class, "value", value);
|
||||
}
|
||||
|
||||
/** The channel of an instance, or null. */
|
||||
@SuppressWarnings("unchecked")
|
||||
public Channel channel(SoundInstance instance) throws Exception {
|
||||
var map = (Map<SoundInstance, ChannelAccess.ChannelHandle>) get(engine, SoundEngine.class, "instanceToChannel");
|
||||
var handle = map.get(instance);
|
||||
return handle == null ? null : (Channel) get(handle, ChannelAccess.ChannelHandle.class, "channel");
|
||||
}
|
||||
|
||||
/** The channel's end: what OpenAL does when a non-looping buffer runs out. */
|
||||
public void finish(SoundInstance instance) throws Exception {
|
||||
var channel = channel(instance);
|
||||
if (channel != null) channel.stop();
|
||||
}
|
||||
|
||||
static String fbits(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
/** One line describing an instance: activity and its AL source. */
|
||||
public String describe(String name, SoundInstance instance) throws Exception {
|
||||
StringBuilder sb = new StringBuilder(" ").append(name).append(" active=").append(manager.isActive(instance));
|
||||
var channel = channel(instance);
|
||||
if (channel == null) {
|
||||
sb.append(" channel=-");
|
||||
} else {
|
||||
int source = (int) get(channel, Channel.class, "source");
|
||||
boolean initialized = ((java.util.concurrent.atomic.AtomicBoolean) get(channel, Channel.class, "initialized")).get();
|
||||
if (!initialized) {
|
||||
sb.append(" channel=released");
|
||||
} else {
|
||||
float[] pos = new float[3];
|
||||
AL10.alGetSourcefv(source, AL10.AL_POSITION, pos);
|
||||
sb.append(String.format(" state=%x gain=%s pitch=%s pos=%s,%s,%s rel=%d loop=%d model=%x max=%s rolloff=%s ref=%s",
|
||||
AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE), fbits(AL10.alGetSourcef(source, AL10.AL_GAIN)),
|
||||
fbits(AL10.alGetSourcef(source, AL10.AL_PITCH)), fbits(pos[0]), fbits(pos[1]), fbits(pos[2]),
|
||||
AL10.alGetSourcei(source, AL10.AL_SOURCE_RELATIVE), AL10.alGetSourcei(source, AL10.AL_LOOPING),
|
||||
AL10.alGetSourcei(source, 0xD000), fbits(AL10.alGetSourcef(source, AL10.AL_MAX_DISTANCE)),
|
||||
fbits(AL10.alGetSourcef(source, AL10.AL_ROLLOFF_FACTOR)), fbits(AL10.alGetSourcef(source, AL10.AL_REFERENCE_DISTANCE))));
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** Print and clear the notifications, then the channel counts. */
|
||||
public void flush(PrintWriter out) {
|
||||
for (String h : heard) out.println(h);
|
||||
heard.clear();
|
||||
out.println(" " + manager.getChannelDebugString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
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.util.RandomSource;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
|
||||
/**
|
||||
* Original oracle: SpawnPlacements.isSpawnPositionOk and checkSpawnRules for an
|
||||
* entity type at a position of a controlled column world. The stand-in
|
||||
* ServerLevel answers block states from the case (air elsewhere), uniform sky
|
||||
* and block light, the sky darkening, thunder, difficulty, dimension type,
|
||||
* biome, sea level, WORLD_SURFACE height, world seed, the surface slime spawn
|
||||
* chance and an optional nearby player. Each case prints the two answers and
|
||||
* the next nextInt(1000) of its random, which pins the number of draws.
|
||||
*/
|
||||
public final class VanillaSpawnRulesOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate, putObject, objectFieldOffset;
|
||||
|
||||
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
|
||||
|
||||
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value);
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
RegistryAccess registries;
|
||||
Map<Integer, BlockState> column = new HashMap<>();
|
||||
int x0, z0, sky, block, darken, sea, surface;
|
||||
boolean thunder;
|
||||
long seed;
|
||||
Difficulty difficulty;
|
||||
DimensionType dimension;
|
||||
Holder<Biome> biome;
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
List<Player> playerList = new ArrayList<>();
|
||||
WorldBorder border = new WorldBorder();
|
||||
int next = 1;
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) {
|
||||
if (pos.getX() != x0 || pos.getZ() != z0) return Blocks.AIR.defaultBlockState();
|
||||
return column.getOrDefault(pos.getY(), Blocks.AIR.defaultBlockState());
|
||||
}
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
@Override public int getBrightness(LightLayer layer, BlockPos pos) { return layer == LightLayer.SKY ? sky : block; }
|
||||
@Override public int getRawBrightness(BlockPos pos, int darkening) { return Math.max(block, sky - darkening); }
|
||||
@Override public int getSkyDarken() { return darken; }
|
||||
@Override public boolean isThundering() { return thunder; }
|
||||
@Override public int getSeaLevel() { return sea; }
|
||||
@Override public int getHeight(Heightmap.Types type, int x, int z) { return surface; }
|
||||
@Override public long getSeed() { return seed; }
|
||||
@Override public DimensionType dimensionType() { return dimension; }
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public WorldBorder getWorldBorder() { return border; }
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override public List players() { return playerList; }
|
||||
}
|
||||
|
||||
static final class OraclePlayer extends Player {
|
||||
final GameType mode;
|
||||
OraclePlayer(Level level, GameType mode) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); this.mode = mode; }
|
||||
@Override public GameType gameMode() { return mode; }
|
||||
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
|
||||
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
|
||||
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); }
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
|
||||
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
|
||||
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();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess();
|
||||
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.registries = access;
|
||||
level.column = new HashMap<>();
|
||||
level.playerList = new ArrayList<>();
|
||||
level.border = new WorldBorder();
|
||||
put(level, Level.class, "random", RandomSource.create(0L));
|
||||
var biomes = access.lookupOrThrow(Registries.BIOME);
|
||||
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var blocks = access.lookupOrThrow(Registries.BLOCK);
|
||||
|
||||
if (args.length > 2 && args[2].equals("facts")) {
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE)
|
||||
w.println(BuiltInRegistries.ENTITY_TYPE.getKey(type) + " peaceful=" + type.isAllowedInPeaceful() + " fire_immune=" + type.fireImmune()
|
||||
+ " placement=" + SpawnPlacements.getPlacementType(type) + " heightmap=" + SpawnPlacements.getHeightmapType(type));
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String raw : lines) {
|
||||
if (raw.isBlank()) continue;
|
||||
Map<String, String> c = new LinkedHashMap<>();
|
||||
for (String token : raw.trim().split("\\s+")) {
|
||||
int eq = token.indexOf('=');
|
||||
if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1));
|
||||
}
|
||||
try {
|
||||
int y = Integer.parseInt(c.getOrDefault("y", "64"));
|
||||
level.x0 = Integer.parseInt(c.getOrDefault("x", "8"));
|
||||
level.z0 = Integer.parseInt(c.getOrDefault("z", "8"));
|
||||
level.column.clear();
|
||||
for (var e : c.entrySet()) {
|
||||
if (e.getKey().startsWith("at")) {
|
||||
int offset = Integer.parseInt(e.getKey().substring(2));
|
||||
level.column.put(y + offset, net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blocks, e.getValue(), false).blockState());
|
||||
}
|
||||
}
|
||||
level.sky = Integer.parseInt(c.getOrDefault("sky", "15"));
|
||||
level.block = Integer.parseInt(c.getOrDefault("light", "0"));
|
||||
level.darken = Integer.parseInt(c.getOrDefault("darken", "0"));
|
||||
level.thunder = c.getOrDefault("thunder", "0").equals("1");
|
||||
level.sea = Integer.parseInt(c.getOrDefault("sea", "63"));
|
||||
level.surface = Integer.parseInt(c.getOrDefault("surface", "0"));
|
||||
level.seed = Long.parseLong(c.getOrDefault("wseed", "0"));
|
||||
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
|
||||
level.dimension = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")))).value();
|
||||
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder()
|
||||
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
|
||||
.set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0")))
|
||||
.build())
|
||||
.build();
|
||||
level.playerList.clear();
|
||||
if (c.containsKey("player")) {
|
||||
String[] p = c.get("player").split(",");
|
||||
Player player = new OraclePlayer(level, GameType.byName(p.length > 3 ? p[3] : "survival"));
|
||||
player.setPos(level.x0 + Double.parseDouble(p[0]), y + Double.parseDouble(p[1]), level.z0 + Double.parseDouble(p[2]));
|
||||
level.playerList.add(player);
|
||||
}
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
|
||||
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "natural").toUpperCase(Locale.ROOT));
|
||||
BlockPos pos = new BlockPos(level.x0, y, level.z0);
|
||||
RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
boolean ok = SpawnPlacements.isSpawnPositionOk(type, level, pos);
|
||||
boolean rules = SpawnPlacements.checkSpawnRules(type, level, reason, pos, random);
|
||||
w.println(c.get("name") + " " + ok + " " + rules + " " + random.nextInt(1000));
|
||||
} catch (Throwable t) {
|
||||
Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t;
|
||||
StringBuilder line = new StringBuilder(c.get("name") + " error " + cause);
|
||||
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame);
|
||||
w.println(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.InputConstants;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
|
||||
/**
|
||||
* Drives the real Options key mappings (keyShift, keySprint, keyAttack and
|
||||
* keyUse are ToggleKeyMappings reading toggleCrouch/toggleSprint/toggleAttack/
|
||||
* toggleUse) through the real static KeyMapping.set/click, releaseAll,
|
||||
* restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as
|
||||
* KeyboardHandler.keyPress, MouseHandler.onButton, Gui.setScreen and
|
||||
* LocalPlayer.respawn call them, and prints each mapping's down state and
|
||||
* pending clicks after every event.
|
||||
*/
|
||||
public final class VanillaToggleKeysOracle {
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
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 unsafe = field(u, "theUnsafe").get(null);
|
||||
Minecraft shell = (Minecraft) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Minecraft.class);
|
||||
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
|
||||
field(Minecraft.class, "instance").set(null, shell);
|
||||
Options options = new Options(shell, Files.createTempDirectory("opts").toFile());
|
||||
KeyMapping[] mappings = {options.keyShift, options.keySprint, options.keyAttack, options.keyUse};
|
||||
List<OptionInstance<Boolean>> toggles = List.of(options.toggleCrouch(), options.toggleSprint(), options.toggleAttack(), options.toggleUse());
|
||||
Field keyField = field(KeyMapping.class, "key");
|
||||
Field clicks = field(KeyMapping.class, "clickCount");
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int n = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
out.println("== " + n++);
|
||||
// A fresh session: everything up, no pending clicks or remembered releases.
|
||||
for (int i = 0; i < 4; i++) {
|
||||
toggles.get(i).set(false);
|
||||
}
|
||||
KeyMapping.resetToggleKeys();
|
||||
KeyMapping.releaseAll();
|
||||
KeyMapping.restoreToggleStatesOnScreenClosed();
|
||||
for (var m : mappings) {
|
||||
while (m.consumeClick()) {
|
||||
}
|
||||
}
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
switch (name) {
|
||||
case "option" -> toggles.get(op.get(1).getAsInt()).set(op.get(2).getAsBoolean());
|
||||
case "key" -> {
|
||||
// KeyboardHandler.keyPress: action 0 releases; a press (1) or an SDL
|
||||
// repeat (-1) sets and clicks only with no screen open.
|
||||
var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]);
|
||||
int action = op.get(2).getAsInt();
|
||||
boolean screen = op.get(3).getAsBoolean();
|
||||
if (action == 0) {
|
||||
KeyMapping.set(key, false);
|
||||
} else if (!screen) {
|
||||
KeyMapping.set(key, true);
|
||||
KeyMapping.click(key);
|
||||
}
|
||||
}
|
||||
case "button" -> {
|
||||
// MouseHandler.onButton: only with no screen or overlay.
|
||||
var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]);
|
||||
boolean pressed = op.get(2).getAsBoolean();
|
||||
if (!op.get(3).getAsBoolean()) {
|
||||
KeyMapping.set(key, pressed);
|
||||
if (pressed) {
|
||||
KeyMapping.click(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "open" -> KeyMapping.releaseAll();
|
||||
case "close" -> KeyMapping.restoreToggleStatesOnScreenClosed();
|
||||
case "respawn" -> KeyMapping.resetToggleKeys();
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
var sb = new StringBuilder(name);
|
||||
for (var m : mappings) {
|
||||
sb.append(' ').append(m.isDown()).append(' ').append(clicks.getInt(m));
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user