diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 56ddf199..013a3200 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ name: Build DuneCore, DuneNPC, DuneEss, and DuneTerrain on: workflow_dispatch: push: - branches: [main] + branches: [main, "feature/native-gui-1.21.8"] jobs: build-website: @@ -143,9 +143,27 @@ jobs: path: DuneNPC/build/libs/*.jar if-no-files-found: error + build-lobby: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '8.14' + - run: gradle -p DuneLobby clean build + - uses: actions/upload-artifact@v4 + with: + name: DuneLobby-Plugin + path: DuneLobby/build/libs/*.jar + if-no-files-found: error + package-server: runs-on: ubuntu-latest - needs: [build-core, build-ess, build-terrain, build-npc] + needs: [build-core, build-ess, build-terrain, build-npc, build-lobby] steps: - name: Checkout source uses: actions/checkout@v4 @@ -155,6 +173,8 @@ jobs: pattern: Dune*-Plugin path: DuneRealms-Server-Package merge-multiple: true + - name: Download verified crossplay plugins + run: python3 tools/download-crossplay.py DuneRealms-Server-Package/crossplay - name: Add resource pack and install instructions run: | curl --fail --location --silent --show-error \ @@ -168,28 +188,32 @@ jobs: cp docs/Dune-User-Manual.pdf DuneRealms-Server-Package/ cp docs/Dune-Complete-Illustrated-Manual.pdf DuneRealms-Server-Package/ cp docs/posters/*.png DuneRealms-Server-Package/ + cp docs/Native-GUI.md DuneRealms-Server-Package/Native-GUI.md cp README.md DuneRealms-Server-Package/Project-README.md cp website/DISCORD-FEEDS.md DuneRealms-Server-Package/DiscordSRV-Website-Setup.md cat > DuneRealms-Server-Package/README.txt <<'EOF' DuneRealms Paper server package - Contents: Vault 2.5.0, DuneCore, DuneNPC, DuneEss, and DuneTerrain plugin JARs, plus DuneResourcePack.zip. + Contents: Vault 2.5.0, all five Dune plugins, and verified Geyser, Floodgate, ViaVersion JARs. + See Native-GUI.md for platform-specific plugin placement. The illustrated user manual and Project-README.md are included for players and administrators. - Install all five plugin JARs in the Paper server's plugins/ folder and restart the server. + Install the applicable plugin JARs in the Paper server's plugins/ folder and restart the server. Install the included resource pack on vanilla or Fabric 1.21.4 clients for sandworm, haunted Fremen, and spice textures. On Fabric, put the ZIP in .minecraft/resourcepacks and enable it in Options > Resource Packs; do not put it in mods/. DuneEss provides the Solaris economy through the included Vault API plugin. Vault 2.5.0 is the GPL-3.0 licensed Foulest/MilkBowl Vault project; its license is included here. Its source is available at https://github.com/Foulest/Vault/tree/2.5.0. - Compatible build target: Paper 1.21.4, Java 21. + Compatible GUI build target: Paper 1.21.8, Java 21. See https://github.com/thomasv6545-glitch/MC for setup and configuration details. EOF + - name: ZIP every server plugin JAR together + run: zip -r DuneRealms-All-Server-Jars.zip DuneRealms-Server-Package - name: Upload one downloadable server package uses: actions/upload-artifact@v4 with: name: DuneRealms-Server-Package - path: DuneRealms-Server-Package/ + path: DuneRealms-All-Server-Jars.zip if-no-files-found: error retention-days: 90 diff --git a/.github/workflows/lobby.yml b/.github/workflows/lobby.yml index c58bb92d..fb57d9a7 100644 --- a/.github/workflows/lobby.yml +++ b/.github/workflows/lobby.yml @@ -3,7 +3,7 @@ on: workflow_dispatch: push: branches: [main, beta] - paths: ['DuneLobby/**', 'worlds/**', '.github/workflows/lobby.yml'] + paths: ['DuneLobby/**', 'worlds/**', '.github/workflows/lobby.yml', 'gui-common/**'] jobs: build: runs-on: ubuntu-latest diff --git a/.github/workflows/network.yml b/.github/workflows/network.yml index 9f507577..362dfe3d 100644 --- a/.github/workflows/network.yml +++ b/.github/workflows/network.yml @@ -2,9 +2,12 @@ name: Package DuneRealms Velocity Network on: workflow_dispatch: push: - branches: [main] + branches: [main, "feature/native-gui-1.21.8"] paths: - 'network/**' + - 'gui-common/**' + - 'tools/**' + - 'DuneLobby/**' - 'DuneTerrain/**' - 'DuneEss/**' - 'DuneNPC/**' @@ -26,13 +29,20 @@ jobs: run: | set -e mkdir -p built-plugins - for project in DuneRealms-minecraft-only DuneTerrain DuneNPC DuneEss; do + for project in DuneRealms-minecraft-only DuneTerrain DuneNPC DuneEss DuneLobby; do (cd "$project" && gradle clean build) done cp DuneRealms-minecraft-only/build/libs/*.jar built-plugins/DuneCore.jar cp DuneTerrain/build/libs/*.jar built-plugins/DuneTerrain.jar cp DuneNPC/build/libs/*.jar built-plugins/DuneNPC.jar - cp DuneEss/build/libs/*.jar built-plugins/DuneEss.jar + cp DuneEss/build/libs/*.jar built-plugins/DuneRealms-Essentials.jar + cp DuneLobby/build/libs/*.jar built-plugins/DuneLobby.jar + - name: Download verified crossplay plugins + run: | + python3 tools/download-crossplay.py built-crossplay + curl --fail --location --silent --show-error https://github.com/Foulest/Vault/releases/download/2.5.0/Vault-2.5.0.jar --output built-crossplay/universal/Vault-2.5.0.jar + echo "3efb1c893d35807c0f3945068858a96af0f131020eee37545bdddb330044b2d9 built-crossplay/universal/Vault-2.5.0.jar" | sha256sum --check --strict + curl --fail --location --silent --show-error https://raw.githubusercontent.com/Foulest/Vault/2.5.0/LICENSE --output built-crossplay/Vault-LICENSE.txt - name: Package six servers and Velocity config run: python3 network/package.py - uses: actions/upload-artifact@v4 diff --git a/.gitignore b/.gitignore index a3213f92..cc448ff8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,9 @@ build/ # Manual render and conversion intermediates tmp/ __pycache__/ + +# Generated release packages and credentials in fresh-install network templates +/built-plugins/ +/built-crossplay/ +/DuneRealms-Velocity-Network/ +/DuneRealms-Velocity-Network.zip diff --git a/DuneEss/build.gradle.kts b/DuneEss/build.gradle.kts index c129cba2..a081f0b5 100644 --- a/DuneEss/build.gradle.kts +++ b/DuneEss/build.gradle.kts @@ -1,20 +1,20 @@ plugins { java } group = "com.example" -version = "1.0.2" +version = "1.0.3" repositories { mavenCentral() maven("https://repo.papermc.io/repository/maven-public/") maven("https://jitpack.io") } dependencies { - compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") compileOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } implementation("org.postgresql:postgresql:42.7.4") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("com.h2database:h2:2.3.232") - testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") testImplementation("org.mockito:mockito-core:5.15.2") testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } testRuntimeOnly("org.junit.platform:junit-platform-launcher") @@ -27,3 +27,14 @@ tasks.jar { java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.withType { options.encoding = "UTF-8" } tasks.test { useJUnitPlatform() } + +repositories { maven("https://repo.opencollab.dev/main/") } +dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") } +sourceSets.main { java.srcDir("../gui-common/src/main/java") } + +tasks.jar { archiveFileName.set("DuneRealms-Essentials.jar") } + +// Explicit test instrumentation works on Java 21 without dynamic self-attachment. +val mockitoAgent by configurations.creating +dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } +tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEss.java b/DuneEss/src/main/java/com/example/duneess/DuneEss.java index a2d5335c..44e8f6c0 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEss.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEss.java @@ -30,9 +30,10 @@ import java.sql.PreparedStatement; import java.util.*; public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener { - private static final List PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv"); + private static final List PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv", "spacing_guild"); private DuneEconomy economy; private ExchangeMenu exchangeMenu; + private EssentialsBasics basics; private String jdbcUrl = "", dbUser = "", dbPassword = ""; private boolean networkEnabled; private String localPlanet; @@ -87,10 +88,12 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom command.setExecutor(this); command.setTabCompleter(this); getServer().getPluginManager().registerEvents(this, this); + basics=new EssentialsBasics(this); + basics.register(); exchangeMenu = new ExchangeMenu(this); exchangeMenu.register(); for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player); - getLogger().info("DuneEss enabled as the Solaris Vault provider."); + getLogger().info("DuneRealms Essentials enabled as the Solaris Vault provider."); } @Override public void onDisable() { @@ -150,6 +153,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if(args.length==0 && sender instanceof Player player) { basics.menu(player); return true; } if (args.length == 0 || args[0].equalsIgnoreCase("help")) { int page = 1; if (args.length > 1 && args[1].equalsIgnoreCase("menu")) { @@ -273,7 +277,17 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom nextMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index + 2); next.setItemMeta(nextMeta); menu.setItem(53, next); - player.openInventory(menu); + java.util.Map actions=new java.util.HashMap<>(); + actions.put(45,()->openHelpMenu(player,index)); + actions.put(53,()->openHelpMenu(player,index+2)); + actions.put(49,player::closeInventory); + for(int slot:slots) { + ItemStack entry=menu.getItem(slot); + if(entry==null) continue; + String command=entry.getItemMeta().getPersistentDataContainer().get(helpActionKey,PersistentDataType.STRING); + if(command!=null) actions.put(slot,()->player.performCommand(command.substring(1))); + } + com.example.dunegui.NativeMenus.inventory(this,player,"Dune Field Guide · "+(index+1),menu,actions); } private ItemStack helpItem(Material material, String name, List lore) { @@ -306,6 +320,33 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom economy.createPlayerAccount(event.getPlayer()); } + @EventHandler(ignoreCancelled=true) + public void spiceSeller(org.bukkit.event.player.PlayerInteractEntityEvent event) { + if(!event.getRightClicked().getPersistentDataContainer().has(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE))return; + event.setCancelled(true); + if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return; + Player player=event.getPlayer(); + Inventory menu=Bukkit.createInventory(null,9,"Spice Seller"); + int quantity=16; + double price=java.math.BigDecimal.valueOf(Math.max(1,getConfig().getInt("currency.spice-price",15))) + .multiply(new java.math.BigDecimal("1.35")).multiply(java.math.BigDecimal.valueOf(quantity)).doubleValue(); + ItemStack offer=new ItemStack(Material.ORANGE_DYE,quantity); ItemMeta meta=offer.getItemMeta(); + meta.setDisplayName("Buy 16 spice · "+economy.format(price)); + meta.setLore(List.of("35% above standard spice price", "Confirm purchase"));offer.setItemMeta(meta);menu.setItem(4,offer); + Map actions=new HashMap<>(); + actions.put(4,()->{ + // Recheck proximity and capacity at confirmation; never charge for undeliverable goods. + if(!event.getRightClicked().isValid() || !player.getWorld().equals(event.getRightClicked().getWorld()) + || player.getLocation().distanceSquared(event.getRightClicked().getLocation())>64)return; + ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta(); + sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm); + if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;} + if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Solaris, or economy unavailable.");return;} + player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+"."); + }); + com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions); + } + private void sellSpice(Player player) { int amount = 0; for (ItemStack item : player.getInventory().getStorageContents()) { @@ -346,7 +387,9 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom item.setItemMeta(meta); inventory.setItem(i, item); } - player.openInventory(inventory); + java.util.Map actions=new java.util.HashMap<>(); + for(int i=0;itravel(player,planet)); } + com.example.dunegui.NativeMenus.inventory(this,player,"Spacing Guild Travel",inventory,actions); } @EventHandler public void onTravelMenuClick(InventoryClickEvent event) { diff --git a/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java b/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java new file mode 100644 index 00000000..af738885 --- /dev/null +++ b/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java @@ -0,0 +1,138 @@ +package com.example.duneess; + +import com.example.dunegui.NativeMenus; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.command.*; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.*; +import org.bukkit.event.player.PlayerQuitEvent; +import java.io.*; +import java.nio.file.*; +import java.util.*; + +/** Deliberately small essentials command surface; vanilla owns bed/anchor respawns. */ +final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener { + private final DuneEss plugin; + private final File file; + private YamlConfiguration homes; + private final Map requests=new HashMap<>(); + private record Request(UUID sender,long expires) {} + EssentialsBasics(DuneEss plugin) { + this.plugin=plugin; + file=new File(plugin.getDataFolder(),"homes.yml"); + homes=YamlConfiguration.loadConfiguration(file); + } + void register() { + for(String name:List.of("home","sethome","delhome","homes","tpa","tpaccept","tpdeny","spawn","server","essentials")) { + PluginCommand command=Objects.requireNonNull(plugin.getCommand(name)); + command.setExecutor(this); command.setTabCompleter(this); + } + Bukkit.getPluginManager().registerEvents(this,plugin); + } + static String homeName(String[] args) { + String name=args.length==0?"home":args[0].toLowerCase(Locale.ROOT); + if(args.length>1 || !name.matches("[a-z0-9_-]{1,24}")) throw new IllegalArgumentException("Use a home name with 1–24 letters, numbers, underscores or hyphens."); + return name; + } + private String key(Player p,String name) { return p.getUniqueId()+"."+name; } + private Set names(Player p) { + var section=homes.getConfigurationSection(p.getUniqueId().toString()); + return section==null?Set.of():section.getKeys(false); + } + private void save() throws IOException { + Path target=file.toPath(), temp=target.resolveSibling("homes.yml.tmp"); + Files.createDirectories(target.getParent()); + Files.writeString(temp,homes.saveToString()); + try { Files.move(temp,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); } + catch(AtomicMoveNotSupportedException ex) { Files.move(temp,target,StandardCopyOption.REPLACE_EXISTING); } + } + private void teleport(Player p,Location location) { + // Local essentials never bypass interplanetary permits, fares, or arrival rules. + if(location==null || location.getWorld()==null) { p.sendMessage("That destination is unavailable on this server."); return; } + if(!p.getWorld().equals(location.getWorld())) { p.sendMessage("Use /server to travel between worlds, then /home at your destination."); return; } + if(!location.getWorld().getWorldBorder().isInside(location) || location.getY()=location.getWorld().getMaxHeight()) { + p.sendMessage("That destination is outside the world's playable bounds."); return; + } + p.teleportAsync(location).thenAccept(success->{ if(!success) p.sendMessage("Teleportation failed. Try again."); }); + } + void menu(Player p) { + List choices=new ArrayList<>(); + choices.add(new NativeMenus.Choice("Set home","Save your current position as home.",()->p.performCommand("sethome"))); + choices.add(new NativeMenus.Choice("Homes","Choose a saved home on this backend.",()->homeMenu(p))); + choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn"))); + choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel"))); + choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance"))); + choices.add(new NativeMenus.Choice("CHOAM Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange"))); + choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu"))); + NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices); + } + private void homeMenu(Player p) { + List choices=names(p).stream().sorted().map(name->new NativeMenus.Choice(name,"Teleport to this saved home.",()->p.performCommand("home "+name))).toList(); + if(choices.isEmpty()) p.sendMessage("You have no homes. Use /sethome [name]."); + else NativeMenus.show(plugin,p,"Your homes",choices); + } + @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { + if(!(sender instanceof Player p)) { sender.sendMessage("Use this command in-game."); return true; } + String action=command.getName(); + if(!p.hasPermission("duneess.basics")) { p.sendMessage("You do not have permission to use essentials."); return true; } + try { + switch(action) { + case "essentials" -> menu(p); + case "homes" -> homeMenu(p); + case "sethome" -> { + String name=homeName(args), path=key(p,name); + if(!homes.contains(path) && names(p).size()>=Math.max(1,plugin.getConfig().getInt("essentials.max-homes",3))) throw new IllegalArgumentException("Your home limit has been reached."); + homes.set(path,p.getLocation()); save(); p.sendMessage("Home saved: "+name); + } + case "home" -> teleport(p,homes.getLocation(key(p,homeName(args)))); + case "delhome" -> { + String name=homeName(args),path=key(p,name); + if(!homes.contains(path)) throw new IllegalArgumentException("That home does not exist."); + homes.set(path,null); save(); p.sendMessage("Home removed: "+name); + } + case "spawn" -> teleport(p,p.getWorld().getSpawnLocation()); + case "server" -> plugin.onCommand(p,Objects.requireNonNull(plugin.getCommand("duneess")),"duneess",args.length==0?new String[]{"travel"}:new String[]{"travel",args[0]}); + case "tpa" -> { + if(args.length!=1) throw new IllegalArgumentException("Usage: /tpa "); + Player target=Bukkit.getPlayerExact(args[0]); + if(target==null || target.equals(p) || !p.canSee(target)) throw new IllegalArgumentException("Choose another online player on this server."); + if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Guild travel to reach that player's world first."); + requests.put(target.getUniqueId(),new Request(p.getUniqueId(),System.nanoTime()+60_000_000_000L)); + target.sendMessage(p.getName()+" requests to teleport to you. /tpaccept or /tpdeny (60 seconds)."); + p.sendMessage("Teleport request sent."); + } + case "tpaccept","tpdeny" -> { + Request request=requests.remove(p.getUniqueId()); + if(request==null || request.expires() { return false; } + } + } catch(IllegalArgumentException ex) { p.sendMessage(ex.getMessage()); } + catch(IOException ex) { + homes=YamlConfiguration.loadConfiguration(file); + plugin.getLogger().warning("Could not persist homes: "+ex.getMessage()); + p.sendMessage("Could not save your homes. No change was committed."); + } + return true; + } + @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args) { + if(!(sender instanceof Player p) || args.length!=1) return List.of(); + Collection values=switch(command.getName()) { + case "home","delhome" -> names(p); + case "tpa" -> Bukkit.getOnlinePlayers().stream().filter(p::canSee).map(Player::getName).toList(); + case "server" -> List.of("arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv","spacing_guild"); + default -> List.of(); + }; + return values.stream().filter(v->v.toLowerCase(Locale.ROOT).startsWith(args[0].toLowerCase(Locale.ROOT))).toList(); + } + @EventHandler public void quit(PlayerQuitEvent event) { + UUID id=event.getPlayer().getUniqueId(); + requests.remove(id); requests.values().removeIf(request->request.sender().equals(id)); + } +} diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java index dd6c3022..05c3eebb 100644 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java +++ b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java @@ -14,7 +14,7 @@ import java.math.BigDecimal; import java.sql.SQLException; import java.util.*; -/** Standard inventory slots work on Java and through Geyser without custom client interfaces. */ +/** Native menus share the existing SQL-backed trading operations. */ @SuppressWarnings("deprecation") final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { private static final List CATEGORIES=List.of("ores","spice","building","equipment","farming","misc"); @@ -28,6 +28,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { final UUID owner; final Map actions=new HashMap<>(); Inventory inventory; + String title; Screen(UUID owner) { this.owner=owner; } @Override public Inventory getInventory() { return inventory; } } @@ -72,6 +73,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { } private Screen screen(Player p,String title) { Screen s=new Screen(p.getUniqueId()); + s.title="CHOAM | "+title; s.inventory=Bukkit.createInventory(s,54,tint(p)+"CHOAM | "+title); Material glass=switch(faction(p)) { case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE; @@ -106,7 +108,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { }); if(p.hasPermission("dune.admin")) button(s,42,Material.COMMAND_BLOCK,"Exchange Administration",()->admin(p)); button(s,49,Material.BARRIER,"Close",p::closeInventory); - p.openInventory(s.inventory); + com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); } private void planetMenu(Player p) { Screen s=screen(p,"Planet Filter"); @@ -114,7 +116,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { String planet=PLANETS.get(i); button(s,11+i,Material.COMPASS,planet,()->{planets.put(p.getUniqueId(),planet); browse(p,"all",0,false,false);}); } - p.openInventory(s.inventory); + com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); } private void admin(Player p) { if(!p.hasPermission("dune.admin")) return; @@ -123,7 +125,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { button(s,24,Material.REDSTONE,"Check Database",()->{ if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared CHOAM database connected."); }); - p.openInventory(s.inventory); + com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); } private ItemStack decode(ExchangeStore.Listing offer) { ItemStack item; @@ -158,7 +160,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { if(rows.isEmpty()) s.inventory.setItem(22,icon(Material.PAPER,"No matching listings","Try another planet or list a held item.")); if(current>0) button(s,45,Material.ARROW,"Previous",()->browse(p,category,current-1,mine,admin)); if(rows.size()>28) button(s,53,Material.ARROW,"Next",()->browse(p,category,current+1,mine,admin)); - p.openInventory(s.inventory); + com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); }); } private void confirm(Player p,long id,boolean reclaim) { @@ -171,7 +173,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{ p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id); }); - button(s,32,Material.RED_CONCRETE,"Never Mind",()->home(p)); p.openInventory(s.inventory); + button(s,32,Material.RED_CONCRETE,"Never Mind",()->home(p)); com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); }); } private boolean fits(Player p,ItemStack item,int amount) { diff --git a/DuneEss/src/main/resources/config.yml b/DuneEss/src/main/resources/config.yml index def0523a..a7cd372a 100644 --- a/DuneEss/src/main/resources/config.yml +++ b/DuneEss/src/main/resources/config.yml @@ -18,3 +18,7 @@ network: servers: {} worlds: [arrakis, giedi_prime, kaitain, caladan, sigma_draconis_iv] + +# Homes are local to each backend. Vanilla bed/anchor respawns remain authoritative. +essentials: + max-homes: 3 diff --git a/DuneEss/src/main/resources/plugin.yml b/DuneEss/src/main/resources/plugin.yml index cb82cb41..dd9b52c2 100644 --- a/DuneEss/src/main/resources/plugin.yml +++ b/DuneEss/src/main/resources/plugin.yml @@ -1,10 +1,11 @@ name: DuneEss -version: 1.0.2 +version: 1.0.3 main: com.example.duneess.DuneEss -api-version: '1.21' +api-version: '1.21.8' depend: [Vault] -softdepend: [DuneCore, DuneTerrain] -description: Dune Solaris economy, Vault provider, spice sales, and Arrakis travel +softdepend: [floodgate, ViaVersion, DuneCore, DuneTerrain] +prefix: DuneRealms Essentials +description: DuneRealms Essentials - Dune Solaris economy, Vault provider, spice sales, and Arrakis travel commands: exchange: description: CHOAM interplanetary player marketplace @@ -14,6 +15,38 @@ commands: description: Solaris, travel, and Arrakis administration usage: /duneess help aliases: [dess] + essentials: + description: Open DuneRealms Essentials + permission: duneess.basics + home: + description: Teleport to a saved home + permission: duneess.basics + sethome: + description: Save a named home + permission: duneess.basics + delhome: + description: Remove a named home + permission: duneess.basics + homes: + description: Choose a saved home + permission: duneess.basics + tpa: + description: Request player teleportation + permission: duneess.basics + tpaccept: + description: Accept a teleport request + permission: duneess.basics + tpdeny: + description: Decline a teleport request + permission: duneess.basics + spawn: + description: Return to world spawn + permission: duneess.basics + server: + description: Open Guild server travel + permission: duneess.basics permissions: + duneess.basics: + default: true dune.admin: default: op diff --git a/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java b/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java new file mode 100644 index 00000000..b6b60cad --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/EssentialsBasicsTest.java @@ -0,0 +1,55 @@ +package com.example.duneess; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class EssentialsBasicsTest { + @Test void normalizesNamesAndHasAStableDefault() { + assertEquals("home",EssentialsBasics.homeName(new String[]{})); + assertEquals("sietch_2",EssentialsBasics.homeName(new String[]{"Sietch_2"})); + } + @Test void rejectsYamlPathsAndInvalidArguments() { + for(String name:new String[]{"../other","player.home","","a b","x".repeat(25)}) + assertThrows(IllegalArgumentException.class,()->EssentialsBasics.homeName(new String[]{name})); + assertThrows(IllegalArgumentException.class,()->EssentialsBasics.homeName(new String[]{"one","two"})); + } + + @org.junit.jupiter.api.io.TempDir java.nio.file.Path directory; + @Test void teleportRequestsRequireConsentAndCannotBeAcceptedTwice() { + DuneEss plugin=org.mockito.Mockito.mock(DuneEss.class); + org.mockito.Mockito.when(plugin.getDataFolder()).thenReturn(directory.toFile()); + EssentialsBasics basics=new EssentialsBasics(plugin); + var source=org.mockito.Mockito.mock(org.bukkit.entity.Player.class); + var target=org.mockito.Mockito.mock(org.bukkit.entity.Player.class); + var world=org.mockito.Mockito.mock(org.bukkit.World.class); + var border=org.mockito.Mockito.mock(org.bukkit.WorldBorder.class); + var request=org.mockito.Mockito.mock(org.bukkit.command.Command.class); + var accept=org.mockito.Mockito.mock(org.bukkit.command.Command.class); + java.util.UUID senderId=java.util.UUID.randomUUID(), targetId=java.util.UUID.randomUUID(); + org.mockito.Mockito.when(source.getUniqueId()).thenReturn(senderId); + org.mockito.Mockito.when(target.getUniqueId()).thenReturn(targetId); + org.mockito.Mockito.when(source.getName()).thenReturn("Sender"); + org.mockito.Mockito.when(source.hasPermission("duneess.basics")).thenReturn(true); + org.mockito.Mockito.when(target.hasPermission("duneess.basics")).thenReturn(true); + org.mockito.Mockito.when(source.canSee(target)).thenReturn(true); + org.mockito.Mockito.when(source.getWorld()).thenReturn(world); + org.mockito.Mockito.when(target.getWorld()).thenReturn(world); + org.mockito.Mockito.when(source.isOnline()).thenReturn(true); + org.mockito.Mockito.when(world.getWorldBorder()).thenReturn(border); + org.mockito.Mockito.when(border.isInside(org.mockito.ArgumentMatchers.any())).thenReturn(true); + org.mockito.Mockito.when(world.getMinHeight()).thenReturn(-64); + org.mockito.Mockito.when(world.getMaxHeight()).thenReturn(320); + var destination=new org.bukkit.Location(world,10,80,10); + org.mockito.Mockito.when(target.getLocation()).thenReturn(destination); + org.mockito.Mockito.when(source.teleportAsync(destination)).thenReturn(java.util.concurrent.CompletableFuture.completedFuture(true)); + org.mockito.Mockito.when(request.getName()).thenReturn("tpa"); + org.mockito.Mockito.when(accept.getName()).thenReturn("tpaccept"); + try(var bukkit=org.mockito.Mockito.mockStatic(org.bukkit.Bukkit.class)) { + bukkit.when(()->org.bukkit.Bukkit.getPlayerExact("Target")).thenReturn(target); + bukkit.when(()->org.bukkit.Bukkit.getPlayer(senderId)).thenReturn(source); + basics.onCommand(source,request,"tpa",new String[]{"Target"}); + org.mockito.Mockito.verify(source,org.mockito.Mockito.never()).teleportAsync(org.mockito.ArgumentMatchers.any(org.bukkit.Location.class)); + basics.onCommand(target,accept,"tpaccept",new String[]{}); + basics.onCommand(target,accept,"tpaccept",new String[]{}); + org.mockito.Mockito.verify(source,org.mockito.Mockito.times(1)).teleportAsync(destination); + } + } +} diff --git a/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java b/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java new file mode 100644 index 00000000..9948a5ac --- /dev/null +++ b/DuneEss/src/test/java/com/example/dunegui/MenuSessionTest.java @@ -0,0 +1,21 @@ +package com.example.dunegui; +import org.junit.jupiter.api.Test; +import java.util.UUID; +import static org.junit.jupiter.api.Assertions.*; +class MenuSessionTest { + @Test void rejectsAnotherPlayerWithoutConsumingTheOwnerAction() { + UUID owner=UUID.randomUUID(); MenuSession session=new MenuSession(owner); + assertFalse(session.claim(UUID.randomUUID())); assertTrue(session.claim(owner)); assertFalse(session.claim(owner)); + } + @Test void openingANewMenuInvalidatesThePreviousConfirmation() { + UUID owner=UUID.randomUUID(); MenuSession old=new MenuSession(owner), next=new MenuSession(owner); + assertFalse(old.claim(owner)); assertTrue(next.claim(owner)); + } + @Test void expiringOldMenuDoesNotInvalidateTheNewMenu() { + UUID owner=UUID.randomUUID(); MenuSession old=new MenuSession(owner), next=new MenuSession(owner); + old.expire(); assertTrue(next.claim(owner)); + } + @Test void expiredMenuCannotTrade() { + UUID owner=UUID.randomUUID(); MenuSession session=new MenuSession(owner); session.expire(); assertFalse(session.claim(owner)); + } +} diff --git a/DuneLobby/build.gradle.kts b/DuneLobby/build.gradle.kts index 587cf6f0..36881ee5 100644 --- a/DuneLobby/build.gradle.kts +++ b/DuneLobby/build.gradle.kts @@ -2,7 +2,13 @@ plugins { java } group = "com.example" version = "1.1.0" repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } -dependencies { compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") } +dependencies { compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") } java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.withType { options.encoding = "UTF-8" } tasks.processResources { from("artwork") { into("artwork") } } + +repositories { maven("https://repo.opencollab.dev/main/") } +dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") } +sourceSets.main { java.srcDir("../gui-common/src/main/java") } + +tasks.jar { archiveFileName.set("DuneRealms-Lobby.jar") } diff --git a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java index 97607ee7..27fc6fac 100644 --- a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java +++ b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java @@ -202,26 +202,28 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec for(int i=0;i=p[1]-9 && z<=p[1]-7) { departure(e.getPlayer(),LobbyBuilder.PLANETS.get(i)); return; } } if(b.getType()==Material.LECTERN) { boolean rules=z>0; List text=getConfig().getStringList(rules?"rules":"news"); - ItemStack book=new ItemStack(Material.WRITTEN_BOOK); BookMeta meta=(BookMeta)book.getItemMeta(); meta.setTitle(rules?"Guild Charter":"Guild News"); meta.setAuthor("Spacing Guild"); - meta.setPages(text.stream().map(line->ChatColor.DARK_GRAY+line).toList()); book.setItemMeta(meta); e.getPlayer().openBook(book); + com.example.dunegui.NativeMenus.show(this,e.getPlayer(),rules?"Guild Charter":"Guild News",String.join("\n\n",text),List.of( + new com.example.dunegui.NativeMenus.Choice("Close","",e.getPlayer()::closeInventory))); + } } private void departure(Player player,String planet) { TravelMenu menu=new TravelMenu(planet); ItemStack confirm=new ItemStack(Material.LIME_CONCRETE); ItemMeta meta=confirm.getItemMeta(); meta.setDisplayName("Confirm departure: "+planet); meta.setLore(List.of("DuneEss fares and access rules apply when installed.")); confirm.setItemMeta(meta); - menu.inventory.setItem(4,confirm); player.openInventory(menu.inventory); + menu.inventory.setItem(4,confirm); + com.example.dunegui.NativeMenus.show(this,player,"Guild departure",List.of( + new com.example.dunegui.NativeMenus.Choice("Confirm departure: "+planet,"DuneEss fares and access rules apply.",()->depart(player,planet)), + new com.example.dunegui.NativeMenus.Choice("Cancel","",player::closeInventory))); } - @EventHandler public void menu(InventoryClickEvent e) { - if(!(e.getView().getTopInventory().getHolder() instanceof TravelMenu menu)) return; - e.setCancelled(true); if(e.getRawSlot()!=4 || !(e.getWhoClicked() instanceof Player player)) return; + private void depart(Player player,String planet) { long now=System.currentTimeMillis(); if(now-travelCooldown.getOrDefault(player.getUniqueId(),0L)<5000) return; travelCooldown.put(player.getUniqueId(),now); Bukkit.getScheduler().runTask(this,()-> { player.closeInventory(); - if(Bukkit.getPluginCommand("duneess")!=null) { player.performCommand("duneess travel "+menu.planet); return; } - World target=Bukkit.getWorld(menu.planet); + if(Bukkit.getPluginCommand("duneess")!=null) { player.performCommand("duneess travel "+planet); return; } + World target=Bukkit.getWorld(planet); if(target!=null) { player.teleport(target.getSpawnLocation()); return; } - String server=getConfig().getString("servers."+menu.planet,""); + String server=getConfig().getString("servers."+planet,""); if(server.isBlank()) { player.sendMessage("No destination configured."); return; } try { ByteArrayOutputStream bytes=new ByteArrayOutputStream(); DataOutputStream out=new DataOutputStream(bytes); out.writeUTF("Connect"); out.writeUTF(server); diff --git a/DuneLobby/src/main/resources/plugin.yml b/DuneLobby/src/main/resources/plugin.yml index 963cbea1..af8be68e 100644 --- a/DuneLobby/src/main/resources/plugin.yml +++ b/DuneLobby/src/main/resources/plugin.yml @@ -1,9 +1,9 @@ name: DuneLobby version: 1.1.0 main: com.example.dunelobby.DuneLobby -api-version: '1.21' +api-version: '1.21.8' load: POSTWORLD -softdepend: [ImageFrame, DuneEss, DuneCore] +softdepend: [floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore] commands: lobby: description: Return to the Spacing Guild lobby diff --git a/DuneNPC/build.gradle.kts b/DuneNPC/build.gradle.kts index 9e0ab353..84c4049a 100644 --- a/DuneNPC/build.gradle.kts +++ b/DuneNPC/build.gradle.kts @@ -8,10 +8,10 @@ repositories { } dependencies { compileOnly(project(":DuneCore")) - compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") compileOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } testImplementation(project(":DuneCore")) - testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.mockito:mockito-core:5.15.2") testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } @@ -20,3 +20,10 @@ dependencies { java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.withType { options.encoding = "UTF-8" } tasks.test { useJUnitPlatform() } + +tasks.jar { archiveFileName.set("DuneRealms-NPC.jar") } + +// Explicit test instrumentation works on Java 21 without dynamic self-attachment. +val mockitoAgent by configurations.creating +dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } +tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } diff --git a/DuneRealms-minecraft-only/build.gradle.kts b/DuneRealms-minecraft-only/build.gradle.kts index 11434392..aeb54918 100644 --- a/DuneRealms-minecraft-only/build.gradle.kts +++ b/DuneRealms-minecraft-only/build.gradle.kts @@ -1,14 +1,14 @@ plugins { java } group = "com.example" -version = "1.0.10" +version = "1.0.11" repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://jitpack.io") } dependencies { - compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") compileOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } implementation("org.postgresql:postgresql:42.7.4") - testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.mockito:mockito-core:5.15.2") testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } @@ -22,3 +22,14 @@ tasks.jar { java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.withType { options.encoding = "UTF-8" } tasks.test { useJUnitPlatform() } + +repositories { maven("https://repo.opencollab.dev/main/") } +dependencies { compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") } +sourceSets.main { java.srcDir("../gui-common/src/main/java") } + +tasks.jar { archiveFileName.set("DuneRealms-Core.jar") } + +// Explicit test instrumentation works on Java 21 without dynamic self-attachment. +val mockitoAgent by configurations.creating +dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } +tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java index 887052e1..754c6054 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java @@ -100,7 +100,9 @@ final class ConfigurableGui { } opened.put(p.getUniqueId(),page); actions.put(p.getUniqueId(),slots); - p.openInventory(inv); + Map nativeActions=new HashMap<>(); + slots.forEach((slot,action)->nativeActions.put(slot,()->execute(p,action))); + com.example.dunegui.NativeMenus.inventory(plugin,p,title,inv,nativeActions); } void click(InventoryClickEvent e) { if(!(e.getWhoClicked() instanceof Player p)) return; diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java index dfd4567e..14b92854 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java @@ -307,14 +307,18 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu armorMeta.setTrim(new ArmorTrim(material, pattern)); } private void kit(Player p) { - String faction = selected.getOrDefault(p.getUniqueId(), "Fremen"); + for (ItemStack item : createFactionKit(selected.getOrDefault(p.getUniqueId(), "Fremen"))) p.getInventory().addItem(item); + } + /** Shared authoritative kit factory for player rewards and fortress loot. */ + public List createFactionKit(String faction) { + List items = new ArrayList<>(); Color armorColor = factionArmorColor(faction); ItemStack shovel=custom(Material.NETHERITE_SHOVEL,"Spice Harvest Shovel","shovel"); shovel.addUnsafeEnchantment(Enchantment.EFFICIENCY,5); shovel.addUnsafeEnchantment(Enchantment.UNBREAKING,3); - p.getInventory().addItem(shovel); + items.add(shovel); if (faction.equalsIgnoreCase("Ordos")) - p.getInventory().addItem(custom(Material.WIND_CHARGE,"Ordos Implosion Charge","ordos_wind_charge")); + items.add(custom(Material.WIND_CHARGE,"Ordos Implosion Charge","ordos_wind_charge")); for (Material m : new Material[]{Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS}) { ItemStack armor = custom(m, "Stillsuit " + m.name().toLowerCase(Locale.ROOT), "stillsuit"); org.bukkit.inventory.meta.LeatherArmorMeta meta = (org.bukkit.inventory.meta.LeatherArmorMeta) armor.getItemMeta(); @@ -329,8 +333,9 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu } if(faction.equalsIgnoreCase("Corrino"))meta.addEnchant(Enchantment.PROTECTION,3,true); armor.setItemMeta(meta); - p.getInventory().addItem(armor); + items.add(armor); } + return items; } private String fullSetFaction(Player player) { String faction=selected.getOrDefault(player.getUniqueId(),"").toLowerCase(Locale.ROOT); diff --git a/DuneRealms-minecraft-only/src/main/resources/plugin.yml b/DuneRealms-minecraft-only/src/main/resources/plugin.yml index 5fc4657a..597aa05b 100644 --- a/DuneRealms-minecraft-only/src/main/resources/plugin.yml +++ b/DuneRealms-minecraft-only/src/main/resources/plugin.yml @@ -1,9 +1,9 @@ name: DuneCore -version: 1.0.10 +version: 1.0.11 main: com.example.dunerealms.DuneCore -api-version: '1.21' +api-version: '1.21.8' depend: [Vault, DuneEss] -softdepend: [DuneTerrain, DiscordSRV] +softdepend: [floodgate, ViaVersion, DuneTerrain, DiscordSRV] description: Dune factions, Arrakis gameplay, politics, and server mechanics commands: dune: diff --git a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SandwormMobsTest.java b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SandwormMobsTest.java index 4494be3a..afac9f5b 100644 --- a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SandwormMobsTest.java +++ b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SandwormMobsTest.java @@ -32,6 +32,7 @@ class SandwormMobsTest { @Test void snifferBodyLinksToHuskBrainAndOnlyBodyDeathRemovesPartner() { DuneCore plugin = mock(DuneCore.class); when(plugin.getName()).thenReturn("DuneCore"); + when(plugin.namespace()).thenReturn("dunecore"); // Paper 1.21.8 NamespacedKey uses Plugin.namespace(). when(plugin.getConfig()).thenReturn(new YamlConfiguration()); World world = mock(World.class); when(world.getName()).thenReturn("arrakis"); Location location = new Location(world, 12, 75, 34); diff --git a/DuneTerrain/README.md b/DuneTerrain/README.md index 529bc2df..3c38ea17 100644 --- a/DuneTerrain/README.md +++ b/DuneTerrain/README.md @@ -1,24 +1,26 @@ -# DuneTerrain for Paper 1.21.4 +# DuneTerrain for Paper 1.21.8 -DuneTerrain is a standalone Paper plugin that generates one Dune planet world per server. It includes the five planet profiles, terrain and ore generation, Arrakis spice deposits and sietches, safe world spawn setup, and a protected Spacing Guild navigator. +DuneRealms terrain runs on Java 21. Build with `gradle build`; install `build/libs/DuneRealms-Terrain.jar`. Keep the existing plugin name/data directory `DuneTerrain`. Existing worlds, player data and configuration files are preserved; new terrain applies only to new chunks. Do not delete or regenerate an existing world to install this update. -New darkstone formations are approximately 100 blocks across (45-55-block radii), with up to three flat plateaus and at most five blocks between levels. Upgrading automatically replaces the old 10/18 default radii in an existing config, while preserving customized sizes. Existing generated chunks are unchanged. With DuneCore installed, loaded spice blooms announce coordinates on Arrakis and start a fifteen-minute countdown to a network-wide Spacing Guild announcement. See [Session 2](../SESSION-2.md). +## Arrakis update -## Build and install +- **Dune-highlands** (`dunerealms:dune-highlands`): irregular, terrain-aligned darkstone mountain regions, roughly 100 blocks across, with three sand terraces. Default terrace rise is four blocks (hard maximum five). Mountain sides rise 32 blocks before the terraces; narrow erosion ridges and jagged darkstone spires add up to 40 blocks on the outer shoulders, leaving the three upper flat terraces intact. Three additional broad sand ledges near the foot of the mountain also have four-block default steps; a steep rocky shoulder separates the lower and upper terrace groups. Centres have a 300–500-block gap to their north, south, east and west neighbours. These replace the old circular plateau formations. +- **Dense Spice** (`dunerealms:dense-spice`): one 30 × 30 rich patch per 512-block placement region, with seed-dependent positions. This is configurable village-like density, not vanilla village placement. Deep orange terracotta represents finite rich spice sand. Each authentic deposit yields four existing tagged Melange Spice items by default. Silk Touch and Fortune cannot clone or multiply it; creative mining consumes the deposit without a reward. A chunk Persistent Data Container stores each deposit's position and removes it on harvest. Ordinary orange terracotta has no spice value. Pistons and explosions cannot move or duplicate registered deposits. Ledger state persists in normal chunk saves across restarts; restoring a world backup restores its historical deposits too. +- A persistent spice seller appears in the centre of each new rich field. Right-click opens the shared native menu and offers 16 tagged spice at **standard DuneEss price × 1.35**. At 15 Solaris each, 16 cost 324 Solaris. Existing spice sales, taxes and CHOAM trading remain unchanged. Confirming purchases checks distance, inventory capacity and successful economy withdrawal. +- **Desert villages**: custom four-house sandstone settlements, with cut-sandstone lanes, villagers, beds, non-farming workstations, lanterns and finite shared supply chests. No farmland, crops or hay bales enter the structure palette. Chests use `dunerealms:chests/desert-village`: bread, dried kelp, apples and raw iron. Placement regions default to 768 blocks, with terrain suitability checks. +- **Old Harkonnen Fortress**: a custom jungle-temple-style Arrakis adaptation with sandstone walls, darkstone pillars, a stepped roof, red banner, stair and underground loot vault. It is a custom layout, not a replacement of Minecraft's built-in jungle temple structure definition. The default attempt rate is one per 1,000 Arrakis chunks, matching the Java desert-well-style chance; uneven terrain can reject an attempt. Its finite chest uses `dunerealms:chests/old-harkonnen-fortress`. When loot is generated, DuneTerrain appends a complete Harkonnen kit from the updated DuneCore kit factory: red faction stillsuit, native equipment attributes and trim, and the enchanted spice shovel. Food and raw iron also come from the loot table. Install updated Core and Terrain together; without the updated Core API, fortress rewards fall back to basic sword/food rather than fabricated faction equipment. -Build the plugin from this directory with Java 21 and Gradle 8.14 or newer: +Dune-highlands receive three naturally generated compact cave sietches per region by default (three times the one-site regional baseline, with a minimum of three). Each has a cave mouth, sleeping and kitchen chambers, a reservoir, and an independent personal supply cache using the existing loot/claim rules. The existing 2,000-block open-desert sietch placement algorithm and large cave template are unchanged. Configure only the new `sietches.highlands` section to tune or disable highland sites; `sietches.spacing` still controls the original desert grid. These extra caves apply only to new chunks; previously generated highlands are not retrofitted. -```sh -gradle clean build -``` +Oasis trees, personal cave sietch supplies, regular suspicious-sand spice deposits and magma-marked spice blows remain enabled. Custom structures are generated only on the Arrakis world. -Copy `build/libs/DuneTerrain-1.0.6.jar` into the Paper server's `plugins/` directory. Set `server.planet` in `plugins/DuneTerrain/config.yml` separately on each backend, then restart. +## Server datapack installation -Valid values are `arrakis`, `giedi_prime`, `kaitain`, `caladan`, and `sigma_draconis_iv`. All five planet profiles are present in each server's config; change `server.planet` to select the world that backend creates. The generated world is named after the selected planet. Adjust its `planets.` settings for terrain, biome, surface, water, vegetation, ores, and spawn coordinates. +`gradle build` also creates `build/distributions/DuneRealms-Dune-Highlands-Datapack.zip`, containing both custom biomes and the structure loot tables. While the server is stopped, copy this ZIP into the **primary world's** `datapacks/` directory (the world selected by `level-name` in `server.properties`), then restart before exploring new terrain. For a primary world named `world`, use `world/datapacks/`; for primary Arrakis, use `arrakis/datapacks/`. Do not replace `level.dat`, world folders or plugin data. Keep the datapack installed after generating custom-biome chunks. It uses Minecraft 1.21.8 data pack format 81. -Install DuneCore alongside DuneTerrain if you want the Guild navigator to open DuneCore's travel menu. DuneCore reads the loaded planet world to identify its local backend. For proxy travel, set `network.local-planet` and `network.servers` in DuneCore's config to match the DuneTerrain selection and proxy server names. +The pack is server-side: no client mods or mandatory resource packs. Without it, the plugin safely uses Desert biome metadata and direct fallback chest supplies; terrain geometry still works. Custom-biome climate and tint translation through Geyser must be checked on a live Java/Bedrock staging network; no live client compatibility is claimed by unit tests. -Paper's `paper-global.yml` and `paper-world-defaults.yml` do not choose terrain generators; Paper reads those for server and world behavior settings. Terrain generators are registered through `bukkit.yml`. DuneTerrain loads at startup and exposes its generator to Paper. If Arrakis is the primary world (`level-name=arrakis`), add this to `bukkit.yml`: +For Arrakis as the primary world, use: ```yaml worlds: @@ -27,15 +29,14 @@ worlds: biome-provider: DuneTerrain:arrakis ``` -For another primary planet, replace both `arrakis` values with that planet name. When using DuneTerrain's separate planet world alongside a normal primary world named `world`, the plugin assigns the generator directly as it creates the planet world; no `bukkit.yml` entry is needed. +Set `server.planet` in `plugins/DuneTerrain/config.yml` to `arrakis`, `giedi_prime`, `kaitain`, `caladan` or `sigma_draconis_iv`. Public Velocity server names may use hyphens; these internal planet IDs keep underscores. A separate planet world created by the plugin gets its generator and biome provider directly. -The generator applies to newly generated chunks. Existing chunks are never replaced by a config change. If the selected planet world already exists with non-Arrakis terrain or rivers, stop the server, back up and move that world's folder out of the server directory, then restart to create it with DuneTerrain. DuneTerrain registers the generator at startup and creates a separate planet world only after Paper has finished loading, if needed. +Existing configurations receive the new features through code defaults. Old radius defaults 10/18 automatically upgrade to 45/55; customized radii are retained. `planets.arrakis.highlands` now controls formation enablement, density and mountain rise. The old `darkstone-islands` radius and terrace settings remain compatible, but its old `spacing` and `enabled` values no longer control highlands. Use `highlands.enabled` to disable the replacement. New density options are `dense-spice.spacing`, `desert-villages.spacing` and `harkonnen-fortress.rarity`. -Arrakis uses the Desert biome throughout and has no vanilla vegetation. Sparse persistent-leaf oasis trees remain about 300 blocks apart. A larger underground cave sietch generates about every 2,000 blocks; it has a broad stone-arched cave entrance, connected sleeping and kitchen chambers, a gently winding descent to a larger bottom reservoir with a waterfall, and a personal cache per player containing at least 250 tagged spice, enchanted gold armor, planks, and bread. Raised darkstone islands generate about every 750 blocks, with broad flat sand plateaus and steep, exposed blackstone and basalt sides. Spice blows also generate about every 2,000 blocks as a magma cluster; touching one with a living entity or hitting it with an arrow or trident releases a rich suspicious-sand field worth about 15,000 Solaris at the default 15 Solaris per spice. Admins can use `/dune admin spiceblow [player]` to teleport to the nearest generated or erupted spice blow. Set `sietches.spacing`, `spice-blow.spacing`, and `planets.arrakis.darkstone-islands.spacing` to adjust structure intervals. Random spice patches generate about 35% of 600-by-600-block regions; each patch has roughly 5,000 Solaris in deposits at the default price. Adjust `spice-deposits.patches` for patch frequency, size, or value. +DuneNPC continues to own Guild Navigators. Install updated DuneCore and DuneEss alongside Terrain for authentic fortress kits and native spice-seller purchases. -DuneCore sends new players who have not chosen a faction from Paper's default `world` to the local planet spawn, so they arrive in the world generated by DuneTerrain. +## Validation limits -As of DuneTerrain 1.0.7, Guild Navigator NPC creation is handled exclusively by DuneNPC. -Install DuneNPC with DuneCore for automatic Navigators and their travel menus. Existing tagged -Navigators are reused. `guild-npc.enabled` now belongs in `plugins/DuneNPC/config.yml`; its legacy -DuneTerrain value is imported when DuneNPC is first configured. +Gradle tests cover irregular terrain contours, terrace steps, cardinal spacing, biome footprint alignment, 30 × 30 patch bounds, seeded rarity and deposit identity persistence/consumption. A reflection probe invokes the actual compiled terrain code to render a development preview. Compilation and mocks do not validate server startup, generated-world registry persistence, chunk event timing, structure physics or real Java/Bedrock/ViaVersion clients. Exercise these on a separate staging world before production. No existing user world was opened or changed during development. + +[Actual generator render](previews/dune-highlands.png) · [Validation](../docs/Arrakis-Update-Validation.md) diff --git a/DuneTerrain/build.gradle.kts b/DuneTerrain/build.gradle.kts index 01f7cfb7..e535abb0 100644 --- a/DuneTerrain/build.gradle.kts +++ b/DuneTerrain/build.gradle.kts @@ -1,7 +1,7 @@ plugins { java } group = "com.example" -version = "1.0.7" +version = "1.0.9" repositories { mavenCentral() @@ -9,7 +9,9 @@ repositories { } dependencies { - compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.mockito:mockito-core:5.15.2") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testRuntimeOnly("org.junit.platform:junit-platform-launcher") } @@ -18,3 +20,16 @@ java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.jar { archiveBaseName.set("DuneTerrain") } tasks.withType { options.encoding = "UTF-8" } tasks.test { useJUnitPlatform() } + +tasks.jar { archiveFileName.set("DuneRealms-Terrain.jar") } + +val highlandsDatapack by tasks.registering(Zip::class) { + from("highlands-datapack") + archiveFileName.set("DuneRealms-Dune-Highlands-Datapack.zip") + destinationDirectory.set(layout.buildDirectory.dir("distributions")) +} +tasks.assemble { dependsOn(highlandsDatapack) } + +val mockitoAgent by configurations.creating +dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } +tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } diff --git a/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/desert-village.json b/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/desert-village.json new file mode 100644 index 00000000..4e66078e --- /dev/null +++ b/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/desert-village.json @@ -0,0 +1,81 @@ +{ + "type": "minecraft:chest", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:bread", + "functions": [ + { + "function": "minecraft:set_count", + "count": { + "type": "minecraft:uniform", + "min": 3, + "max": 7 + } + } + ] + } + ] + }, + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:dried_kelp", + "functions": [ + { + "function": "minecraft:set_count", + "count": { + "type": "minecraft:uniform", + "min": 4, + "max": 10 + } + } + ] + } + ] + }, + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:apple", + "functions": [ + { + "function": "minecraft:set_count", + "count": { + "type": "minecraft:uniform", + "min": 1, + "max": 3 + } + } + ] + } + ] + }, + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:raw_iron", + "functions": [ + { + "function": "minecraft:set_count", + "count": { + "type": "minecraft:uniform", + "min": 2, + "max": 5 + } + } + ] + } + ] + } + ] +} diff --git a/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/old-harkonnen-fortress.json b/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/old-harkonnen-fortress.json new file mode 100644 index 00000000..8a2df5f9 --- /dev/null +++ b/DuneTerrain/highlands-datapack/data/dunerealms/loot_table/chests/old-harkonnen-fortress.json @@ -0,0 +1,35 @@ +{ + "type": "minecraft:chest", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:bread", + "functions": [ + { + "function": "minecraft:set_count", + "count": 8 + } + ] + } + ] + }, + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:raw_iron", + "functions": [ + { + "function": "minecraft:set_count", + "count": 4 + } + ] + } + ] + } + ] +} diff --git a/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dense-spice.json b/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dense-spice.json new file mode 100644 index 00000000..e2b4e57e --- /dev/null +++ b/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dense-spice.json @@ -0,0 +1,138 @@ +{ + "carvers": [], + "downfall": 0.0, + "effects": { + "fog_color": 12544809, + "mood_sound": { + "block_search_extent": 8, + "offset": 2.0, + "sound": "minecraft:ambient.cave", + "tick_delay": 6000 + }, + "music": [ + { + "data": { + "max_delay": 24000, + "min_delay": 12000, + "replace_current_music": false, + "sound": "minecraft:music.overworld.desert" + }, + "weight": 1 + } + ], + "music_volume": 1.0, + "sky_color": 14130515, + "water_color": 4159204, + "water_fog_color": 329011, + "grass_color": 11115357, + "foliage_color": 8293706 + }, + "features": [ + [], + [], + [], + [], + [], + [], + [], + [], + [], + [], + [] + ], + "has_precipitation": false, + "spawn_costs": {}, + "spawners": { + "ambient": [ + { + "type": "minecraft:bat", + "maxCount": 8, + "minCount": 8, + "weight": 10 + } + ], + "axolotls": [], + "creature": [ + { + "type": "minecraft:rabbit", + "maxCount": 3, + "minCount": 2, + "weight": 12 + }, + { + "type": "minecraft:camel", + "maxCount": 1, + "minCount": 1, + "weight": 1 + } + ], + "misc": [], + "monster": [ + { + "type": "minecraft:spider", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:zombie", + "maxCount": 4, + "minCount": 4, + "weight": 19 + }, + { + "type": "minecraft:zombie_villager", + "maxCount": 1, + "minCount": 1, + "weight": 1 + }, + { + "type": "minecraft:skeleton", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:creeper", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:slime", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:enderman", + "maxCount": 4, + "minCount": 1, + "weight": 10 + }, + { + "type": "minecraft:witch", + "maxCount": 1, + "minCount": 1, + "weight": 5 + }, + { + "type": "minecraft:husk", + "maxCount": 4, + "minCount": 4, + "weight": 80 + } + ], + "underground_water_creature": [ + { + "type": "minecraft:glow_squid", + "maxCount": 6, + "minCount": 4, + "weight": 10 + } + ], + "water_ambient": [], + "water_creature": [] + }, + "temperature": 2.0 +} diff --git a/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dune-highlands.json b/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dune-highlands.json new file mode 100644 index 00000000..06da5317 --- /dev/null +++ b/DuneTerrain/highlands-datapack/data/dunerealms/worldgen/biome/dune-highlands.json @@ -0,0 +1,138 @@ +{ + "carvers": [], + "downfall": 0.0, + "effects": { + "fog_color": 13020027, + "mood_sound": { + "block_search_extent": 8, + "offset": 2.0, + "sound": "minecraft:ambient.cave", + "tick_delay": 6000 + }, + "music": [ + { + "data": { + "max_delay": 24000, + "min_delay": 12000, + "replace_current_music": false, + "sound": "minecraft:music.overworld.desert" + }, + "weight": 1 + } + ], + "music_volume": 1.0, + "sky_color": 14136685, + "water_color": 4159204, + "water_fog_color": 329011, + "grass_color": 11115357, + "foliage_color": 8293706 + }, + "features": [ + [], + [], + [], + [], + [], + [], + [], + [], + [], + [], + [] + ], + "has_precipitation": false, + "spawn_costs": {}, + "spawners": { + "ambient": [ + { + "type": "minecraft:bat", + "maxCount": 8, + "minCount": 8, + "weight": 10 + } + ], + "axolotls": [], + "creature": [ + { + "type": "minecraft:rabbit", + "maxCount": 3, + "minCount": 2, + "weight": 12 + }, + { + "type": "minecraft:camel", + "maxCount": 1, + "minCount": 1, + "weight": 1 + } + ], + "misc": [], + "monster": [ + { + "type": "minecraft:spider", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:zombie", + "maxCount": 4, + "minCount": 4, + "weight": 19 + }, + { + "type": "minecraft:zombie_villager", + "maxCount": 1, + "minCount": 1, + "weight": 1 + }, + { + "type": "minecraft:skeleton", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:creeper", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:slime", + "maxCount": 4, + "minCount": 4, + "weight": 100 + }, + { + "type": "minecraft:enderman", + "maxCount": 4, + "minCount": 1, + "weight": 10 + }, + { + "type": "minecraft:witch", + "maxCount": 1, + "minCount": 1, + "weight": 5 + }, + { + "type": "minecraft:husk", + "maxCount": 4, + "minCount": 4, + "weight": 80 + } + ], + "underground_water_creature": [ + { + "type": "minecraft:glow_squid", + "maxCount": 6, + "minCount": 4, + "weight": 10 + } + ], + "water_ambient": [], + "water_creature": [] + }, + "temperature": 2.0 +} diff --git a/DuneTerrain/highlands-datapack/data/minecraft/tags/worldgen/biome/is_overworld.json b/DuneTerrain/highlands-datapack/data/minecraft/tags/worldgen/biome/is_overworld.json new file mode 100644 index 00000000..b0fcfbb3 --- /dev/null +++ b/DuneTerrain/highlands-datapack/data/minecraft/tags/worldgen/biome/is_overworld.json @@ -0,0 +1,7 @@ +{ + "replace": false, + "values": [ + "dunerealms:dune-highlands", + "dunerealms:dense-spice" + ] +} diff --git a/DuneTerrain/highlands-datapack/pack.mcmeta b/DuneTerrain/highlands-datapack/pack.mcmeta new file mode 100644 index 00000000..c9bd004d --- /dev/null +++ b/DuneTerrain/highlands-datapack/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 81, + "description": "DuneRealms Arrakis biomes and structure loot (Minecraft 1.21.8)" + } +} diff --git a/DuneTerrain/previews/dune-highlands.png b/DuneTerrain/previews/dune-highlands.png new file mode 100644 index 00000000..7f2e0d80 Binary files /dev/null and b/DuneTerrain/previews/dune-highlands.png differ diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DenseSpice.java b/DuneTerrain/src/main/java/com/example/duneterrain/DenseSpice.java new file mode 100644 index 00000000..54db5869 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DenseSpice.java @@ -0,0 +1,68 @@ +package com.example.duneterrain; + +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.Villager; +import org.bukkit.event.*; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.persistence.PersistentDataType; +import java.util.*; + +/** Rich deposits are authenticated by a persistent chunk ledger, never by material alone. */ +final class DenseSpice implements Listener { + private final DuneTerrain plugin; + private final NamespacedKey ledger = new NamespacedKey("dunerealms", "rich-spice-deposits"); + DenseSpice(DuneTerrain plugin) { this.plugin=plugin; } + static long mix(long n) { n=(n^(n>>>30))*0xbf58476d1ce4e5b9L; n=(n^(n>>>27))*0x94d049bb133111ebL; return n^(n>>>31); } + // One 30 x 30 patch per 32-chunk region: configurable village-like spacing, no vanilla structure dependency. + static int[] anchor(long seed, int x, int z, int spacing) { + int cx=Math.floorDiv(x,spacing), cz=Math.floorDiv(z,spacing); + long hash=mix(seed^cx*0x9e3779b97f4a7c15L^cz*0xc2b2ae3d27d4eb4fL^0x44454e5345535049L); + return new int[]{cx*spacing+16+(int)Math.floorMod(hash,spacing-62),cz*spacing+16+(int)Math.floorMod(mix(hash),spacing-62)}; + } + static boolean contains(long seed,int x,int z,int spacing) { + int[] a=anchor(seed,x,z,spacing); return x>=a[0]&&x=a[1]&&zv==key); } + private void consume(Block b) { int key=encode(b); b.getChunk().getPersistentDataContainer().set(ledger,PersistentDataType.INTEGER_ARRAY,Arrays.stream(entries(b.getChunk())).filter(v->v!=key).toArray()); } + @EventHandler(priority=EventPriority.LOWEST) public void initialize(ChunkLoadEvent e) { + if(!e.isNewChunk()||!e.getWorld().getName().equalsIgnoreCase("arrakis"))return; + Chunk c=e.getChunk(); List deposits=new ArrayList<>(); + for(int x=0;x<16;x++)for(int z=0;z<16;z++) { + Block b=e.getWorld().getHighestBlockAt(c.getX()*16+x,c.getZ()*16+z); + if(b.getType()==Material.ORANGE_TERRACOTTA)deposits.add(encode(b)); + } + c.getPersistentDataContainer().set(ledger,PersistentDataType.INTEGER_ARRAY,deposits.stream().mapToInt(Integer::intValue).toArray()); + if(deposits.isEmpty())return; + int spacing=Math.max(128,plugin.getConfig().getInt("dense-spice.spacing",512)); + int[] a=anchor(e.getWorld().getSeed(),c.getX()*16+8,c.getZ()*16+8,spacing); + if(Math.floorDiv(a[0]+15,16)!=c.getX()||Math.floorDiv(a[1]+15,16)!=c.getZ())return; + Bukkit.getScheduler().runTask(plugin,()->{ + if(!c.isLoaded())return; + Location loc=e.getWorld().getHighestBlockAt(a[0]+15,a[1]+15).getLocation().add(.5,1,.5); + Villager seller=e.getWorld().spawn(loc,Villager.class,v->{ + v.setCustomName(ChatColor.GOLD+"Spice Seller · +35%");v.setCustomNameVisible(true); + v.setAI(false);v.setInvulnerable(true);v.setPersistent(true);v.setRemoveWhenFarAway(false); + v.getPersistentDataContainer().set(new NamespacedKey("dunerealms","spice-seller"),PersistentDataType.BYTE,(byte)1); + }); + }); + } + @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void harvest(BlockBreakEvent e) { + Block b=e.getBlock(); if(!marked(b))return; + e.setDropItems(false);e.setExpToDrop(0); + } + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void reward(BlockBreakEvent e) { + Block b=e.getBlock();if(!marked(b))return;consume(b); + if(b.getType()==Material.ORANGE_TERRACOTTA && e.getPlayer().getGameMode()!=GameMode.CREATIVE) + b.getWorld().dropItemNaturally(b.getLocation(),DuneTerrain.spiceItem(Math.max(1,Math.min(64,plugin.getConfig().getInt("dense-spice.yield",4))))); + } + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void place(BlockPlaceEvent e) { if(marked(e.getBlock()))consume(e.getBlock()); } + @EventHandler(ignoreCancelled=true) public void push(BlockPistonExtendEvent e) { if(e.getBlocks().stream().anyMatch(this::marked))e.setCancelled(true); } + @EventHandler(ignoreCancelled=true) public void pull(BlockPistonRetractEvent e) { if(e.getBlocks().stream().anyMatch(this::marked))e.setCancelled(true); } + @EventHandler(ignoreCancelled=true) public void explode(EntityExplodeEvent e) { e.blockList().removeIf(this::marked); } + @EventHandler(ignoreCancelled=true) public void explode(BlockExplodeEvent e) { e.blockList().removeIf(this::marked); } +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DesertVillages.java b/DuneTerrain/src/main/java/com/example/duneterrain/DesertVillages.java new file mode 100644 index 00000000..d4f19c98 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DesertVillages.java @@ -0,0 +1,60 @@ +package com.example.duneterrain; + +import org.bukkit.*; +import org.bukkit.block.Chest; +import org.bukkit.entity.EntityType; +import org.bukkit.generator.*; +import java.util.*; + +/** Compact custom sandstone villages: no farm pieces or hay ever enter the palette. */ +final class DesertVillages extends BlockPopulator { + private final DuneTerrain plugin; + DesertVillages(DuneTerrain plugin) { this.plugin=plugin; } + @Override public void populate(WorldInfo world,Random random,int cx,int cz,LimitedRegion r) { + if(!world.getName().equalsIgnoreCase("arrakis")||!plugin.getConfig().getBoolean("desert-villages.enabled",true))return; + int spacing=Math.max(192,plugin.getConfig().getInt("desert-villages.spacing",768)); + // A complete village fits inside one chunk's population buffer. Only the anchor chunk builds it. + int[] a=DenseSpice.anchor(world.getSeed()^0x56494c4c414745L,cx*16+8,cz*16+8,spacing); + int x=a[0]+15,z=a[1]+15; + if(Math.floorDiv(x,16)!=cx||Math.floorDiv(z,16)!=cz)return; + for(int dx=-16;dx<=16;dx+=8)for(int dz=-16;dz<=16;dz+=8) + if(!r.isInRegion(x+dx,world.getMinHeight()+1,z+dz))return; + int y=r.getHighestBlockYAt(x,z); + if(y+7>=world.getMaxHeight())return; + // Avoid mountains and existing rich fields rather than bulldozing their terrain. + for(int dx=-16;dx<=16;dx+=8)for(int dz=-16;dz<=16;dz+=8) + if(Math.abs(r.getHighestBlockYAt(x+dx,z+dz)-y)>8||r.getType(x+dx,r.getHighestBlockYAt(x+dx,z+dz),z+dz)==Material.ORANGE_TERRACOTTA)return; + for(int dx=-15;dx<=15;dx++)for(int dz=-15;dz<=15;dz++) { + int ground=r.getHighestBlockYAt(x+dx,z+dz); + for(int h=Math.min(ground,y);h<=y;h++)r.setType(x+dx,h,z+dz,Material.SANDSTONE); + for(int h=y+1;h<=Math.max(ground,y+6);h++)r.setType(x+dx,h,z+dz,Material.AIR); + r.setType(x+dx,y,z+dz,Math.abs(dx)<=2||Math.abs(dz)<=2?Material.CUT_SANDSTONE:Material.SAND); + } + for(int ox:new int[]{-12,6})for(int oz:new int[]{-12,6}) { + for(int dx=0;dx<7;dx++)for(int dz=0;dz<7;dz++)for(int dy=1;dy<=5;dy++) { + boolean wall=dx==0||dz==0||dx==6||dz==6; + r.setType(x+ox+dx,y+dy,z+oz+dz,dy==5?Material.SMOOTH_SANDSTONE:wall?Material.SANDSTONE:Material.AIR); + } + r.setType(x+ox+3,y+1,z+oz,Material.AIR);r.setType(x+ox+3,y+2,z+oz,Material.AIR); + r.setType(x+ox+1,y+2,z+oz,Material.GLASS_PANE); + r.setType(x+ox+3,y+4,z+oz+3,Material.LANTERN); + // Beds and non-farming job sites make this a functioning village, not empty scenery. + var foot=(org.bukkit.block.data.type.Bed)Material.RED_BED.createBlockData(); + foot.setFacing(org.bukkit.block.BlockFace.SOUTH);foot.setPart(org.bukkit.block.data.type.Bed.Part.FOOT); + var head=(org.bukkit.block.data.type.Bed)foot.clone();head.setPart(org.bukkit.block.data.type.Bed.Part.HEAD); + r.setBlockData(x+ox+2,y+1,z+oz+3,foot);r.setBlockData(x+ox+2,y+1,z+oz+4,head); + r.setType(x+ox+1,y+1,z+oz+4,(ox<0?oz<0?Material.BARREL:Material.FLETCHING_TABLE:oz<0?Material.BLAST_FURNACE:Material.CARTOGRAPHY_TABLE)); + int bx=x+ox+4,bz=z+oz+4; + r.setType(bx,y+1,bz,Material.CHEST); + if(r.getBlockState(bx,y+1,bz) instanceof Chest chest) { + var table=Bukkit.getLootTable(new NamespacedKey("dunerealms","chests/desert-village")); + if(table!=null){chest.setLootTable(table);chest.setSeed(DenseSpice.mix(world.getSeed()^bx*31L^bz));} + else { // Safe stock when the optional biome/loot datapack has not yet been installed. + chest.getSnapshotInventory().addItem(new org.bukkit.inventory.ItemStack(Material.BREAD,4),new org.bukkit.inventory.ItemStack(Material.DRIED_KELP,6),new org.bukkit.inventory.ItemStack(Material.RAW_IRON,3)); + } + chest.update(true,false); + } + r.spawnEntity(new Location(null,x+ox+3.5,y+1,z+oz+3.5),EntityType.VILLAGER); + } + } +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java index bba921ed..05f920c8 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java @@ -219,7 +219,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener { } } - private static ItemStack spiceItem(int amount) { + static ItemStack spiceItem(int amount) { ItemStack item = new ItemStack(Material.ORANGE_DYE, amount); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(ChatColor.GOLD + "Melange Spice"); @@ -276,6 +276,8 @@ public final class DuneTerrain extends JavaPlugin implements Listener { getLogger().info("Upgraded default Arrakis rock formations to about 100 blocks across in new chunks."); } getServer().getPluginManager().registerEvents(this, this); + getServer().getPluginManager().registerEvents(new DenseSpice(this), this); + getServer().getPluginManager().registerEvents(new HarkonnenFortress(this), this); sietchLootIdKey = new NamespacedKey(this, "sietch-loot-id"); String planet = getConfig().getString("server.planet", "arrakis").toLowerCase(Locale.ROOT); @@ -348,10 +350,12 @@ public final class DuneTerrain extends JavaPlugin implements Listener { private static class PlanetChunkGenerator extends ChunkGenerator { private final DuneTerrain plugin; private final String planet; + private record GroundKey(RockPlateaus.Shape shape, int baseHeight, double variation) {} + private final java.util.concurrent.ConcurrentHashMap formationGround = new java.util.concurrent.ConcurrentHashMap<>(); PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; } @Override public List getDefaultPopulators(World world) { return planet.equals("arrakis") && world.getName().equalsIgnoreCase("arrakis") - ? List.of(new SietchPopulator(plugin), new SpiceBlowPopulator(plugin)) : List.of(); + ? List.of(new SietchPopulator(plugin), new SpiceBlowPopulator(plugin), new DesertVillages(plugin), new HarkonnenFortress(plugin)) : List.of(); } @Override public void generateNoise(WorldInfo world, Random random, int chunkX, int chunkZ, ChunkData data) { String path = "planets." + planet + "."; @@ -400,6 +404,12 @@ public final class DuneTerrain extends JavaPlugin implements Listener { placeDarkstoneIsland(data, chunkX, chunkZ, heights, minY, maxY); placeSpiceDeposits(data, heights, random, minY, maxY); placeRandomSpicePatch(data, chunkX, chunkZ, heights); + if (plugin.getConfig().getBoolean("dense-spice.enabled", true)) { + int spacing = Math.max(128, plugin.getConfig().getInt("dense-spice.spacing", 512)); + for (int x=0;x<16;x++) for(int z=0;z<16;z++) + if(DenseSpice.contains(world.getSeed(),chunkX*16+x,chunkZ*16+z,spacing)) + data.setBlock(x,heights[x][z],z,Material.ORANGE_TERRACOTTA); + } } placeOres(data, random, path, minY, maxY); } @@ -441,48 +451,50 @@ public final class DuneTerrain extends JavaPlugin implements Listener { } private void placeDarkstoneIsland(ChunkData data, int chunkX, int chunkZ, int[][] heights, int minY, int maxY) { String path = "planets.arrakis.darkstone-islands."; - if (!plugin.getConfig().getBoolean(path + "enabled", true)) return; - int spacing = Math.max(128, plugin.getConfig().getInt(path + "spacing", 750)); + if (!plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true)) return; + int minimumGap = Math.max(192, plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing", 300)); + int maximumGap = Math.max(minimumGap, plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing", 500)); + int spacing = (minimumGap + maximumGap) / 2; int minRadius = Math.max(6, plugin.getConfig().getInt(path + "min-radius", 45)); int maxRadius = Math.max(minRadius, plugin.getConfig().getInt(path + "max-radius", 55)); int maxRise = Math.max(1, plugin.getConfig().getInt(path + "max-height", 14)); + boolean highlands = plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true); + int mountainRise = highlands ? Math.max(0, Math.min(96, plugin.getConfig().getInt("planets.arrakis.highlands.mountain-rise", 32))) : 0; int baseHeight = plugin.getConfig().getInt("planets.arrakis.terrain.base-height", 70); double variation = plugin.getConfig().getDouble("planets.arrakis.terrain.height-variation", 11); double scale = Math.max(0.001, plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale", 0.02)); int worldMinX = chunkX * 16, worldMinZ = chunkZ * 16; - int firstCellX = Math.floorDiv(worldMinX - maxRadius - 3, spacing), lastCellX = Math.floorDiv(worldMinX + 15 + maxRadius + 3, spacing); - int firstCellZ = Math.floorDiv(worldMinZ - maxRadius - 3, spacing), lastCellZ = Math.floorDiv(worldMinZ + 15 + maxRadius + 3, spacing); - long salt = 0x4441524B49534C41L; + int reach = (int)Math.ceil(maxRadius * 2.0) + 3; + int firstCellX = Math.floorDiv(worldMinX - reach, spacing), lastCellX = Math.floorDiv(worldMinX + 15 + reach, spacing); + int firstCellZ = Math.floorDiv(worldMinZ - reach, spacing), lastCellZ = Math.floorDiv(worldMinZ + 15 + reach, spacing); for (int cellX = firstCellX; cellX <= lastCellX; cellX++) for (int cellZ = firstCellZ; cellZ <= lastCellZ; cellZ++) { - long seed = mix64((long) cellX * 0x9E3779B97F4A7C15L ^ (long) cellZ * 0xC2B2AE3D27D4EB4FL ^ salt); - long centerX = (long) cellX * spacing + Math.floorMod(mix64(seed ^ 0x165667B19E3779F9L), spacing); - long centerZ = (long) cellZ * spacing + Math.floorMod(mix64(seed ^ 0x85EBCA77C2B2AE63L), spacing); - int radius = minRadius + (int) Math.floorMod(seed >>> 1, maxRadius - minRadius + 1L); - int highestGround = Integer.MIN_VALUE; - for (int sampleX = (int)centerX - radius - 2; sampleX <= centerX + radius + 2; sampleX++) - for (int sampleZ = (int)centerZ - radius - 2; sampleZ <= centerZ + radius + 2; sampleZ++) { - if (Math.hypot(sampleX - centerX, sampleZ - centerZ) > radius + 2) continue; - double noise = Math.sin(sampleX * scale) * Math.cos(sampleZ * scale * 1.13) - + Math.sin(sampleX * scale * 2.7 + sampleZ * scale * 1.45) * 0.35; - highestGround = Math.max(highestGround, baseHeight + (int)Math.round(noise * variation)); - } - int plateauCount = RockPlateaus.count(seed, Math.min(maxRise, plugin.getConfig().getInt(path + "max-plateaus", 3))); + long seed = RockPlateaus.formationSeed(cellX, cellZ); + long centerX = RockPlateaus.centerX(cellX,minimumGap,maximumGap); + long centerZ = RockPlateaus.centerZ(cellZ,minimumGap,maximumGap); + int radius = RockPlateaus.radius(seed,minRadius,maxRadius); + RockPlateaus.Shape shape = RockPlateaus.shape(seed, centerX, centerZ, radius, scale); + if (formationGround.size() > 2048) formationGround.clear(); + int highestGround = formationGround.computeIfAbsent(new GroundKey(shape,baseHeight,variation), + key -> RockPlateaus.highestGround(key.shape(),key.baseHeight(),key.variation())); + int allowedPlateaus = Math.max(1, Math.min(3, Math.min(maxRise, plugin.getConfig().getInt(path + "max-plateaus", 3)))); + int plateauCount = highlands ? allowedPlateaus : RockPlateaus.count(seed, allowedPlateaus); int interval = RockPlateaus.interval(plugin.getConfig().getInt(path + "plateau-interval", 5), maxRise, plateauCount); - int plateauY = highestGround + plateauCount * interval; + int plateauY = highestGround + mountainRise + plateauCount * interval; for (int lx = 0; lx < 16; lx++) for (int lz = 0; lz < 16; lz++) { long gx = (long) worldMinX + lx, gz = (long) worldMinZ + lz; - long dx = gx - centerX, dz = gz - centerZ; long rough = mix64(gx * 0x9E3779B97F4A7C15L ^ gz * 0xC2B2AE3D27D4EB4FL ^ seed); - double edge = radius + (((rough >>> 11) * 0x1.0p-53) - 0.5) * 3.0; - double distance = Math.sqrt(dx * dx + dz * dz); - if (distance > edge) continue; + double depth = shape.depth(gx, gz); + if (depth < 0) continue; int baseY = heights[lx][lz]; if (plateauY + 2 >= maxY || baseY <= minY + 1) continue; - int level = RockPlateaus.level(distance, radius, plateauCount); - boolean plateau = level > 0; - int terraceY = highestGround + level * interval; - double slope = Math.max(0.0, Math.min(1.0, (edge - distance) / Math.max(1.0, edge - radius * 0.9))); - int sideTop = highestGround + (int)Math.floor(slope * interval); + int level = RockPlateaus.level(highlands ? (depth - 0.40) / 0.60 : depth, plateauCount); + int lowerLevel = highlands ? RockPlateaus.lowerTerrace(depth) : 0; + boolean plateau = level > 0 || lowerLevel > 0; + int terraceY = lowerLevel > 0 ? highestGround + lowerLevel * interval : highestGround + mountainRise + level * interval; + double slope = Math.max(0.0, Math.min(1.0, depth / (highlands ? 0.46 : 0.10))); + slope = slope * slope * (3 - 2 * slope); + int sideTop = highlands ? baseY + (int)Math.floor(slope * (highestGround + mountainRise - baseY)) + : highestGround + (int)Math.floor(slope * interval); Material[] darkRock = {Material.BLACKSTONE, Material.BASALT, Material.POLISHED_BLACKSTONE}; if (plateau) { for (int y = baseY + 1; y < terraceY; y++) { @@ -490,8 +502,12 @@ public final class DuneTerrain extends JavaPlugin implements Listener { data.setBlock(lx, y, lz, darkRock[hashIndex]); } data.setBlock(lx, terraceY, lz, Material.SAND); + heights[lx][lz] = terraceY; } else { - int sideSurface = Math.max(baseY, sideTop); + int spire = highlands ? RockPlateaus.spireRise(seed,gx,gz,depth, + plugin.getConfig().getInt("planets.arrakis.highlands.spire-height",40)) : 0; + int sideSurface = Math.max(baseY, Math.min(maxY - 2, sideTop + spire)); + heights[lx][lz] = sideSurface; for (int y = baseY; y <= sideSurface; y++) { int hashIndex = (int)Math.floorMod(mix64(rough + y * 0x9E3779B97F4A7C15L), darkRock.length); data.setBlock(lx, y, lz, darkRock[hashIndex]); @@ -591,16 +607,36 @@ public final class DuneTerrain extends JavaPlugin implements Listener { } } private static final class PlanetBiomeProvider extends BiomeProvider { - private final Biome biome; + private final DuneTerrain plugin; + private final String planet; + private final Biome biome, highlands, denseSpice; PlanetBiomeProvider(DuneTerrain plugin, String planet) { - String configured = planet.equals("arrakis") ? "DESERT" : plugin.getConfig().getString("planets." + planet + ".biome", "PLAINS"); - Biome selected; - try { selected = Biome.valueOf(configured.toUpperCase(Locale.ROOT)); } - catch (IllegalArgumentException ex) { selected = Biome.DESERT; } - this.biome = selected; + this.plugin = plugin; this.planet = planet; + String configured = plugin.getConfig().getString("planets." + planet + ".biome", "DESERT"); + NamespacedKey key = NamespacedKey.fromString(configured.toLowerCase(Locale.ROOT)); + Biome selected = key == null ? null : Registry.BIOME.get(key); + this.biome = selected == null ? Biome.DESERT : selected; + String custom = plugin.getConfig().getString("planets.arrakis.highlands.biome", "dunerealms:dune-highlands"); + NamespacedKey customKey = NamespacedKey.fromString(custom); + this.denseSpice = planet.equals("arrakis") && plugin.getConfig().getBoolean("dense-spice.enabled", true) + ? Registry.BIOME.get(new NamespacedKey("dunerealms", "dense-spice")) : null; + this.highlands = planet.equals("arrakis") && plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled", true) + && customKey != null ? Registry.BIOME.get(customKey) : null; + } + @Override public Biome getBiome(WorldInfo info, int x, int y, int z) { + if (denseSpice != null && DenseSpice.contains(info.getSeed(),x,z,Math.max(128,plugin.getConfig().getInt("dense-spice.spacing",512)))) return denseSpice; + if (highlands == null) return biome; + String path = "planets.arrakis.darkstone-islands."; + int minimumGap = Math.max(192, plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing", 300)); + int maximumGap = Math.max(minimumGap, plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing", 500)); + int minimum = Math.max(6, plugin.getConfig().getInt(path + "min-radius", 45)); + int maximum = Math.max(minimum, plugin.getConfig().getInt(path + "max-radius", 55)); + double scale = Math.max(.001, plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale", .02)); + return RockPlateaus.regionDepth(x,z,minimumGap,maximumGap,minimum,maximum,scale) >= 0 ? highlands : biome; + } + @Override public List getBiomes(WorldInfo info) { + Set all = new LinkedHashSet<>(); all.add(biome); if(highlands!=null)all.add(highlands); if(denseSpice!=null)all.add(denseSpice); return List.copyOf(all); } - @Override public Biome getBiome(WorldInfo info, int x, int y, int z) { return biome; } - @Override public List getBiomes(WorldInfo info) { return List.of(biome); } } private static long mix64(long value) { @@ -611,10 +647,12 @@ public final class DuneTerrain extends JavaPlugin implements Listener { private static final class SietchPopulator extends BlockPopulator { private final DuneTerrain plugin; + private final java.util.concurrent.ConcurrentHashMap> highlandSites = new java.util.concurrent.ConcurrentHashMap<>(); private SietchPopulator(DuneTerrain plugin) { this.plugin = plugin; } @Override public void populate(WorldInfo world, Random random, int cx, int cz, LimitedRegion region) { if (!world.getName().equalsIgnoreCase("arrakis")) return; if (!plugin.getConfig().getBoolean("sietches.enabled", true)) return; + populateHighlands(world,cx,cz,region); int spacing = Math.max(256, plugin.getConfig().getInt("sietches.spacing", 2000)); int centerX = cx * 16 + 8, centerZ = cz * 16 + 8; long cellX = Math.floorDiv(centerX, spacing), cellZ = Math.floorDiv(centerZ, spacing); @@ -681,6 +719,50 @@ public final class DuneTerrain extends JavaPlugin implements Listener { set(region, x + lamp[0], hy + lamp[1], z + lamp[2], Material.TORCH); } + private void populateHighlands(WorldInfo world,int cx,int cz,LimitedRegion region) { + if(!plugin.getConfig().getBoolean("planets.arrakis.highlands.enabled",true) + ||!plugin.getConfig().getBoolean("sietches.highlands.enabled",true))return; + int minGap=Math.max(192,plugin.getConfig().getInt("planets.arrakis.highlands.min-spacing",300)); + int maxGap=Math.max(minGap,plugin.getConfig().getInt("planets.arrakis.highlands.max-spacing",500)); + int spacing=(minGap+maxGap)/2; + int minRadius=Math.max(6,plugin.getConfig().getInt("planets.arrakis.darkstone-islands.min-radius",45)); + int maxRadius=Math.max(minRadius,plugin.getConfig().getInt("planets.arrakis.darkstone-islands.max-radius",55)); + double scale=Math.max(.001,plugin.getConfig().getDouble("planets.arrakis.terrain.noise-scale",.02)); + int reach=(int)Math.ceil(maxRadius*2.0)+3; + if(highlandSites.size()>2048)highlandSites.clear(); + for(int gx=Math.floorDiv(cx*16-reach,spacing);gx<=Math.floorDiv(cx*16+15+reach,spacing);gx++) + for(int gz=Math.floorDiv(cz*16-reach,spacing);gz<=Math.floorDiv(cz*16+15+reach,spacing);gz++) { + long seed=RockPlateaus.formationSeed(gx,gz); + var shape=RockPlateaus.shape(seed,RockPlateaus.centerX(gx,minGap,maxGap),RockPlateaus.centerZ(gz,minGap,maxGap),RockPlateaus.radius(seed,minRadius,maxRadius),scale); + var sites=highlandSites.computeIfAbsent(shape,k->HighlandSietches.sites(k, + plugin.getConfig().getInt("sietches.highlands.frequency-multiplier",3),plugin.getConfig().getInt("sietches.highlands.minimum-per-region",3))); + for(var site:sites) { + int x=site.x(),z=site.z(); + if(Math.floorDiv(x,16)!=cx||Math.floorDiv(z,16)!=cz)continue; + int surface=region.getHighestBlockYAt(x,z),hy=surface-11; + if(hy-12<=world.getMinHeight()||surface+2>=world.getMaxHeight())continue; + // Compact multi-room caves fit three sites without the large desert template colliding. + carveRoom(region,x,hy,z,7,4,7); + carveRoom(region,x-5,hy-3,z+5,4,3,4); + carveRoom(region,x+5,hy-3,z+5,4,3,4); + carveTunnelNetwork(region,new int[][]{{x,hy-1,z},{x-3,hy-2,z+3},{x-5,hy-3,z+5}}); + carveTunnelNetwork(region,new int[][]{{x,hy-1,z},{x+3,hy-2,z+3},{x+5,hy-3,z+5}}); + carveCaveEntrance(region,x,z,hy); + furnishSleepingHall(region,x-5,hy-4,z+5); + furnishKitchen(region,x+5,hy-4,z+5); + carveRoom(region,x,hy-8,z+6,4,3,4); + carveTunnelNetwork(region,new int[][]{{x,hy-1,z+2},{x+2,hy-3,z+4},{x+2,hy-5,z+6},{x,hy-8,z+6}}); + for(int dx=-2;dx<=2;dx++)for(int dz=-2;dz<=2;dz++) { + set(region,x+dx,hy-11,z+6+dz,Material.STONE); + set(region,x+dx,hy-10,z+6+dz,Material.WATER); + } + placePersonalChest(region,x,hy-2,z-3,site.cacheId(),0x484947484c414e44L); + set(region,x,hy-3,z,Material.CHISELED_STONE_BRICKS); + set(region,x,hy-2,z,Material.LANTERN); + } + } + } + private static void carveRoom(LimitedRegion region, int cx, int cy, int cz, int rx, int ry, int rz) { for (int dx = -rx; dx <= rx; dx++) for (int dy = -ry; dy <= ry; dy++) for (int dz = -rz; dz <= rz; dz++) { double outer = dx * dx / (double)(rx * rx) + dy * dy / (double)(ry * ry) + dz * dz / (double)(rz * rz); diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java b/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java new file mode 100644 index 00000000..4e5a663f --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java @@ -0,0 +1,66 @@ +package com.example.duneterrain; + +import org.bukkit.*; +import org.bukkit.block.Chest; +import org.bukkit.event.*; +import org.bukkit.event.world.LootGenerateEvent; +import org.bukkit.generator.*; +import org.bukkit.inventory.ItemStack; +import java.util.*; + +/** Arrakis temple adaptation: stepped roof, upper chamber, stair and buried vault. */ +final class HarkonnenFortress extends BlockPopulator implements Listener { + static final NamespacedKey LOOT=new NamespacedKey("dunerealms","chests/old-harkonnen-fortress"); + private final DuneTerrain plugin; + HarkonnenFortress(DuneTerrain plugin) { this.plugin=plugin; } + static boolean attempt(long seed,int cx,int cz,int rarity) { + return Math.floorMod(DenseSpice.mix(seed^cx*0x9e3779b97f4a7c15L^cz*0xc2b2ae3d27d4eb4fL^0x4841524b4f4e4e45L),Math.max(1,rarity))==0; + } + @Override public void populate(WorldInfo world,Random random,int cx,int cz,LimitedRegion r) { + if(!world.getName().equalsIgnoreCase("arrakis")||!plugin.getConfig().getBoolean("harkonnen-fortress.enabled",true) + || !attempt(world.getSeed(),cx,cz,plugin.getConfig().getInt("harkonnen-fortress.rarity",1000)))return; + int x=cx*16+8,z=cz*16+8,y=r.getHighestBlockYAt(x,z); + if(y-7<=world.getMinHeight()||y+10>=world.getMaxHeight())return; + for(int dx:new int[]{-7,7})for(int dz:new int[]{-8,8}) + if(!r.isInRegion(x+dx,y,z+dz)||Math.abs(r.getHighestBlockYAt(x+dx,z+dz)-y)>6)return; + // Jungle-temple proportions translated into sandstone and Harkonnen dark stone. + for(int dx=-6;dx<=6;dx++)for(int dz=-7;dz<=7;dz++)for(int dy=-6;dy<=6;dy++) { + boolean shell=dy==-6||dy==0||dy==6||Math.abs(dx)==6||Math.abs(dz)==7; + Material m=shell?((dx+dz+dy)%5==0?Material.CRACKED_POLISHED_BLACKSTONE_BRICKS:Material.SANDSTONE):Material.AIR; + r.setType(x+dx,y+dy,z+dz,m); + } + for(int level=0;level<3;level++)for(int dx=-5+level;dx<=5-level;dx++)for(int dz=-6+level;dz<=6-level;dz++) + r.setType(x+dx,y+7+level,z+dz,Material.CUT_SANDSTONE); + for(int dx:new int[]{-5,5})for(int dz:new int[]{-6,6})for(int dy=1;dy<=5;dy++)r.setType(x+dx,y+dy,z+dz,Material.POLISHED_BLACKSTONE_BRICKS); + for(int dy=1;dy<=3;dy++)r.setType(x,y+dy,z-7,Material.AIR); + for(int step=0;step<6;step++) { + r.setType(x-3,y-step,z+4-step,Material.SANDSTONE); + for(int clear=1;clear<=3;clear++)r.setType(x-3,y-step+clear,z+4-step,Material.AIR); + } + r.setType(x+3,y-5,z+3,Material.CHEST); + if(r.getBlockState(x+3,y-5,z+3) instanceof Chest chest) { + chest.setCustomName("Old Harkonnen Fortress"); + var table=Bukkit.getLootTable(LOOT); + if(table!=null){chest.setLootTable(table);chest.setSeed(DenseSpice.mix(world.getSeed()^cx^((long)cz<<32)));} + else for(ItemStack item:kit())chest.getSnapshotInventory().addItem(item); + chest.update(true,false); + } + // Ruined red banner and lanterns, no moss, jungle trees, farms or hay. + r.setType(x,y+4,z-8,Material.RED_WALL_BANNER); + var banner=Material.RED_WALL_BANNER.createBlockData(); + ((org.bukkit.block.data.Directional)banner).setFacing(org.bukkit.block.BlockFace.NORTH); + r.setBlockData(x,y+4,z-8,banner); + r.setType(x+3,y-2,z+3,Material.LANTERN); + } + @SuppressWarnings("unchecked") private List kit() { + var core=Bukkit.getPluginManager().getPlugin("DuneCore"); + if(core!=null && core.isEnabled())try { + return (List)core.getClass().getMethod("createFactionKit",String.class).invoke(core,"Harkonnen"); + }catch(ReflectiveOperationException ex){plugin.getLogger().warning("Harkonnen kit requires updated DuneCore: "+ex.getMessage());} + return List.of(new ItemStack(Material.IRON_SWORD),new ItemStack(Material.BREAD,8)); + } + @EventHandler(ignoreCancelled=true) public void loot(LootGenerateEvent e) { + if(!e.getLootTable().getKey().equals(LOOT))return; + List items=new ArrayList<>(e.getLoot());items.addAll(kit());e.setLoot(items); + } +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/HighlandSietches.java b/DuneTerrain/src/main/java/com/example/duneterrain/HighlandSietches.java new file mode 100644 index 00000000..2b015475 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/HighlandSietches.java @@ -0,0 +1,33 @@ +package com.example.duneterrain; + +import java.util.*; + +/** Threefold regional placement, independent of the legacy open-desert sietch grid. */ +final class HighlandSietches { + record Site(int x,int z,long cacheId) {} + static List sites(RockPlateaus.Shape shape,int multiplier,int minimum) { + int target=Math.max(3,Math.min(12,Math.max(minimum,multiplier))); + List candidates=new ArrayList<>(); + int extent=(int)Math.ceil(shape.radius()*1.6); + for(int dx=-extent;dx<=extent;dx+=2)for(int dz=-extent;dz<=extent;dz+=2) { + int x=(int)shape.centerX()+dx,z=(int)shape.centerZ()+dz; + if(shape.depth(x,z)<.25)continue; + candidates.add(new Site(x,z,DenseSpice.mix(shape.seed()^x*341873128712L^z*132897987541L^0x5349455443484849L))); + } + List result=new ArrayList<>(); + // Start at one end, then choose the farthest remaining sites, keeping compact caves apart. + Site center=new Site((int)shape.centerX(),(int)shape.centerZ(),0); + candidates.sort(Comparator.comparingLong(s->distance(s,center)).reversed().thenComparingLong(Site::cacheId)); + while(result.size()distance(s,candidate)).min().orElse(0); + if(nearest>distance){distance=nearest;best=candidate;} + } + if(!result.isEmpty()&&distance<26L*26)break; + result.add(best);candidates.remove(best); + } + return List.copyOf(result); + } + private static long distance(Site a,Site b) {long dx=a.x()-b.x(),dz=a.z()-b.z();return dx*dx+dz*dz;} +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/RockPlateaus.java b/DuneTerrain/src/main/java/com/example/duneterrain/RockPlateaus.java index ca1ab0d8..43677801 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/RockPlateaus.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/RockPlateaus.java @@ -1,18 +1,113 @@ package com.example.duneterrain; -/** Deterministic nested terraces shared by every chunk intersecting a formation. */ +/** Seeded continuous ridge contours, shared across every intersecting chunk. */ final class RockPlateaus { static int count(long seed, int configuredMaximum) { return 1 + (int)Math.floorMod(seed, Math.max(1, Math.min(3, configuredMaximum))); } - static int interval(int configuredInterval, int maximumHeight, int count) { return Math.max(1, Math.min(5, Math.min(configuredInterval, Math.max(1, maximumHeight / count)))); } - - static int level(double distance, double radius, int count) { - double fraction = distance / radius; - if (fraction > 0.9) return 0; - return Math.min(count, 1 + (int)Math.floor((0.9 - fraction) / (0.9 / count))); + static int level(double depth, int count) { + if (depth < 0.10) return 0; + return Math.min(count, 1 + (int)Math.floor((depth - 0.10) / (0.78 / count))); + } + static double terrain(double x, double z, double scale) { + return Math.sin(x * scale) * Math.cos(z * scale * 1.13) + + Math.sin(x * scale * 2.7 + z * scale * 1.45) * 0.35; + } + static Shape shape(long seed, long centerX, long centerZ, double radius, double scale) { + // Follow the local dune contour instead of cutting a circular island across it. + double gx = terrain(centerX + 8, centerZ, scale) - terrain(centerX - 8, centerZ, scale); + double gz = terrain(centerX, centerZ + 8, scale) - terrain(centerX, centerZ - 8, scale); + double angle = Math.atan2(gz, gx) + Math.PI / 2; + return new Shape(seed, centerX, centerZ, radius, scale, Math.cos(angle), Math.sin(angle)); + } + record Shape(long seed, long centerX, long centerZ, double radius, double scale, double cosine, double sine) { + double depth(long x, long z) { + double dx = (x - centerX) / radius, dz = (z - centerZ) / radius; + double u = dx * cosine + dz * sine, v = -dx * sine + dz * cosine; + // Low-frequency domain warping produces connected promontories, bays and uneven terraces. + double warpedU = u + 0.14 * noise(u * 2.0 + 17, v * 2.0 - 9, seed); + double spine = 0.24 * noise(u * 2.2 - 31, 7, seed ^ 0x51ed2705L) + + 0.12 * (terrain(x, z, scale) - terrain(centerX, centerZ, scale)); + double width = 0.57 + 0.14 * noise(u * 2.5, 13, seed ^ 0x6eed0e9dL); + double cross = (v - spine + 0.10 * noise(u * 3, v * 3, ~seed)) / width; + double envelope = Math.pow(Math.pow(Math.abs(warpedU), 2.6) + Math.pow(Math.abs(cross), 2.6), 1.0 / 2.6); + return 1.0 - envelope + 0.17 * noise(u * 3.1 + 4, v * 3.1 - 5, seed ^ 0x9e3779b9L); + } + } + static int lowerTerrace(double depth) { + if(depth < .025 || depth >= .25)return 0; + return Math.min(3,1+(int)Math.floor((depth-.025)/.075)); + } + static int spireRise(long seed, long x, long z, double depth, int height) { + // Thin erosion ridges on the outer mountain shoulder; terrace surfaces remain untouched. + if (depth <= 0.25 || depth >= 0.46 || height <= 0) return 0; + double shoulder = Math.sin(Math.PI * (depth - 0.25) / 0.21); + double ridge = 1.0 - Math.abs(noise(x / 16.0, z / 16.0, seed ^ 0x45524f53494f4eL)); + double broken = 0.65 + 0.35 * (noise(x / 4.5, z / 4.5, ~seed) + 1) / 2; + return (int)Math.floor(Math.min(64,height) * shoulder * Math.pow(ridge,3) * broken); + } + static int highestGround(Shape shape, int baseHeight, double variation) { + int extent = (int)Math.ceil(shape.radius() * 2.0) + 3; + int highest = Integer.MIN_VALUE; + for (int x = (int)shape.centerX() - extent; x <= shape.centerX() + extent; x++) + for (int z = (int)shape.centerZ() - extent; z <= shape.centerZ() + extent; z++) { + if (shape.depth(x,z) >= 0) + highest = Math.max(highest, baseHeight + (int)Math.round(terrain(x,z,shape.scale()) * variation)); + } + return highest == Integer.MIN_VALUE ? baseHeight : highest; + } + static long formationSeed(long cellX, long cellZ) { + return mix(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ 0x4441524B49534C41L); + } + // Shared axis positions keep north/south and east/west neighbours aligned. + // Independent bounded jitter makes each gap lie within the requested limits. + static long axisCenter(long cell, int minimumGap, int maximumGap, long salt) { + int spacing = (minimumGap + maximumGap) / 2; + int jitter = Math.min(spacing - minimumGap, maximumGap - spacing) / 2; + long offset = Math.floorMod(mix(cell ^ salt), jitter * 2L + 1) - jitter; + return cell * spacing + spacing / 2 + offset; + } + static long centerX(long cell, int minimumGap, int maximumGap) { + return axisCenter(cell,minimumGap,maximumGap,0x165667B19E3779F9L); + } + static long centerZ(long cell, int minimumGap, int maximumGap) { + return axisCenter(cell,minimumGap,maximumGap,0x85EBCA77C2B2AE63L); + } + static int radius(long seed, int minimum, int maximum) { + return minimum + (int)Math.floorMod(seed >>> 1, maximum - minimum + 1L); + } + static double regionDepth(int x, int z, int minimumGap, int maximumGap, int minimum, int maximum, double scale) { + int spacing = (minimumGap + maximumGap) / 2; + int reach = (int)Math.ceil(maximum * 2.0) + 3; + double depth = -1; + for (int cx = Math.floorDiv(x - reach, spacing); cx <= Math.floorDiv(x + reach, spacing); cx++) + for (int cz = Math.floorDiv(z - reach, spacing); cz <= Math.floorDiv(z + reach, spacing); cz++) { + long seed = formationSeed(cx, cz); + depth = Math.max(depth, shape(seed, centerX(cx,minimumGap,maximumGap), centerZ(cz,minimumGap,maximumGap), + radius(seed,minimum,maximum), scale).depth(x,z)); + } + return depth; + } + private static long mix(long h) { + h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; + h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; + return h ^ (h >>> 31); + } + static double noise(double x, double z, long seed) { + long ix = (long)Math.floor(x), iz = (long)Math.floor(z); + double tx = x - ix, tz = z - iz; + tx = tx * tx * (3 - 2 * tx); tz = tz * tz * (3 - 2 * tz); + double a = sample(ix, iz, seed), b = sample(ix + 1, iz, seed); + double c = sample(ix, iz + 1, seed), d = sample(ix + 1, iz + 1, seed); + return (a + (b - a) * tx) * (1 - tz) + (c + (d - c) * tx) * tz; + } + private static double sample(long x, long z, long seed) { + long h = x * 0x9E3779B97F4A7C15L ^ z * 0xC2B2AE3D27D4EB4FL ^ seed; + h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; + h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; + return ((h ^ (h >>> 31)) >>> 11) * 0x1.0p-52 - 1; } } diff --git a/DuneTerrain/src/main/resources/config.yml b/DuneTerrain/src/main/resources/config.yml index 27fd17a1..9bcccdd4 100644 --- a/DuneTerrain/src/main/resources/config.yml +++ b/DuneTerrain/src/main/resources/config.yml @@ -9,6 +9,11 @@ server: sietches: enabled: true spacing: 2000 + # Additional sites only in Dune-highlands; open-desert grid stays unchanged. + highlands: + enabled: true + frequency-multiplier: 3 + minimum-per-region: 3 spice-blow: enabled: true @@ -38,7 +43,11 @@ planets: water: {level: 63, swamp-pools: false, coverage: 0.18} vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0} oasis-trees: {enabled: true, spacing: 300, trunk-height: 7} - # Nested flat terraces, hard capped at 3 levels and 5 blocks between levels. + # Server datapack registers this biome; absent pack safely uses DESERT climate. + # Highlands share the irregular rock footprint and have three upper terraces. + highlands: {enabled: true, biome: 'dunerealms:dune-highlands', mountain-rise: 32, spire-height: 40, min-spacing: 300, max-spacing: 500} + # Legacy spacing/enabled below are superseded by highlands settings. + # Upper terraces are hard capped at 3 levels and 5 blocks between levels. # Radius 45-55 gives approximately 90-110 blocks across, including a rough edge. darkstone-islands: {enabled: true, spacing: 750, min-radius: 45, max-radius: 55, max-height: 14, max-plateaus: 3, plateau-interval: 5} # Arrakis: spice only, no mineable ores. @@ -89,3 +98,19 @@ planets: vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0} # Sigma Draconis IV: harsh frontier mining. ores: {min-y: -48, max-y: 48, vein-size: 5, IRON_ORE: 11, COPPER_ORE: 6, REDSTONE_ORE: 12, DIAMOND_ORE: 5} + +# One finite 30 x 30 rich patch per 512-block region; new Arrakis chunks only. +dense-spice: + enabled: true + spacing: 512 + yield: 4 + +# Custom sandstone houses; no farms or hay. Shared finite chest loot. +desert-villages: + enabled: true + spacing: 768 + +# Java desert-well-style attempt rate (1 per 1000 chunks), subject to terrain checks. +harkonnen-fortress: + enabled: true + rarity: 1000 diff --git a/DuneTerrain/src/main/resources/plugin.yml b/DuneTerrain/src/main/resources/plugin.yml index 3c92187a..7e169d09 100644 --- a/DuneTerrain/src/main/resources/plugin.yml +++ b/DuneTerrain/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: DuneTerrain -version: 1.0.7 +version: 1.0.9 main: com.example.duneterrain.DuneTerrain api-version: '1.21' load: STARTUP diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisFeaturesTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisFeaturesTest.java new file mode 100644 index 00000000..b15615dd --- /dev/null +++ b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisFeaturesTest.java @@ -0,0 +1,88 @@ +package com.example.duneterrain; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.persistence.*; +import org.bukkit.event.block.*; +import org.bukkit.entity.Player; +import java.util.*; + +class ArrakisFeaturesTest { + @Test void densePatchesAreExactlyThirtyByThirtyIncludingNegativeCoordinates() { + for(long seed:new long[]{-90,0,123456})for(int cx=-3;cx<=3;cx++)for(int cz=-3;cz<=3;cz++) { + int[] a=DenseSpice.anchor(seed,cx*512,cz*512,512); + int count=0; + for(int x=a[0]-1;x<=a[0]+30;x++)for(int z=a[1]-1;z<=a[1]+30;z++) + if(DenseSpice.contains(seed,x,z,512))count++; + assertEquals(900,count); + assertFalse(DenseSpice.contains(seed,a[0]-1,a[1],512)); + assertFalse(DenseSpice.contains(seed,a[0]+30,a[1],512)); + } + } + @Test void fortressAttemptsAreDeterministicAndWellRare() { + int count=0; + for(int cx=-500;cx<500;cx++)for(int cz=-100;cz<100;cz++) { + boolean yes=HarkonnenFortress.attempt(1701,cx,cz,1000); + assertEquals(yes,HarkonnenFortress.attempt(1701,cx,cz,1000));if(yes)count++; + } + assertTrue(count>140&&count<260,"observed "+count+" in 200000 chunks"); + } + @Test void depositIdentitySurvivesListenerRestartAndCreativeMiningConsumesIt() { + DuneTerrain plugin=mock(DuneTerrain.class);Chunk chunk=mock(Chunk.class);Block block=mock(Block.class); + PersistentDataContainer pdc=mock(PersistentDataContainer.class); + when(chunk.getPersistentDataContainer()).thenReturn(pdc);when(block.getChunk()).thenReturn(chunk); + when(block.getX()).thenReturn(-17);when(block.getY()).thenReturn(80);when(block.getZ()).thenReturn(35); + when(block.getType()).thenReturn(Material.ORANGE_TERRACOTTA); + int[][] saved={new int[]{DenseSpice.encode(block)}}; + when(pdc.getOrDefault(any(),eq(PersistentDataType.INTEGER_ARRAY),any())).thenAnswer(i->saved[0]); + doAnswer(i->{saved[0]=i.getArgument(2);return null;}).when(pdc).set(any(),eq(PersistentDataType.INTEGER_ARRAY),any()); + Player player=mock(Player.class);when(player.getGameMode()).thenReturn(GameMode.CREATIVE); + BlockBreakEvent event=new BlockBreakEvent(block,player); + new DenseSpice(plugin).harvest(event);assertFalse(event.isDropItems()); + new DenseSpice(plugin).reward(event);assertEquals(0,saved[0].length); + BlockBreakEvent repeated=new BlockBreakEvent(block,player);new DenseSpice(plugin).harvest(repeated); + assertTrue(repeated.isDropItems(),"ordinary replacement blocks have no spice identity"); + verify(block,never()).getWorld(); + } + @Test void villageBuildsFourHousesAndChestsWithoutFarmsOrHay() { + DuneTerrain plugin=mock(DuneTerrain.class); + var config=new org.bukkit.configuration.file.YamlConfiguration();when(plugin.getConfig()).thenReturn(config); + var world=mock(org.bukkit.generator.WorldInfo.class);when(world.getName()).thenReturn("arrakis");when(world.getMaxHeight()).thenReturn(320); + var region=mock(org.bukkit.generator.LimitedRegion.class); + when(region.isInRegion(anyInt(),anyInt(),anyInt())).thenReturn(true); + when(region.getHighestBlockYAt(anyInt(),anyInt())).thenReturn(70); + when(region.getType(anyInt(),anyInt(),anyInt())).thenReturn(Material.SAND); + int[] a=DenseSpice.anchor(0x56494c4c414745L,0,0,768); + List palette=new ArrayList<>(); + doAnswer(call->{palette.add(call.getArgument(3));return null;}).when(region).setType(anyInt(),anyInt(),anyInt(),any(Material.class)); + try(var api=mockStatic(Bukkit.class)) { + var bed=mock(org.bukkit.block.data.type.Bed.class);when(bed.clone()).thenReturn(mock(org.bukkit.block.data.type.Bed.class)); + api.when(()->Bukkit.createBlockData(Material.RED_BED)).thenReturn(bed); + new DesertVillages(plugin).populate(world,new Random(0),Math.floorDiv(a[0]+15,16),Math.floorDiv(a[1]+15,16),region); + } + verify(region,times(8)).setBlockData(anyInt(),anyInt(),anyInt(),any(org.bukkit.block.data.BlockData.class)); + assertEquals(4,Collections.frequency(palette,Material.CHEST)); + assertFalse(palette.contains(Material.HAY_BLOCK));assertFalse(palette.contains(Material.FARMLAND));assertFalse(palette.contains(Material.WHEAT)); + verify(region,times(4)).spawnEntity(any(Location.class),eq(org.bukkit.entity.EntityType.VILLAGER)); + } + @Test void fortressHasAccessibleEntryVaultAndSteppedRoof() { + DuneTerrain plugin=mock(DuneTerrain.class); + var config=new org.bukkit.configuration.file.YamlConfiguration();config.set("harkonnen-fortress.rarity",1);when(plugin.getConfig()).thenReturn(config); + var world=mock(org.bukkit.generator.WorldInfo.class);when(world.getName()).thenReturn("arrakis");when(world.getMaxHeight()).thenReturn(320);when(world.getMinHeight()).thenReturn(-64); + var region=mock(org.bukkit.generator.LimitedRegion.class);when(region.isInRegion(anyInt(),anyInt(),anyInt())).thenReturn(true);when(region.getHighestBlockYAt(anyInt(),anyInt())).thenReturn(70); + Map blocks=new HashMap<>(); + doAnswer(call->{blocks.put(call.getArgument(0)+","+call.getArgument(1)+","+call.getArgument(2),call.getArgument(3));return null;}).when(region).setType(anyInt(),anyInt(),anyInt(),any(Material.class)); + try(var api=mockStatic(Bukkit.class)) { + api.when(()->Bukkit.createBlockData(Material.RED_WALL_BANNER)).thenReturn(mock(org.bukkit.block.data.Directional.class)); + new HarkonnenFortress(plugin).populate(world,new Random(0),0,0,region); + } + assertEquals(Material.AIR,blocks.get("8,71,1")); + assertEquals(Material.CHEST,blocks.get("11,65,11")); + assertEquals(Material.CUT_SANDSTONE,blocks.get("8,79,8")); + assertEquals(Material.AIR,blocks.get("5,66,7")); + assertFalse(blocks.containsValue(Material.HAY_BLOCK));assertFalse(blocks.containsValue(Material.FARMLAND)); + } +} diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java new file mode 100644 index 00000000..989b151d --- /dev/null +++ b/DuneTerrain/src/test/java/com/example/duneterrain/HighlandSietchesTest.java @@ -0,0 +1,41 @@ +package com.example.duneterrain; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class HighlandSietchesTest { + @Test void everyDefaultHighlandHasThreeDistinctSpacedCavesInsideItsFootprint() { + for(int cx=-10;cx<=10;cx++)for(int cz=-10;cz<=10;cz++) { + long seed=RockPlateaus.formationSeed(cx,cz); + var shape=RockPlateaus.shape(seed,RockPlateaus.centerX(cx,300,500),RockPlateaus.centerZ(cz,300,500),RockPlateaus.radius(seed,45,55),.02); + var sites=HighlandSietches.sites(shape,3,3);assertEquals(3,sites.size(),"region "+cx+","+cz); + assertEquals(sites,HighlandSietches.sites(shape,3,3)); + assertEquals(3,sites.stream().map(HighlandSietches.Site::cacheId).distinct().count()); + for(var a:sites){assertTrue(shape.depth(a.x(),a.z())>=.25);for(var b:sites)if(a!=b){int dx=a.x()-b.x(),dz=a.z()-b.z();assertTrue(dx*dx+dz*dz>=676);}} + } + } + @Test void highlandPopulationPlacesThreeSeparateCachesWithoutChangingDesertSpacing() throws Exception { + var plugin=org.mockito.Mockito.mock(DuneTerrain.class); + var config=new org.bukkit.configuration.file.YamlConfiguration(); + org.mockito.Mockito.when(plugin.getConfig()).thenReturn(config); + var world=org.mockito.Mockito.mock(org.bukkit.generator.WorldInfo.class); + org.mockito.Mockito.when(world.getMinHeight()).thenReturn(-64); + org.mockito.Mockito.when(world.getMaxHeight()).thenReturn(320); + var region=org.mockito.Mockito.mock(org.bukkit.generator.LimitedRegion.class); + org.mockito.Mockito.when(region.getHighestBlockYAt(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt())).thenReturn(110); + org.mockito.Mockito.when(region.isInRegion(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt())).thenReturn(true); + var cls=Class.forName("com.example.duneterrain.DuneTerrain$SietchPopulator"); + var constructor=cls.getDeclaredConstructor(DuneTerrain.class);constructor.setAccessible(true); + var populator=constructor.newInstance(plugin); + var method=cls.getDeclaredMethod("populateHighlands",org.bukkit.generator.WorldInfo.class,int.class,int.class,org.bukkit.generator.LimitedRegion.class);method.setAccessible(true); + long seed=RockPlateaus.formationSeed(0,0); + var shape=RockPlateaus.shape(seed,RockPlateaus.centerX(0,300,500),RockPlateaus.centerZ(0,300,500),RockPlateaus.radius(seed,45,55),.02); + var chunks=new java.util.HashSet(); + for(var site:HighlandSietches.sites(shape,3,3))chunks.add(Math.floorDiv(site.x(),16)+","+Math.floorDiv(site.z(),16)); + for(var chunk:chunks){var parts=chunk.split(",");method.invoke(populator,world,Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),region);} + org.mockito.Mockito.verify(region,org.mockito.Mockito.times(3)).setType(org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.anyInt(),org.mockito.ArgumentMatchers.eq(org.bukkit.Material.CHEST)); + config.set("sietches.highlands.enabled",false); + org.mockito.Mockito.clearInvocations(region); + method.invoke(populator,world,10,10,region); + org.mockito.Mockito.verifyNoInteractions(region); + assertFalse(config.contains("sietches.spacing")); + } +} diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/RockPlateausTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/RockPlateausTest.java index fa37ee99..9961e5ee 100644 --- a/DuneTerrain/src/test/java/com/example/duneterrain/RockPlateausTest.java +++ b/DuneTerrain/src/test/java/com/example/duneterrain/RockPlateausTest.java @@ -18,19 +18,77 @@ class RockPlateausTest { } } - @Test void terracesAreFlatAndStepDownTowardEdge() { - for (double radius : new double[]{18, 45, 50, 55}) for (int count = 1; count <= 3; count++) { - assertEquals(count, RockPlateaus.level(0, radius, count)); - assertEquals(0, RockPlateaus.level(radius, radius, count)); - int previous = count; + @Test void levelsStayFlatAndBoundedForIrregularContours() { + for (int count = 1; count <= 3; count++) { java.util.Set levels = new java.util.HashSet<>(); - for (int sample = 0; sample <= 1800; sample++) { - int level = RockPlateaus.level(sample * radius / 1800.0, radius, count); - assertTrue(level <= previous && previous - level <= 1); + for (int i = -10; i <= 120; i++) { + int level = RockPlateaus.level(i / 100.0, count); + assertTrue(level >= 0 && level <= count); levels.add(level); - previous = level; } assertEquals(count + 1, levels.size()); } } + @Test void outlinesAreNotRotationallySymmetricAndVaryWithTheSeed() { + var a = RockPlateaus.shape(123, 0, 0, 50, .02); + var b = RockPlateaus.shape(456, 0, 0, 50, .02); + int asymmetric = 0, different = 0; + for (int x = -60; x <= 60; x++) for (int z = -60; z <= 60; z++) { + if ((a.depth(x,z) >= 0) != (a.depth(-z,x) >= 0)) asymmetric++; + if ((a.depth(x,z) >= 0) != (b.depth(x,z) >= 0)) different++; + } + assertTrue(asymmetric > 500); + assertTrue(different > 200); + } + @Test void contourIsContinuousAcrossChunkBoundariesAndOutsideSearchBounds() { + for (long seed : new long[]{-98, 0, 123, 999}) { + var shape = RockPlateaus.shape(seed, -54, -668, 48, .02); + for (int z = -760; z <= -576; z++) { + assertTrue(Math.abs(shape.depth(-49,z) - shape.depth(-48,z)) < .2); + } + for (int p = -120; p <= 120; p++) { + assertTrue(shape.depth(-54 + 82, -668 + p) < 0); + assertTrue(shape.depth(-54 - 82, -668 + p) < 0); + assertTrue(shape.depth(-54 + p, -668 + 82) < 0); + assertTrue(shape.depth(-54 + p, -668 - 82) < 0); + } + } + } + @Test void allCardinalNeighboursAreBetweenThreeAndFiveHundredBlocksApart() { + for (int cell = -10000; cell < 10000; cell++) { + long east = RockPlateaus.centerX(cell + 1,300,500) - RockPlateaus.centerX(cell,300,500); + long north = RockPlateaus.centerZ(cell + 1,300,500) - RockPlateaus.centerZ(cell,300,500); + assertTrue(east >= 300 && east <= 500); + assertTrue(north >= 300 && north <= 500); + } + } + @Test void biomeMaskMatchesTheTerrainFootprint() { + for (int cx=-1;cx<=1;cx++) for(int cz=-1;cz<=1;cz++) { + long seed=RockPlateaus.formationSeed(cx,cz); + long x=RockPlateaus.centerX(cx,300,500), z=RockPlateaus.centerZ(cz,300,500); + var shape=RockPlateaus.shape(seed,x,z,RockPlateaus.radius(seed,45,55),.02); + for(int dx=-80;dx<=80;dx+=8) for(int dz=-80;dz<=80;dz+=8) + assertEquals(shape.depth(x+dx,z+dz)>=0, + RockPlateaus.regionDepth((int)x+dx,(int)z+dz,300,500,45,55,.02)>=0); + } + } + @Test void erosionSpiresStayOnShouldersAndRespectHeightLimits() { + int tallest=0, varying=0, previous=-1; + for(int x=-100;x<=100;x++)for(int z=-100;z<=100;z++) { + int rise=RockPlateaus.spireRise(123,x,z,.355,40); + assertTrue(rise>=0&&rise<=40);tallest=Math.max(tallest,rise); + if(previous>=0&&previous!=rise)varying++;previous=rise; + assertEquals(0,RockPlateaus.spireRise(123,x,z,.46,40)); + assertEquals(0,RockPlateaus.spireRise(123,x,z,-.1,40)); + } + assertTrue(tallest>=30);assertTrue(varying>1000); + } + @Test void lowerTerracesAreThreeFlatStepsSeparatedFromUpperTerraces() { + java.util.Set levels=new java.util.HashSet<>(); + for(int d=0;d<=1000;d++) { + double depth=d/1000.0;int lower=RockPlateaus.lowerTerrace(depth); + if(lower>0){levels.add(lower);assertEquals(0,RockPlateaus.level((depth-.40)/.60,3));assertEquals(0,RockPlateaus.spireRise(1,d,0,depth,40));} + } + assertEquals(java.util.Set.of(1,2,3),levels); + } } diff --git a/README.md b/README.md index 7cbbab2e..c5662389 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Illustrated Arrakis dunes and Shai-Hulud -A Dune-themed Minecraft Java plugin suite for **Paper 1.21.4 and Java 21**. Explore Arrakis, harvest melange, join a faction, trade through the Spacing Guild, and encounter Shai-Hulud. +A Dune-themed Minecraft Java plugin suite for **Paper 1.21.8 and Java 21**. Explore Arrakis, harvest melange, join a faction, trade through the Spacing Guild, and encounter Shai-Hulud. **[Project Dune website](https://project-dune.bonnystoat9.chatgpt.site)** — illustrated landing page, searchable online manual, Races & Houses, Exchange and News. The website is public; profiles and private support tickets require sign-in. Live feeds show “server not connected” until configured; see [DiscordSRV integration](website/DISCORD-FEEDS.md). @@ -27,7 +27,7 @@ A Dune-themed Minecraft Java plugin suite for **Paper 1.21.4 and Java 21**. Expl 2. Stop the Paper server and back up its worlds, plugin data, and any shared database before replacing an existing release. 3. Put Vault, DuneCore, DuneNPC, DuneEss, and DuneTerrain JARs in `plugins/`. Keep only one JAR per plugin. Remove the legacy `DuneRealms.jar` if upgrading from that plugin. 4. Start once to create configuration files. Set the backend's `server.planet` in DuneTerrain and matching `network.local-planet` in DuneCore, then restart after edits. -5. Put `DuneResourcePack.zip` in the client's `.minecraft/resourcepacks` directory and enable it. Vanilla and Fabric clients use the same resource pack; it does not belong in `mods/`. +5. Optionally put `DuneResourcePack.zip` in the client's `.minecraft/resourcepacks` directory and enable it. Vanilla and Fabric clients use the same resource pack; it does not belong in `mods/`. For a planet used as Paper's primary world, configure its generator and biome provider in `bukkit.yml` as explained in the [terrain guide](DuneTerrain/README.md). Existing chunks are preserved when generation settings change. @@ -181,3 +181,10 @@ Expiry pays nothing, keeps cargo, and clears the camp once its last contract end Sietch Armoury now has its own page with all 68 item entries and full suit abilities. Diplomacy displays current leaders, Emperor, Spice Steward and House of Water through the opt-in DuneCore 1.0.10 DiscordSRV snapshot bridge. Configure the dedicated diplomacy channel as described in website/DISCORD-FEEDS.md. + + +### Native menus and DuneRealms Essentials + +See [Native GUI and essentials setup](docs/Native-GUI.md) for Java dialogs, Bedrock forms, +ViaVersion fallbacks, plugin names, crossplay dependency versions, and the staged upgrade checklist. +Resource packs and client mods are optional; the new menus require neither. diff --git a/docs/Arrakis-Update-Validation.md b/docs/Arrakis-Update-Validation.md new file mode 100644 index 00000000..3bd0023e --- /dev/null +++ b/docs/Arrakis-Update-Validation.md @@ -0,0 +1,17 @@ +# Arrakis update validation + +Development branch: `feature/organic-arrakis-plateaus`. + +Built on Java 21 for Paper 1.21.8: DuneRealms-Core 1.0.11, DuneRealms-Essentials 1.0.3, and DuneRealms-Terrain 1.0.9. Existing compiled NPC and Lobby JARs remain unchanged. 50 JUnit tests pass across Core (11), Essentials (19), Terrain (15), and NPC (5). Lobby has no unit tests. + +Terrain tests cover deterministic asymmetric contours, cardinal gaps 300–500, upper and lower terrace groups, bounded erosion ridges, biome footprint alignment, exact 900-column rich patches including negative coordinates, seeded fortress attempt rate, persistent deposit identity consumption across listener restarts, farm-free village palette/bed/job-site generation, and fortress entrance/vault geometry. Deposit tests use mocked Paper chunk PDC and creative harvesting; real server event dispatch still requires staging. + +The development preview invokes the actual compiled private Arrakis formation generator using a ChunkData recording proxy. At X 166, Z 165 the lower flat sand surfaces are Y 85 / 89 / 93 and upper surfaces Y 117 / 121 / 125. Each group has four-block steps. The rocky shoulder between groups is intentionally taller. Both exposed block positions and material types are recorded for the renderer. [Generator render](../DuneTerrain/previews/dune-highlands.png) is not an in-game screenshot or shader promise. + +Biome and loot JSON parse successfully; data pack archive and all five project JARs pass ZIP integrity checks. Release packaging verifies pinned crossplay SHA-256 checksums and includes the server-side Arrakis datapack alongside all server JARs in one ZIP. + +No live Minecraft server or Java/Bedrock clients were run. Biome registry startup, Geyser biome translation, ViaVersion handling, asynchronous chunk generation/population, natural village AI, real block physics, protection-plugin interactions and economy/NPC purchases need a separate staging world. No existing world, configuration, economy database or player data was modified. Install the updated Core and Terrain together for authoritative Harkonnen kit loot, and Essentials for seller purchases. + +Publication requires authenticated DuneGit access. The current browser runtime cannot resume native credential state and Git has no credential helper. No credentials from chat are used; local commits and packages are not proof of a remote push. + +Highland sietch placement: 441 default highland regions across positive and negative coordinates each have three deterministic, distinct sites at least 26 blocks apart inside the highland footprint. A population test also checks three actual chest placements and the highlands-only disable switch. The original open-desert placement formulas and spacing are unchanged; highland sites use separate cache identities. Compact cave geometry, real chunk population, cave connectivity, fluid physics and personal loot still need live staging. diff --git a/docs/Native-GUI-Validation.md b/docs/Native-GUI-Validation.md new file mode 100644 index 00000000..eba444b6 --- /dev/null +++ b/docs/Native-GUI-Validation.md @@ -0,0 +1,37 @@ +# Native GUI branch validation — 2026-10-21 + +Branch: `feature/native-gui-1.21.8`, based on `c692949a78f09a117d84684dbae7f9aef39189af`. + +Java: Temurin 21.0.12.1; Gradle: 8.14; Paper API: 1.21.8. + +| Module | Compile/build | Automated tests | +| --- | --- | --- | +| DuneRealms Essentials | Passed | 19 passed | +| DuneRealms Core | Passed | 11 passed | +| DuneRealms Terrain | Passed | 2 passed | +| DuneRealms NPC | Passed | 5 passed | +| DuneRealms Lobby | Passed | No existing automated tests | + +New checks include owner-bound menu sessions, stale screen invalidation, one-use selection, +expiry, normalized/validated home names and teleport consent with repeated acceptance rejected. +The existing SQL exchange, economy, announcements, terrain, and NPC tests remain enabled. +The Paper API upgrade required stubbing `Plugin.namespace()` in the sandworm mock; production +sandworm code was unchanged. Mockito is now installed explicitly as a test-only Java agent. + +Geyser/Floodgate Spigot and Velocity variants and ViaVersion downloaded successfully and +matched the official pinned SHA-256 metadata. The all-server ZIP has eleven plugin JARs; +the network ZIP verifies 45 JAR placements across the proxy and six backends. ZIP integrity, +plugin descriptors, workflow YAML, Python syntax and `git diff --check` were checked. + +No existing worlds, runtime configuration, database or player data were opened or modified. +The local packaging test creates fresh-install templates only in ignored generated directories. + +## Pending + +* Live Paper 1.21.8/Velocity, Java 1.21.8, supported older Via clients, and Bedrock clients. +* Visual dialog/form behavior, bed/anchor death/respawn, actual transfers and live shared SQL. +* DuneGit push: unauthenticated HTTPS write requires repository authentication. +* GitHub publishing: connected API returned 403, "Your account was suspended". + +No production deployment or merge has been performed. This is a staging candidate, not a +claim of live compatibility. Follow the checklist in Native-GUI.md before production rollout. diff --git a/docs/Native-GUI.md b/docs/Native-GUI.md new file mode 100644 index 00000000..b64afad2 --- /dev/null +++ b/docs/Native-GUI.md @@ -0,0 +1,111 @@ +# DuneRealms native menus and Essentials + +Target: Paper 1.21.8, Java 21. No resource pack or client mod is needed. + +## Plugin filenames + +| Module | Published filename | Existing internal ID / data folder | +| --- | --- | --- | +| DuneCore | DuneRealms-Core.jar | DuneCore | +| DuneEss — DuneRealms Essentials | DuneRealms-Essentials.jar | DuneEss | +| DuneTerrain | DuneRealms-Terrain.jar | DuneTerrain | +| DuneNPC | DuneRealms-NPC.jar | DuneNPC | +| DuneLobby | DuneRealms-Lobby.jar | DuneLobby | + +The internal IDs intentionally remain stable. Do not rename existing plugin data folders. +Stop each backend and replace its old project JARs; do not leave duplicate old/new copies. +Do not replace existing worlds, server properties, configs, balances, SQL databases or player data. +Back up the existing server and database first. The network ZIP is a **fresh-install template**; +never extract it over an existing deployment. Existing configuration files are not rewritten. + +## Menus + +CHOAM Exchange, DuneEss help/travel, the configurable Navigator (including its economy pages), +lobby departures and `/essentials` now use a shared renderer: + +* Bedrock: Floodgate native SimpleForms, checked before Java protocol detection. +* Java 1.21.6+ (protocol 771+): native Paper dialogs, including Paper 1.21.8 clients. +* Earlier clients supported by the existing Via stack: clickable chat actions. +* Unknown Via protocol: clickable chat fallback, avoiding unsupported dialog packets. + +CHOAM listings retain the SQL transactions, tagged item payloads, ownership checks, +capacity checks, purchase/reclaim confirmations and Solaris economy. Actions are owner-bound, +expire after two minutes, accept only one selection and become invalid when a new menu opens. +Bedrock responses schedule gameplay actions on the Bukkit thread. The shared layer does not +shade or duplicate Geyser, Floodgate, ViaVersion or Cumulus APIs. + +The existing DuneNPC/admin-only inventory interfaces are outside this player-menu migration. +Older client login support still depends on the installed ViaBackwards/ViaRewind configuration; +ViaVersion by itself permits newer clients, not every older version. + +## Crossplay package + +`tools/crossplay-lock.json` pins official download URLs and SHA-256 hashes: + +* Geyser 2.12.0 build 1267 (Spigot and Velocity) +* Floodgate 2.2.5 build 141 (Spigot and Velocity) +* ViaVersion 5.12.1 (universal) + +Run `python3 tools/download-crossplay.py built-crossplay` to obtain and verify the JARs. +Upstream metadata was checked on 2026-10-21. These are pinned builds, not moving `latest` URLs. +Run `python3 tools/package-server.py` after the Gradle builds for a local all-JAR ZIP. +The actual supported Bedrock versions follow the selected Geyser release; staging must verify +that version against the production Bedrock clients before rollout. + +For a standalone Paper server: install the Spigot variants and ViaVersion in `plugins/`. +For Velocity: install Geyser-Velocity and Floodgate-Velocity on the proxy; install +Floodgate-Spigot and ViaVersion on every Paper backend. Do not also install Geyser-Spigot +behind a proxy running Geyser. Do not install ViaVersion at both proxy and backend layers. +Retain existing ViaBackwards/ViaRewind plugins if used. + +For backend forms, enable `send-floodgate-data` on the proxy and use the same Floodgate +`key.pem` on the proxy and backends. Keep that private key out of Git and ZIPs. +Set Geyser's `auth-type` to `floodgate`, retain existing UUID/link settings, and keep backend +ports protected. Do not regenerate keys, forwarding secrets or player UUID settings during an upgrade. + +GitHub build.yml publishes **DuneRealms-All-Server-Jars.zip**, containing every Dune plugin, +Vault and the platform-specific crossplay plugins together, plus the lock manifest and instructions. +The network workflow puts the appropriate JARs into each server directory and includes the lobby +plugin only on the Spacing Guild backend. Paper/Velocity engine executables are obtained separately; +this package contains server **plugin** JARs. + +## Minimal essentials + +`/duneess` and `/essentials` open **DuneRealms Essentials**. The existing `/duneess help`, +economy, trade, administration, spice sale and travel commands continue to work. + +* `/sethome [name]`, `/home [name]`, `/delhome [name]`, `/homes` +* `/tpa `, `/tpaccept`, `/tpdeny` (60-second consent requests) +* `/spawn` for the current world +* `/server [planet]` for the existing paid Guild server travel + +Permission: `duneess.basics` (default true); default home limit: three, configurable through +`essentials.max-homes`. Homes persist atomically in `plugins/DuneEss/homes.yml`, keyed by UUID. +They are local to the backend, not synchronized across the proxy. Player requests and home/spawn +teleports remain within the current world, so they cannot bypass planet permits or fares. Use +Guild travel first, then the destination's local homes. Vanilla handles valid bed/anchor respawns; +this plugin does not overwrite existing spawn locations, beds, anchors or respawn event behavior. + +HuskHomes was evaluated as a focused alternative to EssentialsX. It supports global homes and +cross-server player teleports, but also exposes a substantially broader command surface. This +change implements a small original subset inside DuneEss; it does not embed or bundle HuskHomes. +If global homes or cross-server player-to-player teleports are wanted, that requires an explicit +shared destination/arrival design rather than bypassing the existing Guild economy. + +## Verification and rollout + +Run Gradle 8.14 `clean build` for all five modules on Java 21. The feature branch workflows +also compile/test before creating ZIPs. Unit tests cover session ownership, expiry/invalidation, +repeated selection and home-name validation, alongside the existing trading/economy tests. + +Before merging/deployment, verify on an isolated Paper 1.21.8/Velocity staging copy: + +1. Java 1.21.8 dialogs, supported older Via client fallback, and current Bedrock forms. +2. Listing, filtered browsing, pagination, buy, reclaim, full-inventory rejection, offline database, + stale confirmation and repeated click. Compare Solaris and item counts before and after. +3. Help pagination, configured Navigator actions, fares/permits, lobby departures and proxy failure. +4. Save homes, restart, reconnect, request/accept/decline/expiry, permission denial, full home limit, + absent worlds, and vanilla death at a valid bed; test broken beds and anchors as well. +5. Compare world/config/player/database snapshots before and after; deploy only replacement JARs. + +Compilation and unit tests do not establish live Bedrock rendering or proxy transfer compatibility. diff --git a/gui-common/src/main/java/com/example/dunegui/MenuSession.java b/gui-common/src/main/java/com/example/dunegui/MenuSession.java new file mode 100644 index 00000000..210258ae --- /dev/null +++ b/gui-common/src/main/java/com/example/dunegui/MenuSession.java @@ -0,0 +1,20 @@ +package com.example.dunegui; + +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +/** One owner, one active screen, one accepted action, and a short expiry. */ +public final class MenuSession { + private static final ConcurrentHashMap CURRENT=new ConcurrentHashMap<>(); + private final UUID owner; + private final long expires; + private final AtomicBoolean used=new AtomicBoolean(); + public MenuSession(UUID owner) { this.owner=owner; expires=System.nanoTime()+Duration.ofMinutes(2).toNanos(); CURRENT.put(owner,this); } + public boolean claim(UUID actor) { + return owner.equals(actor) && System.nanoTime() actions) { + List choices = new ArrayList<>(); + List information = new ArrayList<>(); + for(int slot=0;slot choices) { + show(plugin,player,title,"",choices); + } + public static void show(JavaPlugin plugin, Player player, String title, String content, List choices) { + MenuSession session=new MenuSession(player.getUniqueId()); + Bukkit.getScheduler().runTaskLater(plugin,session::expire,2400L); + List guarded=choices.stream().map(c->new Choice(c.label(),c.description(),()-> { + if(!session.claim(player.getUniqueId())) return; + Bukkit.getScheduler().runTask(plugin,()-> { if(player.isOnline()) c.action().run(); }); + })).toList(); + if(Bukkit.getPluginManager().isPluginEnabled("floodgate") && Bedrock.isPlayer(player)) { + Bedrock.show(player,title,content,guarded); return; + } + // Dialogs were introduced with protocol 771 (Java 1.21.6). Fail closed if Via cannot identify a client. + if(protocol(player)>=771) { + List buttons=guarded.stream().map(c->ActionButton.builder(Component.text(c.label())) + .tooltip(Component.text(c.description())) + .action(DialogAction.customClick((view,audience)-> { + if(audience instanceof Player actor && actor.getUniqueId().equals(player.getUniqueId())) c.action().run(); + },ClickCallback.Options.builder().uses(1).lifetime(Duration.ofMinutes(2)).build())).build()).toList(); + player.showDialog(Dialog.create(builder->builder.empty() + .base(DialogBase.builder(Component.text(title)).body(content.isBlank()?List.of():List.of(DialogBody.plainMessage(Component.text(content)))).build()) + .type(DialogType.multiAction(buttons).build()))); + return; + } + player.sendMessage(Component.text(title+" (select an option below)")); + if(!content.isBlank()) player.sendMessage(Component.text(content)); + for(Choice choice:guarded) player.sendMessage(Component.text("["+choice.label()+"] "+choice.description()) + .clickEvent(net.kyori.adventure.text.event.ClickEvent.callback(audience->{ + if(audience instanceof Player actor && actor.getUniqueId().equals(player.getUniqueId())) choice.action().run(); + },ClickCallback.Options.builder().uses(1).lifetime(Duration.ofMinutes(2)).build()))); + } + static int protocol(Player player) { + if(Bukkit.getPluginManager().isPluginEnabled("ViaVersion")) { + try { + Class via=Class.forName("com.viaversion.viaversion.api.Via"); + Object api=via.getMethod("getAPI").invoke(null); + return (int)Class.forName("com.viaversion.viaversion.api.ViaAPI") + .getMethod("getPlayerVersion",UUID.class).invoke(api,player.getUniqueId()); + } catch(ReflectiveOperationException | LinkageError ex) { return -1; } + } + return player.getProtocolVersion(); + } + /** Loaded only when the optional Floodgate plugin is enabled. Never shades Cumulus/API classes. */ + private static final class Bedrock { + static boolean isPlayer(Player player) { return org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId()); } + static void show(Player player,String title,String content,List choices) { + var form=org.geysermc.cumulus.form.SimpleForm.builder().title(title).content(content); + for(Choice choice:choices) form.button(choice.label()+ (choice.description().isBlank()?"":"\n"+choice.description())); + form.validResultHandler(response->{ int index=response.clickedButtonId(); if(index>=0 && index