Integrate DuneGroups as a selectable organisation backend #59

Merged
unimatrix merged 5 commits from feat/dunegroups-replacement-20261202 into main 2026-12-02 13:33:00 +01:00
33 changed files with 1394 additions and 54 deletions

View file

@ -0,0 +1,43 @@
name: DuneGroups Replacement Build
on:
workflow_dispatch:
push:
branches: ['feat/dunegroups-replacement-*']
jobs:
dunegroups:
runs-on: dune-ci
steps:
- name: Check out exact revision
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
git checkout --detach FETCH_HEAD
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '9.2.1'
- name: Build and test both replacement plugins
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p JarvisConnector test jar
gradle --no-daemon -p DuneGroups test jar
python3 tools/test_plugin_dunegroups.py -v
mkdir dunegroups-artifacts
cp JarvisConnector/build/libs/jarvistranslator.jar DuneGroups/build/libs/DuneGroups.jar dunegroups-artifacts/
cp tools/{plugin_dunegroups,install-plugin-fleet,write-plugin-manifest,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py dunegroups-artifacts/
printf '%s\n' "$(git rev-parse HEAD)" > dunegroups-artifacts/SOURCE_COMMIT
(cd dunegroups-artifacts && sha256sum -- *.jar *.py SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-DuneGroups-Replacement
path: dunegroups-artifacts/
if-no-files-found: error

View file

@ -28,7 +28,7 @@ jobs:
shell: bash
run: |
set -euo pipefail
modules=(DuneEss DuneLobby DuneLobbyAccount DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector DuneMenus)
modules=(DuneEss DuneLobby DuneLobbyAccount DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector DuneMenus DuneGroups)
mkdir -p plugin-artifacts
for module in "${modules[@]}"; do
gradle --no-daemon -p "$module" test jar
@ -47,13 +47,20 @@ jobs:
(cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS)
- name: Validate rollout contract and build stacked menu overlay
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
python3 tools/test_plugin_ci_policy.py -v
pillager_input="$(mktemp -d)"
python3 tools/plugin_navigator_transition.py --stage-pillager-baseline "$pillager_input/baseline"
DUNE_PILLAGER_BASELINE_DIR="$pillager_input/baseline" python3 tools/test_plugin_pillager_profile.py -v
python3 tools/plugin_navigator_transition.py
# Navigator predates the selectable DuneGroups backend. Validate its
# exact historical connector against the original unchanged contract.
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git 5d727d7f59e6af26fba07a3878fd79035a5923ce
git worktree add --detach "$pillager_input/navigator" FETCH_HEAD
gradle --no-daemon -p "$pillager_input/navigator/JarvisConnector" jar
python3 tools/plugin_navigator_transition.py --historical-jarvis "$pillager_input/navigator/JarvisConnector/build/libs/jarvistranslator.jar"
python3 tools/test_plugin_pillager_art.py -v
python3 tools/test_plugin_fleet_install.py -v
python3 tools/test_plugin_menu_pack.py -v

53
DuneGroups/README.md Normal file
View file

@ -0,0 +1,53 @@
# DuneGroups: replaces Towny and Medieval Factions
Built from canonical plugins main `5d727d7f59e6af26fba07a3878fd79035a5923ce`. Web main `8c25f491...` was not touched or needed. Nothing is pushed to DuneGit. `/plot` and wilderness drafts are not included.
## Switch
`JarvisConnector config.yml: native.backend: legacy | dunegroups` (default `legacy`).
- `legacy`: unchanged behaviour. If DuneGroups is installed it is told to deactivate, so the jar alone changes nothing.
- `dunegroups`: JARVIS activates DuneGroups. If DuneGroups or WorldGuard is missing, JARVIS logs SEVERE and disables itself instead of running without Home Block and WorldGuard projection.
Rollback: set `legacy`, restart. DuneGroups drops every rule and its in-memory projection. Its `homes.yml` is kept for the next activation.
## What replaced what
| Before | Now |
|---|---|
| Towny town home block / Factions home claim | DuneGroups home chunk registry (clans, companies, protected offices, expanded estate chunks, claim revisions) |
| Towny `setPVP(false)` | DuneGroups: nobody can hurt anybody on a company or protected-office home chunk (melee, projectiles, TNT, tamed pets, fire, splash, lingering clouds). Clans stay PvP. Only ever cancels; never clears another plugin's cancellation |
| NativeWorldGuard estate regions | Unchanged class, now also run by the new worker for clans, companies and offices, with wars |
| Home NPCs, Kaitain Emperor NPC | Same code, driven by the new worker |
| Faction roster/roles/neutrality/parents/wars | `OrganisationDirectory`: central projection persisted in `organisation-directory.json` |
| ImperialRaid asking MedievalFactions | `ClanDirectory` (central projection). Paid receipt validation, spawn checks, journal recovery and refunds are unchanged. New: the target claim revision must match the permit |
| Faction AT_WAR/LIEGE edges, Towny nations, mayor/caretaker, power | Retired. No consumer outside the old worker was found. `WarCampaignWorker` is untouched |
## Relocation cleanup
Acknowledged only after verified absence of: DuneGroups claims, WorldGuard regions, the Home NPC, and any legacy Towny/Factions projection (if those plugins are still installed). The cleanup is written to `dunegroups-worker.yml` before the original requestId/keyId is acknowledged, and an unacknowledged one is re-sent first after a restart. No block is ever removed.
## Bank
No bank, balance or Vault code was added or touched. Native roles grant nothing. The shared-inventory SQL (`ExchangeInventory`) is untouched.
## Verified (CI, unimatrixgit/mcdune-backup branch claude/menus-ci)
- DuneGroups builds; 12 unit tests: chunk maths, conflicts, malformed UUID/world/coordinates/revision, stale revision, unresolved vs archived, storage round trip, PvP policy.
- JarvisConnector compiles with all changes; OrganisationDirectoryTest (rosters, roles, neutrality, parents, wars, review retention, duplicate war key, storage); existing TerrainAuthority/NativeCommandPolicy tests pass.
## NOT verified (needs a server)
Reflection into Paper and WorldGuard, the PvP listener on real events, WorldGuard region writes, Home NPC placement, relocation and restart recovery end to end, paid travel, a real raid, and running with both vendor jars absent. Run the canary below before removing either plugin.
## Canary checklist (one planet, vendor jars removed, vendor data kept)
1. Start with `legacy`, confirm normal. Switch to `dunegroups`, restart: expect `DuneGroups active`, no SEVERE.
2. `/jarvis status`: clans/companies/offices/wars/home chunks counts match the website.
3. `/dunegroups here` on a clan, company and office home chunk; hit a player from outside and inside a company chunk; throw a harmful splash and lingering potion.
4. WorldGuard: outsider cannot build in an estate; member can.
5. Home NPC present for a clan and a company. Kaitain: Emperor NPC.
6. Relocate a clan home: old chunk, region and NPC gone, then acknowledged once. Kill the server between persist and ack: after restart it acknowledges once.
7. Break `homes.yml` write permission: sync must fail loudly and keep the old projection.
8. Raid: paid order accepted, spawn checks pass, refund path on a stale revision.
9. Switch back to `legacy`: DuneGroups rules stop immediately.
## Open items found by the audit (not changed)
- `tools/install-plugin-fleet.py:277` still requires a reviewed MedievalFactions runtime. Fleet install fails without it.
- `tools/allow-giedi-nether-pearl.py` and `tools/disable-unused-vendor-settings.*` configure Towny; Giedi Prime's Ender Pearl rule lives in Towny's unclaimed-zone settings and disappears with Towny.
- `DuneTerrain/trails/*-config.yml` carry Towny path settings; harmless without Towny.
- `NativeCommandPolicy` still intercepts `/town`, `/f`, `/mf` etc.; harmless but now redundant.
- Company PvP has no exemption for active war campaigns. If wars on company land must allow PvP, say so.
- Claim revision is read from `homeBlock.claimRevision` (fallback `claimRevision`); confirm the website uses that field.
- The Towny nation/office tree is not reproduced anywhere; only protected neutrality and parents are kept as data.

View file

@ -0,0 +1,14 @@
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.8-R0.1-SNAPSHOT")
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
tasks.test { useJUnitPlatform() }
tasks.jar { archiveFileName.set("DuneGroups.jar") }

View file

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

View file

@ -0,0 +1,148 @@
package com.example.dunegroups;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
/**
* Home blocks for JARVIS clans, companies and protected offices. JARVIS stays the source of truth and calls
* {@link #activate()}, {@link #sync(String)}, {@link #claimCount(String, String)} and {@link #deactivate()} by reflection.
* Installing the jar alone changes nothing: until JARVIS activates it there are no rules and no cached projection in force.
*/
public final class DuneGroups extends JavaPlugin implements CommandExecutor {
private final HomeRegistry registry = new HomeRegistry();
private volatile boolean active;
private boolean fresh;
private File cache;
private Set<String> pvpFreeKinds = Set.of("company", "protected");
private String pvpFreeMessage = "PvP is disabled on company land.";
@Override public void onEnable() {
saveDefaultConfig();
cache = new File(getDataFolder(), "homes.yml");
loadConfigValues();
getServer().getPluginManager().registerEvents(new PvpListener(this), this);
var cmd = getCommand("dunegroups");
if (cmd != null) cmd.setExecutor(this);
getLogger().info("DuneGroups installed and inactive. It starts only when JARVIS uses native.backend: dunegroups.");
}
@Override public void onDisable() { deactivate(); }
private void loadConfigValues() {
reloadConfig();
Set<String> kinds = new HashSet<>();
for (String k : getConfig().getStringList("pvp-free-kinds")) kinds.add(k.toLowerCase(Locale.ROOT));
pvpFreeKinds = kinds;
pvpFreeMessage = getConfig().getString("pvp-free-message", pvpFreeMessage);
}
boolean active() { return active; }
/** Starts the rules and loads the last stored projection. Throws if the stored projection is unreadable. */
public synchronized void activate() {
if (active) return;
if (!fresh) throw new IllegalStateException("Waiting for fresh central state");
active = true;
getLogger().info("DuneGroups active with " + registry.size() + " home chunk(s).");
}
private void readCache() throws IOException {
if (cache.exists()) {
try (var in = Files.newBufferedReader(cache.toPath())) {
Object raw = new Yaml().load(in);
if (raw instanceof Map<?, ?> m) registry.install(HomeRegistry.fromMap((Map<?, ?>) m.get("chunks")), String.valueOf(m.get("state") == null ? "" : m.get("state")));
} catch (RuntimeException broken) { throw new IOException("homes.yml is unreadable: " + broken.getMessage(), broken); }
}
}
/** Stops every rule at once and forgets the in-memory projection. The stored file is kept for the next activation. */
public synchronized void deactivate() {
if (!active && !fresh && registry.size() == 0) return;
active = false;
fresh = false;
registry.install(Map.of(), "");
getLogger().info("DuneGroups deactivated; no rules are in force.");
}
private void store(Map<String, HomeRegistry.Entry> next, String state) throws IOException {
Files.createDirectories(cache.toPath().getParent());
String text = new Yaml().dump(Map.of("state", state, "chunks", HomeRegistry.toMap(next)));
File tmp = new File(getDataFolder(), "homes.yml.tmp");
Files.writeString(tmp.toPath(), text);
try { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); }
catch (java.nio.file.AtomicMoveNotSupportedException unsupported) { Files.move(tmp.toPath(), cache.toPath(), StandardCopyOption.REPLACE_EXISTING); }
}
private static JsonArray rows(JsonObject o, String field) {
JsonElement e = o.get(field);
return e == null || e.isJsonNull() ? null : e.getAsJsonArray();
}
/**
* Payload: {"stateId":"...","clans":[],"companies":[],"offices":[],"unresolved":[{"kind":"clan","id":"..."}]}.
* Replaces every home chunk atomically. Throws on malformed or conflicting data (the last valid projection stays) and on
* any storage failure (nothing is swapped in). Returns the number of home chunks now registered.
*/
public synchronized int sync(String json) throws IOException {
if (!fresh) readCache();
JsonObject o = JsonParser.parseString(json).getAsJsonObject();
Map<String, JsonArray> by = new HashMap<>();
by.put("clan", rows(o, "clans")); by.put("company", rows(o, "companies")); by.put("protected", rows(o, "offices"));
List<HomeRegistry.Ref> unresolved = new ArrayList<>();
if (o.has("unresolved") && o.get("unresolved").isJsonArray())
for (JsonElement v : o.getAsJsonArray("unresolved")) {
JsonObject r = v.getAsJsonObject();
unresolved.add(new HomeRegistry.Ref(r.get("kind").getAsString(), r.get("id").getAsString()));
}
String state = o.has("stateId") ? o.get("stateId").getAsString() : "";
Map<String, HomeRegistry.Entry> next = HomeRegistry.parse(by, unresolved, registry.snapshot());
if (!next.equals(registry.snapshot()) || !state.equals(registry.stateId())) {
store(next, state);
registry.install(next, state);
}
fresh = true;
return registry.size();
}
/** Number of home chunks currently owned by this group. Zero proves the old claim is gone. */
public long claimCount(String kind, String id) { return registry.claimCount(kind, id); }
HomeRegistry.Entry ownerAt(Location at) {
if (!active || at == null || at.getWorld() == null) return null;
return registry.at(at.getWorld().getUID().toString(), Math.floorDiv(at.getBlockX(), 16), Math.floorDiv(at.getBlockZ(), 16));
}
boolean pvpFree(Location at) { var e = ownerAt(at); return e != null && pvpFreeKinds.contains(e.kind()); }
String pvpFreeMessage() { return pvpFreeMessage; }
@Override public boolean onCommand(CommandSender s, Command c, String l, String[] a) {
String sub = a.length == 0 ? "here" : a[0].toLowerCase(Locale.ROOT);
switch (sub) {
case "here" -> {
if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; }
var e = ownerAt(p.getLocation());
s.sendMessage(!active ? "DuneGroups is inactive." : e == null ? "This block is not a home block."
: "Home block of " + e.kind() + " " + e.name() + (e.tag().isBlank() ? "" : " [" + e.tag() + "]") + (pvpFree(p.getLocation()) ? " (PvP-free)." : "."));
}
case "list" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else s.sendMessage((active ? "Active, " : "Inactive, ") + registry.size() + " home chunk(s)."); }
case "reload" -> { if (!s.hasPermission("dunegroups.admin")) s.sendMessage("No permission."); else { loadConfigValues(); s.sendMessage("DuneGroups config reloaded."); } }
default -> s.sendMessage("/dunegroups <here|list|reload>");
}
return true;
}
}

View file

@ -0,0 +1,171 @@
package com.example.dunegroups;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.*;
/**
* Which central clan, company or protected office owns which home chunk. Pure logic, no Bukkit types.
* A bad or conflicting payload is rejected as a whole so the last valid projection stays in force.
*/
final class HomeRegistry {
static final Set<String> KINDS = Set.of("clan", "company", "protected");
private static final int MAX_CHUNKS_PER_GROUP = 10_000, MAX_ROWS = 2_000;
private static final int CHUNK_LIMIT = 1_875_000; // world border 30,000,000 blocks / 16
record Entry(String kind, String id, String name, String tag, long revision) {}
record Ref(String kind, String id) {}
/** Thrown for malformed rows, conflicting ownership and stale revisions. Never applied partially. */
static final class Rejected extends IllegalArgumentException {
Rejected(String message) { super(message); }
}
private volatile Map<String, Entry> chunks = Map.of();
private volatile String stateId = "";
static String key(String world, int chunkX, int chunkZ) { return world + ":" + chunkX + ":" + chunkZ; }
Entry at(String world, int chunkX, int chunkZ) { return chunks.get(key(world, chunkX, chunkZ)); }
int size() { return chunks.size(); }
Map<String, Entry> snapshot() { return chunks; }
String stateId() { return stateId; }
long claimCount(String kind, String id) {
return chunks.values().stream().filter(e -> e.kind().equals(kind) && e.id().equals(id)).count();
}
void install(Map<String, Entry> next, String state) { chunks = Map.copyOf(next); stateId = state == null ? "" : state; }
// ---- parsing ----
private static String str(JsonObject o, String f) {
JsonElement e = o.get(f);
return e == null || e.isJsonNull() || !e.isJsonPrimitive() ? "" : e.getAsString();
}
private static int integer(JsonObject o, String f, String what) {
JsonElement e = o.get(f);
if (e == null || !e.isJsonPrimitive() || !e.getAsJsonPrimitive().isNumber()) throw new Rejected(what + " is not a number");
double d = e.getAsDouble();
if (d != Math.rint(d) || Math.abs(d) > 30_000_000) throw new Rejected(what + " is out of range");
return (int) d;
}
private static boolean uuid(String s) {
try { UUID.fromString(s); return true; } catch (IllegalArgumentException bad) { return false; }
}
private static boolean bool(JsonObject o, String f) {
JsonElement e = o.get(f);
return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isBoolean() && e.getAsBoolean();
}
private static void chunk(int cx, int cz, String what) {
if (Math.abs(cx) > CHUNK_LIMIT || Math.abs(cz) > CHUNK_LIMIT) throw new Rejected(what + " chunk is out of range");
}
/**
* Builds the next chunk map. Lifecycle {@code active} projects. {@code archived} or {@code retired}, hidden rows and ids
* that vanished from the payload are dropped. Any other lifecycle, and every id in {@code unresolved}, keeps whatever
* it owned before: an unresolved record is never treated as an absence.
*/
static Map<String, Entry> parse(Map<String, JsonArray> rowsByKind, Collection<Ref> unresolved, Map<String, Entry> previous) {
Map<String, Entry> out = new HashMap<>();
Set<Ref> keep = new HashSet<>(unresolved);
int rows = 0;
for (var group : new TreeMap<>(rowsByKind).entrySet()) {
String kind = group.getKey();
if (!KINDS.contains(kind)) throw new Rejected("Unknown group kind " + kind);
if (group.getValue() == null) continue;
TreeMap<String, JsonObject> sorted = new TreeMap<>();
for (JsonElement v : group.getValue()) {
if (!v.isJsonObject()) throw new Rejected("Row is not an object");
JsonObject r = v.getAsJsonObject();
String id = str(r, "id");
if (!uuid(id)) throw new Rejected("Invalid " + kind + " id");
if (sorted.put(id, r) != null) throw new Rejected("Duplicate " + kind + " " + id);
if (++rows > MAX_ROWS) throw new Rejected("Too many rows");
}
for (JsonObject r : sorted.values()) {
String id = str(r, "id"), life = str(r, "lifecycle");
if (life.equals("archived") || life.equals("retired") || bool(r, "hidden")) continue;
if (!life.equals("active")) { keep.add(new Ref(kind, id)); continue; }
project(out, kind, id, r, previous);
}
}
for (var entry : previous.entrySet()) {
Entry e = entry.getValue();
if (!keep.contains(new Ref(e.kind(), e.id()))) continue;
Entry now = out.get(entry.getKey());
if (now != null && !(now.kind().equals(e.kind()) && now.id().equals(e.id())))
throw new Rejected("Chunk " + entry.getKey() + " is claimed by an active record while " + e.kind() + " " + e.id() + " is unresolved");
out.putIfAbsent(entry.getKey(), e);
}
return out;
}
private static void project(Map<String, Entry> out, String kind, String id, JsonObject r, Map<String, Entry> previous) {
if (!r.has("homeBlock") || !r.get("homeBlock").isJsonObject()) return;
JsonObject home = r.getAsJsonObject("homeBlock");
if (!"minecraft".equals(str(home, "source"))) return;
String world = str(home, "worldUuid");
if (!uuid(world)) throw new Rejected(kind + " " + id + " has an invalid world");
if (!home.has("position") || !home.get("position").isJsonObject()) throw new Rejected(kind + " " + id + " has no position");
JsonObject pos = home.getAsJsonObject("position");
int x = integer(pos, "x", "x"), z = integer(pos, "z", "z");
long revision = 0;
JsonElement rev = home.has("revision") ? home.get("revision") : r.get("claimRevision");
if (rev != null && !rev.isJsonNull()) {
if (!rev.isJsonPrimitive() || !rev.getAsJsonPrimitive().isNumber() || rev.getAsDouble() < 0 || rev.getAsDouble() != Math.rint(rev.getAsDouble()))
throw new Rejected(kind + " " + id + " has an invalid claim revision");
revision = rev.getAsLong();
if (home.has("revision") && r.has("claimRevision") && (!r.get("claimRevision").isJsonPrimitive() || r.get("claimRevision").getAsLong() != revision))
throw new Rejected(kind + " " + id + " claim revisions disagree");
}
for (Entry old : previous.values())
if (old.kind().equals(kind) && old.id().equals(id) && old.revision() > revision)
throw new Rejected(kind + " " + id + " claim revision " + revision + " is older than the applied " + old.revision());
Entry entry = new Entry(kind, id, str(r, "name"), str(r, "tag"), revision);
Set<String> mine = new LinkedHashSet<>();
mine.add(key(world, Math.floorDiv(x, 16), Math.floorDiv(z, 16)));
if (r.has("claimedChunks") && r.get("claimedChunks").isJsonArray()) {
JsonArray c = r.getAsJsonArray("claimedChunks");
if (c.size() > MAX_CHUNKS_PER_GROUP) throw new Rejected(kind + " " + id + " exceeds the estate bound");
for (JsonElement v : c) {
if (!v.isJsonObject()) throw new Rejected(kind + " " + id + " has a malformed chunk");
JsonObject o = v.getAsJsonObject();
int cx = integer(o, "x", "chunk x"), cz = integer(o, "z", "chunk z");
chunk(cx, cz, kind + " " + id);
mine.add(key(world, cx, cz));
}
}
for (String k : mine) {
Entry other = out.get(k);
if (other != null && !(other.kind().equals(kind) && other.id().equals(id)))
throw new Rejected("Chunk " + k + " is claimed by both " + other.kind() + " " + other.id() + " and " + kind + " " + id);
out.put(k, entry);
}
}
// ---- storage ----
static Map<String, Object> toMap(Map<String, Entry> m) {
Map<String, Object> out = new LinkedHashMap<>();
new TreeMap<>(m).forEach((k, e) -> out.put(k, Map.of("kind", e.kind(), "id", e.id(), "name", e.name(), "tag", e.tag(), "revision", e.revision())));
return out;
}
static Map<String, Entry> fromMap(Map<?, ?> raw) {
Map<String, Entry> out = new HashMap<>();
if (raw == null) return out;
raw.forEach((k, v) -> {
if (!(v instanceof Map<?, ?> o)) throw new Rejected("Cached entry is malformed");
String kind = String.valueOf(o.get("kind")), id = String.valueOf(o.get("id"));
if (!KINDS.contains(kind) || !uuid(id)) throw new Rejected("Cached entry is malformed");
long rev = o.get("revision") instanceof Number n ? n.longValue() : 0;
out.put(String.valueOf(k), new Entry(kind, id, String.valueOf(o.get("name")), String.valueOf(o.get("tag")), rev));
});
return out;
}
}

View file

@ -0,0 +1,67 @@
package com.example.dunegroups;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
import org.bukkit.potion.PotionEffect;
import java.util.Collection;
/** Cancels player-versus-player harm on PvP-free home blocks. Uses ignoreCancelled and never clears a cancellation. */
final class PvpListener implements Listener {
private final DuneGroups plugin;
PvpListener(DuneGroups plugin) { this.plugin = plugin; }
/** The player a damage source belongs to, or null. Covers arrows, tridents, snowballs, TNT, clouds and tamed pets. */
static Player attribution(Entity source) {
if (source instanceof Player p) return p;
if (source instanceof Projectile pr && pr.getShooter() instanceof Player p) return p;
if (source instanceof TNTPrimed tnt && tnt.getSource() instanceof Player p) return p;
if (source instanceof AreaEffectCloud cloud && cloud.getSource() instanceof Player p) return p;
if (source instanceof Tameable pet && pet.getOwner() instanceof Player p) return p;
return null;
}
private boolean blocked(Player attacker, Player victim) {
return plugin.active() && PvpPolicy.blocked(attacker == victim, plugin.pvpFree(attacker.getLocation()), plugin.pvpFree(victim.getLocation()));
}
private static boolean harmful(Collection<PotionEffect> effects) {
for (PotionEffect e : effects) if (PvpPolicy.harmful(e.getType().getKey().getKey())) return true;
return false;
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onDamage(EntityDamageByEntityEvent e) {
if (!(e.getEntity() instanceof Player victim)) return;
Player attacker = attribution(e.getDamager());
if (attacker == null || !blocked(attacker, victim)) return;
e.setCancelled(true);
attacker.sendMessage(plugin.pvpFreeMessage());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCombust(EntityCombustByEntityEvent e) {
if (e.getEntity() instanceof Player victim && attribution(e.getCombuster()) instanceof Player attacker && blocked(attacker, victim)) e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSplash(PotionSplashEvent e) {
if (!(e.getEntity().getShooter() instanceof Player thrower) || !harmful(e.getPotion().getEffects())) return;
for (LivingEntity hit : e.getAffectedEntities())
if (hit instanceof Player victim && blocked(thrower, victim)) e.setIntensity(victim, 0);
}
/** Lingering potions: remove protected players from the cloud's current hit list. */
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCloud(AreaEffectCloudApplyEvent e) {
if (!(e.getEntity().getSource() instanceof Player thrower)) return;
AreaEffectCloud cloud = e.getEntity();
boolean bad = harmful(cloud.getCustomEffects()) || cloud.getBasePotionType() != null && harmful(cloud.getBasePotionType().getPotionEffects());
if (!bad) return;
e.getAffectedEntities().removeIf(hit -> hit instanceof Player victim && blocked(thrower, victim));
}
}

View file

@ -0,0 +1,19 @@
package com.example.dunegroups;
import java.util.Set;
/** Pure rules for the company protection. Only ever decides to cancel; never to re-allow. */
final class PvpPolicy {
private PvpPolicy() {}
/** Potion effect keys (namespaced path names) that harm or hinder the target. */
static final Set<String> HARMFUL = Set.of("poison", "instant_damage", "weakness", "slowness", "wither", "blindness",
"hunger", "mining_fatigue", "nausea", "levitation", "darkness", "infested", "oozing", "weaving", "wind_charged", "bad_omen", "raid_omen");
static boolean harmful(String effectKey) { return HARMFUL.contains(effectKey == null ? "" : effectKey); }
/** Players in a PvP-free chunk can neither hurt nor be hurt, whoever stands outside. Self damage is untouched. */
static boolean blocked(boolean sameActor, boolean attackerInFree, boolean victimInFree) {
return !sameActor && (attackerInFree || victimInFree);
}
}

View file

@ -0,0 +1,4 @@
# DuneGroups only projects JARVIS home blocks. It has no claims, build protection or commands that create groups.
# Kinds that are PvP-free on their home chunk: company, protected (offices). Clans stay PvP.
pvp-free-kinds: [company, protected]
pvp-free-message: "PvP is disabled on company land."

View file

@ -0,0 +1,15 @@
name: DuneGroups
version: 1.0.0
main: com.example.dunegroups.DuneGroups
api-version: '1.21.8'
load: STARTUP
description: Home blocks for JARVIS clans and companies. Companies are PvP-free on their home block. Replaces Towny and Medieval Factions.
commands:
dunegroups:
description: Show who owns the home block you stand on, or reload
usage: /dunegroups <here|list|reload>
permissions:
dunegroups.here:
default: true
dunegroups.admin:
default: op

View file

@ -0,0 +1,101 @@
package com.example.dunegroups;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class HomeRegistryTest {
private static final String W = "11111111-1111-1111-1111-111111111111";
private static final String A = "aaaaaaaa-0000-0000-0000-000000000001", B = "bbbbbbbb-0000-0000-0000-000000000002", C = "cccccccc-0000-0000-0000-000000000003";
private static JsonArray rows(String... json) { return JsonParser.parseString("[" + String.join(",", json) + "]").getAsJsonArray(); }
private static String row(String id, String life, boolean hidden, int x, int z, String claims, String revision) {
return "{\"id\":\"" + id + "\",\"name\":\"N" + id.charAt(0) + "\",\"tag\":\"T\",\"lifecycle\":\"" + life + "\",\"hidden\":" + hidden
+ ",\"homeBlock\":{\"source\":\"minecraft\",\"worldUuid\":\"" + W + "\",\"position\":{\"x\":" + x + ",\"y\":64,\"z\":" + z + "}" + revision + "},\"claimedChunks\":" + claims + "}";
}
private static Map<String, HomeRegistry.Entry> parse(JsonArray clans, JsonArray companies, JsonArray offices, List<HomeRegistry.Ref> unresolved, Map<String, HomeRegistry.Entry> previous) {
Map<String, JsonArray> by = new HashMap<>();
by.put("clan", clans); by.put("company", companies); by.put("protected", offices);
return HomeRegistry.parse(by, unresolved, previous);
}
private static Map<String, HomeRegistry.Entry> parse(JsonArray clans, JsonArray companies) { return parse(clans, companies, null, List.of(), Map.of()); }
@Test void negativeCoordinatesUseFloorDivisionAndExpandedChunksAreIncluded() {
var m = parse(null, rows(row(A, "active", false, -1, -17, "[{\"x\":3,\"z\":4}]", "")));
assertEquals("company", m.get(HomeRegistry.key(W, -1, -2)).kind());
assertNotNull(m.get(HomeRegistry.key(W, 3, 4)));
assertEquals(2, m.size());
}
@Test void archivedHiddenAndNonMinecraftAreDropped() {
var m = parse(rows(row(A, "archived", false, 0, 0, "[]", ""), row(B, "active", true, 100, 100, "[]", "")), rows(
"{\"id\":\"" + C + "\",\"lifecycle\":\"active\",\"hidden\":false,\"homeBlock\":{\"source\":\"discord\"}}"));
assertTrue(m.isEmpty());
}
@Test void overlappingOwnershipRejectsTheWholePayload() {
var ex = assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", "")), rows(row(B, "active", false, 5, 5, "[]", ""))));
assertTrue(ex.getMessage().contains("claimed by both"));
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 0, 0, "[{\"x\":0,\"z\":0}]", ""))));
}
@Test void malformedRowsAreRejected() {
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row("not-a-uuid", "active", false, 0, 0, "[]", ""))));
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", "").replace(W, "bad-world"))));
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 99_999_999, 0, "[]", ""))));
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[{\"x\":\"a\",\"z\":1}]", ""))));
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":-3"))));
assertThrows(HomeRegistry.Rejected.class, () -> parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(A, "active", false, 50, 50, "[]", "")), null));
}
@Test void aStaleClaimRevisionIsRejectedAndKeepsTheOldProjection() {
var first = parse(null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":5")));
assertEquals(5, first.values().iterator().next().revision());
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"revision\":4")), null, List.of(), first));
var newer = parse(null, rows(row(A, "active", false, 200, 200, "[]", ",\"revision\":6")), null, List.of(), first);
assertNull(newer.get(HomeRegistry.key(W, 0, 0)), "old home chunk is released");
assertNotNull(newer.get(HomeRegistry.key(W, 12, 12)));
}
@Test void unresolvedRecordsKeepWhatTheyOwnedAndMissingOnesDoNot() {
var before = parse(rows(row(A, "active", false, 0, 0, "[]", ""), row(B, "active", false, 100, 100, "[]", "")), null);
assertEquals(2, before.size());
// A is under review (listed unresolved and absent from rows); B vanished and is not in review.
var after = parse(rows(), null, null, List.of(new HomeRegistry.Ref("clan", A)), before);
assertEquals(1, after.size());
assertEquals(A, after.values().iterator().next().id());
// A row with an unknown lifecycle counts as unresolved too.
var odd = parse(rows(row(A, "pending-review", false, 0, 0, "[]", "")), null, null, List.of(), before);
assertNotNull(odd.get(HomeRegistry.key(W, 0, 0)));
}
@Test void anUnresolvedRecordCannotHoldAChunkAnActiveRecordNowClaims() {
var before = parse(rows(row(A, "active", false, 0, 0, "[]", "")), null);
assertThrows(HomeRegistry.Rejected.class, () -> parse(null, rows(row(B, "active", false, 0, 0, "[]", "")), null, List.of(new HomeRegistry.Ref("clan", A)), before));
}
@Test void officesProjectAsProtectedAndStorageRoundTrips() {
var m = parse(null, null, rows(row(A, "active", false, 0, 0, "[]", ",\"revision\":7")), List.of(), Map.of());
assertEquals("protected", m.values().iterator().next().kind());
assertEquals(m, HomeRegistry.fromMap(HomeRegistry.toMap(m)));
var r = new HomeRegistry();
r.install(m, "s1");
assertEquals(1, r.claimCount("protected", A));
assertEquals(0, r.claimCount("clan", A));
assertEquals("s1", r.stateId());
r.install(Map.of(), "");
assertEquals(0, r.claimCount("protected", A));
}
@Test void aCorruptCacheEntryIsRejected() {
assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", Map.of("kind", "wizard", "id", A))));
assertThrows(HomeRegistry.Rejected.class, () -> HomeRegistry.fromMap(Map.of("k", "oops")));
}
}

View file

@ -0,0 +1,23 @@
package com.example.dunegroups;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PvpPolicyTest {
@Test void insideTheChunkNobodyCanHurtAnybodyAndOutsidersAreIncluded() {
assertTrue(PvpPolicy.blocked(false, false, true), "outsider hits someone standing on company land");
assertTrue(PvpPolicy.blocked(false, true, false), "someone on company land shoots out");
assertTrue(PvpPolicy.blocked(false, true, true));
}
@Test void outsideCompanyLandNothingChangesAndSelfDamageIsLeftAlone() {
assertFalse(PvpPolicy.blocked(false, false, false));
assertFalse(PvpPolicy.blocked(true, true, true));
}
@Test void harmfulEffectsCoverPotionsAndClouds() {
for (String k : new String[]{"poison", "instant_damage", "slowness", "weakness", "wither", "levitation", "blindness"}) assertTrue(PvpPolicy.harmful(k), k);
for (String k : new String[]{"speed", "regeneration", "instant_health", "fire_resistance", "", null}) assertFalse(PvpPolicy.harmful(k), String.valueOf(k));
}
}

View file

@ -0,0 +1,19 @@
package com.dunerealms.jarvis;
import java.util.*;
import java.util.function.Supplier;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
/** ClanDirectory over the current central projection. */
final class CentralClanDirectory implements ClanDirectory {
private final Supplier<OrganisationDirectory> source;
CentralClanDirectory(Supplier<OrganisationDirectory> source){this.source=source;}
@Override public String clanOf(UUID player){return source.get().clanOfPlayer(player);}
@Override public String name(String id){var g=source.get().clan(id);return g==null?null:g.name();}
@Override public String idByName(String name){for(var g:source.get().clans())if(g.name().equalsIgnoreCase(name))return g.id();return null;}
@Override public List<String> names(){var out=new ArrayList<String>();for(var g:source.get().clans())out.add(g.name());return out;}
@Override public Location home(String id){var g=source.get().clan(id);if(g==null||g.home()==null)return null;World w=Bukkit.getWorld(g.home().world());return w==null?null:new Location(w,g.home().x(),g.home().y(),g.home().z());}
@Override public long homeRevision(String id){var g=source.get().clan(id);return g==null||g.home()==null?-1:g.home().revision();}
}

View file

@ -0,0 +1,19 @@
package com.dunerealms.jarvis;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
/** What Imperial Raid needs to know about clans. Backed by the central projection, or by MedievalFactions in legacy mode. */
interface ClanDirectory {
/** Central clan id of the player's clan, or null. */
String clanOf(UUID player);
/** Clan display name, or null when the id is unknown. */
String name(String clanId);
String idByName(String name);
List<String> names();
/** Registered Home Block position, or null when the clan has none or its world is not loaded. */
Location home(String clanId);
/** Claim revision of that Home Block, or -1 when the source does not carry one. */
long homeRevision(String clanId);
}

View file

@ -0,0 +1,39 @@
package com.dunerealms.jarvis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
/** Publishes a replayable Home Block receipt only after the journal write succeeds. */
final class DuneGroupsAcknowledgements {
@FunctionalInterface interface Writer {
void write(List<String> pending) throws IOException;
}
private List<String> pending = List.of();
List<String> pending() { return pending; }
void restore(Collection<String> receipts) {
pending = List.copyOf(new LinkedHashSet<>(receipts));
}
void append(Collection<String> receipts, Writer writer) throws IOException {
var next = new LinkedHashSet<>(pending);
next.addAll(receipts);
publish(List.copyOf(next), writer);
}
void remove(String receipt, Writer writer) throws IOException {
var next = new ArrayList<>(pending);
next.remove(receipt);
publish(List.copyOf(next), writer);
}
private void publish(List<String> next, Writer writer) throws IOException {
writer.write(next);
pending = next;
}
}

View file

@ -0,0 +1,179 @@
package com.dunerealms.jarvis;
import com.google.gson.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
/**
* Projects central clan, company and protected-office records without Towny or MedievalFactions: Home Blocks and the
* company PvP rule in DuneGroups, estate regions in WorldGuard, Home NPCs, the Kaitain Emperor NPC, and the organisation
* directory used by Imperial Raid. Deeds, rosters and banks stay central. Selected with native.backend: dunegroups.
* Construction fails when DuneGroups or WorldGuard is unavailable so the caller can stop JARVIS instead of running blind.
*/
final class DuneGroupsKeyWorker implements NativeKeys {
private final JavaPlugin plugin;private final SharedGameApi api;private final Plugin groups;private final Method activate,deactivate,sync,claimCount;
private final NativeWorldGuard guards;private final OrganisationHomeNpcs homeNpcs;private final AtomicBoolean busy=new AtomicBoolean();
private final Path stateFile,directoryFile;private final BukkitTask task;private final CentralClanDirectory clanView;
private final FactionsAdapter legacyFactions;private final TownyAdapter legacyTowns;
private final boolean legacyFactionsPresent,legacyTownyPresent;
private final Set<String> ownedClans=new TreeSet<>(),ownedCompanies=new TreeSet<>(),ownedOffices=new TreeSet<>();
private final DuneGroupsAcknowledgements acknowledgements=new DuneGroupsAcknowledgements();
private volatile OrganisationDirectory directory=OrganisationDirectory.EMPTY;
private volatile boolean closed,homeNpcPending;private volatile String status="Waiting for central organisation keys";
private String previousFailure="",appliedState="";
DuneGroupsKeyWorker(JavaPlugin plugin,SharedGameApi api)throws Exception {
this.plugin=plugin;this.api=api;
groups=Bukkit.getPluginManager().getPlugin("DuneGroups");
if(groups==null||!groups.isEnabled())throw new IllegalStateException("DuneGroups unavailable");
activate=groups.getClass().getMethod("activate");deactivate=groups.getClass().getMethod("deactivate");
sync=groups.getClass().getMethod("sync",String.class);claimCount=groups.getClass().getMethod("claimCount",String.class,String.class);
guards=new NativeWorldGuard(plugin); // throws when WorldGuard is unavailable: WorldGuard stays the build-protection authority
homeNpcs=new OrganisationHomeNpcs(plugin);
stateFile=plugin.getDataFolder().toPath().resolve("dunegroups-worker.yml");directoryFile=plugin.getDataFolder().toPath().resolve("organisation-directory.json");
load();
clanView=new CentralClanDirectory(()->directory);
// During migration the old vendors may still be installed. Their projections must be gone before cleanup is acknowledged.
var mf=Bukkit.getPluginManager().getPlugin("MedievalFactions");var towny=Bukkit.getPluginManager().getPlugin("Towny");
FactionsAdapter f=null;TownyAdapter t=null;
if(mf!=null&&mf.isEnabled())try{f=new FactionsAdapter(mf,new HashSet<>());}catch(ReflectiveOperationException|RuntimeException unverifiable){plugin.getLogger().warning("Legacy MedievalFactions cannot be verified; relocation acknowledgements will wait.");}
if(towny!=null&&towny.isEnabled())try{t=new TownyAdapter(towny,new HashSet<>(),new HashSet<>());}catch(ReflectiveOperationException|RuntimeException unverifiable){plugin.getLogger().warning("Legacy Towny cannot be verified; relocation acknowledgements will wait.");}
legacyFactions=f;legacyTowns=t;legacyFactionsPresent=mf!=null;legacyTownyPresent=towny!=null;
task=Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,this::refresh,60L,300L);
}
private static Object invokeOn(Method m,Object target,Object... args)throws Exception{
try{return m.invoke(target,args);}catch(InvocationTargetException e){Throwable c=e.getCause();if(c instanceof Exception x)throw x;throw e;}
}
private Object invoke(Method m,Object... args)throws Exception{return invokeOn(m,groups,args);}
@Override public String status(){return status;}
@Override public void request(){Bukkit.getScheduler().runTaskAsynchronously(plugin,this::refresh);}
@Override public ClanDirectory clans(){return clanView;}
// ---- durable worker state: owned ids (so vanished records can be retired) and acknowledgements not yet delivered ----
private void load()throws IOException {
var yml=YamlConfiguration.loadConfiguration(stateFile.toFile());
ownedClans.addAll(yml.getStringList("clans"));ownedCompanies.addAll(yml.getStringList("companies"));ownedOffices.addAll(yml.getStringList("offices"));
acknowledgements.restore(yml.getStringList("pendingAcks"));
if(Files.exists(directoryFile))try{storedDirectory=OrganisationDirectory.fromJson(JsonParser.parseString(Files.readString(directoryFile)).getAsJsonObject());}
catch(RuntimeException unreadable){plugin.getLogger().warning("Stored organisation directory is unreadable; waiting for the next central state.");}
}
private OrganisationDirectory storedDirectory=OrganisationDirectory.EMPTY;
private void save(OrganisationDirectory next,List<String> acknowledgements)throws IOException {
Files.createDirectories(stateFile.getParent());var yml=new YamlConfiguration();
yml.set("clans",new ArrayList<>(ownedClans));yml.set("companies",new ArrayList<>(ownedCompanies));yml.set("offices",new ArrayList<>(ownedOffices));yml.set("pendingAcks",acknowledgements);
atomic(directoryFile,next.toJson().toString());atomic(stateFile,yml.saveToString());
}
private static void atomic(Path target,String text)throws IOException {
if(Files.exists(target)&&Files.readString(target).equals(text))return;
Path temp=target.resolveSibling(target.getFileName()+".tmp");Files.writeString(temp,text);
Files.move(temp,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
}
private static JsonArray array(JsonObject state,String field){
var e=state.get(field);if(e==null||!e.isJsonArray())throw new IllegalStateException("Native state is missing "+field);return e.getAsJsonArray();
}
private static Set<String> ids(JsonArray rows){var out=new TreeSet<String>();for(var v:rows)out.add(v.getAsJsonObject().get("id").getAsString());return out;}
private static Set<String> reviewIds(JsonArray review,String kind){
var out=new TreeSet<String>();if(review!=null)for(var v:review){var r=v.getAsJsonObject();if(kind.equals(r.get("kind").getAsString()))out.add(r.get("id").getAsString());}return out;
}
/** Rows plus archived stubs for ids we projected earlier that vanished and are not under review, so their regions are removed. */
private static JsonArray withRetired(JsonArray rows,Set<String> owned,Set<String> review){
var records=rows.deepCopy();for(String id:NativeProjectionScope.retired(owned,ids(rows),review)){var stub=new JsonObject();stub.addProperty("id",id);stub.addProperty("lifecycle","archived");records.add(stub);}return records;
}
private static Set<String> activeIds(JsonArray rows){
var out=new TreeSet<String>();for(var v:rows){var r=v.getAsJsonObject();if("active".equals(r.get("lifecycle").getAsString())&&!(r.has("hidden")&&r.get("hidden").getAsBoolean()))out.add(r.get("id").getAsString());}return out;
}
private static String digest(String text)throws Exception {
var hash=MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));var out=new StringBuilder();for(byte b:hash)out.append(String.format("%02x",b));return out.toString();
}
private void deliverPending()throws Exception {
for(String text:acknowledgements.pending()){
api.homeCleanup(JsonParser.parseString(text).getAsJsonObject());
acknowledgements.remove(text, remaining->save(storedDirectory,remaining));
}
}
private void refresh(){
if(closed||!busy.compareAndSet(false,true))return;
try{
String folder=plugin.getDataFolder().getAbsoluteFile().getParentFile().getParentFile().getName().replace('_','-');
String server=plugin.getConfig().getString("native.server-key",folder);
if(!Set.of("lobby","caladan","giedi-prime","kaitain","sigma-draconis-iv","arrakis").contains(server))throw new IllegalStateException("Native server key is not configured");
deliverPending(); // an earlier cleanup that was persisted but not acknowledged goes first, with its original request and key
var state=api.nativeState(server);if(closed)return;
JsonArray clans=array(state,"clans"),companies=array(state,"companies"),offices=array(state,"offices"),wars=array(state,"wars");
if(clans.size()>512||companies.size()>512||offices.size()>512||wars.size()>1000)throw new IllegalStateException("Native inventory invalid");
var review=state.has("review")&&!state.get("review").isJsonNull()?state.getAsJsonArray("review"):null;
var relocations=state.has("relocations")&&!state.get("relocations").isJsonNull()?state.getAsJsonArray("relocations"):new JsonArray();
String desired=clans.toString()+companies+offices+wars+relocations+(review==null?"":review)+(state.has("imperialAppearance")?state.get("imperialAppearance"):"");
if(server.equals("kaitain")){var appearance=state.has("imperialAppearance")&&!state.get("imperialAppearance").isJsonNull()?state.getAsJsonObject("imperialAppearance"):null;Bukkit.getScheduler().runTask(plugin,()->{try{var gui=Bukkit.getPluginManager().getPlugin("DunerealmsGUI");if(gui!=null&&gui.isEnabled())gui.getClass().getMethod("updateImperialQuestNpc",UUID.class,String.class,String.class).invoke(gui,appearance==null?null:UUID.fromString(appearance.get("uuid").getAsString()),appearance==null?null:appearance.get("name").getAsString(),appearance==null?null:appearance.get("term").getAsString());}catch(ReflectiveOperationException|IllegalArgumentException ignored){}});}
if(desired.equals(appliedState)&&!homeNpcPending)return;
var nextDirectory=storedDirectory.next(state); // validates UUIDs and duplicate war keys before anything is applied
var clanRecords=withRetired(clans,ownedClans,reviewIds(review,"clan"));
var companyRecords=withRetired(companies,ownedCompanies,reviewIds(review,"company"));
var officeRecords=withRetired(offices,ownedOffices,reviewIds(review,"protected"));
var payload=new JsonObject();payload.addProperty("stateId",digest(desired));payload.add("clans",clanRecords);payload.add("companies",companyRecords);payload.add("offices",officeRecords);
var unresolved=new JsonArray();if(review!=null)for(var v:review){var r=v.getAsJsonObject();var u=new JsonObject();u.add("kind",r.get("kind"));u.add("id",r.get("id"));unresolved.add(u);}payload.add("unresolved",unresolved);
var nextClans=new TreeSet<>(activeIds(clans));nextClans.addAll(reviewIds(review,"clan"));
var nextCompanies=new TreeSet<>(activeIds(companies));nextCompanies.addAll(reviewIds(review,"company"));
var nextOffices=new TreeSet<>(activeIds(offices));nextOffices.addAll(reviewIds(review,"protected"));
var done=new CompletableFuture<Integer>();var cleanupReady=new ArrayList<JsonObject>();
Bukkit.getScheduler().runTask(plugin,()->{try{
if(closed)throw new IllegalStateException("Translator stopped");
int count=(Integer)invoke(sync,payload.toString()); // throws on a conflict or a failed write; the last valid projection stays
guards.reconcile(clanRecords,"clan",wars);guards.reconcile(companyRecords,"company",wars);guards.reconcile(officeRecords,"protected",wars);
boolean npcs=plugin.getConfig().getBoolean("pol-home-npcs-enabled",true);
if(npcs)try{homeNpcPending=!homeNpcs.reconcile(clanRecords,companies,nextClans,nextCompanies,review);}catch(Exception pending){homeNpcPending=true;plugin.getLogger().warning("Home NPC projection awaiting retry; Home Blocks and estate regions remain intact.");}
for(var entry:relocations){var op=entry.getAsJsonObject();String kind=op.get("kind").getAsString(),id=op.get("id").getAsString();
if(!Set.of("clan","company").contains(kind))throw new IllegalStateException("Relocation cleanup is not complete");
if((Long)invoke(claimCount,kind,id)!=0)throw new IllegalStateException("Relocation cleanup is not complete: Home Block claim remains");
if(!guards.absent(kind,id))throw new IllegalStateException("Relocation cleanup is not complete: WorldGuard region remains");
boolean legacyGone=kind.equals("clan")
?!legacyFactionsPresent||legacyFactions!=null&&legacyFactions.absent(id)
:!legacyTownyPresent||legacyTowns!=null&&legacyTowns.absent(id);
if(!legacyGone){homeNpcPending=true;continue;}
if(npcs&&!homeNpcs.absent(kind,id)){homeNpcPending=true;continue;}
cleanupReady.add(op);}
done.complete(count);}catch(Exception failure){done.completeExceptionally(failure);}});
int chunks=done.get(20,TimeUnit.SECONDS);
ownedClans.clear();ownedClans.addAll(nextClans);ownedCompanies.clear();ownedCompanies.addAll(nextCompanies);ownedOffices.clear();ownedOffices.addAll(nextOffices);
var stagedAcks=new ArrayList<String>();
for(var op:cleanupReady){var ack=new JsonObject();ack.addProperty("server",server);ack.add("requestId",op.get("requestId"));ack.add("keyId",op.get("keyId"));stagedAcks.add(ack.toString());}
acknowledgements.append(stagedAcks, pending->save(nextDirectory,pending));
storedDirectory=nextDirectory;directory=nextDirectory;
var activated=new CompletableFuture<Void>();
Bukkit.getScheduler().runTask(plugin,()->{
try{if(closed)throw new IllegalStateException("Translator stopped");invoke(activate);activated.complete(null);}
catch(Exception failure){activated.completeExceptionally(failure);}
});
activated.get(20,TimeUnit.SECONDS);
deliverPending(); // then the original request and key are acknowledged
appliedState=desired;
long active=nextDirectory.wars().stream().filter(OrganisationDirectory.War::active).count();
status="Central keys connected; "+nextClans.size()+" clans, "+nextCompanies.size()+" companies, "+nextOffices.size()+" offices, "+active+" wars, "+chunks+" home chunks";
if(!previousFailure.isEmpty())plugin.getLogger().info(status);previousFailure="";
}catch(Exception failure){
status="DuneGroups processing pending: "+failure.getClass().getSimpleName();
String reason=failure.getClass().getSimpleName()+":"+failure.getMessage();
if(!reason.equals(previousFailure)){plugin.getLogger().warning(status+" ("+failure.getMessage()+")");previousFailure=reason;}
}finally{busy.set(false);}
}
@Override public void close(){closed=true;task.cancel();try{invoke(deactivate);}catch(Exception ignored){}}
}

View file

@ -0,0 +1,32 @@
package com.dunerealms.jarvis;
import static com.dunerealms.jarvis.NativeReflection.call;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
/** Legacy ClanDirectory over MedievalFactions. Used only while native.backend is legacy. */
final class FactionClanDirectory implements ClanDirectory {
private final Object factions;
FactionClanDirectory(Plugin mf)throws ReflectiveOperationException{
if(mf==null||!mf.isEnabled())throw new IllegalStateException("MedievalFactions unavailable");
factions=call(call(mf,"getServices"),"getFactionService");
}
private String id(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getId"));}
private String nm(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getName"));}
@Override public String clanOf(UUID player){try{Object f=call(factions,"getFactionByPlayerId",player.toString());return f==null?null:id(f);}catch(ReflectiveOperationException|RuntimeException unknown){return null;}}
@Override public String name(String id){try{Object f=call(factions,"getFactionByFactionId",id);return f==null?null:nm(f);}catch(ReflectiveOperationException|RuntimeException unknown){return null;}}
@Override public String idByName(String name){try{for(Object f:(List<?>)call(factions,"getFactions"))if(nm(f).equalsIgnoreCase(name))return id(f);}catch(ReflectiveOperationException|RuntimeException unknown){}return null;}
@Override public List<String> names(){try{var out=new ArrayList<String>();for(Object f:(List<?>)call(factions,"getFactions"))out.add(nm(f));return out;}catch(ReflectiveOperationException|RuntimeException unavailable){return List.of();}}
@Override public Location home(String clanId){
try{Object f=call(factions,"getFactionByFactionId",clanId);if(f==null)return null;Object position=call(f,"getHome");if(position==null)return null;
Object world=position.getClass().getMethod("getWorldId").invoke(position);World w=Bukkit.getWorld(UUID.fromString(String.valueOf(world)));if(w==null)return null;
double x=((Number)position.getClass().getMethod("getX").invoke(position)).doubleValue(),y=((Number)position.getClass().getMethod("getY").invoke(position)).doubleValue(),z=((Number)position.getClass().getMethod("getZ").invoke(position)).doubleValue();
return new Location(w,x,y,z);
}catch(ReflectiveOperationException|RuntimeException unavailable){return null;}
}
@Override public long homeRevision(String clanId){return -1;}
}

View file

@ -33,7 +33,7 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
private java.util.function.BiConsumer<Player,Boolean> pendingRequest;
private final File store;
private final Map<String,Raid> raids=new HashMap<>(); // keyed by raid id
private final Object factions;
private final ClanDirectory clans;
private int task=-1;
private final RaidWorldGuard protection;
@ -50,11 +50,8 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
Location home(){World w=Bukkit.getWorld(world);return w==null?null:new Location(w,x,y,z);}
}
ImperialRaid(JavaPlugin plugin,java.util.function.Consumer<ItemStack> stamp)throws ReflectiveOperationException,java.io.IOException{
this.plugin=plugin;this.stamp=Objects.requireNonNull(stamp);
var mf=Bukkit.getPluginManager().getPlugin("MedievalFactions");
if(mf==null||!mf.isEnabled())throw new IllegalStateException("MedievalFactions unavailable");
factions=call(call(mf,"getServices"),"getFactionService");
ImperialRaid(JavaPlugin plugin,java.util.function.Consumer<ItemStack> stamp,ClanDirectory clans)throws ReflectiveOperationException,java.io.IOException{
this.plugin=plugin;this.stamp=Objects.requireNonNull(stamp);this.clans=Objects.requireNonNull(clans);
protection=new RaidWorldGuard();
raidKey=new NamespacedKey(plugin,"imperial_raid");ordererKey=new NamespacedKey(plugin,"imperial_raid_orderer");captainKey=new NamespacedKey(plugin,"imperial_raid_captain");
settings=ImperialRaidPlan.Settings.defaults();
@ -82,33 +79,14 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
}
// ---- clan lookups (native MedievalFactions roster, mirrored by JARVIS) ----
private Object factionOf(UUID player)throws ReflectiveOperationException{return call(factions,"getFactionByPlayerId",player.toString());}
private String idOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getId"));}
private String nameOf(Object faction)throws ReflectiveOperationException{return String.valueOf(call(faction,"getName"));}
private Object factionByName(String name)throws ReflectiveOperationException{
for(Object f:(List<?>)call(factions,"getFactions"))if(nameOf(f).equalsIgnoreCase(name))return f;
return null;
}
private List<String> factionNames(){
try{var out=new ArrayList<String>();for(Object f:(List<?>)call(factions,"getFactions"))out.add(nameOf(f));return out;}catch(ReflectiveOperationException|RuntimeException unavailable){return List.of();}
}
/** Home Block position, or null when the clan has none or its world is not loaded. */
private Location homeOf(Object faction)throws ReflectiveOperationException{
Object position=call(faction,"getHome");if(position==null)return null;
Object world=position.getClass().getMethod("getWorldId").invoke(position);
World w=Bukkit.getWorld(UUID.fromString(String.valueOf(world)));if(w==null)return null;
double x=((Number)position.getClass().getMethod("getX").invoke(position)).doubleValue(),y=((Number)position.getClass().getMethod("getY").invoke(position)).doubleValue(),z=((Number)position.getClass().getMethod("getZ").invoke(position)).doubleValue();
return new Location(w,x,y,z);
}
private boolean inClan(Player player,String clanId){
try{Object f=factionOf(player.getUniqueId());return f!=null&&clanId.equals(idOf(f));}catch(ReflectiveOperationException|RuntimeException unknown){return false;}
}
// ---- clan lookups (central organisation projection; MedievalFactions only in legacy mode) ----
private boolean inClan(Player player,String clanId){return clanId.equals(clans.clanOf(player.getUniqueId()));}
private boolean allowedVictim(Player player,String orderer){
if(orderer==null||orderer.isBlank()||!player.isOnline()||player.getGameMode()==GameMode.CREATIVE||player.getGameMode()==GameMode.SPECTATOR)return false;
try{Object faction=factionOf(player.getUniqueId());return faction==null||!orderer.equals(idOf(faction));}catch(ReflectiveOperationException|RuntimeException unavailable){return false;}
return !orderer.equals(clans.clanOf(player.getUniqueId()));
}
private List<Player> onlineOf(String clanId){var out=new ArrayList<Player>();for(var p:Bukkit.getOnlinePlayers())if(inClan(p,clanId))out.add(p);return out;}
private List<String> factionNames(){return clans.names();}
// ---- ordering ----
/** An authenticated paid bridge receipt is the only production entry. No native bank mutation. */
@ -116,9 +94,9 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
boolean preflight(Order order){
if(!Bukkit.isPrimaryThread())throw new IllegalStateException("Native preflight requires the server thread");
if(order.ordererId().equals(order.targetId())||order.retaliationLevel()<0||order.retaliationLevel()>3)return false;
try{Object target=call(factions,"getFactionByFactionId",order.targetId());if(target==null)return false;Location home=homeOf(target);
try{if(clans.name(order.targetId())==null)return false;Location home=clans.home(order.targetId());
return home!=null&&home.getWorld().getUID().equals(order.world())&&home.getBlockX()==(int)Math.floor(order.x())&&home.getBlockY()==(int)Math.floor(order.y())&&home.getBlockZ()==(int)Math.floor(order.z())&&home.getWorld().isChunkLoaded(home.getBlockX()>>4,home.getBlockZ()>>4)&&spawnPoints(home,order.targetId()).size()>=ImperialRaidPlan.raiderCount(settings,onlineOf(order.targetId()).size());
}catch(ReflectiveOperationException|RuntimeException unavailable){return false;}
}catch(RuntimeException unavailable){return false;}
}
void accepted(Order order,com.google.gson.JsonObject authoritativePaidReceipt)throws java.io.IOException{
var previous=journal.get(order.id());
@ -185,10 +163,11 @@ final class ImperialRaid implements Listener, CommandExecutor, TabCompleter {
}
com.google.gson.JsonObject preflightEvidence(ImperialRaidPermit permit){
if(!preflight(new Order(permit.id(),permit.orderingClan().toString(),permit.targetClan().toString(),permit.orderingName(),permit.targetName(),permit.world(),permit.x(),permit.y(),permit.z(),0,permit.retaliation())))throw new IllegalStateException("Travel to the target's registered world and load its safe home area first");
long knownRevision=clans.homeRevision(permit.targetClan().toString());if(knownRevision>=0&&knownRevision!=permit.claimRevision())throw new IllegalStateException("The target clan's claim revision has changed");
var result=new com.google.gson.JsonObject();result.addProperty("worldUuid",permit.world().toString());var p=new com.google.gson.JsonObject();p.addProperty("x",permit.x());p.addProperty("y",permit.y());p.addProperty("z",permit.z());result.add("position",p);result.addProperty("claimRevision",permit.claimRevision());result.addProperty("defendersOnline",onlineOf(permit.targetClan().toString()).size());result.addProperty("spawnable",true);result.addProperty("protected",false);result.addProperty("observedAt",System.currentTimeMillis());return result;
}
UUID clanOf(Player player)throws ReflectiveOperationException{Object clan=factionOf(player.getUniqueId());return clan==null?null:UUID.fromString(idOf(clan));}
UUID clanNamed(String name)throws ReflectiveOperationException{Object clan=factionByName(name);return clan==null?null:UUID.fromString(idOf(clan));}
UUID clanOf(Player player)throws ReflectiveOperationException{String clan=clans.clanOf(player.getUniqueId());return clan==null?null:UUID.fromString(clan);}
UUID clanNamed(String name)throws ReflectiveOperationException{String clan=clans.idByName(name);return clan==null?null:UUID.fromString(clan);}
private Raider spawn(Raid raid,Location at,ImperialRaidPlan.Slot slot){
Class<? extends Raider> type=slot.ranged()?Pillager.class:Vindicator.class;

View file

@ -15,10 +15,10 @@ final class ImperialRaidWorker implements AutoCloseable {
private final JavaPlugin plugin;private final SharedGameApi api;private final String server;private final ImperialRaid raid;
private final ImperialRaidRequests requests;private final AtomicBoolean busy=new AtomicBoolean();private final Set<UUID> ordering=java.util.concurrent.ConcurrentHashMap.newKeySet(),acknowledged=java.util.concurrent.ConcurrentHashMap.newKeySet();
private final BukkitTask poll;private volatile boolean closed;private String lastError="";private final long bootAt=System.currentTimeMillis();
ImperialRaidWorker(JavaPlugin plugin,SharedGameApi api,String server,Consumer<ItemStack> stamp)throws Exception{
ImperialRaidWorker(JavaPlugin plugin,SharedGameApi api,String server,Consumer<ItemStack> stamp,ClanDirectory clans)throws Exception{
this.plugin=plugin;this.api=api;this.server=server;if(server.equals("lobby"))throw new IllegalArgumentException("Travel to a planet to order a raid");
requests=new ImperialRaidRequests(plugin.getDataFolder().toPath().resolve("imperial-raid-requests.json"));
raid=new ImperialRaid(plugin,stamp);raid.orderRequests(this::order);raid.pendingRequests(this::resolve);
raid=new ImperialRaid(plugin,stamp,clans);raid.orderRequests(this::order);raid.pendingRequests(this::resolve);
poll=Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,this::refresh,40,100);
}
private static UUID event(UUID order,String kind){return UUID.nameUUIDFromBytes(("imperial-raid:"+order+":"+kind).getBytes(StandardCharsets.UTF_8));}

Some files were not shown because too many files have changed in this diff Show more