forked from unimatrix/web
Split DuneTerrain from DuneCore
This commit is contained in:
parent
5868cfb144
commit
f25b551703
16 changed files with 419 additions and 256 deletions
30
.github/workflows/build.yml
vendored
30
.github/workflows/build.yml
vendored
|
|
@ -7,7 +7,7 @@ on:
|
|||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
build-core:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
|
|
@ -35,6 +35,32 @@ jobs:
|
|||
- name: Upload compiled JAR
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: DuneRealms-Plugin
|
||||
name: DuneCore-Plugin
|
||||
path: DuneRealms-minecraft-only/build/libs/*.jar
|
||||
if-no-files-found: error
|
||||
|
||||
build-terrain:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: DuneTerrain
|
||||
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 DuneTerrain
|
||||
run: gradle clean build
|
||||
- name: Upload compiled JAR
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: DuneTerrain-Plugin
|
||||
path: DuneTerrain/build/libs/*.jar
|
||||
if-no-files-found: error
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# DuneRealms — proxy server deployment (prototype)
|
||||
# DuneCore + DuneTerrain — proxy server deployment (prototype)
|
||||
|
||||
Five separate Paper 1.21.x backend servers connect through a **Velocity** proxy. Each backend installs the same plugin JAR and uses a different `network.local-planet` value in its `config.yml`. Configure `network.servers` with the **exact Velocity server names**. The plugin now generates only its local planet when `network.enabled: true`.
|
||||
Five separate Paper 1.21.x backend servers connect through a **Velocity** proxy. Install both `DuneCore` and `DuneTerrain` on each backend. Set `server.planet` in `plugins/DuneTerrain/config.yml` and `network.local-planet` in `plugins/DuneCore/config.yml` to the same planet on that backend. Set `network.servers` in DuneCore to the **exact Velocity server names**. DuneTerrain keeps all five planet profiles in config, but creates only the selected backend's planet world.
|
||||
|
||||
| Backend | `network.local-planet` | Velocity server name |
|
||||
| Backend | DuneTerrain `server.planet` and DuneCore `network.local-planet` | Velocity server name |
|
||||
|---|---|---|
|
||||
| Arrakis | `arrakis` | `arrakis` |
|
||||
| Giedi Prime | `giedi_prime` | `giedi-prime` |
|
||||
|
|
@ -27,8 +27,8 @@ bungee-plugin-message-channel = true
|
|||
|
||||
Enable Velocity modern forwarding and configure each Paper backend for Velocity forwarding with the same forwarding secret. Block direct external access to backend ports. Players should connect only through the proxy. Check Velocity's current documentation for the exact forwarding options on your versions.
|
||||
|
||||
The Spacing Guild menu uses the `BungeeCord` `Connect` plugin message to ask Velocity to switch servers. This is an asynchronous request **without delivery acknowledgment**. The current plugin deducts travel fare when requesting a transfer, even if the destination is offline.
|
||||
The Spacing Guild navigator is placed by DuneTerrain; DuneCore handles its click and opens the Guild menu. The menu uses the `BungeeCord` `Connect` plugin message to ask Velocity to switch servers. This is an asynchronous request **without delivery acknowledgment**. DuneCore deducts travel fare when requesting a transfer, even if the destination is offline.
|
||||
|
||||
**Critical limitation — not production ready:** `players.yml`, hourly jobs, exchange listings, balances, and inventory are currently local to each backend. They do **not** synchronize across servers. A production network needs a shared authoritative database (e.g., MariaDB/PostgreSQL), transactional fare charges and payouts, cross-server inventory/player-data synchronization, and a proxy-side first-join/homeworld router. Without these, Solaris and contracts will differ between planets, and faction homeworld routing is not reliable. Do not deploy with a live economy until shared state and transfer confirmation are implemented.
|
||||
|
||||
Sandworms and burning sun only activate in the world named `arrakis`. Server job definitions remain per-backend until centralized.
|
||||
Sandworms and burning sun only activate in the world named `arrakis`. Server job definitions remain per-backend until centralized. Existing worlds are not regenerated by changing DuneTerrain settings.
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
# DuneRealms for Paper 1.21.4
|
||||
# DuneCore for Paper 1.21.4
|
||||
|
||||
Requires Java 21 and Gradle 8+. Run `gradle build` and copy `build/libs/DuneRealms-1.0.0.jar` into your Paper server's `plugins/` directory. Restart the server. This project is source code, not a precompiled JAR.
|
||||
Requires Java 21 and Gradle 8+. Run `gradle build` and copy `build/libs/DuneCore-1.0.0.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`.
|
||||
|
||||
Commands: `/dune choose fremen|harkonnen|corrino|atreides`, `/dune kit`, `/dune balance`, `/dune sell`, `/dune travel`, `/dune guildnpc` (OP), `/dune givespice` (OP).
|
||||
|
||||
Worlds are generated on first server start: `arrakis`, `giedi_prime`, `kaitain`, `caladan`. Custom generator selection only applies when a world is first generated. Existing worlds with these names will not be replaced. For safety, back up your server before installing.
|
||||
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.
|
||||
|
||||
Red sand in Arrakis is harvestable spice. You need all four stillsuit pieces equipped and the custom netherite spice shovel in hand. Spice can be sold with `/dune sell` and Solaris spent at Guild NPCs or `/dune travel`. Each faction has a passive perk; Fremen harvest double spice. Player faction and balances persist in `plugins/DuneRealms/players.yml`.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
|
@ -15,7 +15,7 @@ Limitations: this is a gameplay prototype, not a fully polished mod. Custom equi
|
|||
Hostile, oversized husks representing sandworms spawn on sandy surfaces near players **only on Arrakis**, roughly every 10 seconds with a configurable chance. 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.
|
||||
|
||||
## Spice contracts and sandworm blooms
|
||||
- On Arrakis, defeating a sandworm generates a broad patch of red-sand spice deposits with a target base harvest value of 100,000 Solaris (actual value depends on available sandy terrain and faction bonuses).
|
||||
- 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).
|
||||
- Players begin on their faction's homeworld after choosing a faction and respawn there.
|
||||
- `/dune exchange` shows open spice contracts.
|
||||
- `/dune job post <spice quota>` creates a contract.
|
||||
|
|
@ -27,7 +27,7 @@ Hostile, oversized husks representing sandworms spawn on sandy surfaces near pla
|
|||
This is source code, not a tested compiled JAR.
|
||||
|
||||
## Hourly server-issued CHOAM jobs
|
||||
Edit `plugins/DuneRealms/server-jobs.yml` to configure job `title`, `spice-required`, `pay`, and `time-limit-minutes`. `offers-per-hour` controls how many are randomly selected. Listings rotate every hour at UTC hour boundaries. Existing accepted contracts persist through restarts, including their original deadlines; if a definition is removed while active, that contract expires without a fine.
|
||||
Edit `plugins/DuneCore/server-jobs.yml` to configure job `title`, `spice-required`, `pay`, and `time-limit-minutes`. `offers-per-hour` controls how many are randomly selected. Listings rotate every hour at UTC hour boundaries. Existing accepted contracts persist through restarts, including their original deadlines; if a definition is removed while active, that contract expires without a fine.
|
||||
|
||||
Commands: `/dune serverjobs` (list), `/dune serverjobs accept <id>` (accept), `/dune serverjobs reload` (admin; reload definitions). Harvesting spice with the stillsuit and axe advances the active server contract. Successful completion pays the configured amount. Failure after the deadline incurs a **5% fine on the configured pay**, rounded up. Fines can produce negative Solaris balances (debt). Contracts expire even while players are offline, checked every 10 seconds while the server is running.
|
||||
|
||||
|
|
@ -40,7 +40,7 @@ Server-issued contracts are separate from player-to-player exchange contracts. H
|
|||
Each joining player receives a persistent-data-tagged Nether Star named **Dune Navigator** (unless already present). Left-click or right-click while holding it in the main hand opens the main chest GUI. Interaction is cancelled to avoid accidentally hitting or activating blocks. `/dune menuitem` gives a replacement when missing; `/dune` and `/dune gui` still work. The menu item is recognized by its plugin tag, not its display name.
|
||||
|
||||
## Fully configurable GUI (`gui.yml`)
|
||||
The GUI is now configured by `plugins/DuneRealms/gui.yml`, copied from resources on first startup. Every menu has an editable title, chest size (9–54 in multiples of 9), and items with icon, slot, name, lore, and action. Use `/dune guireload` (admin) after editing. Supported actions are `open:<menu-id>`, `dune:<subcommand>`, `close`, and `none`. Arbitrary console commands are intentionally not supported. Dynamic CHOAM jobs, factions, and planets use editable `dynamic` sections, including icon, starting slot, step, lore, and action. Placeholders: `%player%`, `%balance%`, `%travel_cost%`, `%active_job%`, `%id%` (dynamic). Menu opener item continues to work with either mouse button.
|
||||
The GUI is now configured by `plugins/DuneCore/gui.yml`, copied from resources on first startup. Every menu has an editable title, chest size (9–54 in multiples of 9), and items with icon, slot, name, lore, and action. Use `/dune guireload` (admin) after editing. Supported actions are `open:<menu-id>`, `dune:<subcommand>`, `close`, and `none`. Arbitrary console commands are intentionally not supported. Dynamic CHOAM jobs, factions, and planets use editable `dynamic` sections, including icon, starting slot, step, lore, and action. Placeholders: `%player%`, `%balance%`, `%travel_cost%`, `%active_job%`, `%id%` (dynamic). Menu opener item continues to work with either mouse button.
|
||||
|
||||
NOTE: Player-to-player exchange listings can still be accepted through `/dune job accept <player>`; the configurable exchange menu currently includes configurable posting/cancel/leave controls but does not yet render dynamic player listings.
|
||||
|
||||
|
|
@ -75,7 +75,7 @@ Each newly issued leather stillsuit piece receives a distinctive vanilla smithin
|
|||
| Fremen | Orange | Dune | Lapis / blue |
|
||||
| Spacing Guild (reserved) | Black | Eye | Quartz / white |
|
||||
|
||||
Ordos now starts and respawns on its own generated planet `sigma_draconis_iv` (Sigma Draconis IV), instead of Arrakis or Caladan. The world is automatically generated using the project's existing generic world generator; custom biome/terrain styling for Sigma Draconis IV is not yet implemented. The Spacing Guild remains a non-playable faction and does not receive its own kit through normal gameplay. Existing armor is not automatically upgraded; issue a fresh kit.
|
||||
Ordos starts and respawns on its own generated planet `sigma_draconis_iv` (Sigma Draconis IV). Its dark, snowy terrain profile is configured by DuneTerrain. The Spacing Guild remains a non-playable faction and does not receive its own kit through normal gameplay. Existing armor is not automatically upgraded; issue a fresh kit.
|
||||
|
||||
The trims are Minecraft's built-in vanilla patterns, not custom resource-pack models. This source has not been compiled or tested on Paper.
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ dependencies {
|
|||
implementation("org.postgresql:postgresql:42.7.4")
|
||||
}
|
||||
tasks.jar {
|
||||
archiveBaseName.set("DuneCore")
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
from(configurations.runtimeClasspath.get().map { if(it.isDirectory) it else zipTree(it) })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
rootProject.name = "DuneRealms"
|
||||
rootProject.name = "DuneCore"
|
||||
|
|
|
|||
|
|
@ -15,15 +15,15 @@ import java.util.*;
|
|||
|
||||
/** Finite, naturally generated Arrakis water caches and two water-trading careers. */
|
||||
public final class ArrakisWater implements Listener {
|
||||
private final DuneRealms plugin;
|
||||
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 Politics politics;
|
||||
ArrakisWater(DuneRealms plugin,Map<UUID,Integer> money,Runnable save,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;
|
||||
waterKey=new NamespacedKey(plugin,"finite_arrakis_water");
|
||||
waterKey=new NamespacedKey("dunerealms","finite_arrakis_water");
|
||||
}
|
||||
private boolean arrakis(World w){return w.getName().equalsIgnoreCase("arrakis");}
|
||||
public static final class SietchPopulator extends BlockPopulator {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import java.util.*;
|
|||
|
||||
/** Data-driven chest GUI with allowlisted actions; never executes arbitrary console commands. */
|
||||
final class ConfigurableGui {
|
||||
private final DuneRealms plugin;
|
||||
private final DuneCore plugin;
|
||||
private final ServerJobs serverJobs;
|
||||
private final Map<UUID,Integer> money;
|
||||
private final Map<UUID,?> jobs;
|
||||
|
|
@ -24,7 +24,7 @@ final class ConfigurableGui {
|
|||
private final Map<UUID, String> opened = new HashMap<>();
|
||||
private final Map<UUID, Map<Integer,String>> actions = new HashMap<>();
|
||||
|
||||
ConfigurableGui(DuneRealms plugin, ServerJobs serverJobs, Map<UUID,Integer> money,
|
||||
ConfigurableGui(DuneCore plugin, ServerJobs serverJobs, Map<UUID,Integer> money,
|
||||
Map<UUID,?> jobs, String[] planets, String[] factions, Map<UUID,String> selected) {
|
||||
this.plugin=plugin; this.serverJobs=serverJobs; this.money=money; this.jobs=jobs;
|
||||
this.planets=planets; this.factions=factions; this.selected=selected;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,729 @@
|
|||
package com.example.dunerealms;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDeathEvent;
|
||||
import org.bukkit.event.entity.EntityTargetLivingEntityEvent;
|
||||
import org.bukkit.event.entity.EntityTeleportEvent;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeModifier;
|
||||
import org.bukkit.inventory.EquipmentSlotGroup;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.bukkit.inventory.meta.ArmorMeta;
|
||||
import org.bukkit.inventory.meta.trim.ArmorTrim;
|
||||
import org.bukkit.inventory.meta.trim.TrimMaterial;
|
||||
import org.bukkit.inventory.meta.trim.TrimPattern;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
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 {
|
||||
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 NamespacedKey itemKey, npcKey, wormKey, armorFactionKey;
|
||||
private File dataFile;
|
||||
private final Map<UUID, Job> jobs = new HashMap<>();
|
||||
private final Map<UUID, UUID> activeWorkers = new HashMap<>();
|
||||
private record Job(UUID owner, int quota, int harvested) {}
|
||||
private YamlConfiguration data;
|
||||
private ServerJobs serverJobs;
|
||||
private final Map<UUID, Integer> sunExposureSeconds = new HashMap<>();
|
||||
private ConfigurableGui gui;
|
||||
private Politics politics;
|
||||
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;
|
||||
|
||||
@Override public void onEnable() {
|
||||
migrateLegacyData();
|
||||
saveDefaultConfig(); itemKey = new NamespacedKey("dunerealms", "item"); npcKey = new NamespacedKey("dunerealms", "guild"); wormKey = new NamespacedKey("dunerealms", "sandworm"); armorFactionKey = new NamespacedKey("dunerealms", "armor_faction");
|
||||
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));
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
for (String id : data.getConfigurationSection("jobs") == null ? Set.<String>of() : data.getConfigurationSection("jobs").getKeys(false)) {
|
||||
try {
|
||||
UUID owner = UUID.fromString(id);
|
||||
int quota = data.getInt("jobs." + id + ".quota");
|
||||
int harvested = data.getInt("jobs." + id + ".harvested");
|
||||
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");
|
||||
}
|
||||
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);
|
||||
Bukkit.getPluginManager().registerEvents(arrakisWater,this);
|
||||
serverJobs = new ServerJobs(this, money, this::savePlayers);
|
||||
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);
|
||||
Objects.requireNonNull(getCommand("dune")).setExecutor(this);
|
||||
Bukkit.getPluginManager().registerEvents(this, this);
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::spawnSandworms, 200L, 200L);
|
||||
getLogger().info("DuneCore enabled. Gameplay, faction travel, and Arrakis sandworms ready.");
|
||||
}
|
||||
@Override public void onDisable() { 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());}
|
||||
return;
|
||||
}
|
||||
for (UUID id : money.keySet()) { data.set(id + ".solaris", money.get(id)); 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());
|
||||
}
|
||||
try { data.save(dataFile); } catch (IOException ex) { getLogger().warning("Cannot save players: " + ex.getMessage()); }
|
||||
}
|
||||
private ItemStack custom(Material material, String name, String id) {
|
||||
ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.GOLD + name); meta.getPersistentDataContainer().set(itemKey, PersistentDataType.STRING, id);
|
||||
item.setItemMeta(meta); return item;
|
||||
}
|
||||
private boolean is(ItemStack item, String id) { return item != null && item.hasItemMeta() && id.equals(item.getItemMeta().getPersistentDataContainer().get(itemKey, PersistentDataType.STRING)); }
|
||||
private ItemStack menuItem() {
|
||||
ItemStack item = custom(Material.NETHER_STAR, "Dune Navigator", "menu_opener");
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setLore(List.of(ChatColor.YELLOW + "Left or right click to open DuneCore"));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
private void giveMenuItem(Player p) {
|
||||
for (ItemStack item : p.getInventory().getContents()) if (is(item, "menu_opener")) return;
|
||||
Map<Integer, ItemStack> leftover = p.getInventory().addItem(menuItem());
|
||||
if (!leftover.isEmpty()) p.sendMessage(ChatColor.RED + "Your inventory is full. Use /dune menuitem later.");
|
||||
}
|
||||
@EventHandler public void onMenuItemUse(PlayerInteractEvent event) {
|
||||
if (event.getHand() != EquipmentSlot.HAND) return;
|
||||
Action action = event.getAction();
|
||||
if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK
|
||||
&& action != Action.LEFT_CLICK_AIR && action != Action.LEFT_CLICK_BLOCK) return;
|
||||
if (!is(event.getItem(), "menu_opener")) return;
|
||||
event.setCancelled(true);
|
||||
gui.open(event.getPlayer(), "main");
|
||||
}
|
||||
private Color factionArmorColor(String faction) {
|
||||
return switch (faction.toLowerCase(Locale.ROOT)) {
|
||||
case "harkonnen" -> Color.fromRGB(190, 35, 45);
|
||||
case "fremen" -> Color.fromRGB(235, 125, 25);
|
||||
case "ordos" -> Color.fromRGB(45, 155, 75);
|
||||
case "spacing_guild", "guild" -> Color.fromRGB(20, 20, 20);
|
||||
case "atreides" -> Color.fromRGB(45, 105, 210);
|
||||
case "corrino" -> Color.fromRGB(135, 65, 180);
|
||||
default -> Color.fromRGB(95, 83, 67);
|
||||
};
|
||||
}
|
||||
private void checkArrakisSun() {
|
||||
if (!getConfig().getBoolean("arrakis-sun.enabled", true)) return;
|
||||
int lethalSeconds = Math.max(1, getConfig().getInt("arrakis-sun.lethal-seconds", 300));
|
||||
int warningInterval = Math.max(1, getConfig().getInt("arrakis-sun.warning-interval-seconds", 30));
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
UUID id = player.getUniqueId();
|
||||
boolean exposed = player.getWorld().getName().equalsIgnoreCase("arrakis")
|
||||
&& player.getGameMode() != GameMode.CREATIVE
|
||||
&& player.getGameMode() != GameMode.SPECTATOR
|
||||
&& !player.isDead()
|
||||
&& !wearingStillsuit(player)
|
||||
&& player.getWorld().isClearWeather()
|
||||
&& player.getWorld().getTime() < 12300
|
||||
&& player.getWorld().getHighestBlockYAt(player.getLocation()) <= player.getLocation().getBlockY();
|
||||
if (!exposed) {
|
||||
// Taking shelter, reaching night, or putting on a stillsuit resets exposure.
|
||||
if (sunExposureSeconds.remove(id) != null) player.setFireTicks(0);
|
||||
continue;
|
||||
}
|
||||
int seconds = sunExposureSeconds.merge(id, 1, Integer::sum);
|
||||
// The visible burning effect is cosmetic until the exposure timer expires.
|
||||
player.setFireTicks(Math.max(player.getFireTicks(), 40));
|
||||
// Cancel fire damage from this cosmetic effect in the dedicated damage listener.
|
||||
if (seconds == 1 || seconds % warningInterval == 0) {
|
||||
player.sendMessage(ChatColor.RED + "Arrakis sun exposure: " +
|
||||
Math.max(0, lethalSeconds - seconds) + " seconds until fatal heatstroke! Find shade or wear a stillsuit.");
|
||||
}
|
||||
if (seconds >= lethalSeconds) {
|
||||
sunExposureSeconds.remove(id);
|
||||
player.setHealth(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@EventHandler public void onSunDamage(org.bukkit.event.entity.EntityDamageEvent event) {
|
||||
if (!(event.getEntity() instanceof Player player)) return;
|
||||
if (event.getCause() != org.bukkit.event.entity.EntityDamageEvent.DamageCause.FIRE_TICK) return;
|
||||
if (sunExposureSeconds.containsKey(player.getUniqueId())) event.setCancelled(true);
|
||||
}
|
||||
private void applyNetheriteStats(ItemMeta meta, String piece) {
|
||||
// Match vanilla netherite armor points, toughness and knockback resistance.
|
||||
double armor = switch(piece) {
|
||||
case "HELMET" -> 3.0;
|
||||
case "CHESTPLATE" -> 8.0;
|
||||
case "LEGGINGS" -> 6.0;
|
||||
default -> 3.0;
|
||||
};
|
||||
EquipmentSlotGroup slot = switch(piece) {
|
||||
case "HELMET" -> EquipmentSlotGroup.HEAD;
|
||||
case "CHESTPLATE" -> EquipmentSlotGroup.CHEST;
|
||||
case "LEGGINGS" -> EquipmentSlotGroup.LEGS;
|
||||
default -> EquipmentSlotGroup.FEET;
|
||||
};
|
||||
meta.addAttributeModifier(Attribute.ARMOR,
|
||||
new AttributeModifier(new NamespacedKey("dunerealms","stillsuit_armor_"+piece.toLowerCase(Locale.ROOT)),
|
||||
armor, AttributeModifier.Operation.ADD_NUMBER, slot));
|
||||
meta.addAttributeModifier(Attribute.ARMOR_TOUGHNESS,
|
||||
new AttributeModifier(new NamespacedKey("dunerealms","stillsuit_toughness_"+piece.toLowerCase(Locale.ROOT)),
|
||||
3.0, AttributeModifier.Operation.ADD_NUMBER, slot));
|
||||
meta.addAttributeModifier(Attribute.KNOCKBACK_RESISTANCE,
|
||||
new AttributeModifier(new NamespacedKey("dunerealms","stillsuit_knockback_"+piece.toLowerCase(Locale.ROOT)),
|
||||
0.1, AttributeModifier.Operation.ADD_NUMBER, slot));
|
||||
}
|
||||
private void mergeElytra(Player p) {
|
||||
final int price=1_000_000;
|
||||
if(money.getOrDefault(p.getUniqueId(),0)<price) {
|
||||
p.sendMessage(ChatColor.RED+"You need 1,000,000 Solaris."); return;
|
||||
}
|
||||
ItemStack chest=p.getInventory().getChestplate();
|
||||
if(chest==null || chest.getType()!=Material.LEATHER_CHESTPLATE || !is(chest,"stillsuit")) {
|
||||
p.sendMessage(ChatColor.RED+"Wear your faction stillsuit chestplate first."); return;
|
||||
}
|
||||
int elytraSlot=-1;
|
||||
for(int i=0;i<p.getInventory().getStorageContents().length;i++) {
|
||||
ItemStack candidate=p.getInventory().getItem(i);
|
||||
if(candidate!=null && candidate.getType()==Material.ELYTRA) { elytraSlot=i; break; }
|
||||
}
|
||||
if(elytraSlot<0) { p.sendMessage(ChatColor.RED+"Carry an Elytra in your inventory."); return; }
|
||||
ItemStack winged=new ItemStack(Material.ELYTRA);
|
||||
ItemMeta meta=winged.getItemMeta();
|
||||
String faction=selected.getOrDefault(p.getUniqueId(),"Fremen");
|
||||
meta.setDisplayName(ChatColor.GOLD+faction+" Winged Stillsuit");
|
||||
meta.setLore(List.of(ChatColor.LIGHT_PURPLE+"Elytra flight + netherite-level chest protection",
|
||||
ChatColor.GRAY+"Upgraded for 1,000,000 Solaris"));
|
||||
meta.getPersistentDataContainer().set(itemKey,PersistentDataType.STRING,"stillsuit");
|
||||
meta.getPersistentDataContainer().set(armorFactionKey,PersistentDataType.STRING,faction.toLowerCase(Locale.ROOT));
|
||||
applyNetheriteStats(meta,"CHESTPLATE");
|
||||
winged.setItemMeta(meta);
|
||||
p.getInventory().setItem(elytraSlot,null);
|
||||
p.getInventory().setChestplate(winged);
|
||||
money.merge(p.getUniqueId(),-price,Integer::sum);
|
||||
savePlayers();
|
||||
p.sendMessage(ChatColor.GREEN+"Elytra merged with your stillsuit! Paid 1,000,000 Solaris.");
|
||||
}
|
||||
private void applyFactionTrim(ItemMeta meta, String faction) {
|
||||
if (!(meta instanceof ArmorMeta armorMeta)) return;
|
||||
// One distinct vanilla trim pattern per faction, with contrasting trim colors.
|
||||
TrimPattern pattern;
|
||||
TrimMaterial material;
|
||||
switch (faction.toLowerCase(Locale.ROOT)) {
|
||||
case "harkonnen" -> { pattern = TrimPattern.RIB; material = TrimMaterial.DIAMOND; }
|
||||
case "ordos" -> { pattern = TrimPattern.SENTRY; material = TrimMaterial.REDSTONE; }
|
||||
case "atreides" -> { pattern = TrimPattern.COAST; material = TrimMaterial.COPPER; }
|
||||
case "corrino" -> { pattern = TrimPattern.SPIRE; material = TrimMaterial.GOLD; }
|
||||
case "fremen" -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; }
|
||||
case "spacing_guild", "guild" -> { pattern = TrimPattern.EYE; material = TrimMaterial.QUARTZ; }
|
||||
default -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; }
|
||||
}
|
||||
armorMeta.setTrim(new ArmorTrim(material, pattern));
|
||||
}
|
||||
private void kit(Player p) {
|
||||
String faction = selected.getOrDefault(p.getUniqueId(), "Fremen");
|
||||
Color armorColor = factionArmorColor(faction);
|
||||
ItemStack shovel=custom(Material.NETHERITE_SHOVEL,"Spice Harvest Shovel","shovel");
|
||||
shovel.addUnsafeEnchantment(Enchantment.EFFICIENCY,5);
|
||||
shovel.addUnsafeEnchantment(Enchantment.UNBREAKING,3);
|
||||
p.getInventory().addItem(shovel);
|
||||
for (Material m : new Material[]{Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS}) {
|
||||
ItemStack armor = custom(m, "Stillsuit " + m.name().toLowerCase(Locale.ROOT), "stillsuit");
|
||||
org.bukkit.inventory.meta.LeatherArmorMeta meta = (org.bukkit.inventory.meta.LeatherArmorMeta) armor.getItemMeta();
|
||||
meta.setColor(armorColor);
|
||||
meta.setDisplayName(ChatColor.GOLD + faction + " Stillsuit " + m.name().replace("LEATHER_", "").toLowerCase(Locale.ROOT));
|
||||
applyNetheriteStats(meta,m.name().replace("LEATHER_",""));
|
||||
applyFactionTrim(meta,faction);
|
||||
meta.getPersistentDataContainer().set(armorFactionKey,PersistentDataType.STRING,faction.toLowerCase(Locale.ROOT));
|
||||
if(faction.equalsIgnoreCase("Fremen")) {
|
||||
meta.addEnchant(Enchantment.UNBREAKING,3,true);
|
||||
if(m==Material.LEATHER_LEGGINGS)meta.addEnchant(Enchantment.SWIFT_SNEAK,3,true);
|
||||
}
|
||||
if(faction.equalsIgnoreCase("Corrino"))meta.addEnchant(Enchantment.PROTECTION,3,true);
|
||||
armor.setItemMeta(meta);
|
||||
p.getInventory().addItem(armor);
|
||||
}
|
||||
}
|
||||
private String fullSetFaction(Player player) {
|
||||
String faction=selected.getOrDefault(player.getUniqueId(),"").toLowerCase(Locale.ROOT);
|
||||
if(faction.isEmpty())return "";
|
||||
ItemStack[] armor=player.getInventory().getArmorContents();
|
||||
if(armor.length!=4)return "";
|
||||
for(ItemStack piece:armor) {
|
||||
if(!is(piece,"stillsuit"))return "";
|
||||
String tagged=piece.getItemMeta().getPersistentDataContainer().get(armorFactionKey,PersistentDataType.STRING);
|
||||
if(!faction.equals(tagged))return "";
|
||||
}
|
||||
// The chest slot may hold either the stillsuit chestplate or a merged winged stillsuit.
|
||||
return faction;
|
||||
}
|
||||
private void applyFactionSetEffects() {
|
||||
for(Player p:Bukkit.getOnlinePlayers()) {
|
||||
String faction=fullSetFaction(p);
|
||||
if(faction.equals("harkonnen"))
|
||||
p.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH,25,1,true,false,true));
|
||||
// No permanent potion refresh: the attribute is removed immediately when the set breaks.
|
||||
var health=p.getAttribute(Attribute.MAX_HEALTH);
|
||||
if(health!=null) {
|
||||
NamespacedKey key=new NamespacedKey("dunerealms","atreides_full_set_hearts");
|
||||
AttributeModifier existing=null;
|
||||
for(AttributeModifier modifier:health.getModifiers())
|
||||
if(modifier.getKey().equals(key)){existing=modifier;break;}
|
||||
if(existing!=null && !faction.equals("atreides")) {
|
||||
health.removeModifier(existing);
|
||||
if(p.getHealth()>health.getValue())p.setHealth(health.getValue());
|
||||
} else if(existing==null && faction.equals("atreides"))
|
||||
health.addModifier(new AttributeModifier(key,8.0,AttributeModifier.Operation.ADD_NUMBER));
|
||||
}
|
||||
}
|
||||
}
|
||||
@EventHandler public void onOrdosPearl(org.bukkit.event.player.PlayerInteractEvent e) {
|
||||
Player p=e.getPlayer();
|
||||
if(!fullSetFaction(p).equals("ordos"))return;
|
||||
if(e.getHand()!=EquipmentSlot.HAND)return;
|
||||
if(e.getAction()!=Action.RIGHT_CLICK_AIR && e.getAction()!=Action.RIGHT_CLICK_BLOCK)return;
|
||||
ItemStack held=e.getItem();
|
||||
if(held==null||held.getType()!=Material.ENDER_PEARL)return;
|
||||
// Trigger on activation; vanilla pearl throw remains intact.
|
||||
p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY,100,0,true,false,true));
|
||||
p.sendMessage(ChatColor.DARK_GREEN+"Shadow Step: invisible for five seconds.");
|
||||
}
|
||||
private boolean wearingStillsuit(Player p) {
|
||||
for (ItemStack armor : p.getInventory().getArmorContents()) if (!is(armor, "stillsuit")) return false;
|
||||
return true;
|
||||
}
|
||||
private boolean emperorSanctioned(Player p,String planet) {
|
||||
return planet.equalsIgnoreCase("arrakis") && politics.isSpiceSteward(selected.getOrDefault(p.getUniqueId(),""));
|
||||
}
|
||||
public void reportSmuggling(Player p,String commodity,int bounty) {
|
||||
if(sharedDatabase==null){p.sendMessage(ChatColor.RED+"Smuggling bounty unavailable without shared PostgreSQL.");return;}
|
||||
try {
|
||||
sharedDatabase.issueBounty(p.getUniqueId(),p.getWorld().getName(),Math.max(1,bounty));
|
||||
for(Player witness:p.getWorld().getPlayers())
|
||||
witness.sendMessage(ChatColor.RED+commodity+" SMUGGLING: "+p.getName()+
|
||||
" is wanted! Bounty: "+Math.max(1,bounty)+" Solaris.");
|
||||
}catch(Exception ex){getLogger().severe("Smuggling bounty failure: "+ex.getMessage());}
|
||||
}
|
||||
private void checkArrakisArrival(Player p) {
|
||||
if(!p.getWorld().getName().equalsIgnoreCase("arrakis"))return;
|
||||
if(sharedDatabase==null){getLogger().warning("Arrakis smuggler arrival enforcement requires PostgreSQL.");return;}
|
||||
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));
|
||||
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);
|
||||
}
|
||||
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (!(sender instanceof Player p)) { sender.sendMessage("Run this command in-game."); return true; }
|
||||
if (args.length == 0) { gui.open(p, "main"); return true; }
|
||||
if (args[0].equalsIgnoreCase("help")) {
|
||||
p.sendMessage(ChatColor.GOLD + "/dune choose <fremen|harkonnen|corrino|atreides>, kit, balance, sell, water, travel, politics, exchange, serverjobs, serverjobs accept <id>, job post <spice>, job accept <player>, job finish, guildnpc (admin)"); return true;
|
||||
}
|
||||
switch (args[0].toLowerCase(Locale.ROOT)) {
|
||||
case "choose" -> {
|
||||
if (args.length < 2) { p.sendMessage("Choose a faction name."); break; }
|
||||
String choice = args[1];
|
||||
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)]);
|
||||
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 "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."); }
|
||||
case "exchange" -> gui.open(p, "exchange");
|
||||
case "serverjobs" -> serverJobs.command(p, args);
|
||||
case "job" -> jobCommand(p, args);
|
||||
case "guildnpc" -> {
|
||||
if (!p.hasPermission("dune.admin")) { p.sendMessage("Admin only."); break; }
|
||||
Villager v = p.getWorld().spawn(p.getLocation(), Villager.class); v.setCustomName(ChatColor.LIGHT_PURPLE + "Spacing Guild Navigator"); v.setCustomNameVisible(true);
|
||||
v.setProfession(Villager.Profession.CLERIC); v.setAI(false); v.getPersistentDataContainer().set(npcKey, PersistentDataType.BYTE, (byte)1);
|
||||
}
|
||||
case "givespice" -> { if (p.hasPermission("dune.admin")) p.getInventory().addItem(spiceDrop(p, 1)); }
|
||||
default -> p.sendMessage("Use /dune help");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
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);
|
||||
}
|
||||
@EventHandler public void onGuiClick(InventoryClickEvent e) { gui.click(e); }
|
||||
@EventHandler public void onGuiDrag(org.bukkit.event.inventory.InventoryDragEvent e) { gui.drag(e); }
|
||||
private void showExchange(Player p) {
|
||||
p.sendMessage(ChatColor.GOLD + "=== Spice Exchange (15% worker / 85% sponsor) ===");
|
||||
if (jobs.isEmpty()) { p.sendMessage("No jobs listed. Use /dune job post <spice quota>."); return; }
|
||||
for (Job j : jobs.values()) {
|
||||
String name = Bukkit.getOfflinePlayer(j.owner()).getName();
|
||||
p.sendMessage(ChatColor.YELLOW.toString() + (name == null ? j.owner() : name) + ": " + (j.quota()-j.harvested()) + " spice remaining; /dune job accept " + (name == null ? j.owner() : name));
|
||||
}
|
||||
}
|
||||
private void jobCommand(Player p, String[] args) {
|
||||
if (args.length < 2) { showExchange(p); return; }
|
||||
UUID id = p.getUniqueId();
|
||||
switch (args[1].toLowerCase(Locale.ROOT)) {
|
||||
case "post" -> {
|
||||
if (args.length < 3) { p.sendMessage("/dune job post <spice quota>"); return; }
|
||||
int quota;
|
||||
try { quota = Integer.parseInt(args[2]); } catch (NumberFormatException ex) { p.sendMessage("Enter a number."); return; }
|
||||
if (quota < 1 || quota > 100000) { p.sendMessage("Quota must be 1–100000."); return; }
|
||||
if (jobs.containsKey(id)) { p.sendMessage("Finish or cancel your current listing first."); return; }
|
||||
jobs.put(id, new Job(id, quota, 0)); savePlayers();
|
||||
p.sendMessage(ChatColor.GREEN + "Exchange listing posted for " + quota + " spice.");
|
||||
}
|
||||
case "cancel" -> {
|
||||
if (!jobs.containsKey(id)) { p.sendMessage("No listing to cancel."); return; }
|
||||
if (activeWorkers.containsValue(id)) { p.sendMessage("A worker has accepted your job."); return; }
|
||||
jobs.remove(id); savePlayers(); p.sendMessage("Listing cancelled.");
|
||||
}
|
||||
case "accept" -> {
|
||||
if (activeWorkers.containsKey(id)) { p.sendMessage("You already have a job."); return; }
|
||||
if (args.length < 3) { p.sendMessage("/dune job accept <player>"); return; }
|
||||
Job job = jobs.values().stream().filter(j -> {
|
||||
String name = Bukkit.getOfflinePlayer(j.owner()).getName();
|
||||
return j.owner().toString().equalsIgnoreCase(args[2]) || (name != null && name.equalsIgnoreCase(args[2]));
|
||||
}).findFirst().orElse(null);
|
||||
if (job == null || job.owner().equals(id)) { p.sendMessage("Invalid listing."); return; }
|
||||
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");
|
||||
}
|
||||
case "finish" -> {
|
||||
if (activeWorkers.remove(id) == null) { p.sendMessage("No active job."); return; }
|
||||
p.sendMessage("You left the spice job.");
|
||||
}
|
||||
default -> showExchange(p);
|
||||
}
|
||||
}
|
||||
@EventHandler(priority=org.bukkit.event.EventPriority.LOWEST) public void loadNetworkPlayer(PlayerJoinEvent e) {
|
||||
if(sharedDatabase==null)return;
|
||||
try{sharedDatabase.loadPlayer(e.getPlayer(),selected,money);
|
||||
if(getConfig().getString("network.local-planet","arrakis").equalsIgnoreCase("arrakis"))
|
||||
Bukkit.getScheduler().runTaskLater(this,()->{if(e.getPlayer().isOnline())checkArrakisArrival(e.getPlayer());},5L);
|
||||
}
|
||||
catch(Exception ex){getLogger().severe("Shared player load failed: "+ex.getMessage());e.getPlayer().kickPlayer("Your network profile could not be loaded.");}
|
||||
}
|
||||
@EventHandler public void onNetworkQuit(org.bukkit.event.player.PlayerQuitEvent e) {
|
||||
if(sharedDatabase!=null)try{sharedDatabase.savePlayer(e.getPlayer(),selected,money);}
|
||||
catch(Exception ex){getLogger().severe("Shared player save failed: "+ex.getMessage());}
|
||||
}
|
||||
@EventHandler public void onBountyKill(org.bukkit.event.entity.PlayerDeathEvent e) {
|
||||
Player victim=e.getEntity(), killer=victim.getKiller();
|
||||
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();
|
||||
Bukkit.broadcastMessage(ChatColor.GOLD+killer.getName()+" claimed "+reward+" Solaris bounty on "+victim.getName()+"!");}
|
||||
}catch(Exception ex){getLogger().warning("Bounty claim failed: "+ex.getMessage());}
|
||||
}
|
||||
@EventHandler public void onJoin(PlayerJoinEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
Bukkit.getScheduler().runTask(this, () -> giveMenuItem(p));
|
||||
if (!selected.containsKey(p.getUniqueId()) || selected.get(p.getUniqueId()).isEmpty()) p.sendMessage(ChatColor.GOLD + "Choose your faction with /dune choose <fremen|harkonnen|corrino|atreides>.");
|
||||
else Bukkit.getScheduler().runTask(this, () -> {
|
||||
if (p.getWorld().getName().equals("world")) teleport(p, planets[Arrays.asList(factions).indexOf(selected.get(p.getUniqueId()))]);
|
||||
});
|
||||
}
|
||||
@EventHandler public void onRespawn(PlayerRespawnEvent e) {
|
||||
String faction = selected.get(e.getPlayer().getUniqueId());
|
||||
if (faction == null) return;
|
||||
int index = Arrays.asList(factions).indexOf(faction);
|
||||
if (index < 0) return;
|
||||
World w = Bukkit.getWorld(planets[index]);
|
||||
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);
|
||||
}
|
||||
@EventHandler public void onSpice(BlockBreakEvent e) {
|
||||
Block block = e.getBlock();
|
||||
if (!block.getWorld().getName().equals("arrakis") || block.getType() != Material.SUSPICIOUS_SAND) return;
|
||||
Player p = e.getPlayer();
|
||||
ItemStack held = p.getInventory().getItemInMainHand();
|
||||
if (held.getType() != Material.NETHERITE_SHOVEL || !is(held, "shovel")) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage(ChatColor.RED + "Only the Spice Harvest Shovel from /dune kit can mine a spice deposit.");
|
||||
return;
|
||||
}
|
||||
e.setDropItems(false); e.setExpToDrop(0);
|
||||
int amount = selected.getOrDefault(p.getUniqueId(), "").equals("Fremen") ? 2 : 1;
|
||||
serverJobs.harvest(p, amount);
|
||||
UUID sponsor = activeWorkers.get(p.getUniqueId());
|
||||
if (sponsor != null) {
|
||||
Job job = jobs.get(sponsor);
|
||||
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);
|
||||
// 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);
|
||||
int progress = job.harvested() + credited;
|
||||
if (progress >= job.quota()) {
|
||||
jobs.remove(sponsor); activeWorkers.remove(p.getUniqueId());
|
||||
p.sendMessage(ChatColor.GREEN + "Spice contract completed!");
|
||||
} else jobs.put(sponsor, new Job(sponsor, job.quota(), progress));
|
||||
savePlayers();
|
||||
p.sendMessage(ChatColor.GOLD + "Job spice: +" + workerPay + " Solaris (15% share).");
|
||||
// Contract spice is sold automatically, not dropped as a second payout.
|
||||
if (credited == amount) {
|
||||
scheduleSpiceRespawn(block.getLocation());
|
||||
return;
|
||||
}
|
||||
amount -= credited;
|
||||
}
|
||||
}
|
||||
block.getWorld().dropItemNaturally(block.getLocation(), spiceDrop(p, amount));
|
||||
scheduleSpiceRespawn(block.getLocation());
|
||||
}
|
||||
private void scheduleSpiceRespawn(Location location) {
|
||||
Location loc = location.clone();
|
||||
long delay = 20L * getConfig().getLong("spice-respawn-seconds", 120);
|
||||
Bukkit.getScheduler().runTaskLater(this, () -> { if (loc.getChunk().isLoaded() && loc.getBlock().getType() == Material.AIR) loc.getBlock().setType(Material.SUSPICIOUS_SAND); }, delay);
|
||||
}
|
||||
private void migrateLegacyData() {
|
||||
File legacy = new File(getDataFolder().getParentFile(), "DuneRealms");
|
||||
if (!legacy.isDirectory()) return;
|
||||
File current = getDataFolder();
|
||||
if (!current.exists() && !current.mkdirs()) {
|
||||
getLogger().warning("Could not create DuneCore data folder for legacy settings migration.");
|
||||
return;
|
||||
}
|
||||
File[] files = legacy.listFiles(File::isFile);
|
||||
if (files == null) return;
|
||||
for (File source : files) {
|
||||
File destination = new File(current, source.getName());
|
||||
if (destination.exists()) continue;
|
||||
try {
|
||||
java.nio.file.Files.copy(source.toPath(), destination.toPath());
|
||||
getLogger().info("Migrated " + source.getName() + " from the previous DuneRealms data folder.");
|
||||
} catch (IOException ex) {
|
||||
getLogger().warning("Could not migrate " + source.getName() + ": " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
private ItemStack spiceDrop(Player miner, int amount) {
|
||||
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",
|
||||
ChatColor.GRAY + "Mined by: " + miner.getName() + " ; faction: " + faction));
|
||||
spice.setItemMeta(meta);
|
||||
return spice;
|
||||
}
|
||||
private boolean isWorm(Entity entity) {
|
||||
return entity.getPersistentDataContainer().has(wormKey, PersistentDataType.BYTE);
|
||||
}
|
||||
private void spawnSandworms() {
|
||||
if (!getConfig().getBoolean("sandworms.enabled", true)) return;
|
||||
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();
|
||||
Random rng = java.util.concurrent.ThreadLocalRandom.current();
|
||||
for (Player player : world.getPlayers()) {
|
||||
if (count >= max) break;
|
||||
if (rng.nextDouble() > getConfig().getDouble("sandworms.spawn-chance", 0.35)) continue;
|
||||
boolean nearby = world.getNearbyEntities(player.getLocation(), 48, 32, 48).stream().anyMatch(this::isWorm);
|
||||
if (nearby) continue;
|
||||
double angle = rng.nextDouble() * Math.PI * 2;
|
||||
int distance = 22 + rng.nextInt(19);
|
||||
int x = player.getLocation().getBlockX() + (int) (Math.cos(angle) * distance);
|
||||
int z = player.getLocation().getBlockZ() + (int) (Math.sin(angle) * distance);
|
||||
int y = world.getHighestBlockYAt(x, z);
|
||||
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);
|
||||
});
|
||||
world.spawnParticle(Particle.CLOUD, location, 45, 2, 1, 2, 0.1);
|
||||
world.playSound(location, Sound.ENTITY_WARDEN_ROAR, 2f, 0.6f);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
@EventHandler public void onWormTarget(EntityTargetLivingEntityEvent e) {
|
||||
if (isWorm(e.getEntity()) && (!(e.getTarget() instanceof Player) || !e.getEntity().getWorld().getName().equals("arrakis"))) e.setCancelled(true);
|
||||
}
|
||||
@EventHandler public void onWormTeleport(EntityTeleportEvent e) {
|
||||
if (isWorm(e.getEntity()) && e.getTo() != null && !e.getTo().getWorld().getName().equals("arrakis")) e.setCancelled(true);
|
||||
}
|
||||
@EventHandler public void onWormDeath(EntityDeathEvent e) {
|
||||
if (isWorm(e.getEntity())) {
|
||||
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 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);
|
||||
Random random = java.util.concurrent.ThreadLocalRandom.current();
|
||||
for (int dx = -radius; dx <= radius && placed < target; dx++)
|
||||
for (int dz = -radius; dz <= radius && placed < target; dz++) {
|
||||
if (dx*dx + dz*dz > radius*radius || random.nextDouble() > 0.85) continue;
|
||||
int x = center.getBlockX()+dx, z = center.getBlockZ()+dz;
|
||||
int y = w.getHighestBlockYAt(x,z);
|
||||
Block b = w.getBlockAt(x,y,z);
|
||||
if (b.getType() == Material.SAND || b.getType() == Material.RED_SAND) {
|
||||
b.setType(Material.SUSPICIOUS_SAND);
|
||||
placed++;
|
||||
}
|
||||
}
|
||||
w.strikeLightningEffect(center);
|
||||
Bukkit.broadcastMessage(ChatColor.GOLD + "Shai-Hulud has fallen! A spice bloom has appeared on Arrakis (" + placed + " deposits, up to " + (placed * price) + " Solaris at base yield).");
|
||||
}
|
||||
@EventHandler public void onCombat(EntityDamageByEntityEvent e) {
|
||||
if (e.getDamager() instanceof Player p && selected.getOrDefault(p.getUniqueId(), "").equals("Harkonnen")) e.setDamage(e.getDamage() * 1.15);
|
||||
if (e.getEntity() instanceof Player p && selected.getOrDefault(p.getUniqueId(), "").equals("Corrino")) e.setDamage(e.getDamage() * 0.85);
|
||||
}
|
||||
@EventHandler public void onMove(org.bukkit.event.player.PlayerMoveEvent e) {
|
||||
Player p = e.getPlayer(); if (p.getTicksLived() % 100 != 0) return;
|
||||
String faction = selected.getOrDefault(p.getUniqueId(), "");
|
||||
if (faction.equals("Atreides")) p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 130, 0, true, false));
|
||||
if (faction.equals("Fremen") && p.getWorld().getName().equals("arrakis")) p.addPotionEffect(new PotionEffect(PotionEffectType.RESISTANCE, 130, 0, true, false));
|
||||
}
|
||||
}
|
||||
|
|
@ -19,8 +19,8 @@ arrakis-sun:
|
|||
|
||||
# One Paper backend per planet, connected through Velocity's BungeeCord plugin messaging support.
|
||||
network:
|
||||
enabled: false
|
||||
local-planet: arrakis # CHANGE for each backend
|
||||
enabled: true
|
||||
local-planet: arrakis # Match server.planet in DuneTerrain on this backend
|
||||
servers:
|
||||
arrakis: arrakis
|
||||
giedi_prime: giedi-prime
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
name: DuneRealms
|
||||
name: DuneCore
|
||||
version: 1.0.0
|
||||
main: com.example.dunerealms.DuneRealms
|
||||
main: com.example.dunerealms.DuneCore
|
||||
api-version: '1.21'
|
||||
description: Dune-inspired factions, spice, planets and Guild travel
|
||||
softdepend: [DuneTerrain]
|
||||
description: Dune-inspired factions, spice economy, politics and Guild travel
|
||||
commands:
|
||||
dune:
|
||||
description: Dune realms commands
|
||||
|
|
|
|||
19
DuneTerrain/README.md
Normal file
19
DuneTerrain/README.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# DuneTerrain for Paper 1.21.4
|
||||
|
||||
DuneTerrain is a standalone Paper plugin that generates one Dune planet world per server. It includes the five planet profiles, terrain and ore generation, Arrakis spice deposits and sietches, safe world spawn setup, and a protected Spacing Guild navigator.
|
||||
|
||||
## Build and install
|
||||
|
||||
Build the plugin from this directory with Java 21 and Gradle 8.14 or newer:
|
||||
|
||||
```sh
|
||||
gradle clean build
|
||||
```
|
||||
|
||||
Copy `build/libs/DuneTerrain-1.0.0.jar` into the Paper server's `plugins/` directory. Set `server.planet` in `plugins/DuneTerrain/config.yml` separately on each backend, then restart.
|
||||
|
||||
Valid values are `arrakis`, `giedi_prime`, `kaitain`, `caladan`, and `sigma_draconis_iv`. All five planet profiles are present in each server's config; change `server.planet` to select the world that backend creates. The generated world is named after the selected planet. Adjust its `planets.<planet>` settings for terrain, biome, surface, water, vegetation, ores, and spawn coordinates.
|
||||
|
||||
Install DuneCore alongside DuneTerrain if you want the Guild navigator to open DuneCore's travel menu. DuneCore reads the loaded planet world to identify its local backend. For proxy travel, set `network.local-planet` and `network.servers` in DuneCore's config to match the DuneTerrain selection and proxy server names.
|
||||
|
||||
The generator applies only when a world is first created. Existing worlds and already-generated chunks are not replaced by a config change.
|
||||
17
DuneTerrain/build.gradle.kts
Normal file
17
DuneTerrain/build.gradle.kts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
plugins { java }
|
||||
|
||||
group = "com.example"
|
||||
version = "1.0.0"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
}
|
||||
|
||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
|
||||
tasks.jar { archiveBaseName.set("DuneTerrain") }
|
||||
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
|
||||
1
DuneTerrain/settings.gradle.kts
Normal file
1
DuneTerrain/settings.gradle.kts
Normal file
|
|
@ -0,0 +1 @@
|
|||
rootProject.name = "DuneTerrain"
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
package com.example.duneterrain;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Biome;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Villager;
|
||||
import org.bukkit.generator.*;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.util.*;
|
||||
|
||||
public final class DuneTerrain extends JavaPlugin {
|
||||
private static final String[] PLANETS = {"arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv"};
|
||||
private NamespacedKey guildKey;
|
||||
|
||||
@Override public void onEnable() {
|
||||
saveDefaultConfig();
|
||||
guildKey = new NamespacedKey("dunerealms", "guild");
|
||||
String planet = getConfig().getString("server.planet", "arrakis").toLowerCase(Locale.ROOT);
|
||||
if (!Arrays.asList(PLANETS).contains(planet)) {
|
||||
getLogger().severe("Invalid server.planet '" + planet + "'. Choose one of: " + String.join(", ", PLANETS));
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
if (!getConfig().getBoolean("planets." + planet + ".enabled", true)) {
|
||||
getLogger().severe("Planet '" + planet + "' is disabled in config.yml.");
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
World world = Bukkit.createWorld(new WorldCreator(planet)
|
||||
.environment(World.Environment.NORMAL)
|
||||
.generator(new PlanetChunkGenerator(this, planet)));
|
||||
if (world == null) {
|
||||
getLogger().severe("Could not create or load world '" + planet + "'.");
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !planet.equals("arrakis"));
|
||||
world.setTime(planet.equals("giedi_prime") ? 18000 : 6000);
|
||||
setupPlanetSpawn(world, planet);
|
||||
getLogger().info("DuneTerrain is generating " + planet + " on this Paper server.");
|
||||
}
|
||||
|
||||
private void setupPlanetSpawn(World world, String planet) {
|
||||
String path = "planets." + planet + ".spawn.";
|
||||
int x = getConfig().getInt(path + "x", 0), z = getConfig().getInt(path + "z", 0);
|
||||
world.getChunkAt(x >> 4, z >> 4).load(true);
|
||||
Location spawn = findSafeSpawn(world, x, z);
|
||||
world.setSpawnLocation(spawn);
|
||||
if (getConfig().getBoolean("guild-npc.enabled", true)) ensureGuildNpc(world, spawn);
|
||||
}
|
||||
|
||||
private Location findSafeSpawn(World world, int x, int z) {
|
||||
for (int radius = 0; radius <= 12; radius++) {
|
||||
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
|
||||
if (radius > 0 && Math.abs(dx) != radius && Math.abs(dz) != radius) continue;
|
||||
int bx = x + dx, bz = z + dz;
|
||||
int y = world.getHighestBlockYAt(bx, bz);
|
||||
Material ground = world.getBlockAt(bx, y, bz).getType();
|
||||
if (!ground.isSolid() || ground == Material.MAGMA_BLOCK || ground == Material.CACTUS || ground == Material.POWDER_SNOW) continue;
|
||||
if (world.getBlockAt(bx, y + 1, bz).isLiquid() || world.getBlockAt(bx, y + 2, bz).isLiquid()) continue;
|
||||
return new Location(world, bx + 0.5, y + 1, bz + 0.5);
|
||||
}
|
||||
}
|
||||
int y = Math.max(world.getMinHeight() + 2, world.getHighestBlockYAt(x, z) + 1);
|
||||
return new Location(world, x + 0.5, y, z + 0.5);
|
||||
}
|
||||
|
||||
private void ensureGuildNpc(World world, Location spawn) {
|
||||
Location at = findSafeSpawn(world, spawn.getBlockX() + 2, spawn.getBlockZ());
|
||||
for (Entity entity : world.getNearbyEntities(at, 8, 5, 8)) {
|
||||
if (entity instanceof Villager villager && villager.getPersistentDataContainer().has(guildKey, PersistentDataType.BYTE)) {
|
||||
villager.teleport(at);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Villager villager = world.spawn(at, Villager.class);
|
||||
villager.setCustomName(ChatColor.LIGHT_PURPLE + "Spacing Guild Navigator");
|
||||
villager.setCustomNameVisible(true);
|
||||
villager.setProfession(Villager.Profession.CLERIC);
|
||||
villager.setAI(false);
|
||||
villager.setInvulnerable(true);
|
||||
villager.setSilent(true);
|
||||
villager.setPersistent(true);
|
||||
villager.getPersistentDataContainer().set(guildKey, PersistentDataType.BYTE, (byte) 1);
|
||||
}
|
||||
|
||||
private static class PlanetChunkGenerator extends ChunkGenerator {
|
||||
private final DuneTerrain plugin;
|
||||
private final String planet;
|
||||
PlanetChunkGenerator(DuneTerrain plugin, String planet) { this.plugin = plugin; this.planet = planet; }
|
||||
@Override public List<BlockPopulator> getDefaultPopulators(World world) {
|
||||
return planet.equals("arrakis") ? List.of(new SietchPopulator()) : List.of();
|
||||
}
|
||||
@Override public void generateNoise(WorldInfo world, Random random, int chunkX, int chunkZ, ChunkData data) {
|
||||
String path = "planets." + planet + ".";
|
||||
int minY = world.getMinHeight(), maxY = world.getMaxHeight() - 1;
|
||||
int baseHeight = plugin.getConfig().getInt(path + "terrain.base-height", 68);
|
||||
double variation = plugin.getConfig().getDouble(path + "terrain.height-variation", 8);
|
||||
double scale = Math.max(0.001, plugin.getConfig().getDouble(path + "terrain.noise-scale", 0.02));
|
||||
int waterLevel = plugin.getConfig().getInt(path + "water.level", 63);
|
||||
Material surface = configuredMaterial(path + "surface", Material.GRASS_BLOCK);
|
||||
Material filler = configuredMaterial(path + "filler", Material.DIRT);
|
||||
Material core = planet.equals("giedi_prime") || planet.equals("sigma_draconis_iv") ? Material.DEEPSLATE : Material.STONE;
|
||||
double flowers = Math.max(0, plugin.getConfig().getDouble(path + "vegetation.flowers-per-chunk", 0));
|
||||
double treeChance = Math.max(0, plugin.getConfig().getDouble(path + "vegetation.tree-chance", 0));
|
||||
int[][] heights = new int[16][16];
|
||||
for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) {
|
||||
int gx = chunkX * 16 + x, gz = chunkZ * 16 + z;
|
||||
double n = Math.sin(gx * scale) * Math.cos(gz * scale * 1.13)
|
||||
+ Math.sin(gx * scale * 2.7 + gz * scale * 1.45) * 0.35;
|
||||
int h = Math.max(minY + 8, Math.min(maxY - 8, baseHeight + (int) Math.round(n * variation)));
|
||||
heights[x][z] = h;
|
||||
data.setBlock(x, minY, z, Material.BEDROCK);
|
||||
for (int y = minY + 1; y < h - 3; y++) data.setBlock(x, y, z, core);
|
||||
for (int y = h - 3; y < h; y++) data.setBlock(x, y, z, filler);
|
||||
data.setBlock(x, h, z, surface);
|
||||
|
||||
if (plugin.getConfig().getBoolean(path + "water.swamp-pools", false) && h < waterLevel) {
|
||||
double poolNoise = Math.sin(gx * 0.035) * Math.cos(gz * 0.031);
|
||||
double coverage = Math.max(0, Math.min(1, plugin.getConfig().getDouble(path + "water.coverage", 0.18)));
|
||||
if (poolNoise > 0.72 - coverage * 0.75) {
|
||||
for (int y = h + 1; y <= Math.min(waterLevel, maxY); y++) data.setBlock(x, y, z, Material.WATER);
|
||||
}
|
||||
}
|
||||
if (flowers > 0 && surface == Material.GRASS_BLOCK && random.nextDouble() < Math.min(1, flowers / 256.0)) {
|
||||
Material[] flowerTypes = {Material.POPPY, Material.DANDELION, Material.CORNFLOWER,
|
||||
Material.AZURE_BLUET, Material.ALLIUM, Material.OXEYE_DAISY};
|
||||
data.setBlock(x, h + 1, z, flowerTypes[random.nextInt(flowerTypes.length)]);
|
||||
}
|
||||
if (plugin.getConfig().getBoolean(path + "vegetation.trees", false)
|
||||
&& surface == Material.GRASS_BLOCK && random.nextDouble() < treeChance && x >= 3 && x <= 12 && z >= 3 && z <= 12) {
|
||||
placeJungleTree(data, x, h + 1, z, random, maxY);
|
||||
}
|
||||
}
|
||||
if (planet.equals("arrakis")) placeSpiceDeposits(data, heights, random, minY, maxY);
|
||||
placeOres(data, random, path, minY, maxY);
|
||||
}
|
||||
@Override public BiomeProvider getDefaultBiomeProvider(WorldInfo worldInfo) {
|
||||
return new BiomeProvider() {
|
||||
@Override public Biome getBiome(WorldInfo info, int x, int y, int z) {
|
||||
String configured = plugin.getConfig().getString("planets." + planet + ".biome", "PLAINS");
|
||||
try { return Biome.valueOf(configured.toUpperCase(Locale.ROOT)); }
|
||||
catch (IllegalArgumentException ex) { return Biome.PLAINS; }
|
||||
}
|
||||
@Override public List<Biome> getBiomes(WorldInfo info) { return List.of(getBiome(info, 0, 64, 0)); }
|
||||
};
|
||||
}
|
||||
private Material configuredMaterial(String path, Material fallback) {
|
||||
String name = plugin.getConfig().getString(path, fallback.name());
|
||||
Material material = Material.matchMaterial(name == null ? "" : name);
|
||||
return material == null ? fallback : material;
|
||||
}
|
||||
private void placeSpiceDeposits(ChunkData data, int[][] heights, Random random, int minY, int maxY) {
|
||||
int count = Math.max(0, plugin.getConfig().getInt("spice-deposits.per-chunk", 2));
|
||||
for (int i = 0; i < count; i++) {
|
||||
int x = random.nextInt(16), z = random.nextInt(16), y = heights[x][z];
|
||||
if (y + 1 < maxY && y > minY) data.setBlock(x, y, z, Material.SUSPICIOUS_SAND);
|
||||
}
|
||||
}
|
||||
private void placeOres(ChunkData data, Random random, String path, int minWorldY, int maxWorldY) {
|
||||
org.bukkit.configuration.ConfigurationSection ores = plugin.getConfig().getConfigurationSection(path + "ores");
|
||||
if (ores == null) return;
|
||||
int minY = Math.max(minWorldY + 1, plugin.getConfig().getInt(path + "ores.min-y", -48));
|
||||
int maxY = Math.min(maxWorldY - 4, plugin.getConfig().getInt(path + "ores.max-y", 48));
|
||||
int veinSize = Math.max(1, Math.min(16, plugin.getConfig().getInt(path + "ores.vein-size", 5)));
|
||||
if (maxY < minY) return;
|
||||
for (String key : ores.getKeys(false)) {
|
||||
Material ore = Material.matchMaterial(key);
|
||||
if (ore == null || !key.endsWith("_ORE")) continue;
|
||||
int attempts = Math.max(0, Math.min(64, ores.getInt(key, 0)));
|
||||
for (int attempt = 0; attempt < attempts; attempt++) {
|
||||
int x = random.nextInt(16), z = random.nextInt(16), y = minY + random.nextInt(maxY - minY + 1);
|
||||
for (int n = 0; n < veinSize; n++) {
|
||||
int vx = Math.max(0, Math.min(15, x + random.nextInt(3) - 1));
|
||||
int vz = Math.max(0, Math.min(15, z + random.nextInt(3) - 1));
|
||||
int vy = Math.max(minY, Math.min(maxY, y + random.nextInt(3) - 1));
|
||||
Material existing = data.getType(vx, vy, vz);
|
||||
if (existing == Material.STONE || existing == Material.DEEPSLATE || existing == Material.TUFF) data.setBlock(vx, vy, vz, ore);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private void placeJungleTree(ChunkData data, int x, int y, int z, Random random, int maxY) {
|
||||
int height = 4 + random.nextInt(4);
|
||||
if (y + height + 2 >= maxY || data.getType(x, y - 1, z) != Material.GRASS_BLOCK) return;
|
||||
for (int dy = 0; dy < height; dy++) data.setBlock(x, y + dy, z, Material.JUNGLE_LOG);
|
||||
for (int dy = height - 2; dy <= height + 1; dy++) {
|
||||
int radius = dy >= height ? 1 : 2;
|
||||
for (int dx = -radius; dx <= radius; dx++) for (int dz = -radius; dz <= radius; dz++) {
|
||||
if (Math.abs(dx) == radius && Math.abs(dz) == radius && random.nextBoolean()) continue;
|
||||
int lx = x + dx, lz = z + dz, ly = y + dy;
|
||||
if (lx >= 0 && lx < 16 && lz >= 0 && lz < 16 && data.getType(lx, ly, lz).isAir()) data.setBlock(lx, ly, lz, Material.JUNGLE_LEAVES);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static final class SietchPopulator extends BlockPopulator {
|
||||
@Override public void populate(WorldInfo world, Random random, int cx, int cz, LimitedRegion region) {
|
||||
if (!world.getName().equalsIgnoreCase("arrakis") || random.nextInt(90) != 0) return;
|
||||
int x = cx * 16 + 4 + random.nextInt(8), z = cz * 16 + 4 + random.nextInt(8);
|
||||
int y = region.getHighestBlockYAt(x, z);
|
||||
if (y < 65 || y > world.getMaxHeight() - 12 || y - 12 < world.getMinHeight()) return;
|
||||
for (int dx = -4; dx <= 4; dx++) for (int dz = -4; dz <= 4; dz++) for (int dy = -10; dy <= 3; dy++) {
|
||||
int ax = x + dx, az = z + dz, ay = y + dy;
|
||||
if (!region.isInRegion(ax, ay, az)) continue;
|
||||
boolean cave = dy >= -9 && dy <= -5 && Math.abs(dx) <= 3 && Math.abs(dz) <= 3;
|
||||
if (cave) region.setType(ax, ay, az, dy <= -8 ? Material.WATER : Material.AIR);
|
||||
else if (dy >= 0 && dy <= 3 && Math.abs(dx) <= 3 && Math.abs(dz) <= 3) {
|
||||
boolean wall = Math.abs(dx) == 3 || Math.abs(dz) == 3 || dy == 3;
|
||||
region.setType(ax, ay, az, wall ? Material.SANDSTONE : Material.AIR);
|
||||
}
|
||||
}
|
||||
for (int dy = -7; dy <= 2; dy++) {
|
||||
if (region.isInRegion(x, y + dy, z)) region.setType(x, y + dy, z, Material.AIR);
|
||||
if (region.isInRegion(x + 1, y + dy, z)) region.setType(x + 1, y + dy, z, Material.LADDER);
|
||||
}
|
||||
if (region.isInRegion(x, y + 4, z)) region.setType(x, y + 4, z, Material.ORANGE_BANNER);
|
||||
}
|
||||
}
|
||||
}
|
||||
62
DuneTerrain/src/main/resources/config.yml
Normal file
62
DuneTerrain/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# Set this separately on each Paper backend.
|
||||
# Accepted values: arrakis, giedi_prime, kaitain, caladan, sigma_draconis_iv
|
||||
server:
|
||||
planet: arrakis
|
||||
|
||||
guild-npc:
|
||||
enabled: true
|
||||
|
||||
spice-deposits:
|
||||
per-chunk: 2
|
||||
|
||||
planets:
|
||||
arrakis:
|
||||
enabled: true
|
||||
spawn: {x: 0, z: 0}
|
||||
terrain: {base-height: 70, height-variation: 11, noise-scale: 0.02}
|
||||
biome: DESERT
|
||||
surface: SAND
|
||||
filler: RED_SAND
|
||||
water: {level: 63, swamp-pools: false, coverage: 0.18}
|
||||
vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0}
|
||||
ores: {min-y: -48, max-y: 48, vein-size: 5, COAL_ORE: 2, IRON_ORE: 2, COPPER_ORE: 1}
|
||||
giedi_prime:
|
||||
enabled: true
|
||||
spawn: {x: 0, z: 0}
|
||||
terrain: {base-height: 61, height-variation: 5, noise-scale: 0.02}
|
||||
biome: SWAMP
|
||||
surface: BLACKSTONE
|
||||
filler: DEEPSLATE
|
||||
water: {level: 63, swamp-pools: true, coverage: 0.18}
|
||||
vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0}
|
||||
ores: {min-y: -48, max-y: 48, vein-size: 5, COAL_ORE: 14, IRON_ORE: 12, COPPER_ORE: 9, GOLD_ORE: 7, REDSTONE_ORE: 8, LAPIS_ORE: 5, DIAMOND_ORE: 4, EMERALD_ORE: 2}
|
||||
kaitain:
|
||||
enabled: true
|
||||
spawn: {x: 0, z: 0}
|
||||
terrain: {base-height: 70, height-variation: 3, noise-scale: 0.02}
|
||||
biome: PLAINS
|
||||
surface: GRASS_BLOCK
|
||||
filler: DIRT
|
||||
water: {level: 0, swamp-pools: false, coverage: 0.18}
|
||||
vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 64}
|
||||
ores: {min-y: -48, max-y: 48, vein-size: 5, COAL_ORE: 4, IRON_ORE: 5, GOLD_ORE: 15, DIAMOND_ORE: 18, EMERALD_ORE: 3}
|
||||
caladan:
|
||||
enabled: true
|
||||
spawn: {x: 0, z: 0}
|
||||
terrain: {base-height: 67, height-variation: 10, noise-scale: 0.02}
|
||||
biome: JUNGLE
|
||||
surface: GRASS_BLOCK
|
||||
filler: DIRT
|
||||
water: {level: 72, swamp-pools: true, coverage: 0.55}
|
||||
vegetation: {trees: true, tree-chance: 0.035, flowers-per-chunk: 0}
|
||||
ores: {min-y: -48, max-y: 48, vein-size: 5, COAL_ORE: 4, IRON_ORE: 5, COPPER_ORE: 5, DIAMOND_ORE: 2}
|
||||
sigma_draconis_iv:
|
||||
enabled: true
|
||||
spawn: {x: 0, z: 0}
|
||||
terrain: {base-height: 72, height-variation: 14, noise-scale: 0.02}
|
||||
biome: SNOWY_PLAINS
|
||||
surface: SNOW_BLOCK
|
||||
filler: DEEPSLATE
|
||||
water: {level: 0, swamp-pools: false, coverage: 0.18}
|
||||
vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0}
|
||||
ores: {min-y: -48, max-y: 48, vein-size: 5, COAL_ORE: 5, IRON_ORE: 5, COPPER_ORE: 2, DIAMOND_ORE: 2}
|
||||
5
DuneTerrain/src/main/resources/plugin.yml
Normal file
5
DuneTerrain/src/main/resources/plugin.yml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
name: DuneTerrain
|
||||
version: 1.0.0
|
||||
main: com.example.duneterrain.DuneTerrain
|
||||
api-version: '1.21'
|
||||
description: Configurable Dune planet terrain and spawn generator for Paper
|
||||
Loading…
Reference in a new issue

Staff