Optimize launcher preparation with precompiled, batched exporters
Compile and validate original exporter bundles during release builds, cache development compilation, and reuse initialized JVMs and collision data during preparation. Keep legacy preparers compatible while current releases need only a Java runtime. Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.tags.*;
|
||||
|
||||
/** Original launcher transport. Each worker owns one server OR client classpath. */
|
||||
public final class PrepareWorker {
|
||||
private static <T> Runnable restoreTags(Registry<T> registry) {
|
||||
var tags = new HashMap<TagKey<T>, List<Holder<T>>>();
|
||||
registry.getTags().forEach(tag -> tags.put(tag.key(), tag.stream().toList()));
|
||||
return () -> registry.prepareTagReload(new TagLoader.LoadResult<>(registry.key(), tags)).apply();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length > 0 && args[0].equals("validate")) {
|
||||
try (var paths = Files.walk(Path.of(args[1]))) {
|
||||
for (var path : paths.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
String name = Path.of(args[1]).relativize(path).toString()
|
||||
.replace(File.separatorChar, '.').replaceAll("\\.class$", "");
|
||||
var type = Class.forName(name, false, PrepareWorker.class.getClassLoader());
|
||||
type.getDeclaredMethods(); type.getDeclaredConstructors(); type.getDeclaredFields();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Bootstrap replaces System.out. Keep the protocol on the original descriptor.
|
||||
var replies = new PrintWriter(new OutputStreamWriter(new FileOutputStream(FileDescriptor.out), StandardCharsets.UTF_8), true);
|
||||
System.setOut(System.err);
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var resets = new ArrayList<Runnable>();
|
||||
for (var registry : BuiltInRegistries.REGISTRY) resets.add(restoreTags(registry));
|
||||
System.setProperty("horizon.prepare.reuse", "true");
|
||||
try (var input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
|
||||
for (String line; (line = input.readLine()) != null;) {
|
||||
var task = JsonParser.parseString(line).getAsJsonArray();
|
||||
var previousOut = System.out; var previousErr = System.err;
|
||||
String error = "";
|
||||
try (var log = new PrintStream(Files.newOutputStream(Path.of(task.get(0).getAsString()),
|
||||
StandardOpenOption.CREATE, StandardOpenOption.APPEND), true, StandardCharsets.UTF_8)) {
|
||||
System.setOut(log); System.setErr(log);
|
||||
try {
|
||||
var values = task.get(2).getAsJsonArray();
|
||||
var argv = new String[values.size()];
|
||||
for (int i = 0; i < argv.length; i++) argv[i] = values.get(i).getAsString();
|
||||
Class.forName("dev.horizonlab.parity." + task.get(1).getAsString())
|
||||
.getMethod("main", String[].class).invoke(null, (Object) argv);
|
||||
} catch (Throwable failure) {
|
||||
failure.printStackTrace(log); error = failure.toString();
|
||||
} finally {
|
||||
for (var reset : resets) reset.run();
|
||||
}
|
||||
} finally {
|
||||
System.setOut(previousOut); System.setErr(previousErr);
|
||||
}
|
||||
replies.println(new Gson().toJson(error));
|
||||
if (!error.isEmpty()) System.exit(1);
|
||||
}
|
||||
}
|
||||
// Vanilla may have started non-daemon executors. All task outputs are closed now.
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,14 @@ import net.minecraft.world.phys.shapes.*;
|
||||
/** Exports private runtime data locally and invokes actual vanilla cached-shape queries. */
|
||||
public final class VanillaCollisionOracle {
|
||||
static { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); }
|
||||
private static final boolean REUSE = Boolean.getBoolean("horizon.prepare.reuse");
|
||||
private static Map<String,byte[]> generated;
|
||||
private static final Map<BlockState,Tag> encodedStates = new IdentityHashMap<>();
|
||||
private static final Map<VoxelShape,CompoundTag> encodedGrids = new IdentityHashMap<>();
|
||||
private static Tag encode(BlockState state) {
|
||||
if (!REUSE) return BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,state).getOrThrow();
|
||||
return encodedStates.computeIfAbsent(state, s -> BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,s).getOrThrow()).copy();
|
||||
}
|
||||
private static final Field CACHE, COLLISION, DISCRETE;
|
||||
private static final Method INDEX;
|
||||
static {
|
||||
@@ -37,6 +45,7 @@ public final class VanillaCollisionOracle {
|
||||
return shape;
|
||||
}
|
||||
private static CompoundTag grid(VoxelShape shape) throws ReflectiveOperationException {
|
||||
if (REUSE && encodedGrids.containsKey(shape)) return encodedGrids.get(shape).copy();
|
||||
CompoundTag tag = new CompoundTag();
|
||||
tag.putByte("canonical",(byte)(shape==Shapes.empty()?1:shape==Shapes.block()?2:0));
|
||||
tag.putByte("cube", (byte)(shape instanceof CubeVoxelShape ? 1 : 0));
|
||||
@@ -52,13 +61,14 @@ public final class VanillaCollisionOracle {
|
||||
byte[] bits = new byte[discrete.getXSize() * discrete.getYSize() * discrete.getZSize()];
|
||||
for (int x = 0; x < discrete.getXSize(); x++) for (int y = 0; y < discrete.getYSize(); y++) for (int z = 0; z < discrete.getZSize(); z++) bits[(x * discrete.getYSize() + y) * discrete.getZSize() + z] = (byte)(discrete.isFull(x, y, z) ? 1 : 0);
|
||||
tag.putByteArray("occupied", bits);
|
||||
if (REUSE) encodedGrids.put(shape, tag.copy());
|
||||
return tag;
|
||||
}
|
||||
public static CompoundTag occlusionDefinitions() throws Exception {
|
||||
var method=BlockBehaviour.class.getDeclaredMethod("getOcclusionShape",BlockState.class);method.setAccessible(true);
|
||||
var states=new ListTag();var shapes=new ListTag();var ids=new IdentityHashMap<VoxelShape,Integer>();int[] mapping=new int[Block.BLOCK_STATE_REGISTRY.size()];int index=0;
|
||||
for(var state:Block.BLOCK_STATE_REGISTRY) {
|
||||
states.add(BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,state).getOrThrow());
|
||||
states.add(encode(state));
|
||||
var shape=(VoxelShape)method.invoke(state.getBlock(),state);Integer id=ids.get(shape);
|
||||
if(id==null){id=shapes.size();ids.put(shape,id);shapes.add(grid(shape));}
|
||||
mapping[index++]=id;
|
||||
@@ -70,12 +80,16 @@ public final class VanillaCollisionOracle {
|
||||
}
|
||||
private static void inputValues(PrintWriter out, double... values) { for (double value : values) out.printf(" %016x", Double.doubleToRawLongBits(value)); }
|
||||
private static void generate(Path base) throws Exception {
|
||||
if (REUSE && generated != null) {
|
||||
for (var file : generated.entrySet()) Files.write(base.resolve(file.getKey()), file.getValue());
|
||||
return;
|
||||
}
|
||||
ListTag states = new ListTag(), shapes = new ListTag(); CompoundTag defaults = new CompoundTag();
|
||||
Map<VoxelShape,Integer> ids = new IdentityHashMap<>();Set<CompoundTag> grids=new HashSet<>(); int[] mapping = new int[Block.BLOCK_STATE_REGISTRY.size()]; int cachedCount = 0;
|
||||
for (BlockState state : Block.BLOCK_STATE_REGISTRY) {
|
||||
int id = states.size();
|
||||
if (Block.BLOCK_STATE_REGISTRY.getId(state) != id) throw new AssertionError("non-dense states");
|
||||
Tag encoded = BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE, state).getOrThrow(); states.add(encoded);
|
||||
Tag encoded = encode(state); states.add(encoded);
|
||||
if (state == state.getBlock().defaultBlockState()) defaults.putInt(((CompoundTag)encoded).getStringOr("id", ""), id);
|
||||
VoxelShape shape = cached(state);
|
||||
if (shape == null) mapping[id] = -1;
|
||||
@@ -109,6 +123,12 @@ public final class VanillaCollisionOracle {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (REUSE) {
|
||||
// Consumers can overwrite block-registry.nbt; preserve the original bytes.
|
||||
generated = new HashMap<>();
|
||||
for (String file : List.of("block-registry.nbt", "cached-collision.nbt", "inputs.txt"))
|
||||
generated.put(file, Files.readAllBytes(base.resolve(file)));
|
||||
}
|
||||
System.out.printf("HORIZON_COLLISION_RESULT {\"registry_states\":%d,\"cached_states\":%d,\"uncached_states\":%d,\"unique_shapes\":%d,\"unique_grids\":%d,\"queries\":%d}%n", mapping.length,cachedCount,mapping.length-cachedCount,shapes.size(),grids.size(),cachedCount*6);
|
||||
}
|
||||
private static void values(PrintWriter out, String label, double... values) { out.print(label); for (double value : values) out.printf(" %016x",Double.doubleToLongBits(value)); out.println(); }
|
||||
|
||||
Reference in New Issue
Block a user