Merge branch 'parity-base' into parity/old-saves
This commit is contained in:
@@ -0,0 +1,527 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
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.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.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.DifficultyInstance;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.enchantment.ItemEnchantments;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
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.entity.EntityTypeTest;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Original oracle: Mob.finalizeSpawn as vanilla runs it, for every mob type,
|
||||
* spawn reason, difficulty and local difficulty, on a stand-in ServerLevel
|
||||
* (one biome, an optional structure piece, a floor and an optional roof,
|
||||
* chickens standing by, the moon phase).
|
||||
*
|
||||
* Each case seeds the level random (what finalizeSpawn reads through
|
||||
* level.getRandom()) and the entities' own randoms: every entity created
|
||||
* in the case, the case's mobs and the jockeys finalizeSpawn makes, gets
|
||||
* a LegacyRandomSource seeded eseed + its creation index, swapped in
|
||||
* through each EntityType's factory. A pack of mobs is finalized in turn
|
||||
* with the group data passed along, as NaturalSpawner does, each added to
|
||||
* the level with its passengers.
|
||||
*
|
||||
* The log lists every entity of the case in creation order (equipment and
|
||||
* enchantments, drop chances, CanPickUpLoot, LeftHanded, persistence, age,
|
||||
* health, attribute values, effects, the species' variant state and spawn
|
||||
* memories, its vehicle) and the next draws of the level random and of each
|
||||
* entity's random, which pin every draw in between.
|
||||
*/
|
||||
public final class VanillaFinalizeSpawnOracle {
|
||||
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 Object get(Object target, Class<?> owner, String field) {
|
||||
try {
|
||||
Field f = owner.getDeclaredField(field);
|
||||
f.setAccessible(true);
|
||||
return f.get(target);
|
||||
} catch (Exception e) { throw new RuntimeException(e); }
|
||||
}
|
||||
|
||||
static final class Lvl extends ServerLevel {
|
||||
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
|
||||
RegistryAccess registries;
|
||||
net.minecraft.server.MinecraftServer fake;
|
||||
BlockState floor;
|
||||
int floorY, roofY;
|
||||
Holder<Biome> biome;
|
||||
Difficulty difficulty;
|
||||
DimensionType dimensionType;
|
||||
ResourceKey<Level> dimensionKey;
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
|
||||
BiomeManager biomeManager;
|
||||
WorldBorder border = new WorldBorder();
|
||||
GameRules rules;
|
||||
Structures structures;
|
||||
RandomSource levelRandom;
|
||||
long time;
|
||||
int next = 1;
|
||||
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return time; }
|
||||
@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.getY() == floorY) return floor;
|
||||
if (pos.getY() == roofY) return Blocks.STONE.defaultBlockState();
|
||||
return Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
@Override public DimensionType dimensionType() { return dimensionType; }
|
||||
@Override public ResourceKey<Level> dimension() { return dimensionKey; }
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
|
||||
@Override public BiomeManager getBiomeManager() { return biomeManager; }
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
|
||||
@Override public WorldBorder getWorldBorder() { return border; }
|
||||
@Override public GameRules getGameRules() { return rules; }
|
||||
@Override public RandomSource getRandom() { return levelRandom; }
|
||||
@Override public int getSeaLevel() { return 63; }
|
||||
net.minecraft.server.ServerScoreboard scoreboard;
|
||||
@Override public net.minecraft.server.ServerScoreboard getScoreboard() { return scoreboard; }
|
||||
@Override public net.minecraft.world.level.StructureManager structureManager() { return structures; }
|
||||
@Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; }
|
||||
@Override public boolean isSpawningMonsters() { return rules.get(GameRules.SPAWN_MOBS) && rules.get(GameRules.SPAWN_MONSTERS); }
|
||||
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
|
||||
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, net.minecraft.world.entity.Entity sourceEntity, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
|
||||
@Override public void gameEvent(Holder<net.minecraft.world.level.gameevent.GameEvent> gameEvent, Vec3 position, net.minecraft.world.level.gameevent.GameEvent.Context context) {}
|
||||
@Override public void broadcastEntityEvent(Entity entity, byte event) {}
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@Override public List players() { return List.of(); }
|
||||
@Override public Iterable<Entity> getAllEntities() { return entities; }
|
||||
@Override public List<Entity> getEntities(Entity except, AABB bb, Predicate<? super Entity> selector) {
|
||||
List<Entity> out = new ArrayList<>();
|
||||
for (Entity e : entities) if (e != except && e.getBoundingBox().intersects(bb) && selector.test(e)) out.add(e);
|
||||
return out;
|
||||
}
|
||||
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) {
|
||||
List<T> out = new ArrayList<>();
|
||||
for (Entity e : entities) {
|
||||
T t = type.tryCast(e);
|
||||
if (t != null && e.getBoundingBox().intersects(bb) && selector.test(t)) out.add(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity entity) { if (!entities.contains(entity)) entities.add(entity); return true; }
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
|
||||
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) { return null; }
|
||||
}
|
||||
|
||||
/** One structure start whose single piece covers a box around the spawn point. */
|
||||
static final class Structures extends net.minecraft.world.level.StructureManager {
|
||||
Structures() { super(null, null, null); }
|
||||
Lvl level;
|
||||
Structure structure;
|
||||
StructureStart start;
|
||||
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Predicate<Structure> matcher) {
|
||||
return start != null && matcher.test(structure) ? List.of(start) : List.of();
|
||||
}
|
||||
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Structure s) {
|
||||
return start != null && s == structure ? List.of(start) : List.of();
|
||||
}
|
||||
@Override public RegistryAccess registryAccess() { return level.registries; }
|
||||
}
|
||||
|
||||
static final class Piece extends StructurePiece {
|
||||
Piece(BoundingBox box) { super(null, 0, box); }
|
||||
@Override protected void addAdditionalSaveData(net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext context, net.minecraft.nbt.CompoundTag tag) {}
|
||||
@Override public void postProcess(WorldGenLevel level, net.minecraft.world.level.StructureManager structureManager, net.minecraft.world.level.chunk.ChunkGenerator generator, RandomSource random,
|
||||
BoundingBox chunkBB, ChunkPos chunkPos, BlockPos referencePos) {}
|
||||
}
|
||||
|
||||
/** Entities created in the current case, and the seed base of their randoms. */
|
||||
static List<Entity> created = new ArrayList<>();
|
||||
static long entitySeed;
|
||||
static boolean seeding;
|
||||
static int otherIds;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static void wrapFactories() throws Exception {
|
||||
Field factory = EntityType.class.getDeclaredField("factory");
|
||||
long offset = (long) objectFieldOffset.invoke(unsafe, factory);
|
||||
factory.setAccessible(true);
|
||||
for (EntityType<?> type : BuiltInRegistries.ENTITY_TYPE) {
|
||||
EntityType.EntityFactory original = (EntityType.EntityFactory) factory.get(type);
|
||||
EntityType.EntityFactory wrapped = (t, level) -> {
|
||||
Entity e = original.create(t, level);
|
||||
if (e != null && !seeding) e.setId(1000000 + otherIds++);
|
||||
if (e != null && seeding) {
|
||||
try {
|
||||
put(e, Entity.class, "random", RandomSource.create(entitySeed + created.size()));
|
||||
} catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
created.add(e);
|
||||
e.setId(created.size());
|
||||
}
|
||||
return e;
|
||||
};
|
||||
putObject.invoke(unsafe, type, offset, wrapped);
|
||||
}
|
||||
}
|
||||
|
||||
static String hex(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
|
||||
static String hex(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
static String id(Holder<?> h) { return h.unwrapKey().map(k -> k.identifier().toString()).orElse("?"); }
|
||||
|
||||
static final EquipmentSlot[] SLOTS = {EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND, EquipmentSlot.FEET, EquipmentSlot.LEGS,
|
||||
EquipmentSlot.CHEST, EquipmentSlot.HEAD, EquipmentSlot.BODY, EquipmentSlot.SADDLE};
|
||||
|
||||
static String stack(ItemStack s) {
|
||||
StringBuilder b = new StringBuilder(BuiltInRegistries.ITEM.getKey(s.getItem()).toString());
|
||||
if (s.getCount() != 1) b.append('x').append(s.getCount());
|
||||
ItemEnchantments e = s.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);
|
||||
if (!e.isEmpty()) {
|
||||
List<String> list = new ArrayList<>();
|
||||
for (var entry : e.entrySet()) list.add(id(entry.getKey()) + "=" + entry.getIntValue());
|
||||
list.sort(null);
|
||||
b.append('[').append(String.join(",", list)).append(']');
|
||||
}
|
||||
// Components besides enchantments (the ominous banner's).
|
||||
int other = s.getComponentsPatch().forget(t -> t == DataComponents.ENCHANTMENTS).size();
|
||||
if (other > 0) b.append('*').append(other);
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
/** Loaded after the bootstrap. */
|
||||
static final class Lists {
|
||||
static final List<Map.Entry<String, Holder<Attribute>>> ATTRIBUTES = List.of(
|
||||
Map.entry("max_health", Attributes.MAX_HEALTH), Map.entry("movement_speed", Attributes.MOVEMENT_SPEED),
|
||||
Map.entry("follow_range", Attributes.FOLLOW_RANGE), Map.entry("attack_damage", Attributes.ATTACK_DAMAGE),
|
||||
Map.entry("knockback_resistance", Attributes.KNOCKBACK_RESISTANCE), Map.entry("spawn_reinforcements", Attributes.SPAWN_REINFORCEMENTS_CHANCE),
|
||||
Map.entry("jump_strength", Attributes.JUMP_STRENGTH));
|
||||
|
||||
static final List<Map.Entry<String, MemoryModuleType<?>>> MEMORIES = List.of(
|
||||
Map.entry("long_jump_cooldown", MemoryModuleType.LONG_JUMP_COOLDOWN_TICKS), Map.entry("ram_cooldown", MemoryModuleType.RAM_COOLDOWN_TICKS),
|
||||
Map.entry("attack_target_cooldown", MemoryModuleType.ATTACK_TARGET_COOLDOWN), Map.entry("hunted_recently", MemoryModuleType.HUNTED_RECENTLY),
|
||||
Map.entry("dig_cooldown", MemoryModuleType.DIG_COOLDOWN), Map.entry("is_emerging", MemoryModuleType.IS_EMERGING),
|
||||
Map.entry("home", MemoryModuleType.HOME));
|
||||
}
|
||||
|
||||
/** The species state finalizeSpawn sets. */
|
||||
static void variant(Entity e, List<String> v) {
|
||||
if (e instanceof net.minecraft.world.entity.animal.pig.Pig p) {
|
||||
v.add(id(p.getVariant()));
|
||||
v.add(id((Holder<?>) data(p, p.getClass(), "DATA_SOUND_VARIANT_ID")));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.cow.Cow c) {
|
||||
v.add(id(c.getVariant()));
|
||||
v.add(id((Holder<?>) data(c, net.minecraft.world.entity.animal.cow.Cow.class, "DATA_SOUND_VARIANT_ID")));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.cow.MushroomCow m) {
|
||||
v.add(m.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.chicken.Chicken c) {
|
||||
v.add(id(c.getVariant()));
|
||||
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
|
||||
v.add("jockey=" + c.isChickenJockey());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.feline.Cat c) {
|
||||
v.add(id(c.getVariant()));
|
||||
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.wolf.Wolf w) {
|
||||
v.add(id((Holder<?>) call(w, net.minecraft.world.entity.animal.wolf.Wolf.class, "getVariant")));
|
||||
v.add(id((Holder<?>) data(w, w.getClass(), "DATA_SOUND_VARIANT_ID")));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.frog.Frog f) {
|
||||
v.add(id(f.getVariant()));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.nautilus.ZombieNautilus n) {
|
||||
v.add(id(n.getVariant()));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.sheep.Sheep s) {
|
||||
v.add(s.getColor().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.equine.Horse h) {
|
||||
v.add(h.getVariant().getSerializedName() + "/" + h.getMarkings().name().toLowerCase(Locale.ROOT));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.equine.Llama l) {
|
||||
v.add(l.getVariant().getSerializedName() + "/" + l.getStrength());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.equine.SkeletonHorse h) {
|
||||
v.add("trap=" + h.isTrap());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.fox.Fox f) {
|
||||
v.add(f.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.rabbit.Rabbit r) {
|
||||
v.add(r.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.parrot.Parrot p) {
|
||||
v.add(p.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.axolotl.Axolotl a) {
|
||||
v.add(a.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.fish.TropicalFish f) {
|
||||
v.add(String.valueOf(call(f, net.minecraft.world.entity.animal.fish.TropicalFish.class, "getPackedVariant")));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.fish.Salmon s) {
|
||||
v.add(s.getVariant().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.panda.Panda p) {
|
||||
v.add(p.getMainGene().getSerializedName() + "/" + p.getHiddenGene().getSerializedName());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.goat.Goat g) {
|
||||
v.add("scream=" + g.isScreamingGoat() + " horns=" + g.hasLeftHorn() + "," + g.hasRightHorn());
|
||||
} else if (e instanceof net.minecraft.world.entity.monster.cubemob.AbstractCubeMob s) {
|
||||
v.add("size=" + s.getSize());
|
||||
} else if (e instanceof net.minecraft.world.entity.npc.villager.Villager vi) {
|
||||
v.add(id(vi.getVillagerData().type()) + "/" + id(vi.getVillagerData().profession()) + "/" + vi.getVillagerData().level());
|
||||
} else if (e instanceof net.minecraft.world.entity.monster.zombie.ZombieVillager z) {
|
||||
// The profession comes from the constructor's unseeded random.
|
||||
v.add(id(z.getVillagerData().type()) + "/" + z.getVillagerData().level());
|
||||
} else if (e instanceof net.minecraft.world.entity.monster.Phantom p) {
|
||||
v.add("size=" + p.getPhantomSize());
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.turtle.Turtle t) {
|
||||
BlockPos h = (BlockPos) get(t, net.minecraft.world.entity.animal.turtle.Turtle.class, "homePos");
|
||||
v.add("home=" + (h == null ? "-" : h.getX() + "," + h.getY() + "," + h.getZ()));
|
||||
} else if (e instanceof net.minecraft.world.entity.animal.dolphin.Dolphin d) {
|
||||
v.add("air=" + d.getAirSupply());
|
||||
}
|
||||
if (e instanceof net.minecraft.world.entity.monster.zombie.Zombie z) v.add("doors=" + z.canBreakDoors());
|
||||
if (e instanceof net.minecraft.world.entity.monster.PatrollingMonster p) v.add("leader=" + p.isPatrolLeader() + " patrolling=" + call(p, net.minecraft.world.entity.monster.PatrollingMonster.class, "isPatrolling"));
|
||||
if (e instanceof net.minecraft.world.entity.raid.Raider r) v.add("raid=" + r.canJoinRaid());
|
||||
if (e instanceof net.minecraft.world.entity.monster.Strider s) v.add("saddled=" + s.isSaddled());
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static Object data(Entity e, Class<?> owner, String name) {
|
||||
return e.getEntityData().get((net.minecraft.network.syncher.EntityDataAccessor) fieldValue(owner, name));
|
||||
}
|
||||
|
||||
static Object call(Object target, Class<?> owner, String name) {
|
||||
try {
|
||||
Method m = owner.getDeclaredMethod(name);
|
||||
m.setAccessible(true);
|
||||
return m.invoke(target);
|
||||
} catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
}
|
||||
|
||||
static Object fieldValue(Class<?> owner, String name) {
|
||||
try {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f.get(null);
|
||||
} catch (Exception ex) { throw new RuntimeException(ex); }
|
||||
}
|
||||
|
||||
static String describe(Entity e, List<Entity> all) {
|
||||
List<String> t = new ArrayList<>();
|
||||
t.add(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString());
|
||||
Entity vehicle = e.getVehicle();
|
||||
t.add("veh=" + (vehicle == null ? "-" : Integer.toString(all.indexOf(vehicle))));
|
||||
if (e instanceof AgeableMob a) t.add("age=" + a.getAge());
|
||||
else if (e instanceof LivingEntity l) t.add("baby=" + l.isBaby());
|
||||
if (e instanceof LivingEntity l) t.add("hp=" + hex(l.getHealth()));
|
||||
if (e instanceof Mob m) {
|
||||
t.add("lh=" + m.isLeftHanded());
|
||||
t.add("loot=" + m.canPickUpLoot());
|
||||
t.add("persist=" + m.isPersistenceRequired());
|
||||
List<String> eq = new ArrayList<>();
|
||||
for (EquipmentSlot s : SLOTS) {
|
||||
ItemStack st = m.getItemBySlot(s);
|
||||
if (!st.isEmpty()) eq.add(s.getSerializedName() + ":" + stack(st));
|
||||
}
|
||||
t.add("eq=" + (eq.isEmpty() ? "-" : String.join(";", eq)));
|
||||
List<String> drops = new ArrayList<>();
|
||||
for (EquipmentSlot s : SLOTS) {
|
||||
float d = m.getDropChances().byEquipment(s);
|
||||
if (d != 0.085F) drops.add(s.getSerializedName() + ":" + hex(d));
|
||||
}
|
||||
t.add("drop=" + (drops.isEmpty() ? "-" : String.join(";", drops)));
|
||||
}
|
||||
if (e instanceof LivingEntity l) {
|
||||
List<String> attrs = new ArrayList<>();
|
||||
for (var a : Lists.ATTRIBUTES) {
|
||||
AttributeInstance inst = l.getAttribute(a.getValue());
|
||||
if (inst != null) attrs.add(a.getKey() + ":" + hex(inst.getValue()));
|
||||
}
|
||||
t.add("a=" + String.join(",", attrs));
|
||||
List<String> fx = new ArrayList<>();
|
||||
for (MobEffectInstance i : l.getActiveEffects()) fx.add(id(i.getEffect()) + ":" + i.getAmplifier() + ":" + i.getDuration());
|
||||
fx.sort(null);
|
||||
t.add("fx=" + (fx.isEmpty() ? "-" : String.join(",", fx)));
|
||||
Brain<?> brain = l.getBrain();
|
||||
List<String> mem = new ArrayList<>();
|
||||
for (var m : Lists.MEMORIES) {
|
||||
if (!brain.hasMemoryValue(m.getValue())) continue;
|
||||
Object value = brain.getMemory(m.getValue()).orElse(null);
|
||||
String text = value instanceof GlobalPos g ? g.pos().getX() + "," + g.pos().getY() + "," + g.pos().getZ() : String.valueOf(value);
|
||||
mem.add(m.getKey() + ":" + text + ":" + brain.getTimeUntilExpiry(m.getValue()));
|
||||
}
|
||||
if (!mem.isEmpty()) t.add("mem=" + String.join(",", mem));
|
||||
}
|
||||
List<String> v = new ArrayList<>();
|
||||
variant(e, v);
|
||||
if (!v.isEmpty()) t.add("v=" + String.join(" ", v).replace(' ', '_'));
|
||||
return String.join(" ", t);
|
||||
}
|
||||
|
||||
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 = net.minecraft.server.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();
|
||||
var biomes = access.lookupOrThrow(Registries.BIOME);
|
||||
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var blockLookup = access.lookupOrThrow(Registries.BLOCK);
|
||||
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
|
||||
|
||||
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
put(level, ServerLevel.class, "server", server);
|
||||
level.registries = access;
|
||||
// Level.playSound draws a sound seed before the (ignored) seeded sound.
|
||||
put(level, net.minecraft.world.level.Level.class, "soundSeedGenerator", RandomSource.create(0L));
|
||||
level.entities = new ArrayList<>();
|
||||
level.scoreboard = new net.minecraft.server.ServerScoreboard(server);
|
||||
level.border = new WorldBorder();
|
||||
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
|
||||
level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) {
|
||||
@Override public Holder<Biome> getBiome(BlockPos pos) { return level.biome; }
|
||||
@Override public Holder<Biome> getBiome(int x, int y, int z) { return level.biome; }
|
||||
};
|
||||
Structures structures = (Structures) alloc(Structures.class);
|
||||
structures.level = level;
|
||||
level.structures = structures;
|
||||
wrapFactories();
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
w.println("halloween " + net.minecraft.util.SpecialDates.isHalloween());
|
||||
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 {
|
||||
level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")));
|
||||
level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value();
|
||||
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
|
||||
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
|
||||
level.time = Long.parseLong(c.getOrDefault("time", "0"));
|
||||
level.rules.set(GameRules.SPAWN_MONSTERS, !c.getOrDefault("monsters", "1").equals("0"), null);
|
||||
int phase = Integer.parseInt(c.getOrDefault("phase", "0"));
|
||||
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level)
|
||||
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
|
||||
.set(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, MoonPhase.values()[phase]).build())
|
||||
.build();
|
||||
String[] p = c.get("pos").split(",");
|
||||
double x = Double.parseDouble(p[0]), y = Double.parseDouble(p[1]), z = Double.parseDouble(p[2]);
|
||||
BlockPos block = BlockPos.containing(x, y, z);
|
||||
level.floorY = block.getY() - 1;
|
||||
level.floor = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, c.getOrDefault("floor", "minecraft:grass_block"), false).blockState();
|
||||
level.roofY = c.containsKey("roof") ? block.getY() + Integer.parseInt(c.get("roof")) : Integer.MIN_VALUE;
|
||||
structures.start = null;
|
||||
if (c.containsKey("structure")) {
|
||||
structures.structure = structureLookup.getValue(Identifier.parse(c.get("structure")));
|
||||
BoundingBox box = new BoundingBox(block.getX() - 8, block.getY() - 8, block.getZ() - 8, block.getX() + 8, block.getY() + 8, block.getZ() + 8);
|
||||
structures.start = new StructureStart(structures.structure, new ChunkPos(block.getX() >> 4, block.getZ() >> 4), 0,
|
||||
new PiecesContainer(List.of(new Piece(box))));
|
||||
}
|
||||
level.entities.clear();
|
||||
level.levelRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
put(level, Level.class, "random", level.levelRandom);
|
||||
created = new ArrayList<>();
|
||||
entitySeed = Long.parseLong(c.getOrDefault("eseed", "0"));
|
||||
seeding = true;
|
||||
// Chickens already standing by (zombie jockeys look for one).
|
||||
int chickens = Integer.parseInt(c.getOrDefault("chickens", "0"));
|
||||
for (int i = 0; i < chickens; i++) {
|
||||
Entity chicken = EntityTypes.CHICKEN.create(level, EntitySpawnReason.LOAD);
|
||||
chicken.setPos(x + i, y, z);
|
||||
level.entities.add(chicken);
|
||||
}
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
|
||||
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "NATURAL"));
|
||||
float moon = DimensionType.MOON_BRIGHTNESS_PER_PHASE[phase];
|
||||
DifficultyInstance difficulty = new DifficultyInstance(level.difficulty, level.time, Long.parseLong(c.getOrDefault("inhabited", "0")), moon);
|
||||
int pack = Integer.parseInt(c.getOrDefault("pack", "1"));
|
||||
SpawnGroupData group = null;
|
||||
for (int i = 0; i < pack; i++) {
|
||||
Entity e = type.create(level, reason);
|
||||
if (e == null) break; // monsters do not exist in peaceful
|
||||
if (!(e instanceof Mob mob)) throw new IllegalStateException("not a mob");
|
||||
mob.snapTo(x, y, z, 0.0F, 0.0F);
|
||||
group = mob.finalizeSpawn(level, difficulty, reason, group);
|
||||
level.addFreshEntityWithPassengers(mob);
|
||||
}
|
||||
seeding = false;
|
||||
List<String> out = new ArrayList<>();
|
||||
for (Entity e : created) out.add(describe(e, created));
|
||||
for (Entity e : created) out.add("rng " + e.getRandom().nextLong());
|
||||
out.add("next " + level.levelRandom.nextLong());
|
||||
w.println(c.get("name") + " " + String.join(" | ", out));
|
||||
} catch (Throwable t) {
|
||||
seeding = false;
|
||||
Throwable cause = t;
|
||||
while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause();
|
||||
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,52 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.server.LanServer;
|
||||
import net.minecraft.client.server.LanServerDetection;
|
||||
import net.minecraft.client.server.LanServerPinger;
|
||||
|
||||
/**
|
||||
* Vanilla's LAN world discovery for tools/test_lan_parity.py. Each input
|
||||
* line is a case: `ping MOTD PORT` prints the announcement
|
||||
* LanServerPinger sends (its UTF-8 bytes); `heard IP HEX` decodes a received
|
||||
* datagram as LanServerDetection does and adds it to the list
|
||||
* (LanServerList.addServer), printing what it parsed and the list when it
|
||||
* changed; `reset` starts a new list (a new multiplayer screen).
|
||||
*/
|
||||
public final class VanillaLanOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<String> cases = Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8);
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
LanServerDetection.LanServerList list = new LanServerDetection.LanServerList();
|
||||
for (String line : cases) {
|
||||
String[] f = line.split("\t", -1);
|
||||
switch (f[0]) {
|
||||
case "ping" -> {
|
||||
String ping = LanServerPinger.createPingString(f[1], f[2]);
|
||||
out.println("ping " + HexFormat.of().formatHex(ping.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
case "heard" -> {
|
||||
byte[] bytes = HexFormat.of().parseHex(f[2]);
|
||||
String received = new String(bytes, 0, bytes.length, StandardCharsets.UTF_8);
|
||||
out.println("heard motd=" + LanServerPinger.parseMotd(received) + " address=" + LanServerPinger.parseAddress(received));
|
||||
list.addServer(received, InetAddress.getByName(f[1]));
|
||||
List<LanServer> dirty = list.takeDirtyServers();
|
||||
if (dirty != null) {
|
||||
StringBuilder b = new StringBuilder("list");
|
||||
for (LanServer s : dirty) b.append(" [").append(s.getMotd()).append(" @ ").append(s.getAddress()).append(']');
|
||||
out.println(b);
|
||||
}
|
||||
}
|
||||
case "reset" -> list = new LanServerDetection.LanServerList();
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,8 @@ 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.item.ItemEntity;
|
||||
import net.minecraft.world.entity.npc.villager.Villager;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.behavior.BehaviorControl;
|
||||
import net.minecraft.world.entity.ai.behavior.BlockPosTracker;
|
||||
@@ -140,6 +142,10 @@ public final class VanillaMobAiOracle {
|
||||
}
|
||||
}
|
||||
static final List<String> TRACE = new ArrayList<>();
|
||||
/** The entities a scenario ticks, in order: its mobs, then what they spawned. */
|
||||
static final List<Entity> ENTS = new ArrayList<>();
|
||||
static final Map<Entity, Integer> LABELS = new java.util.IdentityHashMap<>();
|
||||
static final UUID PLAYER_UUID = new UUID(0x1234L, 0x5678L);
|
||||
|
||||
static final class MobSpec {
|
||||
String type;
|
||||
@@ -166,6 +172,12 @@ public final class VanillaMobAiOracle {
|
||||
String hand;
|
||||
List<MobSpec> mobs = new ArrayList<>();
|
||||
long levelSeed = 0;
|
||||
/** The day time advances with the game time (sleeping, waking). */
|
||||
boolean daycycle;
|
||||
/** Blocks changed before a given tick: (tick, block or fill line). */
|
||||
List<Object[]> timed = new ArrayList<>();
|
||||
/** Boxes whose block changes are printed every tick. */
|
||||
List<int[]> watches = new ArrayList<>();
|
||||
/** Blocks placed when the scenario starts, so their block entities start afresh and tick. */
|
||||
List<String[]> hearts = new ArrayList<>();
|
||||
/** ServerLevel.isSpawningMonsters during the scenario (a heart spawns creakings). */
|
||||
@@ -192,6 +204,7 @@ public final class VanillaMobAiOracle {
|
||||
case "rain" -> s.rain = true;
|
||||
case "thunder" -> s.thunder = true;
|
||||
case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]);
|
||||
case "daycycle" -> s.daycycle = true;
|
||||
case "spawning" -> s.spawning = true;
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
@@ -199,6 +212,12 @@ public final class VanillaMobAiOracle {
|
||||
}
|
||||
case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); }
|
||||
case "fill", "block" -> s.blocks.add(f);
|
||||
case "at" -> s.timed.add(new Object[] {Integer.parseInt(f[1]), java.util.Arrays.copyOfRange(f, 2, f.length)});
|
||||
case "watch" -> {
|
||||
int[] box = new int[6];
|
||||
for (int i = 0; i < 6; i++) box[i] = Integer.parseInt(f[i + 1]);
|
||||
s.watches.add(box);
|
||||
}
|
||||
case "heart" -> s.hearts.add(f);
|
||||
case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])});
|
||||
case "player" -> {
|
||||
@@ -425,8 +444,12 @@ public final class VanillaMobAiOracle {
|
||||
}
|
||||
|
||||
void build(Scenario s, ServerLevel level) throws Exception {
|
||||
for (String[] b : s.blocks) place(b, level);
|
||||
}
|
||||
|
||||
static void place(String[] b, 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);
|
||||
@@ -453,7 +476,7 @@ public final class VanillaMobAiOracle {
|
||||
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);
|
||||
CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(PLAYER_UUID, "horizon-ai"), false);
|
||||
player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation());
|
||||
Connection connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
new EmbeddedChannel(connection);
|
||||
@@ -479,14 +502,15 @@ public final class VanillaMobAiOracle {
|
||||
} else if (player != null) {
|
||||
player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F);
|
||||
}
|
||||
List<Mob> mobs = new ArrayList<>();
|
||||
ENTS.clear();
|
||||
LABELS.clear();
|
||||
List<Brain<?>> brains = new ArrayList<>();
|
||||
List<Long> seeds = 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()));
|
||||
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, ENTS.size()));
|
||||
mob.setId(id++);
|
||||
mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F);
|
||||
mob.setYHeadRot(spec.yaw);
|
||||
@@ -495,36 +519,74 @@ public final class VanillaMobAiOracle {
|
||||
if (mob instanceof AgeableMob a) a.setBaby(true);
|
||||
else mob.setBaby(true);
|
||||
}
|
||||
List<Runnable> afterAdd = new ArrayList<>();
|
||||
for (String flag : spec.flags) {
|
||||
if (flag.equals("persistent")) mob.setPersistenceRequired();
|
||||
else if (flag.equals("noai")) mob.setNoAi(true);
|
||||
else if (flag.equals("inlove")) ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600);
|
||||
else if (flag.equals("tame") && mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true);
|
||||
else if (flag.startsWith("age=")) ((AgeableMob) mob).setAge(Integer.parseInt(flag.substring(4)));
|
||||
else if (flag.startsWith("strength=")) method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class)
|
||||
.invoke(mob, Integer.parseInt(flag.substring(9)));
|
||||
else if (flag.equals("leashed") || flag.startsWith("leashto=")) {
|
||||
// Leashed once every mob exists (below).
|
||||
String[] kv = flag.split("=", 2);
|
||||
String v = kv.length > 1 ? kv[1] : "";
|
||||
switch (kv[0]) {
|
||||
case "persistent" -> mob.setPersistenceRequired();
|
||||
case "noai" -> mob.setNoAi(true);
|
||||
case "profession" -> {
|
||||
Villager villager = (Villager) mob;
|
||||
villager.setVillagerData(villager.getVillagerData().withProfession(level.registryAccess(),
|
||||
ResourceKey.create(Registries.VILLAGER_PROFESSION, net.minecraft.resources.Identifier.withDefaultNamespace(v))));
|
||||
villager.refreshBrain(level);
|
||||
}
|
||||
case "level" -> {
|
||||
Villager villager = (Villager) mob;
|
||||
villager.setVillagerData(villager.getVillagerData().withLevel(Integer.parseInt(v)));
|
||||
}
|
||||
case "xp" -> ((Villager) mob).setVillagerXp(Integer.parseInt(v));
|
||||
case "food" -> field(Villager.class, "foodLevel").setInt(mob, Integer.parseInt(v));
|
||||
case "age" -> ((AgeableMob) mob).setAge(Integer.parseInt(v));
|
||||
case "inv" -> {
|
||||
for (String item : v.split(",")) {
|
||||
String[] ic = item.split("\\*");
|
||||
((Villager) mob).getInventory().addItem(new net.minecraft.world.item.ItemStack(
|
||||
BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])),
|
||||
ic.length > 1 ? Integer.parseInt(ic[1]) : 1));
|
||||
}
|
||||
}
|
||||
case "gossip" -> {
|
||||
// gossip=player:minor_negative:100
|
||||
String[] g = v.split(":");
|
||||
UUID target = g[0].equals("player") ? PLAYER_UUID : UUID.fromString(g[0]);
|
||||
((Villager) mob).getGossips().add(target,
|
||||
net.minecraft.world.entity.ai.gossip.GossipType.valueOf(g[1].toUpperCase(java.util.Locale.ROOT)), Integer.parseInt(g[2]));
|
||||
}
|
||||
case "slept" -> {
|
||||
long at = Long.parseLong(v);
|
||||
afterAdd.add(() -> mob.getBrain().setMemory(MemoryModuleType.LAST_SLEPT, at));
|
||||
}
|
||||
case "inlove" -> ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600);
|
||||
case "tame" -> { if (mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); }
|
||||
case "strength" -> method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class)
|
||||
.invoke(mob, Integer.parseInt(v));
|
||||
case "leashed", "leashto" -> {
|
||||
// Leashed once every mob exists (below).
|
||||
}
|
||||
default -> throw new IllegalArgumentException(flag);
|
||||
}
|
||||
else throw new IllegalArgumentException(flag);
|
||||
}
|
||||
level.addFreshEntity(mob);
|
||||
for (Runnable r : afterAdd) r.run();
|
||||
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());
|
||||
seedGates(brain, spec.seed);
|
||||
mobs.add(mob);
|
||||
LABELS.put(mob, ENTS.size());
|
||||
ENTS.add(mob);
|
||||
brains.add(brain);
|
||||
seeds.add(spec.seed);
|
||||
}
|
||||
// Leads: to the player ("leashed") or to the n-th mob ("leashto=n").
|
||||
for (int i = 0; i < s.mobs.size(); i++) {
|
||||
for (String flag : s.mobs.get(i).flags) {
|
||||
if (flag.equals("leashed")) ((net.minecraft.world.entity.Leashable) mobs.get(i)).setLeashedTo(player, true);
|
||||
else if (flag.startsWith("leashto=")) ((net.minecraft.world.entity.Leashable) mobs.get(i))
|
||||
.setLeashedTo(mobs.get(Integer.parseInt(flag.substring(8))), true);
|
||||
if (flag.equals("leashed")) ((net.minecraft.world.entity.Leashable) ENTS.get(i)).setLeashedTo(player, true);
|
||||
else if (flag.startsWith("leashto=")) ((net.minecraft.world.entity.Leashable) ENTS.get(i))
|
||||
.setLeashedTo(ENTS.get(Integer.parseInt(flag.substring(8))), true);
|
||||
}
|
||||
}
|
||||
// Hearts start with the scenario: their tickers have not run during the warm-up.
|
||||
@@ -541,12 +603,11 @@ public final class VanillaMobAiOracle {
|
||||
List<Mob> created = new ArrayList<>();
|
||||
Field factoryField = field(EntityType.class, "factory");
|
||||
Object creakingFactory = factoryField.get(EntityTypes.CREAKING);
|
||||
final List<Mob> mobsView = mobs;
|
||||
factoryField.set(EntityTypes.CREAKING, (EntityType.EntityFactory<Creaking>) (type, lvl) -> {
|
||||
Creaking c = new Creaking(type, lvl);
|
||||
try {
|
||||
long seed = 1000 + created.size();
|
||||
if (tracing(s)) field(Entity.class, "random").set(c, new TracingRandom(0L, TRACE, mobsView.size() + created.size()));
|
||||
if (tracing(s)) field(Entity.class, "random").set(c, new TracingRandom(0L, TRACE, ENTS.size() + created.size()));
|
||||
c.getRandom().setSeed(seed);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Object, Sensor<?>> cs = (Map<Object, Sensor<?>>) get(c.getBrain(), "sensors");
|
||||
@@ -562,14 +623,25 @@ public final class VanillaMobAiOracle {
|
||||
boolean spawnMonsters = this.getGameRules().get(GameRules.SPAWN_MONSTERS);
|
||||
this.getGameRules().set(GameRules.SPAWN_MOBS, s.spawning, this);
|
||||
this.getGameRules().set(GameRules.SPAWN_MONSTERS, s.spawning, this);
|
||||
int adopted = 0;
|
||||
level.getRandom().setSeed(s.levelSeed);
|
||||
// Loot drawn from random sequences starts afresh in every scenario.
|
||||
this.getRandomSequences().clear();
|
||||
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));
|
||||
Map<BlockPos, BlockState> watched = new java.util.LinkedHashMap<>();
|
||||
for (int[] box : s.watches)
|
||||
for (int y = box[1]; y <= box[4]; y++)
|
||||
for (int z = box[2]; z <= box[5]; z++)
|
||||
for (int x = box[0]; x <= box[3]; x++) {
|
||||
BlockPos pos = new BlockPos(x + s.originX, y, z + s.originZ);
|
||||
watched.put(pos, level.getBlockState(pos));
|
||||
}
|
||||
for (int i = 0; i < ENTS.size(); i++) print(0, i, ENTS.get(i));
|
||||
for (int t = 1; t <= s.ticks; t++) {
|
||||
if (s.daycycle) this.clockManager().setTotalTicks(clock, s.time + t);
|
||||
for (Object[] e : s.timed) if ((Integer) e[0] == t) place((String[]) e[1], level);
|
||||
level.environmentAttributes().invalidateTickCache();
|
||||
level.updateSkyBrightness();
|
||||
tickTime.invoke(level);
|
||||
@@ -591,41 +663,78 @@ public final class VanillaMobAiOracle {
|
||||
TracingRandom.tick = t;
|
||||
TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo();
|
||||
SOUNDS.clear();
|
||||
for (int i = 0; i < mobs.size(); i++) {
|
||||
for (int i = 0; i < ENTS.size(); i++) {
|
||||
// Villager.refreshBrain builds a new brain with new gates: seed those too.
|
||||
if (mobs.get(i).getBrain() != brains.get(i)) {
|
||||
brains.set(i, mobs.get(i).getBrain());
|
||||
if (ENTS.get(i) instanceof Mob m && m.getBrain() != brains.get(i)) {
|
||||
brains.set(i, m.getBrain());
|
||||
seedGates(brains.get(i), seeds.get(i));
|
||||
}
|
||||
}
|
||||
for (int[] hurt : s.hurts) {
|
||||
if (hurt[0] == t && hurt[1] < mobs.size() && !mobs.get(hurt[1]).isRemoved())
|
||||
mobs.get(hurt[1]).hurtServer(level, level.damageSources().playerAttack(player), 1.0F);
|
||||
if (hurt[0] == t && hurt[1] < ENTS.size() && ENTS.get(hurt[1]) instanceof LivingEntity hurtMob && !hurtMob.isRemoved())
|
||||
hurtMob.hurtServer(level, level.damageSources().playerAttack(player), 1.0F);
|
||||
}
|
||||
for (Mob mob : mobs) {
|
||||
if (mob.isRemoved()) continue;
|
||||
mob.checkDespawn();
|
||||
if (mob.isRemoved()) continue;
|
||||
level.tickNonPassenger(mob);
|
||||
for (Entity e : List.copyOf(ENTS)) {
|
||||
if (e.isRemoved()) continue;
|
||||
e.checkDespawn();
|
||||
if (e.isRemoved()) continue;
|
||||
level.tickNonPassenger(e);
|
||||
}
|
||||
if (!heartPositions.isEmpty()) level.tickBlockEntities();
|
||||
managerTick.invoke(manager);
|
||||
// Created mobs that made it into the level, in creation order.
|
||||
for (; adopted < created.size(); adopted++) {
|
||||
Mob c = created.get(adopted);
|
||||
if (!c.isRemoved()) {
|
||||
mobs.add(c);
|
||||
brains.add(c.getBrain());
|
||||
seeds.add(1000L + adopted);
|
||||
// Villagers the tick spawned (babies) and a heart's creakings tick from the next
|
||||
// one, in the order they were added, with a seeded random of their own. Other
|
||||
// newcomers (animal babies, dropped items) are left out, as the probe leaves them.
|
||||
List<Entity> fresh = new ArrayList<>();
|
||||
for (Entity e : level.getAllEntities())
|
||||
if (!LABELS.containsKey(e) && (e instanceof Villager || created.contains(e))) fresh.add(e);
|
||||
fresh.sort(java.util.Comparator.comparingInt(Entity::getId));
|
||||
for (Entity e : fresh) {
|
||||
int index = ENTS.size();
|
||||
int made = created.indexOf(e);
|
||||
if (made >= 0) {
|
||||
// A heart's creaking: seeded when it was created.
|
||||
LABELS.put(e, index);
|
||||
ENTS.add(e);
|
||||
seeds.add(1000L + made);
|
||||
brains.add(((Mob) e).getBrain());
|
||||
continue;
|
||||
}
|
||||
long seed = spawnSeed(index);
|
||||
LABELS.put(e, index);
|
||||
ENTS.add(e);
|
||||
seeds.add(seed);
|
||||
if (e instanceof Mob mob) {
|
||||
// LivingEntity's constructor turns the head at random (Math.random):
|
||||
// face it the way the body does, as the probe's newborns.
|
||||
mob.setYHeadRot(mob.getYRot());
|
||||
mob.yHeadRotO = mob.getYRot();
|
||||
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, index));
|
||||
mob.getRandom().setSeed(seed);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(mob.getBrain(), "sensors");
|
||||
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
|
||||
seedGates(mob.getBrain(), seed);
|
||||
brains.add(mob.getBrain());
|
||||
} else {
|
||||
brains.add(null);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i));
|
||||
for (int i = 0; i < ENTS.size(); i++) print(t, i, ENTS.get(i));
|
||||
for (BlockPos h : heartPositions) printHeart(t, level, h);
|
||||
for (String sound : SOUNDS) out.println(t + " sound " + sound);
|
||||
for (var w : watched.entrySet()) {
|
||||
BlockState now = level.getBlockState(w.getKey());
|
||||
if (now != w.getValue()) {
|
||||
w.setValue(now);
|
||||
BlockPos p = w.getKey();
|
||||
out.println(t + " block " + (p.getX() - s.originX) + "," + p.getY() + "," + (p.getZ() - s.originZ) + " " + stateName(now));
|
||||
}
|
||||
}
|
||||
for (String line : TRACE) out.println(line);
|
||||
TRACE.clear();
|
||||
}
|
||||
for (Mob mob : mobs) mob.discard();
|
||||
for (Entity e : ENTS) e.discard();
|
||||
for (BlockPos h : heartPositions) level.setBlock(h, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(), 2 | 16);
|
||||
factoryField.set(EntityTypes.CREAKING, creakingFactory);
|
||||
this.getGameRules().set(GameRules.SPAWN_MOBS, spawnMobs, this);
|
||||
@@ -634,6 +743,18 @@ public final class VanillaMobAiOracle {
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/** The random seed of the entity a scenario spawned at this index. */
|
||||
static long spawnSeed(int index) { return 1000L + 7919L * index; }
|
||||
|
||||
static String stateName(BlockState state) {
|
||||
StringBuilder sb = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString());
|
||||
List<String> props = new ArrayList<>();
|
||||
state.getValues().forEach(v -> props.add(v.toString()));
|
||||
props.sort(null);
|
||||
if (!props.isEmpty()) sb.append('[').append(String.join(",", props)).append(']');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** A heart's block state and block entity, and the level random. */
|
||||
static void printHeart(int t, ServerLevel level, BlockPos at) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
@@ -663,16 +784,44 @@ public final class VanillaMobAiOracle {
|
||||
}
|
||||
|
||||
static void seedGate(Object behavior, long seed) throws Exception {
|
||||
if (!(behavior instanceof GateBehavior<?>)) return;
|
||||
ShufflingList<?> list = (ShufflingList<?>) field(GateBehavior.class, "behaviors").get(behavior);
|
||||
field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed));
|
||||
for (Object child : list) seedGate(child, seed);
|
||||
seedLists(behavior, seed, java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seeds every ShufflingList a behaviour holds: a GateBehavior's, and the ones TriggerGate
|
||||
* captures in its lambdas (BehaviorBuilder's one-shots), found through their fields.
|
||||
*/
|
||||
static void seedLists(Object o, long seed, Set<Object> seen, int depth) throws Exception {
|
||||
if (o == null || depth > 8 || !seen.add(o)) return;
|
||||
if (o instanceof ShufflingList<?> list) {
|
||||
field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed));
|
||||
for (Object child : list) seedLists(child, seed, seen, depth + 1);
|
||||
return;
|
||||
}
|
||||
String name = o.getClass().getName();
|
||||
if (!name.startsWith("net.minecraft.world.entity.ai.behavior") || o instanceof Enum<?>) return;
|
||||
for (Class<?> c = o.getClass(); c != null && c.getName().startsWith("net.minecraft"); c = c.getSuperclass()) {
|
||||
for (Field f : c.getDeclaredFields()) {
|
||||
if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) || f.getType().isPrimitive()) continue;
|
||||
f.setAccessible(true);
|
||||
Object v = f.get(o);
|
||||
if (v instanceof Iterable<?> it && !(v instanceof ShufflingList<?>)) {
|
||||
for (Object x : it) seedLists(x, seed, seen, depth + 1);
|
||||
} else if (v instanceof com.mojang.datafixers.util.Pair<?, ?> pair) {
|
||||
seedLists(pair.getFirst(), seed, seen, depth + 1);
|
||||
seedLists(pair.getSecond(), seed, seen, depth + 1);
|
||||
} else {
|
||||
seedLists(v, seed, seen, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String who(Entity e) {
|
||||
if (e == null) return "none";
|
||||
if (e instanceof ServerPlayer) return "player";
|
||||
return "e" + e.getId();
|
||||
Integer label = LABELS.get(e);
|
||||
return "e" + (label != null ? 100000 + label : e.getId());
|
||||
}
|
||||
|
||||
static String goals(GoalSelector selector) {
|
||||
@@ -705,13 +854,24 @@ public final class VanillaMobAiOracle {
|
||||
return v.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
void print(int t, int i, Mob m) throws Exception {
|
||||
void print(int t, int i, Entity e) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(t).append(' ').append(i);
|
||||
if (m.isRemoved()) {
|
||||
out.println(sb.append(" removed ").append(m.getRemovalReason()));
|
||||
if (e.isRemoved()) {
|
||||
out.println(sb.append(" removed ").append(e.getRemovalReason()));
|
||||
return;
|
||||
}
|
||||
if (e instanceof ItemEntity item) {
|
||||
sb.append("\tp ").append(d(item.getX())).append(',').append(d(item.getY())).append(',').append(d(item.getZ()));
|
||||
Vec3 v = item.getDeltaMovement();
|
||||
sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z));
|
||||
sb.append("\tg ").append(item.onGround() ? 1 : 0).append(item.horizontalCollision ? 1 : 0);
|
||||
sb.append("\titem ").append(stack(item.getItem())).append(' ').append(item.getAge()).append(' ')
|
||||
.append(field(ItemEntity.class, "pickupDelay").getInt(item));
|
||||
out.println(sb);
|
||||
return;
|
||||
}
|
||||
Mob m = (Mob) e;
|
||||
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));
|
||||
@@ -752,9 +912,52 @@ public final class VanillaMobAiOracle {
|
||||
mem.sort(null);
|
||||
sb.append("\tmem ").append(String.join(" ", mem));
|
||||
}
|
||||
if (m instanceof Villager villager) sb.append("\tvx ").append(villager(villager));
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static String stack(net.minecraft.world.item.ItemStack stack) {
|
||||
if (stack.isEmpty()) return "-";
|
||||
return BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath() + "*" + stack.getCount();
|
||||
}
|
||||
|
||||
static String uuidLabel(UUID uuid) {
|
||||
if (uuid.equals(PLAYER_UUID)) return "player";
|
||||
for (Entity e : ENTS) if (e.getUUID().equals(uuid)) return who(e);
|
||||
return uuid.toString();
|
||||
}
|
||||
|
||||
/** A villager's data, food, inventory slots, gossip and offers. */
|
||||
static String villager(Villager v) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
var data = v.getVillagerData();
|
||||
sb.append("prof ").append(data.profession().unwrapKey().get().identifier().getPath()).append(" lvl ").append(data.level())
|
||||
.append(" xp ").append(v.getVillagerXp()).append(" food ").append(field(Villager.class, "foodLevel").getInt(v))
|
||||
.append(" age ").append(v.getAge());
|
||||
List<String> slots = new ArrayList<>();
|
||||
var inv = v.getInventory();
|
||||
for (int k = 0; k < inv.getContainerSize(); k++) slots.add(stack(inv.getItem(k)));
|
||||
while (!slots.isEmpty() && slots.getLast().equals("-")) slots.removeLast();
|
||||
sb.append(" inv ").append(slots.isEmpty() ? "-" : String.join(",", slots));
|
||||
List<String> gossips = new ArrayList<>();
|
||||
v.getGossips().getGossipEntries().forEach((uuid, types) -> types.forEach((type, value) ->
|
||||
gossips.add(uuidLabel(uuid) + ":" + type.getSerializedName() + "=" + value)));
|
||||
gossips.sort(null);
|
||||
sb.append(" gossip ").append(gossips.isEmpty() ? "-" : String.join(",", gossips));
|
||||
sb.append(" rep ").append(v.getGossips().getReputation(PLAYER_UUID, x -> true));
|
||||
sb.append(" sleep ").append(v.getSleepingPos().map(Server::pos).orElse("-"));
|
||||
Object offers = get(v, "offers");
|
||||
if (offers != null) {
|
||||
List<String> list = new ArrayList<>();
|
||||
for (var o : (net.minecraft.world.item.trading.MerchantOffers) offers) {
|
||||
list.add(stack(o.getBaseCostA()) + "+" + stack(o.getCostB()) + ">" + stack(o.getResult()) + "/" + o.getUses() + "/"
|
||||
+ o.getMaxUses() + "/" + o.getDemand() + "/" + o.getSpecialPriceDiff());
|
||||
}
|
||||
sb.append(" offers ").append(list.isEmpty() ? "-" : String.join(",", list));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String name(MemoryModuleType<?> type) {
|
||||
return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.DataFormatException;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.Inflater;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.ComponentSerialization;
|
||||
import net.minecraft.network.chat.LastSeenMessages;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.ProtocolInfo;
|
||||
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
|
||||
import net.minecraft.network.protocol.common.ClientboundDisconnectPacket;
|
||||
import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket;
|
||||
import net.minecraft.network.protocol.common.ClientboundPingPacket;
|
||||
import net.minecraft.network.protocol.common.ServerboundClientInformationPacket;
|
||||
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
|
||||
import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket;
|
||||
import net.minecraft.network.protocol.common.ServerboundPongPacket;
|
||||
import net.minecraft.network.protocol.common.custom.BrandPayload;
|
||||
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
|
||||
import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks;
|
||||
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
|
||||
import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket;
|
||||
import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks;
|
||||
import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData;
|
||||
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
|
||||
import net.minecraft.network.protocol.game.GameProtocols;
|
||||
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundChatPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket;
|
||||
import net.minecraft.network.protocol.handshake.ClientIntent;
|
||||
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
|
||||
import net.minecraft.network.protocol.handshake.HandshakeProtocols;
|
||||
import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket;
|
||||
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
|
||||
import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket;
|
||||
import net.minecraft.network.protocol.login.LoginProtocols;
|
||||
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
|
||||
import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket;
|
||||
import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket;
|
||||
import net.minecraft.network.protocol.ping.ServerboundPingRequestPacket;
|
||||
import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket;
|
||||
import net.minecraft.network.protocol.status.ServerStatus;
|
||||
import net.minecraft.network.protocol.status.ServerboundStatusRequestPacket;
|
||||
import net.minecraft.network.protocol.status.StatusProtocols;
|
||||
import net.minecraft.server.level.ClientInformation;
|
||||
import net.minecraft.world.entity.PositionMoveRotation;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* A headless client made of vanilla's own protocol: it frames, compresses and
|
||||
* decodes every packet with the codecs of the pinned server JAR (the client
|
||||
* shares them), so any byte a server sends that vanilla would not read is
|
||||
* recorded as an error. tools/test_dedicated_server_parity.py points it at a
|
||||
* vanilla dedicated server and at Horizon's, with the same settings and
|
||||
* world, and compares the transcripts.
|
||||
*
|
||||
* <p>{@code VanillaProtocolClient HOST PORT NAME OUT} pings the server (status
|
||||
* and ping), joins as NAME in offline mode, goes through login and
|
||||
* configuration, accepts the spawn teleport, waits for the chunks around the
|
||||
* spawn, sends a chat message and the {@code /list} command, and leaves.
|
||||
* Each transcript line is a section and a summary: the login and
|
||||
* configuration packets in order; in play, the packets up to the first chunk
|
||||
* batch in order, then the chunks by position with the hash of their bytes
|
||||
* and the replies to the chat and command. Values that change between runs
|
||||
* (entity ids, keep-alive ids, times, salts) are not part of the summaries.
|
||||
*/
|
||||
public final class VanillaProtocolClient {
|
||||
private Socket socket;
|
||||
private DataInputStream in;
|
||||
private OutputStream out;
|
||||
private int threshold = -1;
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
private ProtocolInfo<?> inbound;
|
||||
private ProtocolInfo<?> outbound;
|
||||
private String state;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
String host = args[0];
|
||||
int port = Integer.parseInt(args[1]);
|
||||
String name = args[2];
|
||||
Path output = Path.of(args[3]);
|
||||
VanillaProtocolClient client = new VanillaProtocolClient();
|
||||
try {
|
||||
client.status(host, port);
|
||||
client.join(host, port, name);
|
||||
} catch (Exception e) {
|
||||
client.lines.add("error " + client.state + " " + e);
|
||||
} finally {
|
||||
if (client.socket != null) client.socket.close();
|
||||
}
|
||||
try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
|
||||
for (String line : client.lines) w.println(line);
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
// ---- connection ---------------------------------------------------
|
||||
|
||||
private void open(String host, int port) throws Exception {
|
||||
socket = new Socket();
|
||||
socket.connect(new InetSocketAddress(host, port), 10_000);
|
||||
socket.setSoTimeout(30_000);
|
||||
socket.setTcpNoDelay(true);
|
||||
in = new DataInputStream(socket.getInputStream());
|
||||
out = socket.getOutputStream();
|
||||
threshold = -1;
|
||||
}
|
||||
|
||||
private static int readVarInt(InputStream in) throws Exception {
|
||||
int value = 0;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
int b = in.read();
|
||||
if (b < 0) throw new EOFException();
|
||||
value |= (b & 0x7F) << (7 * i);
|
||||
if ((b & 0x80) == 0) return value;
|
||||
}
|
||||
throw new IllegalStateException("VarInt too big");
|
||||
}
|
||||
|
||||
private static void writeVarInt(ByteBuf buf, int value) {
|
||||
while ((value & ~0x7F) != 0) {
|
||||
buf.writeByte((value & 0x7F) | 0x80);
|
||||
value >>>= 7;
|
||||
}
|
||||
buf.writeByte(value);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private void send(Packet<?> packet) throws Exception {
|
||||
ByteBuf body = Unpooled.buffer();
|
||||
((ProtocolInfo) outbound).codec().encode(body, packet);
|
||||
byte[] raw = new byte[body.readableBytes()];
|
||||
body.readBytes(raw);
|
||||
ByteBuf frame = Unpooled.buffer();
|
||||
if (threshold >= 0) {
|
||||
ByteBuf inner = Unpooled.buffer();
|
||||
if (raw.length >= threshold) {
|
||||
writeVarInt(inner, raw.length);
|
||||
Deflater d = new Deflater();
|
||||
d.setInput(raw);
|
||||
d.finish();
|
||||
byte[] tmp = new byte[raw.length + 64];
|
||||
while (!d.finished()) {
|
||||
int n = d.deflate(tmp);
|
||||
inner.writeBytes(tmp, 0, n);
|
||||
}
|
||||
d.end();
|
||||
} else {
|
||||
writeVarInt(inner, 0);
|
||||
inner.writeBytes(raw);
|
||||
}
|
||||
writeVarInt(frame, inner.readableBytes());
|
||||
frame.writeBytes(inner);
|
||||
} else {
|
||||
writeVarInt(frame, raw.length);
|
||||
frame.writeBytes(raw);
|
||||
}
|
||||
byte[] bytes = new byte[frame.readableBytes()];
|
||||
frame.readBytes(bytes);
|
||||
out.write(bytes);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/** The next packet's raw payload, decompressed as CompressionDecoder does (validating). */
|
||||
private byte[] readFrame() throws Exception {
|
||||
int length = readVarInt(in);
|
||||
byte[] frame = new byte[length];
|
||||
in.readFully(frame);
|
||||
if (threshold < 0) return frame;
|
||||
ByteBuf buf = Unpooled.wrappedBuffer(frame);
|
||||
int dataLength = readVarInt(new java.io.ByteArrayInputStream(frame));
|
||||
int header = varIntSize(dataLength);
|
||||
buf.skipBytes(header);
|
||||
if (dataLength == 0) {
|
||||
byte[] raw = new byte[buf.readableBytes()];
|
||||
buf.readBytes(raw);
|
||||
return raw;
|
||||
}
|
||||
if (dataLength < threshold) {
|
||||
throw new IllegalStateException("Badly compressed packet - size of " + dataLength + " is below server threshold of " + threshold);
|
||||
}
|
||||
if (dataLength > 8388608) {
|
||||
throw new IllegalStateException("Badly compressed packet - size of " + dataLength + " is larger than protocol maximum of 8388608");
|
||||
}
|
||||
Inflater inflater = new Inflater();
|
||||
inflater.setInput(frame, header, frame.length - header);
|
||||
byte[] raw = new byte[dataLength];
|
||||
int n;
|
||||
try {
|
||||
n = inflater.inflate(raw);
|
||||
} catch (DataFormatException e) {
|
||||
throw new IllegalStateException("bad zlib data", e);
|
||||
}
|
||||
boolean finished = inflater.finished();
|
||||
inflater.end();
|
||||
if (n != dataLength || !finished) throw new IllegalStateException("decompressed " + n + " of " + dataLength + " bytes");
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static int varIntSize(int v) {
|
||||
int n = 1;
|
||||
while ((v & ~0x7F) != 0) {
|
||||
v >>>= 7;
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
private record Received(Packet<?> packet, byte[] payload, String type) {}
|
||||
|
||||
/** The next packet, decoded with the inbound protocol; leftover bytes are an error (PacketDecoder). */
|
||||
private Received read() throws Exception {
|
||||
byte[] payload = readFrame();
|
||||
ByteBuf buf = Unpooled.wrappedBuffer(payload);
|
||||
Packet<?> packet = inbound.codec().decode(buf);
|
||||
if (buf.readableBytes() > 0) {
|
||||
throw new IllegalStateException("Packet " + inbound.id().id() + "/" + packet.type().id() + " was larger than I expected, found "
|
||||
+ buf.readableBytes() + " bytes extra whilst reading");
|
||||
}
|
||||
return new Received(packet, payload, packet.type().id().toString());
|
||||
}
|
||||
|
||||
// ---- summaries ----------------------------------------------------
|
||||
|
||||
private static String sha(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)).substring(0, 16);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String json(Component c) {
|
||||
JsonElement e = ComponentSerialization.CODEC.encodeStart(ParityData.access.createSerializationContext(JsonOps.INSTANCE), c).getOrThrow();
|
||||
return e.toString();
|
||||
}
|
||||
|
||||
/** A record's text without object identities; other objects by their fields. */
|
||||
private static String text(Object o) {
|
||||
String s = String.valueOf(o);
|
||||
if (o != null && s.matches("[\\w.$]+@[0-9a-f]+")) {
|
||||
StringBuilder b = new StringBuilder(o.getClass().getSimpleName()).append('{');
|
||||
for (Class<?> c = o.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
|
||||
for (java.lang.reflect.Field f : c.getDeclaredFields()) {
|
||||
if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
|
||||
try {
|
||||
f.setAccessible(true);
|
||||
b.append(f.getName()).append('=').append(text(f.get(o))).append(", ");
|
||||
} catch (Exception e) {
|
||||
b.append(f.getName()).append("=?, ");
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.append('}').toString();
|
||||
}
|
||||
return s.replaceAll("\\$\\$Lambda/0x[0-9a-f]+@", "\\$\\$Lambda@").replaceAll("@[0-9a-f]{4,}", "@");
|
||||
}
|
||||
|
||||
private void record(String section, String line) {
|
||||
lines.add(section + " " + line);
|
||||
}
|
||||
|
||||
// ---- status -------------------------------------------------------
|
||||
|
||||
private void status(String host, int port) throws Exception {
|
||||
state = "status";
|
||||
open(host, port);
|
||||
outbound = HandshakeProtocols.SERVERBOUND;
|
||||
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.STATUS));
|
||||
outbound = StatusProtocols.SERVERBOUND;
|
||||
inbound = StatusProtocols.CLIENTBOUND;
|
||||
send(ServerboundStatusRequestPacket.INSTANCE);
|
||||
Received r = read();
|
||||
if (r.packet instanceof ClientboundStatusResponsePacket p) {
|
||||
JsonElement e = ServerStatus.CODEC.encodeStart(JsonOps.INSTANCE, p.status()).getOrThrow();
|
||||
// The favicon is compared by its bytes' hash.
|
||||
String s = e.toString().replaceAll("\"favicon\":\"[^\"]*\"", "\"favicon\":\"" + p.status().favicon().map(f -> sha(f.iconBytes())).orElse("") + "\"");
|
||||
record("status", r.type + " " + s);
|
||||
} else {
|
||||
record("status", r.type + " " + text(r.packet));
|
||||
}
|
||||
send(new ServerboundPingRequestPacket(1234567890123L));
|
||||
Received pong = read();
|
||||
record("status", pong.type + " " + (pong.packet instanceof ClientboundPongResponsePacket p ? p.time() : text(pong.packet)));
|
||||
int after = in.read();
|
||||
record("status", "closed-after-pong " + (after < 0));
|
||||
socket.close();
|
||||
}
|
||||
|
||||
// ---- join ---------------------------------------------------------
|
||||
|
||||
private void join(String host, int port, String name) throws Exception {
|
||||
open(host, port);
|
||||
state = "login";
|
||||
outbound = HandshakeProtocols.SERVERBOUND;
|
||||
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN));
|
||||
outbound = LoginProtocols.SERVERBOUND;
|
||||
inbound = LoginProtocols.CLIENTBOUND;
|
||||
UUID uuid = UUIDUtil.createOfflinePlayerUUID(name);
|
||||
send(new ServerboundHelloPacket(name, uuid));
|
||||
while (true) {
|
||||
Received r = read();
|
||||
if (r.packet instanceof ClientboundLoginCompressionPacket p) {
|
||||
threshold = p.getCompressionThreshold();
|
||||
record("login", r.type + " " + threshold);
|
||||
} else if (r.packet instanceof ClientboundLoginFinishedPacket p) {
|
||||
record("login", r.type + " " + p.gameProfile().id() + " " + p.gameProfile().name() + " " + p.gameProfile().properties().size());
|
||||
send(ServerboundLoginAcknowledgedPacket.INSTANCE);
|
||||
break;
|
||||
} else if (r.packet instanceof ClientboundLoginDisconnectPacket p) {
|
||||
record("login", r.type + " " + json(p.reason()));
|
||||
return;
|
||||
} else {
|
||||
record("login", r.type + " " + text(r.packet));
|
||||
}
|
||||
}
|
||||
state = "configuration";
|
||||
outbound = ConfigurationProtocols.SERVERBOUND;
|
||||
inbound = ConfigurationProtocols.CLIENTBOUND;
|
||||
// ClientHandshakePacketListenerImpl.handleLoginFinished: brand, then the options.
|
||||
send(new ServerboundCustomPayloadPacket(new BrandPayload("vanilla")));
|
||||
send(new ServerboundClientInformationPacket(ClientInformation.createDefault()));
|
||||
while (true) {
|
||||
Received r = read();
|
||||
if (r.packet instanceof ClientboundSelectKnownPacks p) {
|
||||
record("config", r.type + " " + text(p.knownPacks()));
|
||||
send(new ServerboundSelectKnownPacks(p.knownPacks()));
|
||||
} else if (r.packet instanceof ClientboundKeepAlivePacket p) {
|
||||
record("config", r.type);
|
||||
send(new ServerboundKeepAlivePacket(p.getId()));
|
||||
} else if (r.packet instanceof ClientboundPingPacket p) {
|
||||
record("config", r.type);
|
||||
send(new ServerboundPongPacket(p.getId()));
|
||||
} else if (r.packet instanceof ClientboundCustomPayloadPacket p) {
|
||||
record("config", r.type + " " + text(p.payload()));
|
||||
} else if (r.packet instanceof net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket p) {
|
||||
// Each registry's tags and what they hold. Vanilla sends the
|
||||
// registries and tags in the order of maps keyed by interned
|
||||
// ResourceKeys (identity hashes), which changes between runs.
|
||||
var registries = new TreeMap<String, String>();
|
||||
for (var e : p.tags().entrySet()) {
|
||||
var tags = new TreeMap<String, String>();
|
||||
for (var t : e.getValue().tags().entrySet()) {
|
||||
tags.put(t.getKey().toString(), t.getValue().toString());
|
||||
}
|
||||
registries.put(e.getKey().identifier().toString(), tags.size() + " " + sha(tags.toString().getBytes()));
|
||||
}
|
||||
record("config", r.type + " " + registries.size() + " registries");
|
||||
registries.forEach((k, v) -> record("config-tags", k + " " + v));
|
||||
} else if (r.packet instanceof ClientboundFinishConfigurationPacket) {
|
||||
record("config", r.type);
|
||||
send(ServerboundFinishConfigurationPacket.INSTANCE);
|
||||
break;
|
||||
} else if (r.packet instanceof ClientboundDisconnectPacket p) {
|
||||
record("config", r.type + " " + json(p.reason()));
|
||||
return;
|
||||
} else {
|
||||
record("config", r.type + " " + (r.payload.length > 200 ? "sha=" + sha(r.payload) : text(r.packet)));
|
||||
}
|
||||
}
|
||||
play();
|
||||
}
|
||||
|
||||
private void play() throws Exception {
|
||||
state = "play";
|
||||
GameProtocols.Context context = new GameProtocols.Context() {
|
||||
@Override
|
||||
public boolean hasInfiniteMaterials() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canUseCommandBlocks() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context);
|
||||
inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
|
||||
socket.setSoTimeout(250);
|
||||
Map<String, String> chunks = new TreeMap<>();
|
||||
Map<String, String> layers = new TreeMap<>();
|
||||
Map<String, Integer> counts = new TreeMap<>();
|
||||
boolean ordered = true;
|
||||
boolean loaded = false;
|
||||
PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0);
|
||||
long lastChunk = 0;
|
||||
long deadline = System.currentTimeMillis() + 90_000;
|
||||
int step = 0;
|
||||
long stepAt = 0;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Received r;
|
||||
try {
|
||||
r = read();
|
||||
} catch (SocketTimeoutException e) {
|
||||
r = null;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
if (r != null) {
|
||||
Packet<?> packet = r.packet;
|
||||
counts.merge(r.type, 1, Integer::sum);
|
||||
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
|
||||
if (packet instanceof ClientboundKeepAlivePacket p) {
|
||||
send(new ServerboundKeepAlivePacket(p.getId()));
|
||||
} else if (packet instanceof ClientboundPingPacket p) {
|
||||
send(new ServerboundPongPacket(p.getId()));
|
||||
} else if (packet instanceof ClientboundPlayerPositionPacket p) {
|
||||
position = PositionMoveRotation.calculateAbsolute(position, p.change(), p.relatives());
|
||||
record("play-move", text(position.position()) + " " + position.yRot() + " " + position.xRot());
|
||||
send(new ServerboundAcceptTeleportationPacket(p.id(), position.position().x, position.position().y, position.position().z,
|
||||
position.yRot(), position.xRot()));
|
||||
send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false));
|
||||
if (!loaded) {
|
||||
send(new ServerboundPlayerLoadedPacket());
|
||||
loaded = true;
|
||||
}
|
||||
} else if (packet instanceof ClientboundChunkBatchFinishedPacket) {
|
||||
send(new ServerboundChunkBatchReceivedPacket(64.0F));
|
||||
} else if (packet instanceof ClientboundLevelChunkWithLightPacket p) {
|
||||
chunks.put(p.x() + "," + p.z(), chunkHash(p));
|
||||
layers.put(p.x() + "," + p.z(), lightLayers(p));
|
||||
lastChunk = now;
|
||||
int px = (int) Math.floor(position.position().x) >> 4;
|
||||
int pz = (int) Math.floor(position.position().z) >> 4;
|
||||
if (p.x() == px && p.z() == pz) chunkParts(p);
|
||||
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0) {
|
||||
record("play-chat", "system " + p.overlay() + " " + json(p.content()));
|
||||
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0) {
|
||||
record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent()
|
||||
+ " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " "
|
||||
+ p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " "
|
||||
+ p.chatType().targetName().map(VanillaProtocolClient::json));
|
||||
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) {
|
||||
record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName());
|
||||
} else if (packet instanceof ClientboundDisconnectPacket p) {
|
||||
record("play", r.type + " " + json(p.reason()));
|
||||
break;
|
||||
}
|
||||
if (ordered) {
|
||||
record("play-start", r.type + " " + summary(r));
|
||||
}
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundCommandsPacket p && counts.get(r.type) == 1) {
|
||||
commandTree(p);
|
||||
}
|
||||
}
|
||||
// Once the chunks stop coming: chat, then /list, then leave.
|
||||
if (loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) {
|
||||
record("play-chunks", chunks.size() + " " + chunks);
|
||||
BLOCK_ENTITIES.forEach((k, v) -> record("play-block-entities", k + " " + v));
|
||||
// Which light layers exist depends on the neighbouring
|
||||
// columns: compared where all eight were sent.
|
||||
Map<String, String> inner = new TreeMap<>();
|
||||
layers.forEach((k, v) -> {
|
||||
String[] xz = k.split(",");
|
||||
int x = Integer.parseInt(xz[0]), z = Integer.parseInt(xz[1]);
|
||||
boolean all = true;
|
||||
for (int dz = -1; dz <= 1; dz++) for (int dx = -1; dx <= 1; dx++) all &= chunks.containsKey((x + dx) + "," + (z + dz));
|
||||
if (all) inner.put(k, v);
|
||||
});
|
||||
record("play-light-layers", inner.size() + " " + inner);
|
||||
step = 1;
|
||||
stepAt = now;
|
||||
send(new ServerboundChatPacket("hello from the parity client", Instant.now(), 0L, Optional.empty(),
|
||||
new LastSeenMessages.Update(0, new BitSet(), (byte) 0)));
|
||||
} else if (step == 1 && now - stepAt > 1500) {
|
||||
step = 2;
|
||||
stepAt = now;
|
||||
send(new ServerboundChatCommandPacket("list"));
|
||||
} else if (step == 2 && now - stepAt > 1500) {
|
||||
record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0));
|
||||
return;
|
||||
}
|
||||
}
|
||||
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* A chunk's blocks, biomes, heightmaps and block entities (its
|
||||
* ClientboundLevelChunkPacketData bytes). The light is left out: both servers relight around chunks
|
||||
* loaded with their saved light, which test_light_parity covers.
|
||||
*/
|
||||
private static final Map<String, String> BLOCK_ENTITIES = new TreeMap<>();
|
||||
|
||||
private static String chunkHash(ClientboundLevelChunkWithLightPacket p) {
|
||||
var data = p.chunkData();
|
||||
var heightmaps = new TreeMap<String, String>();
|
||||
data.getHeightmaps().forEach((k, v) -> heightmaps.put(k.getSerializedName(), java.util.Arrays.toString(v)));
|
||||
FriendlyByteBuf buf = data.getReadBuffer();
|
||||
byte[] sections = new byte[buf.readableBytes()];
|
||||
buf.getBytes(buf.readerIndex(), sections);
|
||||
// What the sections hold, apart from how their palettes encode it.
|
||||
FriendlyByteBuf copy = new FriendlyByteBuf(Unpooled.wrappedBuffer(sections));
|
||||
var factory = PalettedContainerFactory.create(ParityData.access);
|
||||
StringBuilder content = new StringBuilder();
|
||||
while (copy.isReadable()) {
|
||||
LevelChunkSection section = new LevelChunkSection(factory);
|
||||
section.read(copy);
|
||||
for (int y = 0; y < 16; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) {
|
||||
content.append(net.minecraft.world.level.block.Block.getId(section.getBlockState(x, y, z))).append(',');
|
||||
}
|
||||
for (int y = 0; y < 4; y++) for (int z = 0; z < 4; z++) for (int x = 0; x < 4; x++) {
|
||||
content.append(section.getNoiseBiome(x, y, z).getRegisteredName()).append(',');
|
||||
}
|
||||
}
|
||||
StringBuilder entities = new StringBuilder();
|
||||
data.forEachBlockEntityTag(p.x(), p.z(), (pos, type, tag) -> entities.append(pos.toShortString()).append(' ')
|
||||
.append(net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(type)).append(' ').append(tag).append(';'));
|
||||
if (entities.length() > 0) BLOCK_ENTITIES.put(p.x() + "," + p.z(), entities.toString());
|
||||
return "c" + sha(content.toString().getBytes()).substring(0, 8) + "s" + sha(sections).substring(0, 8) + "h" + sha(heightmaps.toString().getBytes()).substring(0, 8) + "e"
|
||||
+ sha(entities.toString().getBytes()).substring(0, 8);
|
||||
}
|
||||
|
||||
/** The light layers a chunk has, sky then block (with data or empty). */
|
||||
private static String lightLayers(ClientboundLevelChunkWithLightPacket p) {
|
||||
var light = p.lightData();
|
||||
BitSet sky = (BitSet) light.skyYMask().clone();
|
||||
sky.or(light.emptySkyYMask());
|
||||
BitSet block = (BitSet) light.blockYMask().clone();
|
||||
block.or(light.emptyBlockYMask());
|
||||
return sky + "/" + block;
|
||||
}
|
||||
|
||||
/** The player's chunk part by part, so a difference in its bytes can be told apart. */
|
||||
private void chunkParts(ClientboundLevelChunkWithLightPacket p) {
|
||||
var data = p.chunkData();
|
||||
for (var e : new TreeMap<>(data.getHeightmaps().entrySet().stream()
|
||||
.collect(java.util.stream.Collectors.toMap(x -> x.getKey().getSerializedName(), x -> x.getValue()))).entrySet()) {
|
||||
record("chunk-heightmap", e.getKey() + " " + java.util.Arrays.toString(e.getValue()).hashCode());
|
||||
}
|
||||
FriendlyByteBuf buf = data.getReadBuffer();
|
||||
byte[] all = new byte[buf.readableBytes()];
|
||||
buf.getBytes(buf.readerIndex(), all);
|
||||
var factory = PalettedContainerFactory.create(ParityData.access);
|
||||
int index = 0;
|
||||
while (buf.isReadable()) {
|
||||
int start = buf.readerIndex();
|
||||
LevelChunkSection section = new LevelChunkSection(factory);
|
||||
section.read(buf);
|
||||
StringBuilder states = new StringBuilder();
|
||||
for (int y = 0; y < 16; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) {
|
||||
states.append(net.minecraft.world.level.block.Block.getId(section.getBlockState(x, y, z))).append(',');
|
||||
}
|
||||
StringBuilder biomes = new StringBuilder();
|
||||
for (int y = 0; y < 4; y++) for (int z = 0; z < 4; z++) for (int x = 0; x < 4; x++) {
|
||||
biomes.append(section.getNoiseBiome(x, y, z).getRegisteredName()).append(',');
|
||||
}
|
||||
byte[] bytes = new byte[buf.readerIndex() - start];
|
||||
buf.getBytes(start, bytes);
|
||||
record("chunk-section", index++ + " states=" + sha(states.toString().getBytes()) + " biomes=" + sha(biomes.toString().getBytes())
|
||||
+ " count=" + (((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF)) + " bytes=" + sha(bytes));
|
||||
}
|
||||
StringBuilder entities = new StringBuilder();
|
||||
data.forEachBlockEntityTag(p.x(), p.z(), (pos, type, tag) -> entities.append(pos.toShortString()).append(' ')
|
||||
.append(net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(type)).append(' ').append(tag).append(';'));
|
||||
record("chunk-block-entities", entities.toString());
|
||||
}
|
||||
|
||||
/** The command tree, one line per top-level command with its subtree. */
|
||||
private void commandTree(net.minecraft.network.protocol.game.ClientboundCommandsPacket p) {
|
||||
var context = net.minecraft.commands.CommandBuildContext.simple(ParityData.access, net.minecraft.world.flag.FeatureFlags.VANILLA_SET);
|
||||
var root = p.getRoot(context, new net.minecraft.network.protocol.game.ClientboundCommandsPacket.NodeBuilder<Object>() {
|
||||
@Override
|
||||
public com.mojang.brigadier.builder.ArgumentBuilder<Object, ?> createLiteral(String id) {
|
||||
return com.mojang.brigadier.builder.LiteralArgumentBuilder.literal(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public com.mojang.brigadier.builder.ArgumentBuilder<Object, ?> createArgument(String id, com.mojang.brigadier.arguments.ArgumentType<?> type,
|
||||
net.minecraft.resources.Identifier suggestionId) {
|
||||
return com.mojang.brigadier.builder.RequiredArgumentBuilder.argument(id + ":" + type.getClass().getSimpleName() + ":" + suggestionId, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public com.mojang.brigadier.builder.ArgumentBuilder<Object, ?> configure(com.mojang.brigadier.builder.ArgumentBuilder<Object, ?> input,
|
||||
boolean executable, boolean restricted) {
|
||||
if (executable) input.executes(c -> 0);
|
||||
return input;
|
||||
}
|
||||
});
|
||||
// Vanilla sends each node's children in registration order, which
|
||||
// its commands report (sorted) does not keep: compared as sets.
|
||||
var lines = new TreeMap<String, String>();
|
||||
for (var child : root.getChildren()) {
|
||||
var paths = new java.util.TreeSet<String>();
|
||||
describe(child, "", paths, new java.util.IdentityHashMap<>());
|
||||
lines.put(child.getName(), paths.size() + " " + sha(String.join("\n", paths).getBytes()));
|
||||
}
|
||||
lines.forEach((k, v) -> record("play-command", k + " " + v));
|
||||
}
|
||||
|
||||
private static void describe(com.mojang.brigadier.tree.CommandNode<Object> node, String path, java.util.Set<String> out,
|
||||
java.util.IdentityHashMap<Object, Boolean> seen) {
|
||||
String here = path + " " + node.getName() + (node.getCommand() != null ? "*" : "");
|
||||
out.add(here + (node.getRedirect() != null ? " -> " + node.getRedirect().getName() : ""));
|
||||
if (seen.put(node, true) != null) return;
|
||||
for (var child : node.getChildren()) describe(child, here, out, seen);
|
||||
}
|
||||
|
||||
/** The first play packets: entity ids, seeds and times aside. */
|
||||
private String summary(Received r) {
|
||||
String t = r.type;
|
||||
if (t.equals("minecraft:login")) {
|
||||
// levels: the server's level keys, in an identity-hashed order after the overworld.
|
||||
var login = (net.minecraft.network.protocol.game.ClientboundLoginPacket) r.packet;
|
||||
var levels = new java.util.TreeSet<String>();
|
||||
login.levels().forEach(l -> levels.add(l.identifier().toString()));
|
||||
return text(r.packet).replaceAll("playerId=-?\\d+", "playerId=_").replaceAll("levels=\\[(ResourceKey\\[[^\\]]*\\](, )?)*\\]", "levels=" + levels);
|
||||
}
|
||||
if (t.equals("minecraft:set_time") || t.equals("minecraft:keep_alive") || t.equals("minecraft:ping")) return "";
|
||||
// The tree is compared below, as sets: the children's order is vanilla's registration order.
|
||||
if (t.equals("minecraft:commands")) return "";
|
||||
if (t.equals("minecraft:set_entity_data")) {
|
||||
return text(((net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket) r.packet).packedItems());
|
||||
}
|
||||
if (t.contains("entity") || t.equals("minecraft:add_entity") || t.equals("minecraft:update_attributes")
|
||||
|| t.equals("minecraft:player_info_update") || t.equals("minecraft:player_position")) {
|
||||
return "";
|
||||
}
|
||||
return r.payload.length > 200 ? "sha=" + sha(r.payload) : text(r.packet);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user