Merge commit '693037a982' into feat/lobby-pack-session-20261204
This commit is contained in:
commit
399162e55e
15 changed files with 579 additions and 14 deletions
54
.forgejo/workflows/guild-cookbook.yml
Normal file
54
.forgejo/workflows/guild-cookbook.yml
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
name: Guild and Cookbook Overlay
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['fix/guild-navigator-*']
|
||||
|
||||
jobs:
|
||||
guild-cookbook:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '9.2.1'
|
||||
- name: Test and package exact overlay donors
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for module in DuneRealmsGUI DuneNPC DuneLobby; do
|
||||
gradle --no-daemon -p "$module" test jar
|
||||
done
|
||||
mkdir guild-cookbook
|
||||
PYTHONPATH=tools python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
from plugin_guild_cookbook import CLASSES
|
||||
from plugin_wild_update import read_archive, write_archive
|
||||
for module, jar in (
|
||||
("gui", "DuneRealmsGUI/build/libs/DunerealmsGUI.jar"),
|
||||
("npc", "DuneNPC/build/libs/DuneRealms-NPC.jar"),
|
||||
("lobby", "DuneLobby/build/libs/DuneRealms-Lobby.jar"),
|
||||
):
|
||||
entries = read_archive(Path(jar).read_bytes())
|
||||
Path(f"guild-cookbook/{module}.zip").write_bytes(write_archive({entry: entries[entry] for entry in CLASSES[module]}))
|
||||
PY
|
||||
cp tools/{GuildCookbookMerge.java,plugin_guild_cookbook.py,plugin_wild_update.py} guild-cookbook/
|
||||
printf '%s\n' "$GITHUB_SHA" > guild-cookbook/SOURCE_COMMIT
|
||||
(cd guild-cookbook && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Guild-Cookbook
|
||||
path: guild-cookbook
|
||||
if-no-files-found: error
|
||||
49
.forgejo/workflows/sigma-cold-pigs.yml
Normal file
49
.forgejo/workflows/sigma-cold-pigs.yml
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
name: Sigma Cold Pigs Overlay
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['fix/sigma-cold-pigs-*']
|
||||
|
||||
jobs:
|
||||
sigma-cold-pigs:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '9.2.1'
|
||||
- name: Test Terrain and package the reviewed donor class
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneTerrain test jar
|
||||
mkdir sigma-cold-pigs
|
||||
PYTHONPATH=tools python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
from plugin_sigma_cold_pigs import ENTRY
|
||||
from plugin_wild_update import read_archive, write_archive
|
||||
jars = list(Path("DuneTerrain/build/libs").glob("*.jar"))
|
||||
assert len(jars) == 1
|
||||
entries = read_archive(jars[0].read_bytes())
|
||||
Path("sigma-cold-pigs/donor.zip").write_bytes(write_archive({ENTRY: entries[ENTRY]}))
|
||||
PY
|
||||
cp tools/{SigmaColdPigMerge.java,plugin_sigma_cold_pigs.py,plugin_wild_update.py} sigma-cold-pigs/
|
||||
printf '%s\n' "$GITHUB_SHA" > sigma-cold-pigs/SOURCE_COMMIT
|
||||
(cd sigma-cold-pigs && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Sigma-Cold-Pigs
|
||||
path: sigma-cold-pigs
|
||||
if-no-files-found: error
|
||||
|
|
@ -175,7 +175,11 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec
|
|||
String role=e.getRightClicked().getPersistentDataContainer().get(roleKey,PersistentDataType.STRING);
|
||||
if(role==null) return; e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return;
|
||||
switch(role) {
|
||||
case "liaison" -> { if(Bukkit.getPluginCommand("duneess")!=null) e.getPlayer().performCommand("duneess travel"); else departure(e.getPlayer(),"arrakis"); }
|
||||
case "liaison" -> {
|
||||
if (!e.getPlayer().performCommand("dunerealmsgui:guildtravel")) {
|
||||
e.getPlayer().sendMessage("The Spacing Guild menu is unavailable.");
|
||||
}
|
||||
}
|
||||
case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); }
|
||||
case "water","spice" -> trade(e.getPlayer(),role);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -99,7 +99,10 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut
|
|||
@EventHandler public void navigator(PlayerInteractEntityEvent event) {
|
||||
if (!event.getRightClicked().getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) return;
|
||||
event.setCancelled(true);
|
||||
if (event.getHand() == EquipmentSlot.HAND) Bukkit.dispatchCommand(event.getPlayer(), "duneess travel");
|
||||
if (event.getHand() != EquipmentSlot.HAND) return;
|
||||
if (!event.getPlayer().performCommand("dunerealmsgui:guildtravel")) {
|
||||
event.getPlayer().sendMessage("The Spacing Guild menu is unavailable.");
|
||||
}
|
||||
}
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!(sender instanceof Player player)) { sender.sendMessage("Run this command in-game."); return true; }
|
||||
|
|
|
|||
|
|
@ -7,13 +7,19 @@ import java.util.ArrayList;
|
|||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
final class CookbookCatalog {
|
||||
private static final List<String> ROMAN = List.of("0", "I", "II", "III", "IV", "V");
|
||||
|
||||
record Recipe(String id, String name, Material material, int mark, String quality, String ingredients, String details) {
|
||||
String grade() { return quality + " · MK " + ROMAN.get(mark); }
|
||||
NamespacedKey key() {
|
||||
if (id.equals("spice_tender")) return new NamespacedKey("minecarttrains", "fuel_cart");
|
||||
if (id.equals("spice_coal")) return new NamespacedKey("dunerealms", id);
|
||||
return new NamespacedKey("dunerealms", "spice_cooker_" + material.name().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
String grade() { return quality + " · MK " + ROMAN.get(mark); }
|
||||
}
|
||||
|
||||
private CookbookCatalog() {}
|
||||
|
|
|
|||
|
|
@ -131,7 +131,27 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
|
|||
var data=item.getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){inventory.setItem(slot,null);break;}
|
||||
}
|
||||
}
|
||||
private void openGuild(Player p,String requested){if(!lobby(p)){try{bridge.returnGuild(p);}catch(Exception unavailable){p.sendMessage("The Guild could not confirm your return. Please retry.");}return;}fetch(p,null,0,null,data->{String house=selection(data);if(house==null){p.sendMessage("Choose and confirm your House before Guild passage.");select(p,data,null);return;}travelMenu(p,data);});}
|
||||
private void openGuild(Player p,String requested){if(!lobby(p)){guildReturnMenu(p);return;}fetch(p,null,0,null,data->{String house=selection(data);if(house==null){p.sendMessage("Choose and confirm your House before Guild passage.");select(p,data,null);return;}travelMenu(p,data);});}
|
||||
private void guildReturnMenu(Player player){
|
||||
String title="Spacing Guild · Return passage";
|
||||
String detail="Return to the Guild Lobby to book onward passage.";
|
||||
Runnable returnToLobby=()->{
|
||||
player.closeInventory();
|
||||
try{bridge.returnGuild(player);}
|
||||
catch(Exception failure){player.sendMessage("The Guild could not confirm your return. Please retry.");}
|
||||
};
|
||||
if(BedrockForms.isBedrock(player)){
|
||||
BedrockForms.show(this,player,title,detail,List.of(new BedrockForms.Choice("Return to Guild Lobby",detail,returnToLobby)));
|
||||
return;
|
||||
}
|
||||
Screen panel=new Screen(player);
|
||||
panel.inventory=Bukkit.createInventory(panel,54,Component.text(title,NamedTextColor.GOLD));
|
||||
panel.inventory.setItem(22,icon(player,"Return to Guild Lobby",detail,"drgui_transparent",Material.COMPASS));
|
||||
panel.actions.put(22,returnToLobby);
|
||||
if(MCGUIMenus.show(player,title,detail,panel.inventory,panel.actions,panel.gate))return;
|
||||
player.openInventory(panel.inventory);
|
||||
expire(panel);
|
||||
}
|
||||
private static GuildBookings.Permit permit(JsonObject data){String house=selection(data);if(house==null||!data.has("keyId")||data.get("keyId").isJsonNull())return null;try{return new GuildBookings.Permit(house,UUID.fromString(data.get("keyId").getAsString()),data.get("version").getAsInt());}catch(RuntimeException invalid){return null;}}
|
||||
private void travelMenu(Player p,JsonObject data){var q=new JsonObject();q.addProperty("action","quote");guildRequest(p,q,quote->{data.add("guildQuote",quote);renderTravelMenu(p,data);});}
|
||||
private void guildRequest(Player p,JsonObject input,Consumer<JsonObject> done){UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(!boarding.add(id)){p.sendMessage("J.A.R.V.I.S. is processing your passage.");return;}Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;String failure=null;try{result=bridge.guild(id,input);}catch(Exception e){failure=e.getMessage();}var response=result;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(id)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The central Guild service is unavailable.":message);return;}done.accept(response);});});}
|
||||
|
|
|
|||
|
|
@ -67,14 +67,57 @@ final class OrganisationMenus implements Listener {
|
|||
}
|
||||
private void cookbookRecipe(Player player,CookbookCatalog.Recipe recipe){
|
||||
var panel=panel(player,"Cookbook · "+recipe.name(),false);
|
||||
panel.description=recipe.grade()+"\n"+recipe.ingredients()+"\n"+recipe.details();
|
||||
put(panel,22,recipe.name(),panel.description,recipe.material(),null);
|
||||
var icon=panel.inventory.getItem(22);
|
||||
var meta=icon.getItemMeta();
|
||||
meta.setItemModel(new NamespacedKey("dunerealms","crafting/"+recipe.id()));
|
||||
icon.setItemMeta(meta);
|
||||
panel.inventory.setItem(22,icon);
|
||||
put(panel,45,"Back","Cookbook",Material.ARROW,()->cookbook(player));close(panel,player);show(player,panel);
|
||||
var nativeRecipe=Bukkit.getRecipe(recipe.key());
|
||||
if(nativeRecipe instanceof org.bukkit.inventory.ShapedRecipe shaped){
|
||||
var shape=shaped.getShape();
|
||||
var ingredients=shaped.getChoiceMap();
|
||||
for(int row=0;row<shape.length;row++){
|
||||
for(int col=0;col<shape[row].length();col++){
|
||||
var choice=ingredients.get(shape[row].charAt(col));
|
||||
if(choice!=null)recipeIngredient(panel,10+row*9+col,recipe,choice);
|
||||
}
|
||||
}
|
||||
}else if(nativeRecipe instanceof org.bukkit.inventory.ShapelessRecipe shapeless){
|
||||
var ingredients=shapeless.getChoiceList();
|
||||
for(int i=0;i<ingredients.size();i++)recipeIngredient(panel,10+i/3*9+i%3,recipe,ingredients.get(i));
|
||||
}else{
|
||||
put(panel,22,"Recipe unavailable","This server has not registered this recipe.",Material.BARRIER,null);
|
||||
}
|
||||
if(nativeRecipe!=null){
|
||||
put(panel,23,"Produces",recipe.details(),Material.ARROW,null);
|
||||
put(panel,25,recipe.name(),recipe.grade()+" · "+nativeRecipe.getResult().getAmount()+" per craft",recipe.material(),null);
|
||||
var icon=panel.inventory.getItem(25);
|
||||
var meta=icon.getItemMeta();
|
||||
meta.setItemModel(new NamespacedKey("dunerealms","crafting/"+recipe.id()));
|
||||
icon.setItemMeta(meta);
|
||||
icon.setAmount(nativeRecipe.getResult().getAmount());
|
||||
panel.inventory.setItem(25,icon);
|
||||
}
|
||||
put(panel,45,"Back","Cookbook",Material.ARROW,()->cookbook(player));close(panel,player);
|
||||
// Keep the native row and column positions, including repeated ingredients.
|
||||
player.openInventory(panel.inventory);
|
||||
Bukkit.getScheduler().runTaskLater(plugin,panel.gate::expire,2400L);
|
||||
}
|
||||
private void recipeIngredient(Panel panel,int slot,CookbookCatalog.Recipe recipe,org.bukkit.inventory.RecipeChoice choice){
|
||||
Material material=choice.getItemStack().getType();
|
||||
String name=material.name().replace('_',' ').toLowerCase(Locale.ROOT);
|
||||
String detail="1 per slot";
|
||||
if(material==Material.ORANGE_DYE){
|
||||
name="Raw Melange Spice";
|
||||
detail="Use genuine raw Melange Spice.";
|
||||
}else if(material==Material.COAL&&recipe.id().equals("spice_tender")){
|
||||
name="Spice Coal";
|
||||
}else if(choice instanceof org.bukkit.inventory.RecipeChoice.MaterialChoice alternatives&&alternatives.getChoices().contains(Material.CHARCOAL)){
|
||||
name="Coal or Charcoal";
|
||||
}
|
||||
put(panel,slot,name,detail,material,null);
|
||||
if(name.equals("Spice Coal")){
|
||||
var icon=panel.inventory.getItem(slot);
|
||||
var meta=icon.getItemMeta();
|
||||
meta.setItemModel(new NamespacedKey("dunerealms","crafting/spice_coal"));
|
||||
icon.setItemMeta(meta);
|
||||
panel.inventory.setItem(slot,icon);
|
||||
}
|
||||
}
|
||||
private void start(Player p,JsonObject data){
|
||||
var panel=panel(p,"Your organisations",false);put(panel,19,"Clan","Your clan and Home Block",Material.GREEN_BANNER,()->choose(p,data,"clans"));put(panel,22,"Company","Your companies and Home Blocks",Material.CYAN_BANNER,()->choose(p,data,"companies"));put(panel,25,"POL","Your current political offices",Material.PURPLE_BANNER,()->choose(p,data,"offices"));close(panel,p);show(p,panel);
|
||||
|
|
|
|||
|
|
@ -10,13 +10,20 @@ import org.bukkit.plugin.Plugin;
|
|||
public final class PlanetMobs implements Listener {
|
||||
private static final Set<String> NETHER=Set.of("BLAZE","GHAST","HOGLIN","MAGMA_CUBE","PIGLIN","PIGLIN_BRUTE","STRIDER","WITHER_SKELETON","ZOGLIN","ZOMBIFIED_PIGLIN","SKELETON","ENDERMAN");
|
||||
private static final Set<String> PASSIVE=Set.of("ALLAY","ARMADILLO","AXOLOTL","BAT","CAMEL","CAT","CHICKEN","COD","COW","DONKEY","FROG","GLOW_SQUID","HORSE","MUSHROOM_COW","MOOSHROOM","MULE","OCELOT","PARROT","PIG","PUFFERFISH","RABBIT","SALMON","SHEEP","SNIFFER","SNOWMAN","SNOW_GOLEM","SQUID","STRIDER","TADPOLE","TROPICAL_FISH","TURTLE","VILLAGER","WANDERING_TRADER");
|
||||
public static boolean allowed(String planet,String mob,boolean island){return switch(planet){case "caladan"->!mob.equals("CREEPER");case "kaitain"->PASSIVE.contains(mob);case "giedi_prime"->NETHER.contains(mob);case "sigma_draconis_iv"->Set.of("SKELETON","STRAY","WITHER_SKELETON","BOGGED").contains(mob)||island&&Set.of("MUSHROOM_COW","MOOSHROOM","SULFUR_CUBE").contains(mob);default->true;};}
|
||||
public static boolean allowed(String planet,String mob,boolean island){if(allowedColdPig(planet,mob))return true;return switch(planet){case "caladan"->!mob.equals("CREEPER");case "kaitain"->PASSIVE.contains(mob);case "giedi_prime"->NETHER.contains(mob);case "sigma_draconis_iv"->Set.of("SKELETON","STRAY","WITHER_SKELETON","BOGGED").contains(mob)||island&&Set.of("MUSHROOM_COW","MOOSHROOM","SULFUR_CUBE").contains(mob);default->true;};}
|
||||
public static boolean allowedSpawn(String planet,String mob,boolean island,String reason){return allowed(planet,mob,island)||planet.equals("giedi_prime")&&(reason.equals("SPAWNER")&&Set.of("SKELETON","ZOMBIE","SPIDER","CAVE_SPIDER").contains(mob)||mob.equals("WARDEN"));}
|
||||
public static void start(Plugin plugin){Bukkit.getPluginManager().registerEvents(new PlanetMobs(),plugin);Bukkit.getPluginManager().registerEvents(new NativePlants(),plugin);PlanetSoil.start(plugin);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void spawning(CreatureSpawnEvent event){var e=event.getEntity();String planet=e.getWorld().getName();if(!TemperateLandscape.enabled(planet))return;
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void spawning(CreatureSpawnEvent event){if(sigmaColdPig(event))return;var e=event.getEntity();String planet=e.getWorld().getName();if(!TemperateLandscape.enabled(planet))return;
|
||||
if(e instanceof PiglinAbstract piglin&&planet.equals("giedi_prime"))piglin.setImmuneToZombification(true);if(e instanceof Hoglin hoglin&&planet.equals("giedi_prime"))hoglin.setImmuneToZombification(true);
|
||||
if(event.getSpawnReason()==CreatureSpawnEvent.SpawnReason.CUSTOM||e.hasMetadata("NPC")||e instanceof Tameable pet&&pet.isTamed())return;
|
||||
var at=e.getLocation();if(planet.equals("sigma_draconis_iv")&&e.getType().name().equals("SULFUR_CUBE")&&at.getBlock().getBiome().getKey().getKey().equals("sulfur_caves"))return;if(!allowedSpawn(planet,e.getType().name(),TemperateLandscape.islandDistance(e.getWorld().getSeed(),at.getBlockX(),at.getBlockZ())<112,event.getSpawnReason().name()))event.setCancelled(true);
|
||||
}
|
||||
private static boolean allowedColdPig(String world,String type){return "sigma_draconis_iv".equals(world)&&"PIG".equals(type);}
|
||||
private static boolean sigmaColdPig(CreatureSpawnEvent event){
|
||||
if(!(event.getEntity() instanceof Pig pig)||!allowedColdPig(pig.getWorld().getName(),"PIG")
|
||||
||event.getSpawnReason()==CreatureSpawnEvent.SpawnReason.CUSTOM||pig.hasMetadata("NPC"))return false;
|
||||
pig.setVariant(Pig.Variant.COLD);
|
||||
return true;
|
||||
}
|
||||
@EventHandler public void loaded(ServerLoadEvent event){var world=Bukkit.getWorld("giedi_prime");if(world!=null){world.setTime(18000);world.setStorm(false);world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE,false);world.setGameRule(GameRule.DO_WEATHER_CYCLE,false);}var arrakis=Bukkit.getWorld("arrakis");if(arrakis!=null)arrakis.setGameRule(GameRule.WATER_SOURCE_CONVERSION,false);}
|
||||
}
|
||||
|
|
|
|||
81
tools/GuildCookbookMerge.java
Normal file
81
tools/GuildCookbookMerge.java
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.Handle;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
class GuildCookbookMerge {
|
||||
private static final String GUI = "com/dunerealms/gui/";
|
||||
private static final Map<String, Set<String>> TARGETS = Map.of(
|
||||
GUI + "DuneGUI", Set.of("openGuild", "guildReturnMenu"),
|
||||
GUI + "OrganisationMenus", Set.of("cookbookRecipe", "recipeIngredient"),
|
||||
GUI + "CookbookCatalog$Recipe", Set.of("key"),
|
||||
"com/example/dunelobby/DuneLobby", Set.of("entityInteract"),
|
||||
"com/example/dunenpc/DuneNPC", Set.of("navigator"));
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3) throw new IllegalArgumentException("Expected retained, donor and output classes");
|
||||
var retainedReader = new ClassReader(Files.readAllBytes(Path.of(args[0])));
|
||||
var retained = parse(retainedReader);
|
||||
var donor = parse(new ClassReader(Files.readAllBytes(Path.of(args[1]))));
|
||||
var targets = TARGETS.get(retained.name);
|
||||
if (targets == null || !retained.name.equals(donor.name)) throw new IllegalArgumentException("Unexpected overlay class");
|
||||
var additions = new LinkedHashMap<String, MethodNode>();
|
||||
var renamed = new HashMap<String, String>();
|
||||
for (String target : targets.stream().sorted().toList()) {
|
||||
var method = donor.methods.stream().filter(m -> m.name.equals(target)).toList();
|
||||
if (method.size() != 1) throw new IllegalArgumentException("Expected one donor method " + target);
|
||||
prepare(donor, method.getFirst(), additions, renamed);
|
||||
}
|
||||
for (var entry : additions.entrySet()) {
|
||||
var method = entry.getValue();
|
||||
if (!targets.contains(method.name) &&
|
||||
retained.methods.stream().anyMatch(old -> old.name.equals(method.name) && old.desc.equals(method.desc))) {
|
||||
throw new IllegalArgumentException("Unexpected existing helper " + method.name);
|
||||
}
|
||||
retained.methods.removeIf(old -> old.name.equals(method.name) && old.desc.equals(method.desc));
|
||||
retained.methods.add(method);
|
||||
}
|
||||
var writer = new ClassWriter(retainedReader, 0);
|
||||
retained.accept(writer);
|
||||
Files.write(Path.of(args[2]), writer.toByteArray());
|
||||
}
|
||||
|
||||
private static void prepare(ClassNode donor, MethodNode method, Map<String, MethodNode> copies,
|
||||
Map<String, String> renamed) {
|
||||
String key = method.name + method.desc;
|
||||
if (copies.putIfAbsent(key, method) != null) return;
|
||||
for (var instruction : method.instructions) {
|
||||
if (!(instruction instanceof InvokeDynamicInsnNode dynamic)) continue;
|
||||
for (int i = 0; i < dynamic.bsmArgs.length; i++) {
|
||||
if (!(dynamic.bsmArgs[i] instanceof Handle handle) || !handle.getOwner().equals(donor.name) ||
|
||||
!handle.getName().startsWith("lambda$")) continue;
|
||||
String original = handle.getName() + handle.getDesc();
|
||||
String replacement = renamed.get(original);
|
||||
if (replacement == null) {
|
||||
var helper = donor.methods.stream().filter(m -> m.name.equals(handle.getName()) &&
|
||||
m.desc.equals(handle.getDesc())).findFirst().orElseThrow();
|
||||
replacement = "guildCookbook$" + handle.getName();
|
||||
renamed.put(original, replacement);
|
||||
helper.name = replacement;
|
||||
prepare(donor, helper, copies, renamed);
|
||||
}
|
||||
dynamic.bsmArgs[i] = new Handle(handle.getTag(), handle.getOwner(), replacement,
|
||||
handle.getDesc(), handle.isInterface());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ClassNode parse(ClassReader reader) {
|
||||
var node = new ClassNode();
|
||||
reader.accept(node, 0);
|
||||
return node;
|
||||
}
|
||||
}
|
||||
69
tools/SigmaColdPigMerge.java
Normal file
69
tools/SigmaColdPigMerge.java
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
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.FrameNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.JumpInsnNode;
|
||||
import org.objectweb.asm.tree.LabelNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
class SigmaColdPigMerge {
|
||||
private static final String OWNER = "com/example/duneterrain/PlanetMobs";
|
||||
private static final String PIG = "(Ljava/lang/String;Ljava/lang/String;)Z";
|
||||
private static final String SPAWN = "(Lorg/bukkit/event/entity/CreatureSpawnEvent;)";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3) throw new IllegalArgumentException("Expected retained, 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(m -> m.name.equals("sigmaColdPig") || m.name.equals("allowedColdPig"))) {
|
||||
throw new IllegalArgumentException("Unexpected retained PlanetMobs class");
|
||||
}
|
||||
retained.methods.add(method(donor, "sigmaColdPig", SPAWN + "Z"));
|
||||
retained.methods.add(method(donor, "allowedColdPig", PIG));
|
||||
var allowed = method(retained, "allowed", "(Ljava/lang/String;Ljava/lang/String;Z)Z");
|
||||
var check = new InsnList();
|
||||
check.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
check.add(new VarInsnNode(Opcodes.ALOAD, 1));
|
||||
check.add(new MethodInsnNode(Opcodes.INVOKESTATIC, OWNER, "allowedColdPig", PIG, false));
|
||||
prefix(allowed, check, true);
|
||||
var spawning = method(retained, "spawning", SPAWN + "V");
|
||||
var convert = new InsnList();
|
||||
convert.add(new VarInsnNode(Opcodes.ALOAD, 1));
|
||||
convert.add(new MethodInsnNode(Opcodes.INVOKESTATIC, OWNER, "sigmaColdPig", SPAWN + "Z", false));
|
||||
prefix(spawning, convert, false);
|
||||
var writer = new ClassWriter(reader, 0);
|
||||
retained.accept(writer);
|
||||
Files.write(Path.of(args[2]), writer.toByteArray());
|
||||
}
|
||||
|
||||
private static void prefix(MethodNode method, InsnList instructions, boolean returnsValue) {
|
||||
var resume = new LabelNode();
|
||||
instructions.add(new JumpInsnNode(Opcodes.IFEQ, resume));
|
||||
if (returnsValue) instructions.add(new InsnNode(Opcodes.ICONST_1));
|
||||
instructions.add(new InsnNode(returnsValue ? Opcodes.IRETURN : Opcodes.RETURN));
|
||||
instructions.add(resume);
|
||||
instructions.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null));
|
||||
method.instructions.insert(instructions);
|
||||
method.maxStack = Math.max(method.maxStack, 2);
|
||||
}
|
||||
|
||||
private static ClassNode parse(ClassReader reader) {
|
||||
var node = new ClassNode();
|
||||
reader.accept(node, 0);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static MethodNode method(ClassNode node, String name, String descriptor) {
|
||||
return node.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(descriptor))
|
||||
.findFirst().orElseThrow(() -> new IllegalArgumentException("Missing expected method " + name));
|
||||
}
|
||||
}
|
||||
44
tools/WoodcuttingOriginMerge.java
Normal file
44
tools/WoodcuttingOriginMerge.java
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
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.MethodInsnNode;
|
||||
|
||||
class WoodcuttingOriginMerge {
|
||||
private static final String OWNER = "io/gitlab/jumperdenfer/features/WoodCuttingFeature";
|
||||
private static final String PRODUCER = "dropProducedPlanks";
|
||||
private static final String DROP = "(Lorg/bukkit/Location;Lorg/bukkit/inventory/ItemStack;)Lorg/bukkit/entity/Item;";
|
||||
private static final String WRAPPER = "(Lorg/bukkit/World;" + DROP.substring(1);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3) throw new IllegalArgumentException("Expected baseline, donor and output classes");
|
||||
var retainedBytes = Files.readAllBytes(Path.of(args[0]));
|
||||
var retainedReader = new ClassReader(retainedBytes);
|
||||
var retained = parse(retainedReader);
|
||||
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(PRODUCER))) {
|
||||
throw new IllegalArgumentException("Unexpected vendor class");
|
||||
}
|
||||
var listener = retained.methods.stream().filter(method -> method.name.equals("onBlockPlace") &&
|
||||
method.desc.equals("(Lorg/bukkit/event/block/BlockPlaceEvent;)V")).findFirst().orElseThrow();
|
||||
var drops = java.util.Arrays.stream(listener.instructions.toArray()).filter(instruction ->
|
||||
instruction instanceof MethodInsnNode call && call.getOpcode() == Opcodes.INVOKEINTERFACE &&
|
||||
call.owner.equals("org/bukkit/World") && call.name.equals("dropItem") && call.desc.equals(DROP)).toList();
|
||||
if (drops.size() != 1) throw new IllegalArgumentException("Expected exactly one sawmill output call");
|
||||
listener.instructions.set(drops.getFirst(), new MethodInsnNode(Opcodes.INVOKESTATIC, OWNER, PRODUCER, WRAPPER, false));
|
||||
retained.methods.add(donor.methods.stream().filter(method ->
|
||||
method.name.equals(PRODUCER) && method.desc.equals(WRAPPER)).findFirst().orElseThrow());
|
||||
var writer = new ClassWriter(retainedReader, 0);
|
||||
retained.accept(writer);
|
||||
Files.write(Path.of(args[2]), writer.toByteArray());
|
||||
}
|
||||
|
||||
private static ClassNode parse(ClassReader reader) {
|
||||
var node = new ClassNode();
|
||||
reader.accept(node, 0);
|
||||
return node;
|
||||
}
|
||||
}
|
||||
53
tools/plugin_guild_cookbook.py
Normal file
53
tools/plugin_guild_cookbook.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"""Assemble reviewed Guild and Cookbook methods onto the installed plugin 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
|
||||
|
||||
CLASSES = {
|
||||
"gui": (
|
||||
"com/dunerealms/gui/DuneGUI.class",
|
||||
"com/dunerealms/gui/OrganisationMenus.class",
|
||||
"com/dunerealms/gui/CookbookCatalog$Recipe.class",
|
||||
),
|
||||
"npc": ("com/example/dunenpc/DuneNPC.class",),
|
||||
"lobby": ("com/example/dunelobby/DuneLobby.class",),
|
||||
}
|
||||
|
||||
|
||||
def assemble(module, baseline, baseline_sha, donor, donor_sha, output, classpath):
|
||||
baseline_bytes = baseline.read_bytes()
|
||||
donor_bytes = donor.read_bytes()
|
||||
if digest(baseline_bytes) != baseline_sha or digest(donor_bytes) != donor_sha:
|
||||
raise ValueError("Unexpected baseline or donor checksum")
|
||||
retained = read_archive(baseline_bytes)
|
||||
compiled = read_archive(donor_bytes)
|
||||
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("GuildCookbookMerge.java")
|
||||
with TemporaryDirectory() as temporary:
|
||||
temp = Path(temporary)
|
||||
for index, entry in enumerate(CLASSES[module]):
|
||||
old, new, merged = (temp / f"{index}-{name}.class" for name in ("retained", "donor", "merged"))
|
||||
old.write_bytes(retained[entry])
|
||||
new.write_bytes(compiled[entry])
|
||||
subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new), str(merged)], check=True)
|
||||
retained[entry] = merged.read_bytes()
|
||||
with output.open("xb") as candidate:
|
||||
candidate.write(write_archive(retained))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("module", choices=CLASSES)
|
||||
parser.add_argument("baseline", type=Path)
|
||||
parser.add_argument("baseline_sha")
|
||||
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()))
|
||||
60
tools/plugin_sigma_cold_pigs.py
Normal file
60
tools/plugin_sigma_cold_pigs.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"""Build the Sigma-only cold pig class graft and two biome mob-list changes."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from plugin_wild_update import digest, read_archive, write_archive
|
||||
|
||||
TERRAIN_SHA = "2c9d56d64253a8ee49d3411dc32e4da3885e2cd1bc35b00b64ca920f180c1eb5"
|
||||
BIOME_SHA = "0116d155df34e6c9c0482c0f7e21404ea69ea1357819005acfdb110ab748b139"
|
||||
ENTRY = "com/example/duneterrain/PlanetMobs.class"
|
||||
|
||||
|
||||
def checked(path, sha):
|
||||
source = path.read_bytes()
|
||||
if digest(source) != sha:
|
||||
raise ValueError(f"Unreviewed baseline or donor: {path.name}")
|
||||
return read_archive(source)
|
||||
|
||||
|
||||
def assemble(terrain, biomes, donor, donor_sha, terrain_output, biomes_output, classpath):
|
||||
existing = checked(terrain, TERRAIN_SHA)
|
||||
pack = checked(biomes, BIOME_SHA)
|
||||
compiled = checked(donor, donor_sha)
|
||||
for name in ("snowy_plains", "snowy_taiga"):
|
||||
entry = f"data/minecraft/worldgen/biome/{name}.json"
|
||||
data = json.loads(pack[entry])
|
||||
spawners = data["spawners"]["creature"]
|
||||
if any(spawner["type"] == "minecraft:pig" for spawner in spawners):
|
||||
raise ValueError("Pig spawn already registered")
|
||||
spawners.append({"type": "minecraft:pig", "weight": 4, "minCount": 2, "maxCount": 3})
|
||||
pack[entry] = (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
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
|
||||
with TemporaryDirectory() as temporary:
|
||||
temp = Path(temporary)
|
||||
old, new, merged = (temp / f"{name}.class" for name in ("retained", "donor", "merged"))
|
||||
old.write_bytes(existing[ENTRY])
|
||||
new.write_bytes(compiled[ENTRY])
|
||||
helper = Path(__file__).with_name("SigmaColdPigMerge.java")
|
||||
subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new), str(merged)], check=True)
|
||||
existing[ENTRY] = merged.read_bytes()
|
||||
for path, contents in ((terrain_output, existing), (biomes_output, pack)):
|
||||
with path.open("xb") as result:
|
||||
result.write(write_archive(contents))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("terrain", type=Path)
|
||||
parser.add_argument("biomes", type=Path)
|
||||
parser.add_argument("donor", type=Path)
|
||||
parser.add_argument("donor_sha")
|
||||
parser.add_argument("terrain_output", type=Path)
|
||||
parser.add_argument("biomes_output", type=Path)
|
||||
parser.add_argument("classpath", help="ASM core and tree JARs")
|
||||
assemble(**vars(parser.parse_args()))
|
||||
49
tools/plugin_woodcutting_origin.py
Normal file
49
tools/plugin_woodcutting_origin.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""Build the scoped provenance overlay for the reviewed WoodCutting runtime."""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from plugin_wild_update import digest, read_archive, write_archive
|
||||
|
||||
BASELINE = "de19fff89bd43c00a8dad8013dc8898ef56cf811825ba424b811cd8bffd78169"
|
||||
ENTRY = "io/gitlab/jumperdenfer/features/WoodCuttingFeature.class"
|
||||
|
||||
|
||||
def assemble(baseline, output, classpath):
|
||||
baseline_bytes = baseline.read_bytes()
|
||||
if digest(baseline_bytes) != BASELINE:
|
||||
raise ValueError("Unreviewed WoodCutting runtime")
|
||||
entries = read_archive(baseline_bytes)
|
||||
root = Path(__file__).resolve().parent
|
||||
java_home = os.environ.get("JAVA_HOME")
|
||||
|
||||
def executable(name):
|
||||
name += ".exe" if os.name == "nt" else ""
|
||||
return str(Path(java_home) / "bin" / name) if java_home else name
|
||||
|
||||
with TemporaryDirectory() as temporary:
|
||||
temp = Path(temporary)
|
||||
current, merged = temp / "retained.class", temp / "merged.class"
|
||||
current.write_bytes(entries[ENTRY])
|
||||
subprocess.run([
|
||||
executable("javac"), "--release", "21", "-classpath", classpath, "-d", str(temp),
|
||||
str(root.parent / "vendor/woodcutting/WoodCuttingFeature.java"),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
executable("java"), "--class-path", classpath,
|
||||
str(root / "WoodcuttingOriginMerge.java"),
|
||||
str(current), str(temp / ENTRY), str(merged),
|
||||
], check=True)
|
||||
entries[ENTRY] = merged.read_bytes()
|
||||
with output.open("xb") as candidate:
|
||||
candidate.write(write_archive(entries))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("baseline", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("classpath", help="Paper API, its dependencies, and ASM core and tree JARs")
|
||||
assemble(**vars(parser.parse_args()))
|
||||
23
vendor/woodcutting/WoodCuttingFeature.java
vendored
Normal file
23
vendor/woodcutting/WoodCuttingFeature.java
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package io.gitlab.jumperdenfer.features;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Item;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
class WoodCuttingFeature {
|
||||
private static Item dropProducedPlanks(World world, Location position, ItemStack planks) {
|
||||
var meta = planks.getItemMeta();
|
||||
if (meta != null) {
|
||||
var data = meta.getPersistentDataContainer();
|
||||
var origin = new NamespacedKey("dunerealms", "origin_world");
|
||||
if (!data.has(origin) && !data.has(new NamespacedKey("dunerealms", "preview_only"))) {
|
||||
data.set(origin, PersistentDataType.STRING, world.getName());
|
||||
planks.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
return world.dropItem(position, planks);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff