package com.dunerealms.npc; import java.io.StringReader; import java.io.StringWriter; import java.util.*; import org.bukkit.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.persistence.PersistentDataType; import org.bukkit.plugin.java.JavaPlugin; /** Citizens owns appearance/lifecycle; existing DuneNPC/JARVIS markers still own every action. */ public final class CitizensBridge implements Listener { private static final NamespacedKey ORIGINAL = new NamespacedKey("dunerealms", "original_npc_uuid"); private final JavaPlugin plugin; private final Set keys; private boolean warned; private CitizensBridge(JavaPlugin plugin, Set keys) { this.plugin = plugin; this.keys = Set.copyOf(keys); } public static void start(JavaPlugin plugin, NamespacedKey... keys) { var bridge = new CitizensBridge(plugin, Set.of(keys)); Bukkit.getPluginManager().registerEvents(bridge, plugin); Bukkit.getScheduler().runTask(plugin, bridge::scan); Bukkit.getScheduler().runTaskTimer(plugin, bridge::scan, 140L, 200L); var citizens = Bukkit.getPluginManager().getPlugin("Citizens"); if (citizens != null) try { var event = Class.forName("net.citizensnpcs.api.event.NPCSpawnEvent", true, citizens.getClass().getClassLoader()).asSubclass(Event.class); Bukkit.getPluginManager().registerEvent(event, bridge, EventPriority.MONITOR, (listener, value) -> { try { bridge.restore(value.getClass().getMethod("getNPC").invoke(value)); } catch (ReflectiveOperationException failure) { plugin.getLogger().warning("Citizens marker restore pending: " + failure.getClass().getSimpleName()); } }, plugin); } catch (ReflectiveOperationException failure) { plugin.getLogger().warning("Citizens spawn integration pending: " + failure.getClass().getSimpleName()); } } @EventHandler public void world(WorldLoadEvent event) { Bukkit.getScheduler().runTaskLater(plugin, this::scan, 60L); } private static Class api(String name) throws ReflectiveOperationException { var citizens = Bukkit.getPluginManager().getPlugin("Citizens"); if (citizens == null || !citizens.isEnabled()) throw new IllegalStateException("Citizens is not enabled"); return Class.forName(name, true, citizens.getClass().getClassLoader()); } private static Object registry() throws ReflectiveOperationException { Object registry = api("net.citizensnpcs.api.CitizensAPI").getMethod("getNPCRegistry").invoke(null); if (registry == null) throw new IllegalStateException("Citizens registry is not ready"); return registry; } private static Object npcCall(Object npc, String method, Class[] types, Object... args) throws ReflectiveOperationException { return api("net.citizensnpcs.api.npc.NPC").getMethod(method, types).invoke(npc, args); } private static Object read(Object npc, String key) throws ReflectiveOperationException { Object data = npcCall(npc, "data", new Class[0]); return api("net.citizensnpcs.api.npc.MetadataStore").getMethod("get", String.class).invoke(data, key); } private static void write(Object npc, String key, String value) throws ReflectiveOperationException { Object data = npcCall(npc, "data", new Class[0]); api("net.citizensnpcs.api.npc.MetadataStore").getMethod("setPersistent", String.class, Object.class).invoke(data, key, value); } public static UUID identity(Entity entity) { String value = entity.getPersistentDataContainer().has(ORIGINAL, PersistentDataType.STRING) ? entity.getPersistentDataContainer().get(ORIGINAL, PersistentDataType.STRING) : null; try { return value == null ? entity.getUniqueId() : UUID.fromString(value); } catch (IllegalArgumentException invalid) { return entity.getUniqueId(); } } public static Entity resolve(UUID id) { Entity nativeEntity = Bukkit.getEntity(id); if (nativeEntity != null) return nativeEntity; try { for (Object npc : (Iterable) registry()) { if (id.toString().equals(read(npc, "dr-original"))) return (Entity) npcCall(npc, "getEntity", new Class[0]); } } catch (ReflectiveOperationException | IllegalStateException unavailable) { /* Keep the journal for a later retry. */ } return null; } private static Object citizen(Entity entity) throws ReflectiveOperationException { return api("net.citizensnpcs.api.npc.NPCRegistry").getMethod("getNPC", Entity.class).invoke(registry(), entity); } public static boolean teleport(Entity entity, Location target) { try { Object npc = citizen(entity); if (npc != null) { npcCall(npc, "teleport", new Class[]{Location.class, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.class}, target, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.PLUGIN); return entity.getWorld().equals(target.getWorld()) && entity.getLocation().distanceSquared(target) < 1; } } catch (ReflectiveOperationException | IllegalStateException unavailable) { /* Native entity path remains valid. */ } return entity.teleport(target); } public static void remove(Entity entity) { try { Object npc = citizen(entity); if (npc != null) { npcCall(npc, "destroy", new Class[0]); return; } } catch (ReflectiveOperationException | IllegalStateException unavailable) { /* Native projection. */ } entity.remove(); } public static void skin(Entity entity, String name) { try { Object npc = citizen(entity); if (npc == null) return; Class type = api("net.citizensnpcs.trait.SkinTrait"); Object trait = npcCall(npc, "getOrAddTrait", new Class[]{Class.class}, type); type.getMethod("setSkinName", String.class, boolean.class).invoke(trait, name, true); } catch (ReflectiveOperationException | IllegalStateException unavailable) { /* Existing appearance remains. */ } } public static LivingEntity spawnContact(JavaPlugin plugin, Location location, String name, NamespacedKey marker) { Object npc = null; try { Object registry = registry(); npc = api("net.citizensnpcs.api.npc.NPCRegistry").getMethod("createNPC", EntityType.class, String.class).invoke(registry, EntityType.PLAYER, name); UUID original = UUID.randomUUID(); write(npc, "dr-id", plugin.getName() + ":" + location.getWorld().getUID() + ":" + marker + ":" + original); write(npc, "dr-owner", plugin.getName()); write(npc, "dr-original", original.toString()); Properties markers = new Properties(); markers.setProperty(marker.toString(), "b:1"); StringWriter text = new StringWriter(); markers.store(text, null); write(npc, "dr-markers", text.toString()); npcCall(npc, "setProtected", new Class[]{boolean.class}, true); if (!(boolean) npcCall(npc, "spawn", new Class[]{Location.class}, location)) throw new IllegalStateException("Citizens spawn blocked"); new CitizensBridge(plugin, Set.of(marker)).restore(npc); LivingEntity result = (LivingEntity) npcCall(npc, "getEntity", new Class[0]); api("net.citizensnpcs.api.npc.NPCRegistry").getMethod("saveToStore").invoke(registry); return result; } catch (ReflectiveOperationException | java.io.IOException | IllegalStateException failure) { if (npc != null) try { npcCall(npc, "destroy", new Class[0]); } catch (ReflectiveOperationException ignored) { } plugin.getLogger().warning("Citizens contact could not spawn; no vanilla trader created: " + failure.getMessage()); return null; } } public static void walk(Entity entity, Location target) { try { Object npc = citizen(entity); if (npc == null) return; Object navigator = npcCall(npc, "getNavigator", new Class[0]); api("net.citizensnpcs.api.ai.Navigator").getMethod("setTarget", Location.class).invoke(navigator, target); } catch (ReflectiveOperationException | IllegalStateException unavailable) { /* Retry on the next roam tick. */ } } private void restore(Object npc) throws ReflectiveOperationException { if (!plugin.getName().equals(read(npc, "dr-owner"))) return; Object entity = npcCall(npc, "getEntity", new Class[0]); Object value = read(npc, "dr-markers"); if (!(entity instanceof LivingEntity living) || !(value instanceof String text)) return; try { Properties markers = new Properties(); markers.load(new StringReader(text)); for (String raw : markers.stringPropertyNames()) { NamespacedKey key = NamespacedKey.fromString(raw); if (key == null) continue; String item = markers.getProperty(raw); if (item.startsWith("b:")) living.getPersistentDataContainer().set(key, PersistentDataType.BYTE, Byte.valueOf(item.substring(2))); else if (item.startsWith("s:")) living.getPersistentDataContainer().set(key, PersistentDataType.STRING, item.substring(2)); } String original = (String) read(npc, "dr-original"); if (original != null) living.getPersistentDataContainer().set(ORIGINAL, PersistentDataType.STRING, original); } catch (java.io.IOException | IllegalArgumentException invalid) { throw new IllegalStateException("Invalid persisted NPC markers", invalid); } } private void scan() { try { Object registry = registry(); warned = false; // Citizens recreates its Bukkit entity after chunk/server reload; restore identity before backend reconciliation. for (Object npc : (Iterable) registry) restore(npc); for (World world : Bukkit.getWorlds()) for (LivingEntity entity : new ArrayList<>(world.getLivingEntities())) { if (keys.stream().noneMatch(key -> entity.getPersistentDataContainer().has(key))) continue; if (citizen(entity) == null) convert(entity, registry); } } catch (ReflectiveOperationException | IllegalStateException failure) { if (!warned) plugin.getLogger().warning("NPC conversion awaiting Citizens; existing NPC backend retained: " + failure.getMessage()); warned = true; } } private void convert(LivingEntity legacy, Object registry) throws ReflectiveOperationException { var marker = keys.stream().sorted(Comparator.comparing(NamespacedKey::toString)).filter(key -> legacy.getPersistentDataContainer().has(key)).findFirst().orElseThrow(); String markerValue = legacy.getPersistentDataContainer().has(marker, PersistentDataType.STRING) ? legacy.getPersistentDataContainer().get(marker, PersistentDataType.STRING) : null; boolean unique = marker.toString().equals("dunecore:smuggler") || marker.toString().equals("dunerealms:spice-seller"); String stable = plugin.getName() + ":" + legacy.getWorld().getUID() + ":" + marker + ":" + (unique ? identity(legacy) : markerValue == null ? "1" : markerValue); Object npc = null; for (Object candidate : (Iterable) registry) if (stable.equals(read(candidate, "dr-id"))) { npc = candidate; break; } boolean created = npc == null; if (created) { String name = legacy.getCustomName() == null ? "DuneRealms contact" : ChatColor.stripColor(legacy.getCustomName()); npc = api("net.citizensnpcs.api.npc.NPCRegistry").getMethod("createNPC", EntityType.class, String.class).invoke(registry, EntityType.PLAYER, name); write(npc, "dr-id", stable); write(npc, "dr-owner", plugin.getName()); write(npc, "dr-original", identity(legacy).toString()); Properties markers = new Properties(); for (NamespacedKey key : legacy.getPersistentDataContainer().getKeys()) { String text = legacy.getPersistentDataContainer().has(key, PersistentDataType.STRING) ? legacy.getPersistentDataContainer().get(key, PersistentDataType.STRING) : null; if (text != null) markers.setProperty(key.toString(), "s:" + text); else if (legacy.getPersistentDataContainer().has(key, PersistentDataType.BYTE)) { Byte flag = legacy.getPersistentDataContainer().get(key, PersistentDataType.BYTE); if (flag != null) markers.setProperty(key.toString(), "b:" + flag); } } try { StringWriter text = new StringWriter(); markers.store(text, null); write(npc, "dr-markers", text.toString()); } catch (java.io.IOException impossible) { throw new IllegalStateException(impossible); } } try { npcCall(npc, "setProtected", new Class[]{boolean.class}, true); if (!(boolean) npcCall(npc, "isSpawned", new Class[0]) && !(boolean) npcCall(npc, "spawn", new Class[]{Location.class}, legacy.getLocation())) throw new IllegalStateException("Citizens spawn was blocked"); restore(npc); Entity replacement = (Entity) npcCall(npc, "getEntity", new Class[0]); if (replacement == null || !replacement.isValid()) throw new IllegalStateException("Citizens entity unavailable"); api("net.citizensnpcs.api.npc.NPCRegistry").getMethod("saveToStore").invoke(registry); legacy.remove(); // Only retire the old body after the functional replacement is present and persisted. } catch (ReflectiveOperationException | IllegalStateException failure) { if (created) npcCall(npc, "destroy", new Class[0]); throw failure; } } }