Preserve actual workstation origins across native bulk crafting
Some checks failed
Native Workstation Origin Overlay / native-workstation (push) Successful in 1m27s
DuneRealms Plugin CI / plugins (push) Successful in 9m48s
DuneRealms Resourcepack CI / resourcepack (push) Failing after 18s

This commit is contained in:
unimatrixgit 2026-12-04 21:32:11 +01:00
commit c3a36b2a30
2 changed files with 368 additions and 13 deletions

View file

@ -0,0 +1,76 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
class NativeWorkstationMerge {
private static final String PKG = "com/dunerealms/jarvis/";
private static final String OWNER = PKG + "ItemMetadataOverlay";
private static final String EVENTS = "org/bukkit/event/";
private static final String INVENTORY = EVENTS + "inventory/";
private static final String BLOCK = EVENTS + "block/";
private static final String ITEM = "Lorg/bukkit/inventory/ItemStack;";
private static final Map<String, String> ORIGINS = Map.of(
"craft", INVENTORY + "PrepareItemCraftEvent", "smelt", INVENTORY + "FurnaceSmeltEvent",
"smith", INVENTORY + "PrepareSmithingEvent", "campfire", BLOCK + "BlockCookEvent");
public static void main(String[] args) throws Exception {
if (args.length != 3) throw new IllegalArgumentException("Expected baseline, donor and output classes");
var reader = new ClassReader(Files.readAllBytes(Path.of(args[0])));
var retained = parse(reader);
var donor = parse(new ClassReader(Files.readAllBytes(Path.of(args[1]))));
if (!OWNER.equals(retained.name) || !OWNER.equals(donor.name) ||
retained.methods.stream().anyMatch(method -> method.name.equals("startWorkstationOrigins"))) {
throw new IllegalArgumentException("Unexpected retained workstation implementation");
}
retained.methods.remove(method(retained, "stonecut", "(L" + INVENTORY + "InventoryClickEvent;)V"));
retained.methods.add(method(donor, "startWorkstationOrigins", "()V"));
var startup = method(retained, "registerCrafter", "()V");
var started = Arrays.stream(startup.instructions.toArray()).filter(i ->
i instanceof FieldInsnNode field && field.getOpcode() == Opcodes.PUTFIELD && field.owner.equals(OWNER)
&& field.name.equals("crafterRegistered") && field.desc.equals("Z")).toList();
if (started.size() != 1) throw new IllegalArgumentException("Expected one native registration guard");
var newListener = new InsnList();
newListener.add(new VarInsnNode(Opcodes.ALOAD, 0));
newListener.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, OWNER, "startWorkstationOrigins", "()V", false));
startup.instructions.insert(started.getFirst(), newListener);
for (var output : ORIGINS.entrySet()) origin(retained, output.getKey(), output.getValue());
var writer = new ClassWriter(reader, 0);
retained.accept(writer);
Files.write(Path.of(args[2]), writer.toByteArray());
}
private static void origin(ClassNode retained, String name, String event) {
var method = method(retained, name, "(L" + event + ";)V");
var calls = Arrays.stream(method.instructions.toArray()).filter(i ->
i instanceof MethodInsnNode call && call.getOpcode() == Opcodes.INVOKESTATIC &&
call.owner.equals(PKG + "ItemOrigin") && call.name.equals("created") &&
call.desc.equals("(" + ITEM + ")V")).toList();
if (calls.size() != 1) throw new IllegalArgumentException("Expected one retained origin call in " + name);
String eventType = name.equals("craft") || name.equals("smith") ? INVENTORY + "InventoryEvent" : BLOCK + "BlockEvent";
method.instructions.insertBefore(calls.getFirst(), new VarInsnNode(Opcodes.ALOAD, 1));
method.instructions.set(calls.getFirst(), new MethodInsnNode(Opcodes.INVOKESTATIC, PKG + "WorkstationOrigins",
"originAt", "(" + ITEM + "L" + eventType + ";)V", false));
method.maxStack = Math.max(method.maxStack, 2);
}
private static MethodNode method(ClassNode node, String name, String desc) {
return node.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(desc))
.findFirst().orElseThrow(() -> new IllegalArgumentException("Missing expected method " + name));
}
private static ClassNode parse(ClassReader reader) {
var node = new ClassNode();
reader.accept(node, 0);
return node;
}
}

View file

@ -0,0 +1,53 @@
"""Build scoped native workstation overlays on the three reviewed live JARVIS variants."""
import argparse
import os
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from plugin_wild_update import digest, read_archive, write_archive
PKG = "com/dunerealms/jarvis/"
ENTRY = PKG + "ItemMetadataOverlay.class"
NEW = [PKG + "WorkstationOrigins.class", PKG + "WorkstationOrigins$NativeBatch.class"]
BASELINES = {
"5edc2595210d7b683e185a3442b0c762a6f62af645ad9702c28bf363ba3c2427",
"d914bf7ab726a596471154fb69f5d8e64998f3a7342b9580450e85dfc66709ac",
"33c95e514d3b42185d70511156c58bada28a05ff9ccc151f33ddc50bf6a60d76",
}
def assemble(baseline, donor, donor_sha, output, classpath):
existing = baseline.read_bytes()
compiled = donor.read_bytes()
if digest(existing) not in BASELINES or digest(compiled) != donor_sha:
raise ValueError("Unexpected baseline or donor checksum")
retained = read_archive(existing)
source = read_archive(compiled)
if any(entry in retained for entry in NEW):
raise ValueError("The reviewed baseline already contains native workstation output hooks")
java_home = os.environ.get("JAVA_HOME")
executable = "java.exe" if os.name == "nt" else "java"
java = str(Path(java_home) / "bin" / executable) if java_home else executable
helper = Path(__file__).with_name("NativeWorkstationMerge.java")
with TemporaryDirectory() as temporary:
temp = Path(temporary)
old, new, merged = (temp / f"{name}.class" for name in ("retained", "donor", "merged"))
old.write_bytes(retained[ENTRY])
new.write_bytes(source[ENTRY])
subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new), str(merged)], check=True)
retained[ENTRY] = merged.read_bytes()
for entry in NEW:
retained[entry] = source[entry]
with output.open("xb") as candidate:
candidate.write(write_archive(retained))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("baseline", type=Path)
parser.add_argument("donor", type=Path)
parser.add_argument("donor_sha")
parser.add_argument("output", type=Path)
parser.add_argument("classpath", help="ASM core and tree JARs")
assemble(**vars(parser.parse_args()))