Add DuneEss economy, paged help, and Sniffer sandworms

This commit is contained in:
unimatrixgit 2026-10-13 04:48:51 +02:00
commit ef02af28b8
20 changed files with 932 additions and 376 deletions

View file

@ -1,5 +1,5 @@
name: Build DuneCore and DuneTerrain
name: Build DuneCore, DuneEss, and DuneTerrain
on:
workflow_dispatch:
@ -64,3 +64,29 @@ jobs:
name: DuneTerrain-Plugin
path: DuneTerrain/build/libs/*.jar
if-no-files-found: error
build-ess:
runs-on: ubuntu-latest
defaults:
run:
working-directory: DuneEss
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.14'
- name: Compile DuneEss
run: gradle clean build
- name: Upload compiled JAR
uses: actions/upload-artifact@v4
with:
name: DuneEss-Plugin
path: DuneEss/build/libs/*.jar
if-no-files-found: error

20
DuneEss/build.gradle.kts Normal file
View file

@ -0,0 +1,20 @@
plugins { java }
group = "com.example"
version = "1.0.0"
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("com.github.MilkBowl:VaultAPI:1.7")
implementation("org.postgresql:postgresql:42.7.4")
}
tasks.jar {
archiveBaseName.set("DuneEss")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
}
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }

View file

@ -0,0 +1 @@
rootProject.name = "DuneEss"

View file

@ -0,0 +1,244 @@
package com.example.duneess;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** DuneEss's Solaris ledger and Vault economy service. */
@SuppressWarnings("deprecation")
final class DuneEconomy implements Economy {
private final DuneEss plugin;
private final Map<UUID, Double> balances = new HashMap<>();
private final File file;
private final YamlConfiguration data;
private final boolean allowNegative;
private final String singular, plural;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
private boolean databaseEnabled;
DuneEconomy(DuneEss plugin) {
this.plugin = plugin;
this.file = new File(plugin.getDataFolder(), "balances.yml");
this.data = YamlConfiguration.loadConfiguration(file);
this.allowNegative = plugin.getConfig().getBoolean("currency.allow-negative-balances", true);
this.singular = plugin.getConfig().getString("currency.singular", "Solaris");
this.plural = plugin.getConfig().getString("currency.plural", "Solaris");
loadDatabaseSettings();
loadBalances();
}
private void loadDatabaseSettings() {
if (!plugin.getConfig().getBoolean("database.use-core-database", true)) return;
File coreConfig = new File(plugin.getDataFolder().getParentFile(), "DuneCore/config.yml");
if (!coreConfig.isFile()) return;
YamlConfiguration core = YamlConfiguration.loadConfiguration(coreConfig);
if (!core.getBoolean("database.enabled", false)) return;
jdbcUrl = core.getString("database.jdbc-url", "");
dbUser = core.getString("database.username", "");
dbPassword = core.getString("database.password", "");
databaseEnabled = !jdbcUrl.isBlank();
}
private Connection connect() throws SQLException {
return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
}
private void loadBalances() {
try { file.getParentFile().mkdirs(); } catch (Exception ignored) { }
for (String key : data.getKeys(false)) {
try { balances.put(UUID.fromString(key), money(data.getDouble(key))); }
catch (IllegalArgumentException ignored) { }
}
importLegacyFile();
if (databaseEnabled) {
try (Connection c = connect(); Statement s = c.createStatement()) {
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_economy_balances (uuid UUID PRIMARY KEY, balance NUMERIC(20,2) NOT NULL DEFAULT 0)");
boolean empty;
try (ResultSet rows = s.executeQuery("SELECT NOT EXISTS (SELECT 1 FROM dune_economy_balances)")) {
empty = rows.next() && rows.getBoolean(1);
}
if (empty) {
importLegacyDatabase(c);
importLocalBalances(c);
}
try (ResultSet rows = s.executeQuery("SELECT uuid,balance FROM dune_economy_balances")) {
while (rows.next()) balances.put(rows.getObject(1, UUID.class), money(rows.getDouble(2)));
}
} catch (SQLException ex) {
databaseEnabled = false;
plugin.getLogger().severe("Could not open the shared Solaris database; using the migrated local ledger: " + ex.getMessage());
}
}
saveLocal();
}
private void importLegacyFile() {
if (!balances.isEmpty()) return;
File old = new File(plugin.getDataFolder().getParentFile(), "DuneCore/players.yml");
if (!old.isFile()) old = new File(plugin.getDataFolder().getParentFile(), "DuneRealms/players.yml");
if (!old.isFile()) return;
YamlConfiguration legacy = YamlConfiguration.loadConfiguration(old);
for (String key : legacy.getKeys(false)) try {
UUID id = UUID.fromString(key);
if (legacy.contains(key + ".solaris")) balances.put(id, money(legacy.getDouble(key + ".solaris")));
} catch (IllegalArgumentException ignored) { }
if (!balances.isEmpty()) plugin.getLogger().info("Imported " + balances.size() + " Solaris balances from the previous Dune data file.");
}
private void importLegacyDatabase(Connection c) {
try (Statement s = c.createStatement(); ResultSet rows = s.executeQuery("SELECT uuid,solaris FROM dune_players WHERE solaris<>0")) {
try (PreparedStatement insert = c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
while (rows.next()) {
insert.setObject(1, rows.getObject(1, UUID.class));
insert.setBigDecimal(2, BigDecimal.valueOf(rows.getDouble(2)));
insert.addBatch();
}
insert.executeBatch();
}
plugin.getLogger().info("Imported legacy Solaris balances from the shared Dune player table.");
} catch (SQLException ignored) {
// Older installations may not have enabled the shared player database.
}
}
private void importLocalBalances(Connection c) {
if (balances.isEmpty()) return;
try (PreparedStatement insert = c.prepareStatement(
"INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
for (Map.Entry<UUID, Double> entry : balances.entrySet()) {
insert.setObject(1, entry.getKey());
insert.setBigDecimal(2, BigDecimal.valueOf(entry.getValue()));
insert.addBatch();
}
insert.executeBatch();
plugin.getLogger().info("Migrated local Solaris balances into the shared economy database.");
} catch (SQLException ex) {
plugin.getLogger().warning("Could not migrate local Solaris balances to PostgreSQL: " + ex.getMessage());
}
}
private static double money(double amount) {
if (!Double.isFinite(amount)) return 0;
return BigDecimal.valueOf(amount).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
private synchronized void saveLocal() {
for (Map.Entry<UUID, Double> entry : balances.entrySet()) data.set(entry.getKey().toString(), entry.getValue());
try { data.save(file); }
catch (IOException ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); }
}
private synchronized double balance(UUID id) {
if (databaseEnabled) {
try (Connection c = connect(); PreparedStatement q = c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=?")) {
q.setObject(1, id);
try (ResultSet row = q.executeQuery()) {
if (row.next()) {
double value = money(row.getDouble(1));
balances.put(id, value);
return value;
}
}
} catch (SQLException ex) { plugin.getLogger().warning("Solaris balance read failed: " + ex.getMessage()); }
}
return balances.getOrDefault(id, 0.0);
}
private synchronized void set(UUID id, double value) {
value = money(value);
balances.put(id, value);
if (databaseEnabled) {
try (Connection c = connect(); PreparedStatement q = c.prepareStatement(
"INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO UPDATE SET balance=EXCLUDED.balance")) {
q.setObject(1, id); q.setBigDecimal(2, BigDecimal.valueOf(value)); q.executeUpdate();
} catch (SQLException ex) { plugin.getLogger().severe("Solaris database save failed: " + ex.getMessage()); }
}
saveLocal();
}
synchronized void add(UUID id, double amount) { set(id, balance(id) + amount); }
synchronized void subtract(UUID id, double amount) { set(id, balance(id) - amount); }
private EconomyResponse response(double amount, double balance, EconomyResponse.ResponseType type, String message) {
return new EconomyResponse(amount, balance, type, message);
}
private EconomyResponse deposit(OfflinePlayer player, double amount) {
if (amount < 0 || !Double.isFinite(amount)) return response(amount, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
set(player.getUniqueId(), getBalance(player) + amount);
return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
}
private EconomyResponse withdraw(OfflinePlayer player, double amount) {
double current = getBalance(player);
if (amount < 0 || !Double.isFinite(amount)) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
if (!allowNegative && current < amount) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Insufficient funds.");
set(player.getUniqueId(), current - amount);
return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
}
@Override public boolean isEnabled() { return plugin.isEnabled(); }
@Override public String getName() { return "DuneEss"; }
@Override public boolean hasBankSupport() { return false; }
@Override public int fractionalDigits() { return 0; }
@Override public String format(double amount) { return String.format(java.util.Locale.US, "%,.0f %s", amount, Math.abs(amount) == 1 ? singular : plural); }
@Override public String currencyNamePlural() { return plural; }
@Override public String currencyNameSingular() { return singular; }
@Override public boolean hasAccount(String name) { return hasAccount(Bukkit.getOfflinePlayer(name)); }
@Override public boolean hasAccount(OfflinePlayer player) { return balances.containsKey(player.getUniqueId()) || player.hasPlayedBefore() || player.isOnline(); }
@Override public boolean hasAccount(String name, String world) { return hasAccount(name); }
@Override public boolean hasAccount(OfflinePlayer player, String world) { return hasAccount(player); }
@Override public double getBalance(String name) { return getBalance(Bukkit.getOfflinePlayer(name)); }
@Override public double getBalance(OfflinePlayer player) { return balance(player.getUniqueId()); }
@Override public double getBalance(String name, String world) { return getBalance(name); }
@Override public double getBalance(OfflinePlayer player, String world) { return getBalance(player); }
@Override public boolean has(String name, double amount) { return has(Bukkit.getOfflinePlayer(name), amount); }
@Override public boolean has(OfflinePlayer player, double amount) { return amount >= 0 && getBalance(player) >= amount; }
@Override public boolean has(String name, String world, double amount) { return has(name, amount); }
@Override public boolean has(OfflinePlayer player, String world, double amount) { return has(player, amount); }
@Override public EconomyResponse withdrawPlayer(String name, double amount) { return withdraw(Bukkit.getOfflinePlayer(name), amount); }
@Override public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { return withdraw(player, amount); }
@Override public EconomyResponse withdrawPlayer(String name, String world, double amount) { return withdrawPlayer(name, amount); }
@Override public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double amount) { return withdraw(player, amount); }
@Override public EconomyResponse depositPlayer(String name, double amount) { return deposit(Bukkit.getOfflinePlayer(name), amount); }
@Override public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { return deposit(player, amount); }
@Override public EconomyResponse depositPlayer(String name, String world, double amount) { return depositPlayer(name, amount); }
@Override public EconomyResponse depositPlayer(OfflinePlayer player, String world, double amount) { return deposit(player, amount); }
@Override public EconomyResponse createBank(String name, String player) { return unsupported(); }
@Override public EconomyResponse createBank(String name, OfflinePlayer player) { return unsupported(); }
@Override public EconomyResponse deleteBank(String name) { return unsupported(); }
@Override public EconomyResponse bankBalance(String name) { return unsupported(); }
@Override public EconomyResponse bankHas(String name, double amount) { return unsupported(); }
@Override public EconomyResponse bankWithdraw(String name, double amount) { return unsupported(); }
@Override public EconomyResponse bankDeposit(String name, double amount) { return unsupported(); }
@Override public EconomyResponse isBankOwner(String name, String player) { return unsupported(); }
@Override public EconomyResponse isBankOwner(String name, OfflinePlayer player) { return unsupported(); }
@Override public EconomyResponse isBankMember(String name, String player) { return unsupported(); }
@Override public EconomyResponse isBankMember(String name, OfflinePlayer player) { return unsupported(); }
@Override public List<String> getBanks() { return new ArrayList<>(); }
@Override public boolean createPlayerAccount(String name) { return createPlayerAccount(Bukkit.getOfflinePlayer(name)); }
@Override public boolean createPlayerAccount(OfflinePlayer player) {
UUID id = player.getUniqueId();
if (!balances.containsKey(id)) set(id, money(plugin.getConfig().getDouble("currency.starting-balance", 0)));
return true;
}
@Override public boolean createPlayerAccount(String name, String world) { return createPlayerAccount(name); }
@Override public boolean createPlayerAccount(OfflinePlayer player, String world) { return createPlayerAccount(player); }
private EconomyResponse unsupported() { return response(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "DuneEss does not provide bank accounts."); }
}

View file

@ -0,0 +1,471 @@
package com.example.duneess;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.*;
public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener {
private static final List<String> PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv");
private DuneEconomy economy;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
private boolean networkEnabled;
private String localPlanet;
private NamespacedKey spiceKey;
private NamespacedKey helpPageKey, helpActionKey;
private static final String HELP_TITLE = ChatColor.DARK_RED + "Dune Field Guide";
private static final List<List<HelpEntry>> HELP_PAGES = List.of(
List.of(
new HelpEntry("/duneess balance", "Check your Solaris wallet.", Material.GOLD_INGOT),
new HelpEntry("/duneess sell", "Sell all tagged spice in your inventory.", Material.ORANGE_DYE),
new HelpEntry("/duneess travel", "Open the Spacing Guild planet selector.", Material.ENDER_PEARL),
new HelpEntry("/duneess travel arrakis", "Pay the fare and travel to Arrakis.", Material.MAP),
new HelpEntry("/dune", "Open the Dune Navigator menu.", Material.NETHER_STAR)
),
List.of(
new HelpEntry("/dune choose fremen", "Choose Fremen; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER),
new HelpEntry("/dune kit", "Receive your faction stillsuit and spice shovel.", Material.NETHERITE_SHOVEL),
new HelpEntry("/dune elytra", "Upgrade a worn stillsuit chestplate with an Elytra.", Material.ELYTRA),
new HelpEntry("/dune politics status", "View the Spacing Trust, leaders, and imperial appointments.", Material.WRITABLE_BOOK),
new HelpEntry("/dune water status", "View your Arrakis water-trading career.", Material.WATER_BUCKET)
),
List.of(
new HelpEntry("/dune serverjobs", "Browse hourly CHOAM spice contracts.", Material.EMERALD),
new HelpEntry("/dune job", "Browse player-posted spice contracts.", Material.BOOK),
new HelpEntry("/dune job post 100", "Post a 100-spice contract; change the amount to suit your listing.", Material.PAPER),
new HelpEntry("/dune water sell", "Sell water collected on Arrakis.", Material.BUCKET),
new HelpEntry("/dune exchange", "Open the spice exchange menu.", Material.CHEST)
),
List.of(
new HelpEntry("/duneess admin solari <player> <amount>", "Grant Solaris to an online player.", Material.GOLD_INGOT),
new HelpEntry("/duneess admin teleport arrakis", "Force yourself to Arrakis spawn.", Material.COMPASS),
new HelpEntry("/duneess admin teleport sietch", "Teleport yourself to a generated sietch.", Material.CHEST),
new HelpEntry("/duneess admin teleport spiceblow", "Teleport yourself to a generated spice blow.", Material.MAGMA_BLOCK),
new HelpEntry("/duneess admin spicebloom", "Place an untriggered bloom about 50 blocks ahead of you.", Material.GLOWSTONE),
new HelpEntry("/dune guireload", "Reload DuneCore's configurable Navigator menu.", Material.COMPARATOR)
)
);
private record HelpEntry(String command, String description, Material icon) {}
@Override public void onEnable() {
saveDefaultConfig();
loadCoreSettings();
spiceKey = new NamespacedKey("dunerealms", "item");
helpPageKey = new NamespacedKey(this, "help_page");
helpActionKey = new NamespacedKey(this, "help_action");
economy = new DuneEconomy(this);
getServer().getServicesManager().register(Economy.class, economy, this, ServicePriority.Highest);
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
PluginCommand command = Objects.requireNonNull(getCommand("duneess"));
command.setExecutor(this);
command.setTabCompleter(this);
getServer().getPluginManager().registerEvents(this, this);
for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player);
getLogger().info("DuneEss enabled as the Solaris Vault provider.");
}
@Override public void onDisable() {
getServer().getServicesManager().unregister(Economy.class, economy);
}
public Economy economy() { return economy; }
/** Free faction selection arrival, routed through DuneEss so Core owns no player-facing teleport command logic. */
public void factionArrival(Player player, String planet) {
planet = planet.toLowerCase(Locale.ROOT);
if (!PLANETS.contains(planet)) return;
if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) {
player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized.");
return;
}
if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) {
String server = getConfig().getString("network.servers." + planet, "");
if (server.isBlank()) server = YamlConfiguration.loadConfiguration(
new File(getDataFolder().getParentFile(), "DuneCore/config.yml")).getString("network.servers." + planet, "");
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
sendToServer(player, server, planet);
return;
}
World world = Bukkit.getWorld(planet);
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
if (player.teleport(world.getSpawnLocation())) {
player.sendMessage(ChatColor.AQUA + "Faction arrival: " + planet);
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
}
}
private void loadCoreSettings() {
File coreFile = new File(getDataFolder().getParentFile(), "DuneCore/config.yml");
YamlConfiguration core = YamlConfiguration.loadConfiguration(coreFile);
if (getConfig().getBoolean("database.use-core-database", true) && core.getBoolean("database.enabled", false)) {
jdbcUrl = core.getString("database.jdbc-url", "");
dbUser = core.getString("database.username", "");
dbPassword = core.getString("database.password", "");
}
boolean useCore = getConfig().getBoolean("network.use-core-settings", true);
networkEnabled = useCore ? core.getBoolean("network.enabled", getConfig().getBoolean("network.enabled", false)) : getConfig().getBoolean("network.enabled", false);
localPlanet = useCore ? core.getString("network.local-planet", getConfig().getString("network.local-planet", "arrakis")) : getConfig().getString("network.local-planet", "arrakis");
}
Connection connectEconomyDatabase() throws Exception {
if (jdbcUrl.isBlank()) throw new IllegalStateException("No shared economy database configured");
return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
int page = 1;
if (args.length > 1) try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { }
if (sender instanceof Player player) openHelpMenu(player, page);
else help(sender);
return true;
}
String root = args[0].toLowerCase(Locale.ROOT);
if (root.equals("balance")) {
Player target = args.length > 1 && sender.hasPermission("dune.admin") ? Bukkit.getPlayerExact(args[1]) : sender instanceof Player p ? p : null;
if (target == null) { sender.sendMessage("Usage: /duneess balance [online player]"); return true; }
sender.sendMessage(ChatColor.GOLD + target.getName() + " has " + economy.format(economy.getBalance(target)) + ".");
return true;
}
if (root.equals("sell")) { if (sender instanceof Player player) sellSpice(player); else sender.sendMessage("Run this command in-game."); return true; }
if (root.equals("travel")) {
if (!(sender instanceof Player player)) { sender.sendMessage("Run this command in-game."); return true; }
if (args.length == 1) { openTravelMenu(player); return true; }
travel(player, args[1]); return true;
}
if (root.equals("admin")) return admin(sender, args);
sender.sendMessage(ChatColor.YELLOW + "Use /duneess help.");
return true;
}
private void help(CommandSender sender) {
sender.sendMessage(ChatColor.GOLD + "Dune Field Guide: use /duneess help [page] in-game to browse the command pages.");
sender.sendMessage(ChatColor.GRAY + "DuneEss provides Solaris and Guild travel. DuneCore provides factions, politics, and contracts.");
}
private void openHelpMenu(Player player, int page) {
int index = Math.max(0, Math.min(HELP_PAGES.size() - 1, page - 1));
Inventory menu = Bukkit.createInventory(null, 54, HELP_TITLE + ChatColor.DARK_GRAY + " " + (index + 1) + "/" + HELP_PAGES.size());
ItemStack frame = helpItem(Material.BLACK_STAINED_GLASS_PANE, ChatColor.DARK_GRAY + " ", null);
for (int slot = 0; slot < 9; slot++) { menu.setItem(slot, frame); menu.setItem(45 + slot, frame); }
for (int row = 1; row <= 4; row++) { menu.setItem(row * 9, frame); menu.setItem(row * 9 + 8, frame); }
ItemStack heading = helpItem(Material.WRITABLE_BOOK, ChatColor.GOLD + "Dune Field Guide",
List.of(ChatColor.GRAY + "Page " + (index + 1) + " of " + HELP_PAGES.size(), ChatColor.DARK_GRAY + "Click a command to run it."));
menu.setItem(4, heading);
int[] slots = {10, 12, 14, 16, 28, 30, 32};
int n = 0;
for (HelpEntry entry : HELP_PAGES.get(index)) {
ItemStack item = helpItem(entry.icon(), ChatColor.YELLOW + entry.command(),
List.of(ChatColor.GRAY + entry.description(), ChatColor.GREEN + "Click to run"));
ItemMeta itemMeta = item.getItemMeta();
if (!entry.command().contains("<") && !entry.command().contains("["))
itemMeta.getPersistentDataContainer().set(helpActionKey, PersistentDataType.STRING, entry.command());
item.setItemMeta(itemMeta);
menu.setItem(slots[n++], item);
}
ItemStack previous = helpItem(index == 0 ? Material.GRAY_STAINED_GLASS_PANE : Material.ARROW,
ChatColor.YELLOW + "Previous page", List.of(ChatColor.GRAY + (index == 0 ? "You are on the first page." : "Go to page " + index)));
ItemMeta previousMeta = previous.getItemMeta();
previousMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index);
previous.setItemMeta(previousMeta);
menu.setItem(45, previous);
menu.setItem(49, helpItem(Material.BARRIER, ChatColor.RED + "Close", List.of(ChatColor.GRAY + "Close this guide.")));
ItemStack next = helpItem(index == HELP_PAGES.size() - 1 ? Material.GRAY_STAINED_GLASS_PANE : Material.ARROW,
ChatColor.YELLOW + "Next page", List.of(ChatColor.GRAY + (index == HELP_PAGES.size() - 1 ? "You are on the last page." : "Go to page " + (index + 2))));
ItemMeta nextMeta = next.getItemMeta();
nextMeta.getPersistentDataContainer().set(helpPageKey, PersistentDataType.INTEGER, index + 2);
next.setItemMeta(nextMeta);
menu.setItem(53, next);
player.openInventory(menu);
}
private ItemStack helpItem(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
if (lore != null) meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
@EventHandler public void onHelpMenuClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().startsWith(HELP_TITLE)) return;
event.setCancelled(true);
ItemStack clicked = event.getCurrentItem();
if (clicked == null || !clicked.hasItemMeta()) return;
ItemMeta meta = clicked.getItemMeta();
Integer page = meta.getPersistentDataContainer().get(helpPageKey, PersistentDataType.INTEGER);
if (page != null) { openHelpMenu(player, page); return; }
if (clicked.getType() == Material.BARRIER) { player.closeInventory(); return; }
String action = meta.getPersistentDataContainer().get(helpActionKey, PersistentDataType.STRING);
if (action != null) { player.closeInventory(); player.performCommand(action.substring(1)); }
}
@EventHandler public void onHelpMenuDrag(org.bukkit.event.inventory.InventoryDragEvent event) {
if (event.getView().getTitle().startsWith(HELP_TITLE)) event.setCancelled(true);
}
@EventHandler public void onPlayerJoin(PlayerJoinEvent event) {
economy.createPlayerAccount(event.getPlayer());
}
private void sellSpice(Player player) {
int amount = 0;
for (ItemStack item : player.getInventory().getStorageContents()) {
if (isSpice(item)) { amount += item.getAmount(); item.setAmount(0); }
}
if (amount == 0) { player.sendMessage(ChatColor.RED + "You have no tagged spice to sell."); return; }
int price = Math.max(1, getConfig().getInt("currency.spice-price", 15));
int gross = Math.multiplyExact(amount, price);
int net = callCoreSaleAdjustment(player, gross);
economy.depositPlayer(player, net);
player.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + economy.format(net) + ".");
}
private boolean isSpice(ItemStack item) {
return item != null && item.hasItemMeta()
&& "spice".equals(item.getItemMeta().getPersistentDataContainer().get(spiceKey, PersistentDataType.STRING));
}
private int callCoreSaleAdjustment(Player player, int gross) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return gross;
try {
Method method = core.getClass().getMethod("processSpiceSale", Player.class, int.class);
Object value = method.invoke(core, player, gross);
if (value instanceof Number n) return Math.max(0, n.intValue());
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not apply DuneCore spice trade rules: " + ex.getMessage()); }
return gross;
}
private void openTravelMenu(Player player) {
Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Spacing Guild Travel");
for (int i = 0; i < PLANETS.size(); i++) {
String planet = PLANETS.get(i);
ItemStack item = new ItemStack(Material.ENDER_PEARL);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + planet + " — " + getConfig().getInt("currency.travel-price", 100) + " Solaris");
meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet);
item.setItemMeta(meta);
inventory.setItem(i, item);
}
player.openInventory(inventory);
}
@EventHandler public void onTravelMenuClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Spacing Guild Travel")) return;
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
if (item == null || !item.hasItemMeta()) return;
String planet = item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey(this, "planet"), PersistentDataType.STRING);
if (planet == null) return;
player.closeInventory();
travel(player, planet);
}
private void travel(Player player, String planet) {
planet = planet.toLowerCase(Locale.ROOT);
if (!PLANETS.contains(planet)) { player.sendMessage(ChatColor.RED + "Unknown planet."); return; }
if (planet.equals("arrakis") && !callCoreArrakisAuthorization(player)) { player.sendMessage(ChatColor.RED + "Arrakis travel was not authorized."); return; }
if (networkEnabled && !planet.equalsIgnoreCase(localPlanet)) {
String server = getConfig().getString("network.servers." + planet, "");
if (server.isBlank()) {
YamlConfiguration core = YamlConfiguration.loadConfiguration(new File(getDataFolder().getParentFile(), "DuneCore/config.yml"));
server = core.getString("network.servers." + planet, "");
}
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare);
return;
}
World world = Bukkit.getWorld(planet);
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!player.teleport(world.getSpawnLocation())) {
if (fare > 0) economy.depositPlayer(player, fare);
player.sendMessage(ChatColor.RED + "Guild travel failed. Your fare was returned.");
} else {
player.sendMessage(ChatColor.AQUA + "Spacing Guild arrival: " + planet);
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
}
}
private boolean sendToServer(Player player, String server, String planet) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
data.writeUTF("Connect"); data.writeUTF(server);
player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray());
player.sendMessage(ChatColor.AQUA + "Spacing Guild transfer requested: " + planet);
return true;
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned.");
return false;
}
}
private boolean callCoreArrakisAuthorization(Player player) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return true;
try {
Method method = core.getClass().getMethod("authorizeArrakisTravel", Player.class);
return Boolean.TRUE.equals(method.invoke(core, player));
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not authorize Arrakis travel with DuneCore: " + ex.getMessage()); return false; }
}
private void callCoreArrakisArrival(Player player) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core == null || !core.isEnabled()) return;
try { core.getClass().getMethod("enforceArrakisArrival", Player.class).invoke(core, player); }
catch (ReflectiveOperationException ex) { getLogger().warning("Could not enforce Arrakis arrival rules: " + ex.getMessage()); }
}
private int travelFare(Player player, String planet) {
if (planet.equals("arrakis")) {
Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core != null && core.isEnabled()) try {
Method method = core.getClass().getMethod("hasFreeArrakisTravel", Player.class);
if (Boolean.TRUE.equals(method.invoke(core, player))) return 0;
} catch (ReflectiveOperationException ex) { getLogger().warning("Could not check Arrakis travel rights: " + ex.getMessage()); }
}
return Math.max(0, getConfig().getInt("currency.travel-price", 100));
}
private boolean admin(CommandSender sender, String[] args) {
if (!sender.hasPermission("dune.admin")) { sender.sendMessage(ChatColor.RED + "Admin only."); return true; }
if (args.length < 2) { sender.sendMessage("Usage: /duneess admin <solari|teleport|spicebloom> ..."); return true; }
if (args[1].equalsIgnoreCase("solari")) {
if (args.length != 4) { sender.sendMessage("Usage: /duneess admin solari <player> <amount>"); return true; }
Player target = Bukkit.getPlayerExact(args[2]);
if (target == null) { sender.sendMessage(ChatColor.RED + "That player must be online."); return true; }
try {
double amount = Double.parseDouble(args[3]);
if (amount <= 0 || !Double.isFinite(amount)) throw new NumberFormatException();
economy.depositPlayer(target, amount);
sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + ".");
target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance.");
} catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Solaris amount."); }
return true;
}
if (args[1].equalsIgnoreCase("spicebloom")) {
Player bloomTarget = args.length > 2 ? Bukkit.getPlayerExact(args[2]) : sender instanceof Player p ? p : null;
if (bloomTarget == null) { sender.sendMessage("Usage: /duneess admin spicebloom [online player]"); return true; }
World arrakisWorld = Bukkit.getWorld("arrakis");
if (arrakisWorld == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
spawnSpiceBloom(sender, bloomTarget, arrakisWorld);
return true;
}
if (!args[1].equalsIgnoreCase("teleport")) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
if (args.length < 3) { sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]"); return true; }
Player target = args.length > 3 ? Bukkit.getPlayerExact(args[3]) : sender instanceof Player p ? p : null;
if (target == null) { sender.sendMessage(ChatColor.RED + "Specify an online player from console."); return true; }
World arrakis = Bukkit.getWorld("arrakis");
if (arrakis == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server."); return true; }
switch (args[2].toLowerCase(Locale.ROOT)) {
case "arrakis" -> finishTeleport(sender, target, arrakis.getSpawnLocation(), "Arrakis spawn");
case "sietch" -> teleportToSietch(sender, target, arrakis);
case "spiceblow" -> teleportToSpiceBlow(sender, target, arrakis);
default -> sender.sendMessage("Usage: /duneess admin teleport <arrakis|sietch|spiceblow> [player]");
}
return true;
}
private void finishTeleport(CommandSender sender, Player target, Location location, String label) {
if (target.teleport(location)) { target.sendMessage(ChatColor.AQUA + "An admin sent you to " + label + "."); sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to " + label + "."); }
else sender.sendMessage(ChatColor.RED + "Teleport failed.");
}
private void teleportToSietch(CommandSender sender, Player target, World world) {
Location origin = target.getWorld().equals(world) ? target.getLocation() : world.getSpawnLocation();
for (long[] c : candidates(origin, 0x534945544348L)) {
int x=(int)c[0], z=(int)c[1];
world.getChunkAt(x >> 4, z >> 4).load(true);
int chestX=x, chestZ=z-10, estimate=world.getHighestBlockYAt(x+12,z+12);
for (int y=Math.max(world.getMinHeight()+1,estimate-80); y<=Math.min(world.getMaxHeight()-1,estimate+5); y++) {
Block b=world.getBlockAt(chestX,y,chestZ);
if (b.getType()==Material.CHEST && b.getState() instanceof org.bukkit.block.Chest chest && "Personal Sietch Cache".equals(chest.getCustomName())) {
finishTeleport(sender,target,new Location(world,x+.5,y+14,z+.5),"a sietch"); return;
}
}
}
sender.sendMessage(ChatColor.RED+"No generated sietch was found nearby. Explore new Arrakis terrain, then retry.");
}
private void teleportToSpiceBlow(CommandSender sender, Player target, World world) {
for (long[] c : candidates(target.getWorld().equals(world)?target.getLocation():world.getSpawnLocation(),0x5350494345424c4fL)) {
int x=(int)c[0],z=(int)c[1]; world.getChunkAt(x>>4,z>>4).load(true);
int top=world.getHighestBlockYAt(x,z); Material marker=world.getBlockAt(x,top,z).getType();
if(marker==Material.MAGMA_BLOCK||marker==Material.GLOWSTONE) {
int sx=x+4,sz=z+4; finishTeleport(sender,target,new Location(world,sx+.5,world.getHighestBlockYAt(sx,sz)+1,sz+.5),"a spice blow"); return;
}
}
sender.sendMessage(ChatColor.RED+"No spice blow was found nearby. Explore new Arrakis terrain, then retry.");
}
private List<long[]> candidates(Location origin,long salt) {
int spacing=2000; long gx0=Math.floorDiv(origin.getBlockX(),spacing),gz0=Math.floorDiv(origin.getBlockZ(),spacing);
List<long[]> points=new ArrayList<>();
for(long gx=gx0-2;gx<=gx0+2;gx++)for(long gz=gz0-2;gz<=gz0+2;gz++){
long h1=mix64(gx*0x9E3779B97F4A7C15L^gz*0xC2B2AE3D27D4EB4FL^salt);
long h2=mix64(gz*0x165667B19E3779F9L^gx*0x85EBCA77C2B2AE63L^~salt);
long x=gx*spacing+8+Math.floorMod(h1,spacing-16),z=gz*spacing+8+Math.floorMod(h2,spacing-16);
long dx=x-origin.getBlockX(),dz=z-origin.getBlockZ();points.add(new long[]{x,z,dx*dx+dz*dz});
}
points.sort(Comparator.comparingLong(point->point[2]));return points;
}
private static long mix64(long value){value=(value^(value>>>30))*0xBF58476D1CE4E5B9L;value=(value^(value>>>27))*0x94D049BB133111EBL;return value^(value>>>31);}
private void spawnSpiceBloom(CommandSender sender, Player target, World world) {
if(!target.getWorld().equals(world)){sender.sendMessage(ChatColor.RED+"The target must be on Arrakis.");return;}
double base=Math.toRadians(90.0-target.getLocation().getYaw()); Block center=null;
for(int offset=-12;offset<=12;offset++){
double angle=base+Math.toRadians(offset*15.0);int x=target.getLocation().getBlockX()+(int)Math.round(Math.cos(angle)*50),z=target.getLocation().getBlockZ()+(int)Math.round(Math.sin(angle)*50),y=world.getHighestBlockYAt(x,z);boolean ok=true;
for(int dx=-1;dx<=1&&ok;dx++)for(int dz=-1;dz<=1;dz++){Block b=world.getBlockAt(x+dx,y,z+dz);if((b.getType()!=Material.SAND&&b.getType()!=Material.RED_SAND)||!world.getBlockAt(x+dx,y+1,z+dz).isPassable()){ok=false;break;}}
if(ok&&world.getBlockAt(x,y+2,z).isPassable()){center=world.getBlockAt(x,y,z);break;}
}
if(center==null){sender.sendMessage(ChatColor.RED+"No clear sand patch was found 50 blocks ahead.");return;}
int x=center.getX(),y=center.getY(),z=center.getZ();for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)world.getBlockAt(x+dx,y,z+dz).setType(Material.MAGMA_BLOCK,false);world.getBlockAt(x,y+1,z).setType(Material.MAGMA_BLOCK,false);
sender.sendMessage(ChatColor.GREEN+"Placed a spice bloom near "+x+", "+z+".");target.sendMessage(ChatColor.GOLD+"A spice bloom appeared about 50 blocks ahead.");
}
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if(args.length==1)return complete(List.of("help","balance","sell","travel","admin"),args[0]);
if(args[0].equalsIgnoreCase("help")&&args.length==2)return complete(List.of("1","2","3","4"),args[1]);
if(args[0].equalsIgnoreCase("travel")&&args.length==2)return complete(PLANETS,args[1]);
if(args[0].equalsIgnoreCase("admin")&&sender.hasPermission("dune.admin")){
if(args.length==2)return complete(List.of("solari","teleport","spicebloom"),args[1]);
if(args[1].equalsIgnoreCase("teleport")&&args.length==3)return complete(List.of("arrakis","sietch","spiceblow"),args[2]);
if(args[1].equalsIgnoreCase("spicebloom")&&args.length==3)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[2]);
if((args[1].equalsIgnoreCase("teleport")||args[1].equalsIgnoreCase("solari"))&&args.length==4)return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[3]);
}
if(args[0].equalsIgnoreCase("balance")&&args.length==2&&sender.hasPermission("dune.admin"))return complete(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),args[1]);
return List.of();
}
private List<String> complete(Collection<String> options,String prefix){return options.stream().filter(s->s.toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))).sorted(String.CASE_INSENSITIVE_ORDER).toList();}
}

View file

@ -0,0 +1,20 @@
currency:
singular: Solaris
plural: Solaris
spice-price: 15
travel-price: 100
starting-balance: 0
allow-negative-balances: true
# DuneEss automatically reuses DuneCore's existing PostgreSQL settings when enabled.
# Set use-core-database to false to use local balances.yml storage instead.
database:
use-core-database: true
network:
use-core-settings: true
enabled: true
local-planet: arrakis
servers: {}
worlds: [arrakis, giedi_prime, kaitain, caladan, sigma_draconis_iv]

View file

@ -0,0 +1,15 @@
name: DuneEss
version: 1.0.0
main: com.example.duneess.DuneEss
api-version: '1.21'
depend: [Vault]
softdepend: [DuneCore, DuneTerrain]
description: Dune Solaris economy, Vault provider, spice sales, and Arrakis travel
commands:
duneess:
description: Solaris, travel, and Arrakis administration
usage: /duneess help
aliases: [dess]
permissions:
dune.admin:
default: op

View file

@ -1,20 +1,20 @@
# DuneCore for Paper 1.21.4
Requires Java 21 and Gradle 8+. Run `gradle build` and copy `build/libs/DuneCore-1.0.3.jar` into your Paper server's `plugins/` directory. DuneCore provides factions, spice gameplay, politics, jobs, and Guild travel. Install the separate `DuneTerrain` plugin to generate the server's planet world. Remove the old `DuneRealms.jar` from the Paper `plugins/` folder when upgrading to `DuneCore.jar`.
Requires Java 21 and Gradle 8+. Build each project folder separately. Install Vault, then `DuneEss`, `DuneCore`, and `DuneTerrain` into Paper's `plugins/` directory. DuneEss owns Solaris and Guild/admin travel and registers its economy through Vault; DuneCore provides factions, spice gameplay, politics, and jobs; DuneTerrain generates the planet worlds. Remove the old `DuneRealms.jar` when upgrading.
Commands: `/dune choose fremen|harkonnen|corrino|atreides|ordos`, `/dune kit`, `/dune balance`, `/dune sell`, `/dune travel`, `/dune guildnpc` (OP), `/dune givespice` (OP). Use `/dune help` for a categorized command guide with descriptions; tab completion suggests valid subcommands, factions, online players, and contract IDs.
Commands: `/dune choose fremen|harkonnen|corrino|atreides|ordos`, `/dune kit`, `/dune guildnpc` (OP), `/dune givespice` (OP), `/duneess balance`, `/duneess sell`, `/duneess travel [planet]`, and `/duneess admin ...`. Use `/dune help` or `/duneess help` for the paginated in-game guide; tab completion suggests valid subcommands, factions, online players, and contract IDs.
For proxy travel, configure `network.local-planet` for this backend and the `network.servers` proxy names. The selected world is generated by DuneTerrain, with `server.planet` in `plugins/DuneTerrain/config.yml` set to the same planet. DuneTerrain applies terrain generation only when the world is first created; existing worlds and generated chunks are not replaced. On Arrakis, defaults place cave sietches and spice blows about every 2,000 blocks, and raised darkstone islands about every 750 blocks, with broad flat sand plateaus and steep exposed blackstone and basalt sides. Sietches include a stone-arched cave entrance, sleeping and kitchen chambers, a gently winding descent to a larger reservoir with a waterfall, and a personal cache with at least 250 tagged spice, enchanted gold armor, planks, and bread. Hitting a spice blow with an arrow or trident, or touching it with a living entity, releases a rich spice field worth about 15,000 Solaris. Oasis trees remain sparse at roughly 300-block spacing. Admins can use `/dune admin sietch [player]` and `/dune admin spiceblow [player]` to teleport to the nearest generated structure, `/dune admin spicebloom [player]` or `/dune admin spiceblow spawn [player]` to place an untriggered spice bloom about 50 blocks ahead, `/dune admin arrakis [player]` to reach the Arrakis spawn, and `/dune admin solari <player> <amount>` to grant Solaris to an online player. Hostile Spice Raider husks spawn randomly on Arrakis, with an increased chance near fields worth more than 5,000 Solaris; configure them under `spice-raiders` in DuneCore's config.
For proxy travel, configure `network.local-planet` for this backend and the `network.servers` proxy names. The selected world is generated by DuneTerrain, with `server.planet` in `plugins/DuneTerrain/config.yml` set to the same planet. DuneTerrain applies terrain generation only when the world is first created; existing worlds and generated chunks are not replaced. On Arrakis, defaults place cave sietches and spice blows about every 2,000 blocks, and raised darkstone islands about every 750 blocks, with broad flat sand plateaus and steep exposed blackstone and basalt sides. Sietches include a stone-arched cave entrance, sleeping and kitchen chambers, a gently winding descent to a larger reservoir with a waterfall, and a personal cache with at least 250 tagged spice, enchanted gold armor, planks, and bread. Hitting a spice blow with an arrow or trident, or touching it with a living entity, releases a rich spice field worth about 15,000 Solaris. Oasis trees remain sparse at roughly 300-block spacing. Admins can use `/duneess admin teleport <arrakis|sietch|spiceblow> [player]` for Arrakis landmarks, `/duneess admin spicebloom [player]` to place an untriggered bloom about 50 blocks ahead, and `/duneess admin solari <player> <amount>` to grant Solaris. Hostile Haunted Fremen husks spawn on Arrakis, with an increased chance near fields worth more than 5,000 Solaris; configure them under `spice-raiders` in DuneCore's config.
Suspicious sand on Arrakis is harvestable spice. Use the tagged netherite spice shovel from `/dune kit`. Spice can be sold with `/dune sell` and Solaris spent through Guild travel. Each faction has a passive perk; Fremen harvest double spice. Player faction and balances persist in `plugins/DuneCore/players.yml`; the plugin migrates existing flat files from `plugins/DuneRealms/` on first startup after the rename.
Suspicious sand on Arrakis is harvestable spice. Use the tagged netherite spice shovel from `/dune kit`. Spice can be sold with `/duneess sell` and Solaris spent through Guild travel. Each faction has a passive perk; Fremen harvest double spice. Faction data persists in `plugins/DuneCore/players.yml`; DuneEss imports legacy balances from old Dune player files and stores them in its own balances file or shared economy table.
Limitations: this is a gameplay prototype, not a fully polished mod. Custom equipment uses vanilla items and colored names, not resource-pack models. Worlds have themed terrain, but no cities, unique buildings, or detailed biome decorations. Guild NPCs are placed by operators. No permissions-based faction change for ordinary players. The plugin has not been compiled or tested against a running Paper server in this environment.
Admins with `dune.admin` can force a local teleport to the loaded Arrakis world with `/dune admin arrakis [player]`. Omit the player name to teleport yourself. From console, specify an online player. This bypasses normal faction and proxy travel routing and requires Arrakis to be loaded on that backend.
Admins with `dune.admin` can force teleport to Arrakis or generated landmarks with `/duneess admin teleport <destination> [player]`. Omit the player name to teleport yourself. From console, specify an online player. These commands require the Arrakis world to be loaded on that backend.
## Sandworms (Shai-Hulud)
Hostile, oversized husks representing sandworms spawn on sandy surfaces near players **only on Arrakis**, at most once per hour serverwide by default. The successful spawn time is saved in the plugin config, so a restart does not reset the cooldown. They target players, have 500 health and 30 base melee attack damage (Warden-level values), and play a Warden roar when emerging. They cannot teleport to other worlds. Settings are under `sandworms` in `config.yml`. The worm is represented by a scaled vanilla husk; a true animated worm model would require a resource pack or model plugin.
Hostile oversized Sniffers representing sandworms spawn on sandy surfaces near players **only on Arrakis**, at most once per hour serverwide by default. The successful spawn time is saved in the plugin config, so a restart does not reset the cooldown. They have 500 health and 8 melee damage, and play a Warden roar when emerging. Their movement speed is 0.16: a little faster than walking, but players can outrun them by sprinting. Settings are under `sandworms` in `config.yml`. `DuneResourcePack.zip` adds a sandworm texture, haunted Fremen husk texture, and distinct spice-gold suspicious sand. Vanilla resource packs change textures, not Sniffer geometry.
## Spice contracts and sandworm blooms
- On Arrakis, defeating a sandworm generates a broad patch of suspicious-sand spice deposits with a target base harvest value of 100,000 Solaris (actual value depends on available sandy terrain and faction bonuses).

View file

@ -1,9 +1,10 @@
plugins { java }
group = "com.example"
version = "1.0.3"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") }
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("com.github.MilkBowl:VaultAPI:1.7")
implementation("org.postgresql:postgresql:42.7.4")
}
tasks.jar {

View file

@ -1,6 +1,7 @@
package com.example.dunerealms;
import org.bukkit.*;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.*;
@ -18,11 +19,10 @@ public final class ArrakisWater implements Listener {
private final DuneCore plugin;
private final NamespacedKey waterKey;
private final Map<UUID, String> careers = new HashMap<>();
private final Map<UUID,Integer> money;
private final Runnable save;
private final Economy economy;
private final Politics politics;
ArrakisWater(DuneCore plugin,Map<UUID,Integer> money,Runnable save,Politics politics) {
this.plugin=plugin;this.money=money;this.save=save;this.politics=politics;
ArrakisWater(DuneCore plugin,Economy economy,Politics politics) {
this.plugin=plugin;this.economy=economy;this.politics=politics;
waterKey=new NamespacedKey("dunerealms","finite_arrakis_water");
}
private boolean arrakis(World w){return w.getName().equalsIgnoreCase("arrakis");}
@ -81,7 +81,7 @@ public final class ArrakisWater implements Listener {
int count=0;
for(ItemStack item:p.getInventory().getStorageContents())if(tagged(item))count+=item.getAmount();
if(count==0){p.sendMessage(ChatColor.RED+"You have no collected Arrakis water buckets.");return;}
int spice=plugin.getConfig().getInt("spice-sell-price",100);
int spice=plugin.spiceSellPrice();
int base=Math.max(1,spice/2);
boolean appointed=politics.isAuthorizedWater(plugin.factionOf(p));
boolean smuggler=!appointed;
@ -92,7 +92,7 @@ public final class ArrakisWater implements Listener {
ItemStack item=p.getInventory().getItem(i);
if(tagged(item))p.getInventory().setItem(i,null);
}
money.merge(p.getUniqueId(),gross-levy,Integer::sum);save.run();
economy.depositPlayer(p,gross-levy);
p.sendMessage(ChatColor.GOLD+"Sold "+count+" water buckets for "+(gross-levy)+" Solaris (Trust levy "+levy+").");
}
@EventHandler public void onCollect(PlayerBucketFillEvent e) {
@ -100,7 +100,7 @@ public final class ArrakisWater implements Listener {
if(politics.isAuthorizedWater(plugin.factionOf(p)))return;
if(e.getBlockClicked().getRelative(e.getBlockFace()).getType()!=Material.WATER)return;
if(Math.random()>=plugin.getConfig().getDouble("arrakis-water.smuggler-retaliation-chance",0.30))return;
int spice=plugin.getConfig().getInt("spice-sell-price",100);
int spice=plugin.spiceSellPrice();
int profit=(int)Math.round(Math.max(1,spice/2)*1.45);
String world=p.getWorld().getName();
try{

View file

@ -1,6 +1,7 @@
package com.example.dunerealms;
import org.bukkit.*;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
@ -16,7 +17,7 @@ import java.util.*;
final class ConfigurableGui {
private final DuneCore plugin;
private final ServerJobs serverJobs;
private final Map<UUID,Integer> money;
private final Economy economy;
private final Map<UUID,?> jobs;
private final String[] planets, factions;
private final Map<UUID,String> selected;
@ -24,9 +25,9 @@ final class ConfigurableGui {
private final Map<UUID, String> opened = new HashMap<>();
private final Map<UUID, Map<Integer,String>> actions = new HashMap<>();
ConfigurableGui(DuneCore plugin, ServerJobs serverJobs, Map<UUID,Integer> money,
ConfigurableGui(DuneCore plugin, ServerJobs serverJobs, Economy economy,
Map<UUID,?> jobs, String[] planets, String[] factions, Map<UUID,String> selected) {
this.plugin=plugin; this.serverJobs=serverJobs; this.money=money; this.jobs=jobs;
this.plugin=plugin; this.serverJobs=serverJobs; this.economy=economy; this.jobs=jobs;
this.planets=planets; this.factions=factions; this.selected=selected;
if(!new File(plugin.getDataFolder(),"gui.yml").exists()) plugin.saveResource("gui.yml",false);
reload();
@ -35,8 +36,8 @@ final class ConfigurableGui {
private String color(String input) { return ChatColor.translateAlternateColorCodes('&',input); }
private String replace(String text, Player p) {
return color(text.replace("%player%",p.getName())
.replace("%balance%",String.valueOf(money.getOrDefault(p.getUniqueId(),0)))
.replace("%travel_cost%",String.valueOf(plugin.getConfig().getInt("travel-price",100)))
.replace("%balance%",String.valueOf((int)economy.getBalance(p)))
.replace("%travel_cost%",String.valueOf(plugin.travelPrice()))
.replace("%active_job%",serverJobs.activeDescription(p)));
}
private ItemStack item(Player p, String icon, String title, List<String> lore) {

View file

@ -1,6 +1,7 @@
package com.example.dunerealms;
import org.bukkit.*;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.block.Block;
import org.bukkit.command.*;
import org.bukkit.configuration.file.YamlConfiguration;
@ -39,14 +40,13 @@ import org.bukkit.potion.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
public final class DuneCore extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
private final String[] planets = {"arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv"};
private final String[] factions = {"Fremen", "Harkonnen", "Corrino", "Atreides", "Ordos"};
private final Map<UUID, String> selected = new HashMap<>();
private final Map<UUID, Integer> money = new HashMap<>();
private Economy economy;
private final Map<UUID, Long> wormAttackAt = new HashMap<>();
private NamespacedKey itemKey, npcKey, wormKey, armorFactionKey, raiderKey;
private File dataFile;
private final Map<UUID, Job> jobs = new HashMap<>();
@ -62,7 +62,6 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
private SharedDatabase sharedDatabase;
public SharedDatabase sharedDatabase(){return sharedDatabase;}
public String factionOf(Player player){return selected.getOrDefault(player.getUniqueId(),"");}
public Map<UUID,Integer> walletMap(){return money;}
public void persistPlayers(){savePlayers();}
private ArrakisWater arrakisWater;
@ -71,7 +70,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
saveDefaultConfig(); itemKey = new NamespacedKey("dunerealms", "item"); npcKey = new NamespacedKey("dunerealms", "guild"); wormKey = new NamespacedKey("dunerealms", "sandworm"); armorFactionKey = new NamespacedKey("dunerealms", "armor_faction"); raiderKey = new NamespacedKey("dunerealms", "spice_raider");
dataFile = new File(getDataFolder(), "players.yml"); data = YamlConfiguration.loadConfiguration(dataFile);
for (String key : data.getKeys(false)) try {
UUID id = UUID.fromString(key); selected.put(id, data.getString(key + ".faction", "")); money.put(id, data.getInt(key + ".solaris", 0));
UUID id = UUID.fromString(key); selected.put(id, data.getString(key + ".faction", ""));
} catch (IllegalArgumentException ignored) { }
for (String id : data.getConfigurationSection("jobs") == null ? Set.<String>of() : data.getConfigurationSection("jobs").getKeys(false)) {
try {
@ -81,26 +80,27 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if (quota > harvested) jobs.put(owner, new Job(owner, quota, harvested));
} catch (IllegalArgumentException ignored) {}
}
if (getConfig().getBoolean("network.enabled", true)) {
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
}
org.bukkit.plugin.RegisteredServiceProvider<Economy> economyRegistration = Bukkit.getServicesManager().getRegistration(Economy.class);
if (economyRegistration == null) { getLogger().severe("Install Vault and DuneEss before DuneCore."); getServer().getPluginManager().disablePlugin(this); return; }
economy = economyRegistration.getProvider();
if(getConfig().getBoolean("database.enabled",false)) {
try { sharedDatabase=new SharedDatabase(this); }
catch(Exception ex){getLogger().severe("Shared database required but unavailable: "+ex.getMessage());getServer().getPluginManager().disablePlugin(this);return;}
}
politics = new Politics(this, selected, money, this::savePlayers, sharedDatabase);
arrakisWater = new ArrakisWater(this,money,this::savePlayers,politics);
politics = new Politics(this, selected, economy, sharedDatabase);
arrakisWater = new ArrakisWater(this,economy,politics);
Bukkit.getPluginManager().registerEvents(arrakisWater,this);
serverJobs = new ServerJobs(this, money, this::savePlayers);
serverJobs = new ServerJobs(this, economy);
serverJobs.load();
Bukkit.getScheduler().runTaskTimer(this, this::checkArrakisSun, 20L, 20L);
Bukkit.getScheduler().runTaskTimer(this, this::applyFactionSetEffects, 20L, 20L);
gui = new ConfigurableGui(this, serverJobs, money, jobs, planets, factions, selected);
gui = new ConfigurableGui(this, serverJobs, economy, jobs, planets, factions, selected);
PluginCommand duneCommand = Objects.requireNonNull(getCommand("dune"));
duneCommand.setExecutor(this);
duneCommand.setTabCompleter(this);
Bukkit.getPluginManager().registerEvents(this, this);
Bukkit.getScheduler().runTaskTimer(this, this::spawnSandworms, 200L, 200L);
Bukkit.getScheduler().runTaskTimer(this, this::updateSandworms, 20L, 10L);
Bukkit.getScheduler().runTaskTimer(this, this::spawnSpiceRaiders, 200L, 200L);
getLogger().info("DuneCore enabled. Gameplay, faction travel, Arrakis threats, and spice raiders ready.");
}
@ -109,17 +109,14 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if(serverJobs!=null)serverJobs.save(); savePlayers();
}
private void savePlayers() {
if(sharedDatabase!=null){
for(Player player:Bukkit.getOnlinePlayers())try{sharedDatabase.savePlayer(player,selected,money);}
catch(Exception ex){getLogger().severe("Shared save failed for "+player.getName()+": "+ex.getMessage());}
if (sharedDatabase != null) {
for (Player player : Bukkit.getOnlinePlayers()) try { sharedDatabase.savePlayer(player, selected); }
catch (Exception ex) { getLogger().severe("Shared save failed for " + player.getName() + ": " + ex.getMessage()); }
return;
}
for (UUID id : money.keySet()) { data.set(id + ".solaris", money.get(id)); data.set(id + ".faction", selected.getOrDefault(id, "")); }
for (UUID id : selected.keySet()) data.set(id + ".faction", selected.getOrDefault(id, ""));
data.set("jobs", null);
for (Job job : jobs.values()) {
data.set("jobs." + job.owner() + ".quota", job.quota());
data.set("jobs." + job.owner() + ".harvested", job.harvested());
}
for (Job job : jobs.values()) { data.set("jobs." + job.owner() + ".quota", job.quota()); data.set("jobs." + job.owner() + ".harvested", job.harvested()); }
try { data.save(dataFile); } catch (IOException ex) { getLogger().warning("Cannot save players: " + ex.getMessage()); }
}
private ItemStack custom(Material material, String name, String id) {
@ -224,7 +221,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
}
private void mergeElytra(Player p) {
final int price=1_000_000;
if(money.getOrDefault(p.getUniqueId(),0)<price) {
if(!economy.has(p,price)) {
p.sendMessage(ChatColor.RED+"You need 1,000,000 Solaris."); return;
}
ItemStack chest=p.getInventory().getChestplate();
@ -249,8 +246,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
winged.setItemMeta(meta);
p.getInventory().setItem(elytraSlot,null);
p.getInventory().setChestplate(winged);
money.merge(p.getUniqueId(),-price,Integer::sum);
savePlayers();
economy.withdrawPlayer(p, price);
p.sendMessage(ChatColor.GREEN+"Elytra merged with your stillsuit! Paid 1,000,000 Solaris.");
}
private void applyFactionTrim(ItemMeta meta, String faction) {
@ -405,6 +401,12 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
private boolean emperorSanctioned(Player p,String planet) {
return planet.equalsIgnoreCase("arrakis") && politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),""));
}
public int spiceSellPrice() { org.bukkit.plugin.Plugin p=Bukkit.getPluginManager().getPlugin("DuneEss"); return p instanceof JavaPlugin j ? Math.max(1,j.getConfig().getInt("currency.spice-price",15)) : 15; }
public int travelPrice() { org.bukkit.plugin.Plugin p=Bukkit.getPluginManager().getPlugin("DuneEss"); return p instanceof JavaPlugin j ? Math.max(0,j.getConfig().getInt("currency.travel-price",100)) : 100; }
public int processSpiceSale(Player p,int gross) { if(!politics.isAuthorizedSpice(selected.getOrDefault(p.getUniqueId(),"")))reportSmuggling(p,"SPICE",gross); return Math.max(0,gross-politics.levy(p.getUniqueId(),gross)); }
public boolean hasFreeArrakisTravel(Player p) { return emperorSanctioned(p,"arrakis"); }
public boolean authorizeArrakisTravel(Player p) { if(!emperorSanctioned(p,"arrakis"))return true; if(sharedDatabase==null)return false; try{sharedDatabase.issueArrakisPermit(p.getUniqueId(),System.currentTimeMillis()+120000L);return true;}catch(java.sql.SQLException ex){getLogger().warning("Could not issue Arrakis permit: "+ex.getMessage());return false;} }
public void enforceArrakisArrival(Player player) { checkArrakisArrival(player); }
public void reportSmuggling(Player p,String commodity,int bounty) {
if(sharedDatabase==null){p.sendMessage(ChatColor.RED+"Smuggling bounty unavailable without shared PostgreSQL.");return;}
try {
@ -420,117 +422,25 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
try {
if(politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),"")))return;
if(sharedDatabase.consumeArrakisPermit(p.getUniqueId()))return;
int bounty=Math.max(1,(int)Math.round(Math.max(1,getConfig().getInt("spice-sell-price",100)/2.0)*1.45));
int bounty=Math.max(1,(int)Math.round(Math.max(1,spiceSellPrice()/2.0)*1.45));
sharedDatabase.issueBounty(p.getUniqueId(),"arrakis",bounty);
for(Player local:p.getWorld().getPlayers())local.sendMessage(ChatColor.RED+
"UNSANCTIONED ARRIVAL ON ARRAKIS: "+p.getName()+" is wanted for smuggling! Bounty: "+bounty+" Solaris.");
p.sendMessage(ChatColor.RED+"Your arrival was not sanctioned by the Emperor. You are wanted on Arrakis!");
}catch(Exception ex){getLogger().severe("Arrakis travel authorization failed: "+ex.getMessage());p.kickPlayer("Arrival authorization unavailable. Please reconnect.");}
}
private void teleport(Player p, String planet) {
if (!Arrays.asList(planets).contains(planet)) { p.sendMessage(ChatColor.RED + "Unknown planet."); return; }
if (getConfig().getBoolean("network.enabled", true)) {
String local = localPlanet();
if (planet.equals(local)) { p.sendMessage(ChatColor.YELLOW + "You are already on " + planet); return; }
String target = getConfig().getString("network.servers." + planet);
if (target == null || target.isBlank()) { p.sendMessage(ChatColor.RED + "Planet server not configured."); return; }
try {
// Only the current Steward of Dune has legal spice travel privileges.
if(emperorSanctioned(p,planet)) {
if(sharedDatabase==null){p.sendMessage(ChatColor.RED+"Emperor-sanctioned travel requires shared database.");return;}
try {
sharedDatabase.issueArrakisPermit(p.getUniqueId(), System.currentTimeMillis() + 120000L);
} catch (java.sql.SQLException ex) {
getLogger().log(java.util.logging.Level.SEVERE,
"Failed to issue Arrakis travel permit for " + p.getName(), ex);
p.sendMessage(ChatColor.RED + "Unable to authorize Arrakis travel. Please try again.");
return;
}
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream data = new DataOutputStream(bytes);
data.writeUTF("Connect"); data.writeUTF(target);
p.sendPluginMessage(this, "BungeeCord", bytes.toByteArray());
p.sendMessage(ChatColor.AQUA + "Spacing Guild transfer requested: " + planet);
} catch (IOException ex) { getLogger().warning("Proxy transfer failed: " + ex.getMessage()); }
return;
}
World w = Bukkit.getWorld(planet); if (w == null) { p.sendMessage("World unavailable."); return; }
Location arrival = w.getSpawnLocation().clone();
p.teleport(arrival);
if(planet.equals("arrakis"))Bukkit.getScheduler().runTaskLater(this,()->checkArrakisArrival(p),1L);
p.sendMessage(ChatColor.AQUA + "Spacing Guild arrival: " + planet);
}
private boolean isLocalPlanet(String planet) {
return !getConfig().getBoolean("network.enabled", true)
|| planet.equals(localPlanet());
}
private String localPlanet() {
String configured = getConfig().getString("network.local-planet", "arrakis");
if (Arrays.asList(planets).contains(configured) && Bukkit.getWorld(configured) != null) return configured;
for (String planet : planets) if (Bukkit.getWorld(planet) != null) return planet;
return configured;
}
private void travelMenu(Player p) {
Inventory inv = Bukkit.createInventory(null, 9, "Spacing Guild Travel");
for (int i = 0; i < planets.length; i++) inv.setItem(i, custom(Material.ENDER_PEARL, planets[i] + " - " + getConfig().getInt("travel-price") + " Solaris", "travel:" + planets[i]));
p.openInventory(inv);
private void factionArrival(Player p,String planet) {
org.bukkit.plugin.Plugin ess=Bukkit.getPluginManager().getPlugin("DuneEss");
if(ess==null||!ess.isEnabled()){p.sendMessage(ChatColor.RED+"DuneEss is required for faction travel.");return;}
try{ess.getClass().getMethod("factionArrival",Player.class,String.class).invoke(ess,p,planet);}catch(ReflectiveOperationException ex){getLogger().warning("Faction arrival failed: "+ex.getMessage());}
}
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length > 0 && args[0].equalsIgnoreCase("help")) {
sendHelp(sender);
if (sender instanceof Player player) Bukkit.dispatchCommand(player, "duneess help"); else sendHelp(sender);
return true;
}
if (args.length > 0 && args[0].equalsIgnoreCase("admin")) {
if (!sender.hasPermission("dune.admin")) { sender.sendMessage(ChatColor.RED + "Admin only."); return true; }
if (args.length < 2 || (!args[1].equalsIgnoreCase("arrakis") && !args[1].equalsIgnoreCase("sietch")
&& !args[1].equalsIgnoreCase("spiceblow") && !args[1].equalsIgnoreCase("spicebloom") && !args[1].equalsIgnoreCase("solari"))) {
sender.sendMessage(ChatColor.YELLOW + "Usage: /dune admin <arrakis|sietch|spiceblow [spawn]|spicebloom> [player] | solari <player> <amount>"); return true;
}
if (args[1].equalsIgnoreCase("solari")) {
if (args.length != 4) { sender.sendMessage(ChatColor.YELLOW + "Usage: /dune admin solari <player> <amount>"); return true; }
Player recipient = Bukkit.getPlayerExact(args[2]);
if (recipient == null) { sender.sendMessage(ChatColor.RED + "That player must be online."); return true; }
int amount;
try { amount = Integer.parseInt(args[3]); }
catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Amount must be a positive whole number."); return true; }
if (amount <= 0 || (long)money.getOrDefault(recipient.getUniqueId(), 0) + amount > Integer.MAX_VALUE) {
sender.sendMessage(ChatColor.RED + "Amount must be positive and the resulting balance cannot exceed the Solaris limit."); return true;
}
money.merge(recipient.getUniqueId(), amount, Integer::sum);
savePlayers();
recipient.sendMessage(ChatColor.GOLD + "An admin added " + amount + " Solaris to your balance. New balance: " + money.get(recipient.getUniqueId()) + ".");
sender.sendMessage(ChatColor.GREEN + "Added " + amount + " Solaris to " + recipient.getName() + ". Balance: " + money.get(recipient.getUniqueId()) + ".");
return true;
}
boolean spawnBloom = args[1].equalsIgnoreCase("spicebloom")
|| (args[1].equalsIgnoreCase("spiceblow") && args.length >= 3 && args[2].equalsIgnoreCase("spawn"));
int playerArg = args[1].equalsIgnoreCase("spiceblow") && args.length >= 3 && args[2].equalsIgnoreCase("spawn") ? 3 : 2;
Player target;
if (args.length > playerArg) {
target = Bukkit.getPlayerExact(args[playerArg]);
if (target == null) { sender.sendMessage(ChatColor.RED + "That player is not online."); return true; }
} else if (sender instanceof Player player) target = player;
else { sender.sendMessage(ChatColor.YELLOW + "From console, specify an online player: /dune admin spicebloom <player>"); return true; }
World arrakis = Bukkit.getWorld("arrakis");
if (arrakis == null) { sender.sendMessage(ChatColor.RED + "Arrakis is not loaded on this server. Set DuneTerrain's server.planet to arrakis and restart this backend."); return true; }
if (spawnBloom) {
spawnSpiceBloom(sender, target, arrakis);
return true;
}
if (args[1].equalsIgnoreCase("sietch")) {
teleportToNearestSietch(sender, target, arrakis);
return true;
}
if (args[1].equalsIgnoreCase("spiceblow")) {
teleportToNearestSpiceBlow(sender, target, arrakis);
return true;
}
if (target.teleport(arrakis.getSpawnLocation())) {
target.sendMessage(ChatColor.AQUA + "An admin sent you to Arrakis.");
sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to Arrakis.");
} else sender.sendMessage(ChatColor.RED + "Teleport to Arrakis failed.");
return true;
if (args.length > 0 && List.of("admin","balance","sell","travel").contains(args[0].toLowerCase(Locale.ROOT))) {
sender.sendMessage(ChatColor.YELLOW + "Solaris, Guild travel, and admin teleports are now in DuneEss. Use /duneess help."); return true;
}
if (!(sender instanceof Player p)) { sender.sendMessage("Run this command in-game."); return true; }
if (args.length == 0) { gui.open(p, "main"); return true; }
@ -541,24 +451,14 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
String match = Arrays.stream(factions).filter(f -> f.equalsIgnoreCase(choice)).findFirst().orElse(null);
if (match == null) { p.sendMessage("Unknown faction."); break; }
if (selected.containsKey(p.getUniqueId()) && !selected.get(p.getUniqueId()).isEmpty() && !p.hasPermission("dune.admin")) { p.sendMessage("Faction already selected."); break; }
selected.put(p.getUniqueId(), match); money.putIfAbsent(p.getUniqueId(), 0); savePlayers(); kit(p); teleport(p, planets[Arrays.asList(factions).indexOf(match)]);
selected.put(p.getUniqueId(), match); economy.createPlayerAccount(p); savePlayers(); kit(p); factionArrival(p, planets[Arrays.asList(factions).indexOf(match)]);
p.sendMessage(ChatColor.GREEN + "You joined " + match + "!");
}
case "elytra" -> mergeElytra(p);
case "kit" -> { if (!selected.containsKey(p.getUniqueId())) { p.sendMessage("Choose a faction first."); break; } kit(p); }
case "politics", "trust" -> politics.command(p, args);
case "water" -> arrakisWater.command(p,args);
case "balance" -> p.sendMessage(ChatColor.YELLOW + "Solaris: " + money.getOrDefault(p.getUniqueId(), 0));
case "sell" -> {
int amount = 0;
for (ItemStack stack : p.getInventory().getStorageContents()) if (is(stack, "spice")) { amount += stack.getAmount(); stack.setAmount(0); }
if(amount>0 && !politics.isAuthorizedSpice(selected.getOrDefault(p.getUniqueId(),""))) {
reportSmuggling(p,"SPICE",amount*getConfig().getInt("spice-sell-price"));
}
int gross = amount * getConfig().getInt("spice-sell-price"); int tax = politics.levy(p.getUniqueId(), gross); int earned = gross - tax; money.merge(p.getUniqueId(), earned, Integer::sum); savePlayers();
p.sendMessage(ChatColor.GOLD + "Sold " + amount + " spice for " + earned + " Solaris ("+tax+" deposited into Spacing Trust).");
}
case "travel" -> travelMenu(p);
case "balance", "sell", "travel" -> p.sendMessage(ChatColor.YELLOW + "Solaris and Guild travel moved to /duneess.");
case "menu", "gui" -> gui.open(p, "main");
case "guireload" -> { if (p.hasPermission("dune.admin")) { gui.reload(); p.sendMessage("GUI configuration reloaded."); } else p.sendMessage("Admin only."); }
case "menuitem" -> { giveMenuItem(p); p.sendMessage(ChatColor.GREEN + "Dune Navigator ready."); }
@ -588,11 +488,11 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
helpLine(sender, "/dune menuitem", "Give yourself a portable Dune Navigator item.");
helpSection(sender, "Travel");
helpLine(sender, "/dune travel", "Open the Spacing Guild planet travel menu.");
helpLine(sender, "/duneess travel [planet]", "Open Guild travel or travel to a planet.");
helpSection(sender, "Solaris and spice");
helpLine(sender, "/dune balance", "Check your Solaris balance.");
helpLine(sender, "/dune sell", "Sell tagged spice from your inventory for Solaris.");
helpLine(sender, "/duneess balance", "Check your Solaris balance.");
helpLine(sender, "/duneess sell", "Sell tagged spice from your inventory for Solaris.");
helpLine(sender, "/dune exchange", "Open the player-posted spice job exchange.");
helpSection(sender, "Politics");
@ -624,12 +524,12 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
helpLine(sender, "/dune guireload", "Reload the configurable Navigator menu.");
helpLine(sender, "/dune guildnpc", "Spawn a Spacing Guild Navigator at your location.");
helpLine(sender, "/dune givespice", "Give yourself one spice item.");
helpLine(sender, "/dune admin arrakis [player]", "Teleport a player to the loaded Arrakis spawn.");
helpLine(sender, "/dune admin sietch [player]", "Teleport a player to a generated Arrakis sietch.");
helpLine(sender, "/dune admin spiceblow [player]", "Teleport a player to the nearest generated spice blow.");
helpLine(sender, "/dune admin spicebloom [player]", "Place an untriggered spice bloom about 50 blocks ahead of a player on Arrakis.");
helpLine(sender, "/dune admin spiceblow spawn [player]", "Alias for placing a spice bloom about 50 blocks ahead.");
helpLine(sender, "/dune admin solari <player> <amount>", "Add Solaris to an online player's balance.");
helpLine(sender, "/duneess admin teleport arrakis [player]", "Teleport a player to the loaded Arrakis spawn.");
helpLine(sender, "/duneess admin teleport sietch [player]", "Teleport a player to a generated Arrakis sietch.");
helpLine(sender, "/duneess admin teleport spiceblow [player]", "Teleport a player to the nearest generated spice blow.");
helpLine(sender, "/duneess admin spicebloom [player]", "Place an untriggered spice bloom about 50 blocks ahead of a player on Arrakis.");
helpLine(sender, "/duneess admin solari <player> <amount>", "Add Solaris to an online player's balance.");
}
}
@ -646,8 +546,8 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
String root = args[0].toLowerCase(Locale.ROOT);
if (args.length == 1) {
List<String> commands = new ArrayList<>(List.of("help", "choose", "elytra", "kit", "politics", "trust", "water",
"balance", "sell", "travel", "menu", "gui", "menuitem", "exchange", "serverjobs", "job"));
if (sender.hasPermission("dune.admin")) commands.addAll(List.of("admin", "guireload", "guildnpc", "givespice"));
"menu", "gui", "menuitem", "exchange", "serverjobs", "job"));
if (sender.hasPermission("dune.admin")) commands.addAll(List.of("guireload", "guildnpc", "givespice"));
return matching(commands, args[0]);
}
@ -670,20 +570,6 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if (root.equals("job") && args.length == 2) return matching(List.of("post", "accept", "finish", "cancel"), args[1]);
if (root.equals("job") && args.length == 3 && args[1].equalsIgnoreCase("accept")) return onlinePlayerNames(args[2]);
if (root.equals("admin") && sender.hasPermission("dune.admin")) {
if (args.length == 2) return matching(List.of("arrakis", "sietch", "spiceblow", "spicebloom", "solari"), args[1]);
String action = args[1].toLowerCase(Locale.ROOT);
if (action.equals("solari") && args.length == 3) return onlinePlayerNames(args[2]);
if (action.equals("solari") && args.length == 4) return matching(List.of("100", "500", "1000", "5000"), args[3]);
if (action.equals("spiceblow") && args.length == 3) {
List<String> options = new ArrayList<>(onlinePlayerNames(args[2]));
if ("spawn".startsWith(args[2].toLowerCase(Locale.ROOT))) options.add("spawn");
return options;
}
if (action.equals("spiceblow") && args.length == 4 && args[2].equalsIgnoreCase("spawn")) return onlinePlayerNames(args[3]);
if ((action.equals("arrakis") || action.equals("sietch") || action.equals("spicebloom")) && args.length == 3)
return onlinePlayerNames(args[2]);
}
return List.of();
}
@ -697,129 +583,10 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
.distinct().sorted(String.CASE_INSENSITIVE_ORDER).toList();
}
private void teleportToNearestSietch(CommandSender sender, Player target, World arrakis) {
Location origin = target.getWorld().equals(arrakis) ? target.getLocation() : arrakis.getSpawnLocation();
int spacing = 2000;
long cellX = Math.floorDiv(origin.getBlockX(), spacing), cellZ = Math.floorDiv(origin.getBlockZ(), spacing);
List<long[]> candidates = new ArrayList<>();
for (long gx = cellX - 2; gx <= cellX + 2; gx++) for (long gz = cellZ - 2; gz <= cellZ + 2; gz++) {
long h1 = sietchMix64(gx * 0x9E3779B97F4A7C15L ^ gz * 0xC2B2AE3D27D4EB4FL ^ 0x534945544348L);
long h2 = sietchMix64(gz * 0x165667B19E3779F9L ^ gx * 0x85EBCA77C2B2AE63L ^ ~0x534945544348L);
long x = gx * spacing + 8 + Math.floorMod(h1, spacing - 16);
long z = gz * spacing + 8 + Math.floorMod(h2, spacing - 16);
long dx = x - origin.getBlockX(), dz = z - origin.getBlockZ();
candidates.add(new long[]{x, z, dx * dx + dz * dz});
}
candidates.sort(Comparator.comparingLong(candidate -> candidate[2]));
for (long[] candidate : candidates) {
int x = (int)candidate[0], z = (int)candidate[1], chestX = x, chestZ = z - 10;
arrakis.getChunkAt(x >> 4, z >> 4).load(true);
arrakis.getChunkAt(chestX >> 4, chestZ >> 4).load(true);
int estimate = arrakis.getHighestBlockYAt(x + 12, z + 12);
int low = Math.max(arrakis.getMinHeight() + 1, estimate - 80);
int high = Math.min(arrakis.getMaxHeight() - 1, estimate + 5);
for (int y = low; y <= high; y++) {
Block block = arrakis.getBlockAt(chestX, y, chestZ);
if (block.getType() != Material.CHEST || !(block.getState() instanceof org.bukkit.block.Chest chest)
|| !"Personal Sietch Cache".equals(chest.getCustomName())) continue;
Location destination = new Location(arrakis, x + 0.5, y + 14, z + 0.5);
if (target.teleport(destination)) {
target.sendMessage(ChatColor.AQUA + "An admin sent you to a sietch on Arrakis.");
sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to a sietch cache at " + x + ", " + z + ".");
} else sender.sendMessage(ChatColor.RED + "Teleport to the sietch failed.");
return;
}
}
sender.sendMessage(ChatColor.RED + "No generated sietch was found nearby. Explore new Arrakis terrain with DuneTerrain enabled, then try again.");
}
private static long sietchMix64(long value) {
value = (value ^ (value >>> 30)) * 0xBF58476D1CE4E5B9L;
value = (value ^ (value >>> 27)) * 0x94D049BB133111EBL;
return value ^ (value >>> 31);
}
private void teleportToNearestSpiceBlow(CommandSender sender, Player target, World arrakis) {
Location origin = target.getWorld().equals(arrakis) ? target.getLocation() : arrakis.getSpawnLocation();
int spacing = 2000;
long cellX = Math.floorDiv(origin.getBlockX(), spacing), cellZ = Math.floorDiv(origin.getBlockZ(), spacing);
List<long[]> candidates = new ArrayList<>();
long salt = 0x5350494345424c4fL;
for (long gx = cellX - 2; gx <= cellX + 2; gx++) for (long gz = cellZ - 2; gz <= cellZ + 2; gz++) {
long h1 = sietchMix64(gx * 0x9E3779B97F4A7C15L ^ gz * 0xC2B2AE3D27D4EB4FL ^ salt);
long h2 = sietchMix64(gz * 0x165667B19E3779F9L ^ gx * 0x85EBCA77C2B2AE63L ^ ~salt);
long x = gx * spacing + 8 + Math.floorMod(h1, spacing - 16);
long z = gz * spacing + 8 + Math.floorMod(h2, spacing - 16);
long dx = x - origin.getBlockX(), dz = z - origin.getBlockZ();
candidates.add(new long[]{x, z, dx * dx + dz * dz});
}
candidates.sort(Comparator.comparingLong(candidate -> candidate[2]));
for (long[] candidate : candidates) {
int x = (int)candidate[0], z = (int)candidate[1];
arrakis.getChunkAt(x >> 4, z >> 4).load(true);
int top = arrakis.getHighestBlockYAt(x, z);
Material marker = arrakis.getBlockAt(x, top, z).getType();
if (marker != Material.MAGMA_BLOCK && marker != Material.GLOWSTONE) continue;
int safeX = x + 4, safeZ = z + 4;
int safeY = arrakis.getHighestBlockYAt(safeX, safeZ) + 1;
if (target.teleport(new Location(arrakis, safeX + 0.5, safeY, safeZ + 0.5))) {
target.sendMessage(ChatColor.AQUA + "An admin sent you to a spice blow on Arrakis.");
sender.sendMessage(ChatColor.GREEN + "Teleported " + target.getName() + " to the nearest spice blow at " + x + ", " + z + ".");
} else sender.sendMessage(ChatColor.RED + "Teleport to the spice blow failed.");
return;
}
sender.sendMessage(ChatColor.RED + "No spice blow was found nearby. Explore new Arrakis terrain with DuneTerrain enabled, then try again.");
}
private void spawnSpiceBloom(CommandSender sender, Player target, World arrakis) {
if (!target.getWorld().equals(arrakis)) {
sender.sendMessage(ChatColor.RED + "The target player must be on Arrakis to spawn a spice bloom 50 blocks away.");
return;
}
double baseAngle = Math.toRadians(90.0 - target.getLocation().getYaw());
int originX = target.getLocation().getBlockX(), originZ = target.getLocation().getBlockZ();
Block center = null;
int[][] offsets = {{0,0},{1,0},{-1,0},{2,0},{-2,0},{3,0},{-3,0},{4,0},{-4,0},{5,0},{-5,0},{6,0},{-6,0},{7,0},{-7,0},{8,0},{-8,0},{9,0},{-9,0},{10,0},{-10,0},{11,0},{-11,0},{12,0},{-12,0}};
for (int[] offset : offsets) {
double angle = baseAngle + Math.toRadians(offset[0] * 15.0);
int x = originX + (int)Math.round(Math.cos(angle) * 50.0);
int z = originZ + (int)Math.round(Math.sin(angle) * 50.0);
int y = arrakis.getHighestBlockYAt(x, z);
boolean suitable = true;
for (int dx = -1; dx <= 1 && suitable; dx++) for (int dz = -1; dz <= 1; dz++) {
Block surface = arrakis.getBlockAt(x + dx, y, z + dz);
if ((surface.getType() != Material.SAND && surface.getType() != Material.RED_SAND)
|| !arrakis.getBlockAt(x + dx, y + 1, z + dz).isPassable()) { suitable = false; break; }
}
if (suitable && arrakis.getBlockAt(x, y + 2, z).isPassable()) {
center = arrakis.getBlockAt(x, y, z);
break;
}
}
if (center == null) {
sender.sendMessage(ChatColor.RED + "No flat, clear sand patch was found about 50 blocks in front of " + target.getName() + ".");
return;
}
int x = center.getX(), y = center.getY(), z = center.getZ();
for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++)
arrakis.getBlockAt(x + dx, y, z + dz).setType(Material.MAGMA_BLOCK, false);
arrakis.getBlockAt(x, y + 1, z).setType(Material.MAGMA_BLOCK, false);
target.sendMessage(ChatColor.GOLD + "An untriggered spice bloom was placed about 50 blocks ahead at " + x + ", " + z + ".");
sender.sendMessage(ChatColor.GREEN + "Spawned a spice bloom about 50 blocks in front of " + target.getName() + " at " + x + ", " + z + ".");
}
void runGuiCommand(Player p, String command) {
String[] args = command.trim().split("\\s+");
if (args.length == 0 || args[0].isEmpty()) return;
if (args[0].equalsIgnoreCase("travel") && args.length == 2) {
String world = args[1].toLowerCase(Locale.ROOT);
if (!Arrays.asList(planets).contains(world)) return;
int cost = (world.equals("arrakis") && politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),""))) ? 0 : getConfig().getInt("travel-price", 100);
if (money.getOrDefault(p.getUniqueId(), 0) < cost) { p.sendMessage(ChatColor.RED+"Not enough Solaris."); return; }
money.merge(p.getUniqueId(), -cost, Integer::sum);
savePlayers(); teleport(p, world); return;
}
onCommand(p, Objects.requireNonNull(getCommand("dune")), "dune", args);
void runGuiCommand(Player p,String command) {
String[] args=command.trim().split("\\s+"); if(args.length==0||args[0].isEmpty())return;
if(List.of("travel","balance","sell").contains(args[0].toLowerCase(Locale.ROOT))){Bukkit.dispatchCommand(p,"duneess "+command.trim());return;}
onCommand(p,Objects.requireNonNull(getCommand("dune")),"dune",args);
}
@EventHandler public void onGuiClick(InventoryClickEvent e) { gui.click(e); }
@EventHandler public void onGuiDrag(org.bukkit.event.inventory.InventoryDragEvent e) { gui.drag(e); }
@ -860,7 +627,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if (activeWorkers.containsValue(job.owner())) { p.sendMessage("That job is already taken."); return; }
activeWorkers.put(id, job.owner());
p.sendMessage(ChatColor.GREEN + "Job accepted! Harvest spice on Arrakis. Earnings are automatically split 15/85.");
teleport(p, "arrakis");
Bukkit.dispatchCommand(p, "duneess travel arrakis");
}
case "finish" -> {
if (activeWorkers.remove(id) == null) { p.sendMessage("No active job."); return; }
@ -871,7 +638,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
}
@EventHandler(priority=org.bukkit.event.EventPriority.LOWEST) public void loadNetworkPlayer(PlayerJoinEvent e) {
if(sharedDatabase==null)return;
try{sharedDatabase.loadPlayer(e.getPlayer(),selected,money);
try{sharedDatabase.loadPlayer(e.getPlayer(),selected);
if(getConfig().getString("network.local-planet","arrakis").equalsIgnoreCase("arrakis"))
Bukkit.getScheduler().runTaskLater(this,()->{if(e.getPlayer().isOnline())checkArrakisArrival(e.getPlayer());},5L);
}
@ -879,7 +646,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
}
@EventHandler public void onNetworkQuit(org.bukkit.event.player.PlayerQuitEvent e) {
restoreOrdosArmor(e.getPlayer().getUniqueId());
if(sharedDatabase!=null)try{sharedDatabase.savePlayer(e.getPlayer(),selected,money);}
if(sharedDatabase!=null)try{sharedDatabase.savePlayer(e.getPlayer(),selected);}
catch(Exception ex){getLogger().severe("Shared player save failed: "+ex.getMessage());}
}
@EventHandler public void onBountyKill(org.bukkit.event.entity.PlayerDeathEvent e) {
@ -887,7 +654,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if(killer==null||killer.equals(victim)||sharedDatabase==null)return;
try {
int reward=sharedDatabase.claimBounty(victim.getUniqueId(),killer.getUniqueId());
if(reward>0){money.merge(killer.getUniqueId(),reward,Integer::sum);savePlayers();
if(reward>0){economy.depositPlayer(killer,reward);
Bukkit.broadcastMessage(ChatColor.GOLD+killer.getName()+" claimed "+reward+" Solaris bounty on "+victim.getName()+"!");}
}catch(Exception ex){getLogger().warning("Bounty claim failed: "+ex.getMessage());}
}
@ -898,7 +665,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
p.sendMessage(ChatColor.GOLD + "Choose your faction with /dune choose <fremen|harkonnen|corrino|atreides>.");
}
Bukkit.getScheduler().runTask(this, () -> {
World localWorld = Bukkit.getWorld(localPlanet());
World localWorld = Bukkit.getWorld(getConfig().getString("network.local-planet", "arrakis"));
if (p.isOnline() && localWorld != null && p.getWorld().getName().equalsIgnoreCase("world")) {
p.teleport(localWorld.getSpawnLocation());
}
@ -913,17 +680,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if (w != null) e.setRespawnLocation(w.getSpawnLocation().clone());
}
@EventHandler public void onNpc(PlayerInteractEntityEvent e) {
if (e.getRightClicked().getPersistentDataContainer().has(npcKey, PersistentDataType.BYTE)) { e.setCancelled(true); travelMenu(e.getPlayer()); }
}
@EventHandler public void onMenu(InventoryClickEvent e) {
if (!e.getView().getTitle().equals("Spacing Guild Travel")) return;
e.setCancelled(true); if (!(e.getWhoClicked() instanceof Player p)) return;
ItemStack clicked = e.getCurrentItem(); if (clicked == null || !clicked.hasItemMeta()) return;
String id = clicked.getItemMeta().getPersistentDataContainer().get(itemKey, PersistentDataType.STRING);
if (id == null || !id.startsWith("travel:")) return;
String planet = id.substring(7); int cost = getConfig().getInt("travel-price");
if (money.getOrDefault(p.getUniqueId(), 0) < cost) { p.sendMessage(ChatColor.RED + "You need " + cost + " Solaris."); return; }
money.merge(p.getUniqueId(), -cost, Integer::sum); savePlayers(); p.closeInventory(); teleport(p, planet);
if (e.getRightClicked().getPersistentDataContainer().has(npcKey, PersistentDataType.BYTE)) { e.setCancelled(true); Bukkit.dispatchCommand(e.getPlayer(), "duneess travel"); }
}
@EventHandler public void onSpice(BlockBreakEvent e) {
Block block = e.getBlock();
@ -944,13 +701,13 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
if (job == null) activeWorkers.remove(p.getUniqueId());
else {
int credited = Math.min(amount, job.quota() - job.harvested());
int unitPrice = getConfig().getInt("spice-sell-price", 100);
int unitPrice = spiceSellPrice();
// Pay in whole Solaris with exact 15/85 split over accumulated earnings.
int oldValue = job.harvested() * unitPrice;
int newValue = (job.harvested() + credited) * unitPrice;
int workerPay = (int)((newValue * 15L) / 100 - (oldValue * 15L) / 100);
money.merge(p.getUniqueId(), workerPay, Integer::sum);
money.merge(sponsor, credited * unitPrice - workerPay, Integer::sum);
economy.depositPlayer(p, workerPay);
economy.depositPlayer(Bukkit.getOfflinePlayer(sponsor), credited * unitPrice - workerPay);
int progress = job.harvested() + credited;
if (progress >= job.quota()) {
jobs.remove(sponsor); activeWorkers.remove(p.getUniqueId());
@ -999,7 +756,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
ItemStack spice = custom(Material.ORANGE_DYE, "Melange Spice", "spice").asQuantity(amount);
ItemMeta meta = spice.getItemMeta();
String faction = selected.getOrDefault(miner.getUniqueId(), "Unaffiliated");
meta.setLore(List.of(ChatColor.GOLD + "Price: " + getConfig().getInt("spice-sell-price", 100) + " Solaris each",
meta.setLore(List.of(ChatColor.GOLD + "Price: " + spiceSellPrice() + " Solaris each",
ChatColor.GRAY + "Mined by: " + miner.getName() + " ; faction: " + faction));
spice.setItemMeta(meta);
return spice;
@ -1032,7 +789,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
String path = "spice-raiders.";
int radius = Math.max(8, getConfig().getInt(path + "field-radius", 24));
int valueThreshold = Math.max(1, getConfig().getInt(path + "field-value-threshold", 5000));
int price = Math.max(1, getConfig().getInt("spice-sell-price", 15));
int price = spiceSellPrice();
int required = valueThreshold / price + 1;
World world = player.getWorld();
int centerX = player.getLocation().getBlockX(), centerZ = player.getLocation().getBlockZ();
@ -1057,7 +814,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
Location spawn = new Location(world, x + 0.5, y + 1, z + 0.5);
return world.spawn(spawn, Husk.class, raider -> {
raider.getPersistentDataContainer().set(raiderKey, PersistentDataType.BYTE, (byte)1);
raider.setCustomName(ChatColor.DARK_RED + "Spice Raider");
raider.setCustomName(ChatColor.DARK_RED + "Haunted Fremen");
raider.setCustomNameVisible(true);
raider.setRemoveWhenFarAway(true);
raider.setCanPickupItems(false);
@ -1079,7 +836,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
World world = Bukkit.getWorld("arrakis");
if (world == null) return;
int max = Math.max(0, getConfig().getInt("sandworms.max-per-world", 12));
int count = (int) world.getEntitiesByClass(Husk.class).stream().filter(this::isWorm).count();
int count = (int) world.getEntitiesByClass(Sniffer.class).stream().filter(this::isWorm).count();
Random rng = java.util.concurrent.ThreadLocalRandom.current();
for (Player player : world.getPlayers()) {
if (count >= max) break;
@ -1094,19 +851,12 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
Material surface = world.getBlockAt(x, y, z).getType();
if (surface != Material.SAND && surface != Material.RED_SAND) continue;
Location location = new Location(world, x + 0.5, y + 1, z + 0.5);
Husk worm = world.spawn(location, Husk.class, h -> {
h.getPersistentDataContainer().set(wormKey, PersistentDataType.BYTE, (byte) 1);
h.setCustomName(ChatColor.GOLD + "Shai-Hulud | Sandworm");
h.setCustomNameVisible(true);
h.setRemoveWhenFarAway(true);
h.setAdult();
h.setCanPickupItems(false);
h.getAttribute(Attribute.MAX_HEALTH).setBaseValue(getConfig().getDouble("sandworms.health", 500.0));
h.setHealth(h.getAttribute(Attribute.MAX_HEALTH).getValue());
h.getAttribute(Attribute.ATTACK_DAMAGE).setBaseValue(getConfig().getDouble("sandworms.attack-damage", 30.0));
h.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(0.33);
h.getAttribute(Attribute.SCALE).setBaseValue(3.5);
h.setTarget(player);
Sniffer worm = world.spawn(location, Sniffer.class, h -> {
h.getPersistentDataContainer().set(wormKey, PersistentDataType.BYTE, (byte)1);
h.setCustomName(ChatColor.GOLD + "Shai-Hulud | Sandworm"); h.setCustomNameVisible(true); h.setRemoveWhenFarAway(true); h.setAware(true);
h.getAttribute(Attribute.MAX_HEALTH).setBaseValue(getConfig().getDouble("sandworms.health", 500.0)); h.setHealth(h.getAttribute(Attribute.MAX_HEALTH).getValue());
h.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(getConfig().getDouble("sandworms.movement-speed", 0.16));
h.getAttribute(Attribute.SCALE).setBaseValue(getConfig().getDouble("sandworms.scale", 2.8));
});
world.spawnParticle(Particle.CLOUD, location, 45, 2, 1, 2, 0.1);
world.playSound(location, Sound.ENTITY_WARDEN_ROAR, 2f, 0.6f);
@ -1116,6 +866,18 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
return;
}
}
private void updateSandworms() {
World world=Bukkit.getWorld("arrakis");if(world==null)return;
double speed=Math.max(0.55,Math.min(1.15,getConfig().getDouble("sandworms.path-speed",0.82)));
double damage=Math.max(1.0,getConfig().getDouble("sandworms.attack-damage",8.0));long cooldown=Math.max(1000L,getConfig().getLong("sandworms.attack-cooldown-ms",2200L));long now=System.currentTimeMillis();
for(Sniffer worm:world.getEntitiesByClass(Sniffer.class)){if(!isWorm(worm)||worm.isDead())continue;
Player target=world.getPlayers().stream().filter(Player::isOnline).min(Comparator.comparingDouble(p->p.getLocation().distanceSquared(worm.getLocation()))).orElse(null);
if(target==null||target.getLocation().distanceSquared(worm.getLocation())>64*64){worm.getPathfinder().stopPathfinding();continue;}
if(target.getLocation().distanceSquared(worm.getLocation())<=3.5*3.5){worm.getPathfinder().stopPathfinding();if(now>=wormAttackAt.getOrDefault(worm.getUniqueId(),0L)){target.damage(damage,worm);wormAttackAt.put(worm.getUniqueId(),now+cooldown);}}
else worm.getPathfinder().moveTo(target.getLocation(),speed);
}
}
@EventHandler public void onWormTarget(EntityTargetLivingEntityEvent e) {
if (isWorm(e.getEntity()) && (!(e.getTarget() instanceof Player) || !e.getEntity().getWorld().getName().equals("arrakis"))) e.setCancelled(true);
}
@ -1124,14 +886,14 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
}
@EventHandler public void onWormDeath(EntityDeathEvent e) {
if (isWorm(e.getEntity())) {
e.getDrops().clear(); e.setDroppedExp(0);
wormAttackAt.remove(e.getEntity().getUniqueId()); e.getDrops().clear(); e.setDroppedExp(0);
generateWormSpiceField(e.getEntity().getLocation());
}
}
private void generateWormSpiceField(Location center) {
World w = center.getWorld();
if (w == null || !w.getName().equals("arrakis")) return;
int price = Math.max(1, getConfig().getInt("spice-sell-price", 100));
int price = spiceSellPrice();
int target = Math.max(1, (int)Math.ceil(100000.0 / price));
int placed = 0;
int radius = Math.max(8, (int)Math.ceil(Math.sqrt(target / Math.PI)) + 5);

View file

@ -1,6 +1,7 @@
package com.example.dunerealms;
import org.bukkit.ChatColor;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.YamlConfiguration;
@ -18,15 +19,14 @@ import java.util.*;
public final class Politics {
private final JavaPlugin plugin;
private final Map<UUID,String> factions;
private final Map<UUID,Integer> wallets;
private final Runnable saveWallets;
private final Economy economy;
private final File file;
private final SharedDatabase database;
private final YamlConfiguration state;
private static final String[] HOUSES={"Fremen","Harkonnen","Corrino","Atreides","Ordos"};
public Politics(JavaPlugin plugin, Map<UUID,String> factions, Map<UUID,Integer> wallets, Runnable saveWallets, SharedDatabase database) {
this.plugin=plugin; this.factions=factions; this.wallets=wallets; this.saveWallets=saveWallets;this.database=database;
public Politics(JavaPlugin plugin, Map<UUID,String> factions, Economy economy, SharedDatabase database) {
this.plugin=plugin; this.factions=factions; this.economy=economy;this.database=database;
file=new File(plugin.getDataFolder(),"politics.yml");
state=YamlConfiguration.loadConfiguration(file);
refresh();
@ -92,8 +92,8 @@ public final class Politics {
if(args.length<3) {msg(p,"Usage: /dune politics deposit <solaris>");return true;}
int amount;
try {amount=Integer.parseInt(args[2]);} catch(NumberFormatException e){msg(p,"Invalid amount.");return true;}
if(amount<=0 || wallets.getOrDefault(p.getUniqueId(),0)<amount){msg(p,"Insufficient Solaris.");return true;}
wallets.merge(p.getUniqueId(),-amount,Integer::sum); saveWallets.run();
if(amount<=0 || !economy.has(p,amount)){msg(p,"Insufficient Solaris.");return true;}
economy.withdrawPlayer(p,amount);
state.set("trust",state.getLong("trust")+amount); save();
msg(p,"Deposited "+amount+" Solaris into the Spacing Trust.");return true;
}

View file

@ -17,8 +17,7 @@ final class ServerJobs {
private record Template(String id, String title, int spiceRequired, int pay, long limitSeconds) {}
private record Active(String id, long acceptedAt, int harvested) {}
private final JavaPlugin plugin;
private final Map<UUID,Integer> balances;
private final Runnable saveBalances;
private final Economy economy;
private final Map<String,Template> templates = new LinkedHashMap<>();
private final Map<UUID,Active> active = new HashMap<>();
private final File stateFile;
@ -26,8 +25,8 @@ final class ServerJobs {
private long rotationStart;
private List<String> offers = new ArrayList<>();
ServerJobs(JavaPlugin plugin, Map<UUID,Integer> balances, Runnable saveBalances) {
this.plugin=plugin; this.balances=balances; this.saveBalances=saveBalances;
ServerJobs(JavaPlugin plugin, Economy economy) {
this.plugin=plugin; this.economy=economy;
stateFile=new File(plugin.getDataFolder(),"server-jobs-state.yml");
jobsFile=new File(plugin.getDataFolder(),"server-jobs.yml");
}
@ -87,8 +86,7 @@ final class ServerJobs {
active.remove(player);
if(t==null) return;
int fine=(int)Math.ceil(t.pay()*0.05);
balances.merge(player,-fine,Integer::sum); // Negative balances represent debt.
saveBalances.run();
economy.withdrawPlayer(Bukkit.getOfflinePlayer(player),fine); // DuneEss permits contract debt.
Player online=Bukkit.getPlayer(player);
if(online!=null) online.sendMessage(ChatColor.RED+"CHOAM contract failed: "+t.title()+". Fine: "+fine+" Solaris (5% of pay).");
}
@ -102,8 +100,7 @@ final class ServerJobs {
int progress=Math.min(t.spiceRequired(),a.harvested()+amount);
if(progress>=t.spiceRequired()) {
active.remove(p.getUniqueId());
balances.merge(p.getUniqueId(),t.pay(),Integer::sum);
saveBalances.run();
economy.depositPlayer(p,t.pay());
p.sendMessage(ChatColor.GREEN+"CHOAM contract complete: "+t.title()+"! Paid "+t.pay()+" Solaris.");
} else active.put(p.getUniqueId(),new Active(a.id(),a.acceptedAt(),progress));
save();

View file

@ -42,8 +42,7 @@ public final class SharedDatabase {
public void loadPlayer(
Player p,
Map<UUID, String> factions,
Map<UUID, Integer> money
Map<UUID, String> factions
) throws Exception {
try (Connection c = connect()) {
try (PreparedStatement ins = c.prepareStatement(
@ -53,15 +52,13 @@ public final class SharedDatabase {
}
try (PreparedStatement q = c.prepareStatement(
"SELECT faction,solaris,inventory FROM dune_players WHERE uuid=?")) {
"SELECT faction,inventory FROM dune_players WHERE uuid=?")) {
q.setObject(1, p.getUniqueId());
try (ResultSet r = q.executeQuery()) {
if (r.next()) {
factions.put(p.getUniqueId(), r.getString(1));
money.put(p.getUniqueId(), r.getInt(2));
String blob = r.getString(3);
String blob = r.getString(2);
if (blob != null && !blob.isBlank()) {
ItemStack[] contents = decode(blob);
p.getInventory().setContents(contents);
@ -74,20 +71,17 @@ public final class SharedDatabase {
public void savePlayer(
Player p,
Map<UUID, String> factions,
Map<UUID, Integer> money
Map<UUID, String> factions
) throws Exception {
try (Connection c = connect(); PreparedStatement q = c.prepareStatement(
"INSERT INTO dune_players(uuid,faction,solaris,inventory) VALUES(?,?,?,?) "
"INSERT INTO dune_players(uuid,faction,inventory) VALUES(?,?,?) "
+ "ON CONFLICT(uuid) DO UPDATE SET "
+ "faction=EXCLUDED.faction,"
+ "solaris=EXCLUDED.solaris,"
+ "inventory=EXCLUDED.inventory")) {
q.setObject(1, p.getUniqueId());
q.setString(2, factions.getOrDefault(p.getUniqueId(), ""));
q.setInt(3, money.getOrDefault(p.getUniqueId(), 0));
q.setString(4, encode(p.getInventory().getContents()));
q.setString(3, encode(p.getInventory().getContents()));
q.executeUpdate();
}
}

View file

@ -1,14 +1,16 @@
spice-sell-price: 15
travel-price: 100
spice-respawn-seconds: 120
# Sandworms spawn near players on Arrakis only, at most once per interval serverwide.
# Damage 30 and health 500 approximate Warden-level threat.
# Sniffer-based worm: a little faster than walking, but slower than a sprinting player.
sandworms:
enabled: true
health: 500.0
attack-damage: 30.0
max-per-world: 12
attack-damage: 8.0
attack-cooldown-ms: 2200
movement-speed: 0.16
path-speed: 0.82
scale: 2.8
max-per-world: 3
spawn-chance: 0.35
spawn-interval-seconds: 3600

View file

@ -2,8 +2,9 @@ name: DuneCore
version: 1.0.3
main: com.example.dunerealms.DuneCore
api-version: '1.21'
depend: [Vault, DuneEss]
softdepend: [DuneTerrain]
description: Dune-inspired factions, spice economy, politics and Guild travel
description: Dune factions, Arrakis gameplay, politics, and server mechanics
commands:
dune:
description: Dune realms commands

BIN
DuneResourcePack.zip Normal file

Binary file not shown.

View file

@ -95,9 +95,9 @@ public final class DuneTerrain extends JavaPlugin implements Listener {
String path = "spice-blow.";
int targetValue = Math.max(1, getConfig().getInt(path + "target-value", 15000));
int unitPrice = Math.max(1, getConfig().getInt(path + "unit-price", 15));
org.bukkit.plugin.Plugin core = Bukkit.getPluginManager().getPlugin("DuneCore");
if (core instanceof JavaPlugin corePlugin)
unitPrice = Math.max(1, corePlugin.getConfig().getInt("spice-sell-price", unitPrice));
org.bukkit.plugin.Plugin economy = Bukkit.getPluginManager().getPlugin("DuneEss");
if (economy instanceof JavaPlugin economyPlugin)
unitPrice = Math.max(1, economyPlugin.getConfig().getInt("currency.spice-price", unitPrice));
int targetDeposits = (int)Math.ceil(targetValue / (double)unitPrice);
int radius = Math.max(12, getConfig().getInt(path + "radius", 24));
List<Block> candidates = new ArrayList<>();

View file

@ -4,3 +4,4 @@ main: com.example.duneterrain.DuneTerrain
api-version: '1.21'
load: STARTUP
description: Configurable Dune planet terrain and spawn generator for Paper
softdepend: [DuneEss]