Add persistent quest and organisation contacts with shared dialogue and character artwork

This commit is contained in:
Dev 2026-11-25 14:44:27 +01:00
commit e51579554c
9 changed files with 425 additions and 81 deletions

View file

@ -28,6 +28,8 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
private MCGUIMenus modernMenus;
private EcologyArtwork ecologyArtwork;
private QuestMenus quests;
private PolQuestNpc polQuestNpcs;
public void updateImperialQuestNpc(UUID uuid,String name,String term){if(polQuestNpcs!=null)polQuestNpcs.imperialAppearance(uuid,name,term);}
private ExchangeMenus exchange;
private SpiceMenus spice;
private ItemPreviewMenu itemPreviews;
@ -80,6 +82,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
Bukkit.getScheduler().runTaskTimer(this,this::tick,20L,20L);
Bukkit.getScheduler().runTaskLater(this,this::ensureRegistrar,40L);
new QuartermasterNpc(this,p->quests.quartermaster(p,()->exchange.open(p),()->exchange.openKits(p)));
polQuestNpcs=new PolQuestNpc(this,(p,role)->quests.openRole(p,role));
Bukkit.getScheduler().runTaskTimer(this,()->{for(Player p:Bukkit.getOnlinePlayers()){removeOldNavigators(p);refreshSidebar(p);}},80L,600L);
getLogger().info("House selector and Mentat screens enabled; central J.A.R.V.I.S. bridge; no Core/Lobby replacement.");
}
@ -91,6 +94,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
if(sender instanceof Player player&&(command.getName().equals("exchange")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("exchange"))){exchange.open(player);return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length>0&&args[0].equalsIgnoreCase("previewitem")){try{if(args.length!=3)throw new IllegalArgumentException();int revision=Integer.parseInt(args[2]);if(revision<1||revision>999999)throw new IllegalArgumentException();itemPreviews.open(player,UUID.fromString(args[1]),revision);}catch(IllegalArgumentException invalid){player.sendMessage("Use /drgui previewitem <saved-design-id> <revision>");}return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("quests")){quests.open(player);return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==2&&args[0].equalsIgnoreCase("movenpc")){polQuestNpcs.move(player,args[1]);return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("lore")){organisations.lore(player);return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==0){organisations.console(player);return true;}
if(sender instanceof Player player&&command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("item")){giveCodex(player,true);return true;}
@ -173,6 +177,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
}
private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);}
private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void organisationContact(org.bukkit.event.player.PlayerInteractEntityEvent event){String marker=event.getRightClicked().getPersistentDataContainer().get(new NamespacedKey("dunerealms","organisation_home_npc"),PersistentDataType.STRING);if(marker==null)return;event.setCancelled(true);if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;String[] parts=marker.split(":",2);if(parts.length!=2||!Set.of("clan","company").contains(parts[0]))return;try{String id=UUID.fromString(parts[1]).toString();organisations.openHomeNpc(event.getPlayer(),parts[0].equals("clan")?"clans":"companies",id);}catch(IllegalArgumentException ignored){}}
@EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}}
@EventHandler(priority=EventPriority.HIGHEST) public void oldNavigator(PlayerInteractEvent e){if(e.getHand()!=EquipmentSlot.HAND||e.getItem()==null||!e.getItem().hasItemMeta()||!e.getAction().isRightClick())return;var data=e.getItem().getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){e.setCancelled(true);organisations.console(e.getPlayer());return;}}
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);openGuild(e.getPlayer(),null);}}

View file

@ -26,6 +26,7 @@ final class HouseBridge {
}
JsonObject request(UUID player, String faction, int version, UUID requestId) throws Exception { return (JsonObject) call(house, player, faction, version, requestId); }
JsonObject quests(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestQuests",UUID.class,JsonObject.class),player,input);}
JsonObject decisions(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestPoliticalDecisions",UUID.class,JsonObject.class),player,input);}
JsonObject spice(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestSpice",UUID.class,JsonObject.class),player,input);}
int spiceCount(org.bukkit.entity.Player p)throws Exception{return ((Number)call(translator.getClass().getMethod("spiceCount",org.bukkit.entity.Player.class),p)).intValue();}
int spiceCount(org.bukkit.entity.Player p,String channel)throws Exception{return ((Number)call(translator.getClass().getMethod("spiceCount",org.bukkit.entity.Player.class,String.class),p,channel)).intValue();}
@ -35,6 +36,7 @@ final class HouseBridge {
java.util.UUID refinerNpc(org.bukkit.entity.Player player)throws Exception{return (java.util.UUID)call(translator.getClass().getMethod("refinerNpc",org.bukkit.entity.Player.class),player);}
void refineSpice(org.bukkit.entity.Player player,JsonObject permit)throws Exception{call(translator.getClass().getMethod("refineSpice",org.bukkit.entity.Player.class,JsonObject.class),player,permit);}
java.util.UUID starterNpc(org.bukkit.entity.Player player)throws Exception{return (java.util.UUID)call(translator.getClass().getMethod("starterNpc",org.bukkit.entity.Player.class),player);}
java.util.UUID questCharacterNpc(org.bukkit.entity.Player player,String role)throws Exception{return (java.util.UUID)call(translator.getClass().getMethod("questCharacterNpc",org.bukkit.entity.Player.class,String.class),player,role);}
void research(org.bukkit.entity.Player p,JsonObject permit)throws Exception{call(translator.getClass().getMethod("research",org.bukkit.entity.Player.class,JsonObject.class),p,permit);}
JsonObject refitSnapshot(org.bukkit.entity.Player p)throws Exception{return (JsonObject)call(translator.getClass().getMethod("refitSnapshot",org.bukkit.entity.Player.class),p);}
boolean refitEquipment(org.bukkit.entity.Player p,JsonObject permit)throws Exception{return Boolean.TRUE.equals(call(translator.getClass().getMethod("refitEquipment",org.bukkit.entity.Player.class,JsonObject.class),p,permit));}

View file

@ -32,7 +32,7 @@ final class MCGUIMenus implements AutoCloseable {
contentType=Class.forName("ai.resourcepack.ui.framework.api.ViewContent",true,cl);optionsType=Class.forName("ai.resourcepack.ui.framework.api.ViewOptions",true,cl);
defaultOptions=optionsType.getField("DEFAULT").get(null);openView=api.getMethod("openView",Player.class,contentType,optionsType);
Class<?> page=Class.forName("ai.resourcepack.ui.html.Page",true,cl),load=Class.forName("ai.resourcepack.ui.html.Page$Loader",true,cl),state=Class.forName("ai.resourcepack.ui.html.css.Selector$State",true,cl),renderer=Class.forName("ai.resourcepack.ui.html.HtmlRenderer",true,cl);
Files.createDirectories(base.getParent());loader=load.getConstructor(boolean.class,Path.class).newInstance(false,base.getParent().resolve("cache"));
Files.createDirectories(base.getParent());Path avatarArt=base.getParent().resolve("art");Files.createDirectories(avatarArt);for(int i=0;i<8;i++){String name="npc_avatar_"+i+".png";try(var source=plugin.getResource("mcgui-npc-avatars/"+name)){if(source!=null)Files.copy(source,avatarArt.resolve(name),StandardCopyOption.REPLACE_EXISTING);}}loader=load.getConstructor(boolean.class,Path.class).newInstance(false,base.getParent().resolve("cache"));
pageOf=page.getMethod("of",String.class,Path.class,load);none=state.getField("NONE").get(null);render=renderer.getMethod("render",page,int.class,int.class,double.class,double.class,state);
for(Method m:renderer.getMethods())if(m.getName().equals("state")&&m.getParameterCount()==2)hoverState=m;
Class<?> canvas=Class.forName("ai.resourcepack.ui.framework.api.Canvas",true,cl);draw=canvas.getMethod("draw",java.awt.image.BufferedImage.class,int.class,int.class);

File diff suppressed because one or more lines are too long

View file

@ -5,8 +5,8 @@ import java.util.UUID;
/** The shared artwork and per-planet material layers use independent pack IDs. */
final class NetworkArtworkPolicy {
static final UUID PACK_ID=UUID.fromString("a7b5ab7d-d8d8-5b51-b016-71a5f4c00008");
static final Pack WORLD=new Pack("https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v5.zip","4699d6b181d72a64265c48e82427dd670a8c3fac");
static final Pack LOBBY=new Pack("https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-Lobby-v5.zip","e4b937a0af2ea7eebd790c661b4703f899fedf2d");
static final Pack WORLD=new Pack("https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v6.zip","faa231adf01f7564010ed360c69f5b021ac4e677");
static final Pack LOBBY=new Pack("https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-Lobby-v6.zip","55c04dd4bd65163d0d9b04eacc0a2e18de5fe86d");
record Pack(String url,String hash){}
private NetworkArtworkPolicy(){}
static Pack select(boolean lobby,String url,String hash){

View file

@ -33,6 +33,12 @@ final class OrganisationMenus implements Listener {
Bukkit.getScheduler().runTask(plugin,()->{busy.remove(p.getUniqueId());if(!p.isOnline())return;if(result==null){p.sendMessage("Your organisation keys are temporarily unavailable. Please reopen the menu.");return;}if(kind==null)start(p,result);else choose(p,result,kind);});
});
}
void openHomeNpc(Player p,String kind,String id){
if(!Set.of("clans","companies").contains(kind)||!busy.add(p.getUniqueId()))return;UUID world=p.getWorld().getUID();
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;try{data=bridge.organisations(p.getUniqueId());}catch(Exception ignored){}JsonObject result=data;if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTask(plugin,()->{busy.remove(p.getUniqueId());if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(result!=null&&result.has(kind))for(var item:result.getAsJsonArray(kind)){var row=item.getAsJsonObject();if(row.has("id")&&id.equals(row.get("id").getAsString())){organisation(p,result,kind,row);return;}}p.sendMessage("This organisation contact is available to current authorised members.");});
});
}
void lore(Player p){
var panel=panel(p,"Item lore archive · Preview",false);String[] kinds={"MENU","EQUIPMENT","KIT","COMPONENT","TICKET","CASH","RIHLA","DEED","QUEST"};Material[] materials={Material.COMPASS,Material.IRON_SWORD,Material.CHEST,Material.AMETHYST_SHARD,Material.PAPER,Material.GOLD_NUGGET,Material.WRITABLE_BOOK,Material.MAP,Material.BOOK};
for(int i=0;i<kinds.length;i++){String kind=kinds[i];Map<String,String> facts=switch(kind){case "EQUIPMENT"->Map.of("Grade","From issued equipment key","House","From House key","Durability","From actual item");case "KIT"->Map.of("Contents","From kit definition","State","Design preview");case "COMPONENT"->Map.of("Recipe","From crafting definition");case "TICKET"->Map.of("Route","From passage key","Departure",":00 / :20 / :40");case "CASH"->Map.of("Value","From bank withdrawal","State","Design preview");case "RIHLA"->Map.of("Recipient","From RIA key","Amount","From transfer record");case "DEED"->Map.of("Organisation","From registered deed","Holder","From current authority");case "QUEST"->Map.of("Objective","From mission key","Progress","From verified events");default->Map.of("Service","DuneRealms","Access","Current JARVIS keys");};try{panel.inventory.setItem(18+i,bridge.lorePreview(kind,materials[i],kind.replace('_',' '),facts));}catch(Exception unavailable){p.sendMessage("The lore renderer is temporarily unavailable.");return;}}

View file

@ -31,7 +31,7 @@ final class PersonalSidebar {
view=new View(old,board,new HashSet<>());views.put(p.getUniqueId(),view);p.setScoreboard(board);
}
JsonObject briefing=object(data,"briefing"),personal=object(briefing,"personal"),reputation=object(briefing,"reputation"),bank=object(briefing,"bank");
List<String> lines=List.of("§6Personal level: §f"+value(personal,"level"),"§7XP: §f"+xp(personal),"§6Reputation level: §f"+value(reputation,"level"),"§7Rep XP: §f"+xp(reputation)," ","§6Bank: §f"+amount(bank),"§6House: §f"+clean(house),"§6Clan: §f"+organisation(briefing,"clans"),"§6Company: §f"+organisation(briefing,"companies")," ","§7Quest: §f"+clean(personal==null?null:string(personal,"quest")),"§8/scoreboard · show / hide");
List<String> lines=List.of("§6Personal level: §f"+value(personal,"level"),"§7XP: §f"+xp(personal),"§6Reputation level: §f"+value(reputation,"level"),"§7Rep XP: §f"+xp(reputation)," ","§6Bank: §f"+amount(bank),"§6House: §f"+clean(house),"§6Clan: §f"+organisation(briefing,"clans"),"§6Company: §f"+organisation(briefing,"companies")," ","§7Quest: §f"+clean(string(personal,"quest")),"§7Progress: §f"+progress(personal),"§7POL: §f"+clean(string(reputation,"quest")),"§7Progress: §f"+progress(reputation),"§8/scoreboard · show / hide");
for(String old:view.lines())view.board().resetScores(old);view.lines().clear();Objective objective=view.board().getObjective("dr_personal");
for(int i=0;i<lines.size();i++){String line=lines.get(i)+"§"+Integer.toHexString(i);objective.getScore(line).setScore(lines.size()-i);view.lines().add(line);}
}
@ -39,6 +39,7 @@ final class PersonalSidebar {
private static String string(JsonObject data,String key){return data!=null&&data.has(key)&&!data.get(key).isJsonNull()?data.get(key).getAsString():null;}
private static String value(JsonObject data,String key){String value=string(data,key);return value==null?"—":value;}
private static String xp(JsonObject data){String xp=string(data,"xp");if(xp==null)return "—";String next=string(data,"nextXP");return xp+(next==null?"":" / "+next);}
private static String progress(JsonObject data){if(data==null||string(data,"quest")==null)return "—";if(data.has("questReady")&&data.get("questReady").getAsBoolean())return "Ready to claim";String p=string(data,"questProgress"),t=string(data,"questTarget");return p==null||t==null?"—":p+" / "+t;}
private static String amount(JsonObject bank){String balance=string(bank,"balance");if(balance==null)return "—";try{return new BigDecimal(balance).setScale(2).toPlainString()+" DM";}catch(NumberFormatException invalid){return "—";}}
private static String organisation(JsonObject data,String key){if(data==null||!data.has(key)||!data.get(key).isJsonArray())return "—";var names=data.getAsJsonArray(key);if(names.isEmpty())return "—";return clean(names.get(0).getAsString())+(names.size()>1?" (+"+(names.size()-1)+")":"");}
private static String clean(String value){if(value==null||value.isBlank())return "—";String safe=ChatColor.stripColor(value).replaceAll("[\\p{Cntrl}]","");return safe.length()>28?safe.substring(0,27)+"…":safe;}

View file

@ -0,0 +1,57 @@
package com.dunerealms.gui;
import java.io.File;
import java.util.*;
import java.util.function.BiConsumer;
import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.key.Key;
/** One persistent named quest contact per role/world; existing service NPCs are not replaced. */
final class PolQuestNpc implements Listener {
record Role(String key,String name,String world,String faction,Set<String> branches,int offset){}
private static final List<Role> ROLES=List.of(
new Role("thufir_hawat","Thufir Hawat","caladan","atreides",Set.of("atreides"),-3),
new Role("duncan_idaho","Duncan Idaho","caladan","atreides",Set.of("clan"),-6),
new Role("piter_de_vries","Piter de Vries","giedi_prime","harkonnen",Set.of("harkonnen"),-3),
new Role("hasimir_fenring","Count Hasimir Fenring","kaitain","corrino",Set.of("corrino"),-3),
new Role("imperial_attendant","Imperial audience · Representation","kaitain","corrino",Set.of("imperial"),-6),
new Role("roma_atani","Roma Atani","sigma_draconis_iv","ordos",Set.of("ordos","company"),-3),
new Role("stilgar","Stilgar","arrakis","fremen",Set.of("fremen","spice-harvesting"),-3),
new Role("shadout_mapes","Shadout Mapes · Provisioner","arrakis","fremen",Set.of("fremen-husbandry"),-6),
new Role("chani","Chani · Desert survival","arrakis","fremen",Set.of("fremen-husbandry"),-9),
new Role("liet_kynes","Liet-Kynes · Ecology","arrakis","fremen",Set.of("fremen-husbandry"),-12));
static final NamespacedKey KEY=new NamespacedKey("dunerealms","quest_character");
private final JavaPlugin plugin;private final BiConsumer<Player,Role> open;private final File file;private final YamlConfiguration positions;
private UUID imperialUuid;private String imperialName,imperialTerm;private long imperialRetry;
PolQuestNpc(JavaPlugin plugin,BiConsumer<Player,Role> open){this.plugin=plugin;this.open=open;file=new File(plugin.getDataFolder(),"quest-npc-positions.yml");positions=YamlConfiguration.loadConfiguration(file);Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getWorlds().forEach(this::ensure),100);}
private static Role role(String id,World world){return ROLES.stream().filter(r->r.key().equals(id)&&r.world().equals(world.getName())).findFirst().orElse(null);}
private String base(Role role){return role.world()+"."+role.key();}
private Location saved(Role role,World world){String b=base(role);return positions.contains(b+".x")?new Location(world,positions.getDouble(b+".x"),positions.getDouble(b+".y"),positions.getDouble(b+".z"),(float)positions.getDouble(b+".yaw"),(float)positions.getDouble(b+".pitch")):null;}
private void save(Role role,LivingEntity npc){Location l=npc.getLocation();String b=base(role);positions.set(b+".entity",npc.getUniqueId().toString());positions.set(b+".x",l.getX());positions.set(b+".y",l.getY());positions.set(b+".z",l.getZ());positions.set(b+".yaw",l.getYaw());positions.set(b+".pitch",l.getPitch());try{positions.save(file);}catch(java.io.IOException failure){plugin.getLogger().warning("Quest NPC position could not be saved: "+role.key());}}
private LivingEntity existing(Role role,World world){String id=positions.getString(base(role)+".entity");if(id!=null)try{Entity e=Bukkit.getEntity(UUID.fromString(id));if(e instanceof LivingEntity living&&role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING)))return living;}catch(IllegalArgumentException ignored){}return world.getEntitiesByClass(LivingEntity.class).stream().filter(e->role.key().equals(e.getPersistentDataContainer().get(KEY,PersistentDataType.STRING))).findFirst().orElse(null);}
private static boolean usable(Location at){return at.getBlock().isPassable()&&at.clone().add(0,1,0).getBlock().isPassable()&&at.clone().add(0,-1,0).getBlock().getType().isSolid();}
private static Location initial(Role role,World world){Location spawn=world.getSpawnLocation();for(int distance:new int[]{role.offset(),-role.offset(),role.offset()-2,role.offset()+2}){Location at=spawn.clone().add(distance,0,0);if(usable(at))return at;}return null;}
private void configure(Role role,LivingEntity npc){npc.setInvulnerable(true);npc.setPersistent(true);npc.setRemoveWhenFarAway(false);npc.setSilent(true);npc.setCollidable(false);if(npc instanceof Mob mob)mob.setAI(false);npc.customName(Component.text("✦ "+role.name(),NamedTextColor.AQUA));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(KEY,PersistentDataType.STRING,role.key());try{npc.getClass().getMethod("setImmovable",boolean.class).invoke(npc,true);}catch(ReflectiveOperationException ignored){}}
private static Class<?> profileType()throws ClassNotFoundException{return Class.forName("io.papermc.paper.datacomponent.item.ResolvableProfile");}
private static Object skin(String role)throws ReflectiveOperationException{Class<?> profile=profileType(),builder=Class.forName(profile.getName()+"$Builder"),patch=Class.forName(profile.getName()+"$SkinPatch"),patchBuilder=Class.forName(profile.getName()+"$SkinPatchBuilder");Object b=profile.getMethod("resolvableProfile").invoke(null),p=patch.getMethod("skinPatch").invoke(null);patchBuilder.getMethod("body",Key.class).invoke(p,Key.key("dunerealms","textures/entity/npc/"+role+".png"));patchBuilder.getMethod("model",org.bukkit.profile.PlayerTextures.SkinModel.class).invoke(p,org.bukkit.profile.PlayerTextures.SkinModel.CLASSIC);Object built=patchBuilder.getMethod("build").invoke(p);builder.getMethod("name",String.class).invoke(b,"DRQuestContact");builder.getMethod("skinPatch",patch).invoke(b,built);return builder.getMethod("build").invoke(b);}
private static void profile(LivingEntity npc,Object value)throws ReflectiveOperationException{Class.forName("org.bukkit.entity.Mannequin").getMethod("setProfile",profileType()).invoke(npc,value);}
@SuppressWarnings("unchecked") private LivingEntity spawn(Role role,Location at){try{Class<? extends LivingEntity> type=(Class<? extends LivingEntity>)Class.forName("org.bukkit.entity.Mannequin");Object appearance=skin(role.key());LivingEntity npc=at.getWorld().spawn(at,type,e->configure(role,e));try{profile(npc,appearance);return npc;}catch(ReflectiveOperationException failure){npc.remove();throw failure;}}catch(ReflectiveOperationException|LinkageError|IllegalArgumentException unavailable){plugin.getLogger().warning("Character appearance is unavailable for "+role.key()+"; using neutral stationary fallback.");return at.getWorld().spawn(at,Villager.class,v->{v.setProfession(Villager.Profession.LIBRARIAN);configure(role,v);});}}
private void ensure(World world){for(Role role:ROLES){if(!role.world().equals(world.getName()))continue;Location at=saved(role,world);if(at==null)at=initial(role,world);if(at==null){plugin.getLogger().warning("No safe spawn-space for quest NPC "+role.key());continue;}at.getChunk().load();LivingEntity npc=existing(role,world);if(npc==null){if(!usable(at)){plugin.getLogger().warning("Saved quest NPC location obstructed: "+role.key());continue;}npc=spawn(role,at);}configure(role,npc);save(role,npc);if(role.key().equals("imperial_attendant"))applyImperial(npc);}}
void imperialAppearance(UUID uuid,String name,String term){boolean changed=!Objects.equals(imperialTerm,term)||!Objects.equals(imperialUuid,uuid);imperialUuid=uuid;imperialName=name;imperialTerm=term;if(!changed&&System.currentTimeMillis()<imperialRetry)return;World world=Bukkit.getWorld("kaitain");if(world==null)return;Role role=role("imperial_attendant",world);Location at=saved(role,world);if(at!=null)at.getChunk().load();LivingEntity e=existing(role,world);if(e!=null)applyImperial(e);}
private void applyImperial(LivingEntity npc){String term=imperialTerm;UUID uuid=imperialUuid;String name=imperialName;imperialRetry=System.currentTimeMillis()+600000;try{profile(npc,skin("imperial_attendant"));}catch(ReflectiveOperationException ignored){}npc.customName(Component.text("✦ Imperial attendant",NamedTextColor.AQUA));if(uuid==null||name==null)return;
Bukkit.createProfile(uuid).update().whenComplete((publicProfile,error)->{if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{if(error!=null||publicProfile==null||!publicProfile.hasTextures()||!npc.isValid()||!Objects.equals(term,imperialTerm)||!Objects.equals(uuid,imperialUuid))return;try{Class<?> pp=Class.forName("com.destroystokyo.paper.profile.PlayerProfile");Object resolved=profileType().getMethod("resolvableProfile",pp).invoke(null,publicProfile);profile(npc,resolved);npc.customName(Component.text("✦ Imperial audience · "+name+" (representation)",NamedTextColor.AQUA));}catch(ReflectiveOperationException ignored){/* Keep the neutral attendant. */}});});
}
boolean move(Player player,String key){if(!player.hasPermission("dune.admin")){player.sendMessage("Current NPC administration permission required.");return false;}Role role=role(key,player.getWorld());if(role==null){player.sendMessage("Choose a quest character assigned to this world.");return false;}Location at=player.getLocation();if(!usable(at)){player.sendMessage("Choose a clear standing space for the NPC.");return false;}Location old=saved(role,player.getWorld());if(old!=null)old.getChunk().load();LivingEntity npc=existing(role,player.getWorld());if(npc==null){player.sendMessage("The original quest NPC is unavailable; no duplicate was created.");return false;}if(!npc.teleport(at))return false;save(role,npc);player.sendMessage("Moved "+role.name()+"; its original identity was retained.");return true;}
@EventHandler public void world(WorldLoadEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->ensure(e.getWorld()),100);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void interact(PlayerInteractEntityEvent e){String id=e.getRightClicked().getPersistentDataContainer().get(KEY,PersistentDataType.STRING);if(id==null)return;Role role=role(id,e.getPlayer().getWorld());if(role==null)return;e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)open.accept(e.getPlayer(),role);}
}

View file

@ -18,6 +18,7 @@ import net.kyori.adventure.text.event.ClickEvent;
final class QuestMenus implements Listener {
private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer<Player> back;
private final Map<UUID,UUID> pending=new HashMap<>();
private final Map<UUID,PolQuestNpc.Role> roleScope=new HashMap<>();
private static final class Panel implements InventoryHolder {
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final Inventory inventory;final String title;String description="Your current J.A.R.V.I.S. mission journal";
Panel(Player p,String title){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));}
@ -36,8 +37,34 @@ final class QuestMenus implements Listener {
}
private void show(Player p,Panel screen){if(BedrockForms.isBedrock(p)){BedrockForms.show(plugin,p,screen.title,screen.description,List.copyOf(screen.choices));return;}if(MCGUIMenus.show(p,screen.title,screen.description,screen.inventory,screen.actions,screen.gate))return;p.openInventory(screen.inventory);Bukkit.getScheduler().runTaskLater(plugin,screen.gate::expire,2400L);}
void close(){pending.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();}
void open(Player p){var screen=panel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);}
void starterJournal(Player p){load(p,"personal","h",null,0);}
void open(Player p){roleScope.remove(p.getUniqueId());var screen=panel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);}
void starterJournal(Player p){roleScope.remove(p.getUniqueId());load(p,"personal","h",null,0);}
void openRole(Player p,PolQuestNpc.Role role){roleScope.put(p.getUniqueId(),role);load(p,"pol",null,null,0);}
private boolean roleAllowed(JsonObject data,PolQuestNpc.Role role,JsonObject q){String branch=text(q,"branch","");return data.has("npcContact")&&!data.get("npcContact").isJsonNull()&&role.faction().equals(text(data,"npcFaction",""))&&role.branches().contains(branch)&&(!branch.equals("fremen-husbandry")||role.key().equals(text(q,"issuer","")))&&!website(q);}
private void roleAvatar(Panel screen,JsonObject data,PolQuestNpc.Role role){if(!data.has("npcContact")||data.get("npcContact").isJsonNull())return;var contact=data.getAsJsonObject("npcContact");int cell=contact.getAsJsonObject("avatar").get("cell").getAsInt();if(cell<0||cell>7)return;put(screen,4,text(contact,"name",role.name()),text(contact,"role","Quest contact"),Material.PLAYER_HEAD,null);var item=screen.inventory.getItem(4);var meta=item.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,"npc_avatar_"+cell);item.setItemMeta(meta);screen.inventory.setItem(4,item);}
private void roleJournal(Player p,JsonObject data,PolQuestNpc.Role role,String selected){
var available=new ArrayList<JsonObject>();for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(roleAllowed(data,role,q)&&!text(q,"state","").equals("claimed")&&(Set.of("active","completed").contains(text(q,"state",""))||yes(q,"canStart")))available.add(q);}
if(selected!=null){var row=available.stream().filter(q->selected.equals(text(q,"id",""))).findFirst().orElse(null);if(row!=null){roleSelected(p,data,role,row);return;}}
var screen=panel(p,"NPC dashboard · "+role.name());screen.description="Choose the exact mission you wish to discuss.";roleAvatar(screen,data,role);var ordered=new ArrayList<JsonObject>(available);ordered.sort(Comparator.comparingInt(q->Set.of("active","completed").contains(text(q,"state",""))?0:1));
int slot=9;for(var q:ordered){if(slot>=45)break;String status=Set.of("active","completed").contains(text(q,"state",""))?"Progress: "+text(q,"progress","0")+" / "+text(q,"target","1"):"Eligible to accept";put(screen,slot++,text(q,"title","Mission"),status+"\n"+text(q,"objective",""),Material.WRITABLE_BOOK,()->roleSelected(p,data,role,q));}
if(ordered.isEmpty())put(screen,13,"No eligible missions","Read the website journal for the full record.",Material.MAP,null);
if(Set.of("thufir_hawat","piter_de_vries","hasimir_fenring","roma_atani","imperial_attendant","jessica_atreides","gaius_helen_mohiam","alia_atreides","edric","guild_navigator","duncan_idaho").contains(role.key()))put(screen,48,"POL decisions","See only current executable political decisions",Material.BOOK,()->roleDecisionDashboard(p,data,role));put(screen,49,"Website journal","Full mission choices and history",Material.MAP,()->website(p));show(p,screen);
}
private void roleDecisionDashboard(Player p,JsonObject contact,PolQuestNpc.Role role){var input=new JsonObject();input.addProperty("action","read");input.addProperty("npcRole",role.key());decisionRequest(p,role,input,data->{var screen=panel(p,"NPC dashboard · "+role.name());screen.description="Choose a decision you currently have the authority to execute.";roleAvatar(screen,contact,role);int slot=9;for(var e:data.getAsJsonArray("decisions")){var row=e.getAsJsonObject();if(slot>=45)break;put(screen,slot++,text(row,"title","Decision"),"Required Reputation: "+text(row,"level","—")+"\n"+(text(row,"kind","").equals("website")?"Continue through the verified website workflow.":"Review funding and confirm."),Material.BOOK,()->roleDecisionDetails(p,contact,role,row,null,null));}if(slot==9)put(screen,13,"No executable decisions","Your current office, authority and cooldown determine what appears here.",Material.MAP,null);put(screen,48,"Back","Mission dashboard",Material.ARROW,()->load(p,"pol",null,null,0));put(screen,49,"Website","Full decision definitions and history",Material.MAP,()->decisionWebsite(p));show(p,screen);});}
private void decisionWebsite(Player p){p.closeInventory();p.sendMessage(Component.text("Review POL decisions on the website →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));}
private void roleDecisionDetails(Player p,JsonObject contact,PolQuestNpc.Role role,JsonObject row,String account,String parameter){var screen=panel(p,"NPC turn-in · "+role.name());screen.description="Review your explicit political decision before committing any funds.";roleAvatar(screen,contact,role);String kind=text(row,"kind","");String fee=text(row,"feeMinor","0");String amount;try{amount=new java.math.BigDecimal(fee).movePointLeft(2).toPlainString()+" DM";}catch(NumberFormatException invalid){amount="—";}put(screen,13,text(row,"title","Decision"),"Required Reputation: "+text(row,"level","—")+"\nBase cost: "+amount+"\nAward: "+text(row,"reputation","—")+" Reputation",Material.BOOK,null);
if(kind.equals("website")){put(screen,31,"Open website workflow","This decision requires the existing website controls.",Material.MAP,()->decisionWebsite(p));}
else if(account==null){int slot=18;for(var e:row.getAsJsonArray("accounts")){var a=e.getAsJsonObject();if(slot>=35)break;String id=text(a,"id","");try{if(new java.math.BigInteger(text(a,"availableMinor","0")).compareTo(new java.math.BigInteger(fee))<0)continue;}catch(NumberFormatException invalid){continue;}put(screen,slot++,text(a,"name","Funding account"),"Account "+text(a,"number","")+" · available "+new java.math.BigDecimal(text(a,"availableMinor","0")).movePointLeft(2).toPlainString()+" DM",Material.GOLD_INGOT,()->roleDecisionDetails(p,contact,role,row,id,parameter));}}
else if(row.has("parameters")&&parameter==null){int slot=18;for(var item:row.getAsJsonArray("parameters")){var value=item.getAsJsonObject();if(slot>=35)break;put(screen,slot++,text(value,"label","Parameter"),"Select this exact parameter",Material.PAPER,()->roleDecisionDetails(p,contact,role,row,account,text(value,"value","")));}}
else{put(screen,22,"Confirmed selection","Funding account "+account+(parameter==null?"":"\nParameter: "+parameter),Material.GOLD_INGOT,null);UUID requestId=UUID.randomUUID();put(screen,31,"Confirm and execute","Commit the reviewed decision once through J.A.R.V.I.S.",Material.LIME_DYE,()->{var input=new JsonObject();input.addProperty("action","execute");input.addProperty("npcRole",role.key());input.addProperty("decisionId",text(row,"id",""));input.addProperty("requestId",requestId.toString());input.addProperty("sourceAccount",account);input.addProperty("confirmed",true);if(parameter!=null)input.addProperty("parameter",parameter);decisionRequest(p,role,input,result->roleDecisionResult(p,contact,role,row,result));});}
put(screen,49,"Back","Current executable decisions",Material.ARROW,()->roleDecisionDashboard(p,contact,role));show(p,screen);
}
private void roleDecisionResult(Player p,JsonObject contact,PolQuestNpc.Role role,JsonObject row,JsonObject result){var screen=panel(p,"NPC next quest · "+role.name());screen.description="The decision has been recorded. Review the signed history for its full effect.";roleAvatar(screen,contact,role);put(screen,13,text(row,"title","Decision"),"Reference: "+text(result,"keyId","Recorded")+"\nReputation: "+text(result,"xp","—"),Material.LIME_DYE,null);put(screen,31,"Next decision","See the remaining current eligible decisions",Material.BOOK,()->roleDecisionDashboard(p,contact,role));put(screen,49,"Later","Return to the contact dashboard",Material.ARROW,()->load(p,"pol",null,null,0));show(p,screen);}
private void decisionRequest(Player p,PolQuestNpc.Role role,JsonObject input,Consumer<JsonObject> callback){try{bridge.questCharacterNpc(p,role.key());request(p,input,callback,true);}catch(Exception unavailable){p.sendMessage("Return to this political quest contact.");}}
private void roleSelected(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){if(!Set.of("active","completed").contains(text(row,"state",""))){roleIntro(p,data,role,row);return;}details(p,"pol",data,text(row,"branch",""),0,row);}
private void roleIntro(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){var screen=panel(p,"NPC next quest · "+role.name());screen.description="There is work still to be done. Will you accept this mission?";roleAvatar(screen,data,role);put(screen,13,text(row,"title","Next mission"),text(row,"objective","")+"\nReputation: "+text(row,"xp","—"),Material.WRITABLE_BOOK,null);put(screen,30,"Accept","Accept exactly this mission",Material.LIME_DYE,()->act(p,"pol",text(row,"branch",""),0,row,"start"));put(screen,32,"Later","Return to the contact's mission dashboard",Material.ARROW,()->roleJournal(p,data,role,null));show(p,screen);}
private void roleThanks(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){var screen=panel(p,"NPC turn-in · "+role.name());screen.description="Your work has been verified. Thank you.";roleAvatar(screen,data,role);put(screen,13,text(row,"title","Completed mission"),"Verified reward recorded through J.A.R.V.I.S.",Material.LIME_DYE,null);put(screen,31,"Next quest","Find the next eligible mission in this selected arc",Material.BOOK,()->roleNext(p,role,row));put(screen,49,"Later","Return to the mission dashboard",Material.ARROW,()->load(p,"pol",null,null,0));show(p,screen);}
private void roleNext(Player p,PolQuestNpc.Role role,JsonObject completed){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind","pol");input.addProperty("npcRole",role.key());request(p,input,data->{String id=text(completed,"id",""),branch=text(completed,"branch",""),metric=text(completed,"metric","");for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(!branch.equals(text(q,"branch",""))||!yes(q,"canStart")||text(q,"state","").equals("claimed"))continue;boolean next=metric.equals(text(q,"metric",""));if(q.has("requires"))for(var req:q.getAsJsonArray("requires"))if(id.equals(req.getAsString()))next=true;if(!next)continue;if(roleAllowed(data,role,q)){roleIntro(p,data,role,q);return;}}roleJournal(p,data,role,null);});}
private void website(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));}
private void workshop(Player p,int page){var input=new JsonObject();input.addProperty("action","read_refits");input.addProperty("kind","pol");request(p,input,data->{var screen=panel(p,"Organisation workshop");var owners=data.getAsJsonArray("owners");int offset=page*36;for(int i=offset;i<Math.min(owners.size(),offset+36);i++){var owner=owners.get(i).getAsJsonObject();put(screen,i-offset,text(owner,"label","Organisation"),"Use your specialist’s researched MK and rarity for this organisation",Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE,()->prepareRefit(p,owner));}if(owners.isEmpty())put(screen,22,"Specialist required","Your current organisation deed must grant equipment research authority.",Material.GRAY_DYE,null);if(page>0)put(screen,45,"Previous","Earlier organisations",Material.ARROW,()->workshop(p,page-1));if(offset+36<owners.size())put(screen,53,"Next","More organisations",Material.ARROW,()->workshop(p,page+1));put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));show(p,screen);});}
private void prepareRefit(Player p,JsonObject owner){try{var input=new JsonObject();input.addProperty("action","prepare_refit");input.addProperty("kind","pol");var selected=new JsonObject();selected.add("kind",owner.get("kind"));selected.add("id",owner.get("id"));input.add("owner",selected);input.add("snapshot",bridge.refitSnapshot(p));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{var plan=permit.getAsJsonObject("plan");var output=plan.getAsJsonObject("output");var screen=panel(p,"Review equipment refit");StringBuilder cost=new StringBuilder("Surrender the held original and:");for(var token:plan.getAsJsonObject("consume").getAsJsonArray("templates"))cost.append("\n1 ").append(token.getAsJsonObject().get("id").getAsString().replace("dr_","").replace('_',' '));Material material=Material.matchMaterial(output.get("material").getAsString());put(screen,13,"MK "+output.get("equipmentMark").getAsString()+" · "+output.get("quality").getAsString().replace('_',' '),"Original identity, name, lore and wear retained.\nExisting enchantments scale with the next tier.\nReputation level "+plan.get("requiredReputationLevel").getAsString()+" required.\n"+cost,material==null?Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE:material,null);put(screen,30,"Refit original",cost+"\nOne minute between refits. Review expires after 30 seconds.",Material.LIME_DYE,()->confirmRefit(p,input));put(screen,32,"Back","Return without consuming anything",Material.ARROW,()->workshop(p,0));show(p,screen);});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Hold your original near Gurney’s quartermaster.":failure.getMessage(),NamedTextColor.RED));}}
@ -46,13 +73,14 @@ final class QuestMenus implements Listener {
// An appointment or organisation may have changed while that panel was open.
request(p,input,verified->{try{boolean done=bridge.refitEquipment(p,verified);p.sendMessage(Component.text(done?"Original equipment upgraded. Organisation name and MK are purple.":"This refit was already processed.",NamedTextColor.GREEN));}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refit not confirmed. Reopen the workshop.":failure.getMessage(),NamedTextColor.RED));}});
}
private void request(Player p,JsonObject input,Consumer<JsonObject> result){
private void request(Player p,JsonObject input,Consumer<JsonObject> result){request(p,input,result,false);}
private void request(Player p,JsonObject input,Consumer<JsonObject> result,boolean decision){
UUID owner=p.getUniqueId();if(pending.containsKey(owner))return;UUID operation=UUID.randomUUID(),world=p.getWorld().getUID();pending.put(owner,operation);p.closeInventory();p.sendMessage(Component.text("Jarvis executing matrix",NamedTextColor.GOLD));
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=bridge.quests(owner,input);}catch(Exception failure){error=failure instanceof java.io.IOException?failure.getMessage():"The mission journal is unavailable. Reopen it before retrying.";}JsonObject received=data;String message=error;if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=decision?bridge.decisions(owner,input):bridge.quests(owner,input);}catch(Exception failure){error=failure instanceof java.io.IOException?failure.getMessage():"The mission journal is unavailable. Reopen it before retrying.";}JsonObject received=data;String message=error;if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTask(plugin,()->{if(!operation.equals(pending.get(owner)))return;pending.remove(owner);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(message!=null){p.sendMessage(message);return;}if(p.getOpenInventory().getType()!=InventoryType.CRAFTING)return;result.accept(received);});
});
}
private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}if(branch==null)branches(p,kind,data);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});}
private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);var contact=roleScope.get(p.getUniqueId());if(contact!=null&&kind.equals("pol"))input.addProperty("npcRole",contact.key());request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}var role=roleScope.get(p.getUniqueId());if(role!=null&&kind.equals("pol")){roleJournal(p,data,role,selected);return;}if(branch==null)branches(p,kind,data);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});}
private void branches(Player p,String kind,JsonObject data){
var screen=panel(p,kind.equals("pol")?"Reputation branches":"Personal mission branches");var branches=new LinkedHashMap<String,String>();for(var entry:data.getAsJsonArray("quests")){String id=text(entry.getAsJsonObject(),"branch","missions");branches.putIfAbsent(id,id);}
if(data.has("branches"))for(var entry:data.getAsJsonArray("branches")){var branch=entry.getAsJsonObject();String id=text(branch,"id","");if(branches.containsKey(id))branches.put(id,text(branch,"title",id));}
@ -66,7 +94,7 @@ final class QuestMenus implements Listener {
put(screen,45,"Branches","Choose another branch",Material.ARROW,()->branches(p,kind,data));if(page>0)put(screen,47,"Previous","Previous missions",Material.PAPER,()->quests(p,kind,data,branch,page-1));put(screen,49,"Refresh","Read current verified quest records",Material.CLOCK,()->load(p,kind,branch,null,page));if(offset+36<rows.size())put(screen,51,"Next","More missions",Material.PAPER,()->quests(p,kind,data,branch,page+1));show(p,screen);
}
private void details(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){
var screen=panel(p,"Quest dossier");String title=text(row,"title","Quest"),state=text(row,"state","Pending"),description=text(row,"objective","Complete the verified objective.")+"\nProgress: "+text(row,"progress","0")+" / "+text(row,"target","0")+"\nState: "+state+"\n"+(kind.equals("pol")?"Reputation: ":"XP: ")+text(row,"xp","Not configured");
var role=roleScope.get(p.getUniqueId());var screen=panel(p,role!=null&&kind.equals("pol")?"NPC turn-in · "+role.name():"Quest dossier");if(role!=null&&kind.equals("pol")){screen.description="Let us review your selected mission.";roleAvatar(screen,data,role);}String title=text(row,"title","Quest"),state=text(row,"state","Pending"),description=text(row,"objective","Complete the verified objective.")+"\nProgress: "+text(row,"progress","0")+" / "+text(row,"target","0")+"\nState: "+state+"\n"+(kind.equals("pol")?"Reputation: ":"XP: ")+text(row,"xp","Not configured");
if(row.has("personalXP")&&!row.get("personalXP").isJsonNull())description+="\nBase Personal XP: "+row.get("personalXP").getAsInt();if(row.has("baseDMMinor")&&!row.get("baseDMMinor").isJsonNull())description+="\nBase funded reward: "+String.format(Locale.ROOT,"%.2f DM",row.get("baseDMMinor").getAsLong()/100.0);
put(screen,13,title,description,website(row)?Material.WRITABLE_BOOK:Material.LIGHT_BLUE_DYE,null);
if(website(row))put(screen,31,"Open website journal","This objective belongs to the website",Material.MAP,()->website(p));
@ -80,19 +108,19 @@ final class QuestMenus implements Listener {
if(kind.equals("pol")&&text(row,"id","").equals("POL-SMUGGLERS-01")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Meet the underground network","Stand near an Arrakis Smuggler.\nAccept Esmar Tuek’s introduction, then claim the quest.",Material.ORANGE_DYE,()->{try{bridge.smugglerIntroduction(p);p.sendMessage("Introduction recorded. Refresh this quest in a few seconds.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage());}});
if(kind.equals("pol")&&Set.of("POL-BOUNTY-01","POL-BOUNTY-02").contains(text(row,"id",""))&&!state.equals("claimed"))put(screen,33,"View active bounty jobs","On Arrakis, use the native bounty list and accept a target.",Material.MAP,()->{p.closeInventory();p.performCommand("dune bounty");});
if(kind.equals("pol")&&row.has("research")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")||state.equals("completed")))put(screen,33,"Submit research samples","Stand near Gurney Halleck.\nSurrender the materials shown in this quest.",Material.SMITHING_TABLE,()->research(p,kind,branch,page,row));
if(kind.equals("pol")&&Set.of("pol-jerboa-meat-25","pol-jerboa-meat-50").contains(text(row,"metric",""))&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Surrender cooked Jerboa meat","Stand near Gurney Halleck on Arrakis.\nSurrender the required genuine cooked Jerboa meat; no reuse of previous turn-ins.",Material.COOKED_RABBIT,()->meatTurnin(p,kind,branch,page,row));
if(kind.equals("pol")&&row.has("supply")&&!row.get("supply").isJsonNull()&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active"))){var supply=row.getAsJsonObject("supply");put(screen,33,"Surrender mission supplies","Stand near Gurney's quartermaster on Arrakis.\nSurrender "+supply.get("quantity").getAsInt()+" genuine "+text(supply,"label","supplies")+".",Material.CHEST,()->supplyTurnin(p,kind,branch,page,row));}
if(kind.equals("pol")&&Set.of("pol-jerboa-meat-25","pol-jerboa-meat-50").contains(text(row,"metric",""))&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Surrender cooked Jerboa meat","Stand near Shadout Mapes on Arrakis.\nSurrender the required genuine cooked Jerboa meat; no reuse of previous turn-ins.",Material.COOKED_RABBIT,()->meatTurnin(p,kind,branch,page,row));
if(kind.equals("pol")&&row.has("supply")&&!row.get("supply").isJsonNull()&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active"))){var supply=row.getAsJsonObject("supply");put(screen,33,"Surrender mission supplies","Stand near "+text(supply,"contact","the mission contact")+".\nSurrender "+supply.get("quantity").getAsInt()+" genuine "+text(supply,"label","supplies")+".",Material.CHEST,()->supplyTurnin(p,kind,branch,page,row));}
if(kind.equals("personal")&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state))){
if(text(row,"id","").equals("S1-H-01"))put(screen,33,"Collect House T0 kit","Available directly from /start.\nFour Common MK 0 stillsuit pieces at half durability.\nOne Uncommon MK I wooden spice shovel.\nOne original kit per account and season.",Material.NETHERITE_CHESTPLATE,()->starter(p,kind,branch,page,row,"obtain"));
if(text(row,"id","").equals("S1-H-02")){put(screen,29,"Prepare four repair parts","Buy, craft with genuine spice or collect native 5% mob drops.\nRepair plate, Binding patch, Tool fitting, Calibration piece.\nOptional: prepare all four from the ordinary materials.",Material.IRON_INGOT,()->starter(p,kind,branch,page,row,"parts"));put(screen,33,"Surrender original kit & parts","Hand in the four original bound armour pieces\nand all four verified repair parts.\nThen claim this quest to receive the intact kit.",Material.ANVIL,()->starter(p,kind,branch,page,row,"repair"));}
}
if(row.has("recipe")&&!row.get("recipe").isJsonNull())put(screen,22,"Revealed recipe","Craft on Arrakis · Very Rare · MK XI\nNetherite | Membrane | Netherite\nIron | Diamond | Iron\nContaminated spice | Membrane | Contaminated spice",Material.ELYTRA,null);
put(screen,45,"Back","Mission branch",Material.ARROW,()->quests(p,kind,data,branch,page));put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen);
put(screen,45,"Back","Mission selection",Material.ARROW,()->{var currentRole=roleScope.get(p.getUniqueId());if(currentRole!=null&&kind.equals("pol"))roleJournal(p,data,currentRole,null);else quests(p,kind,data,branch,page);});put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen);
}
private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage(),NamedTextColor.RED));}}
private void research(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_research");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.research(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Research receipt pending. Refresh your quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit Gurney Halleck.":failure.getMessage(),NamedTextColor.RED));}}
private void meatTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_husbandry_turnin");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.husbandryTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Meat turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit Gurney Halleck on Arrakis.":failure.getMessage());}}
private void supplyTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_pol_supply");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.polSupplyTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Supply turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit the Arrakis quartermaster.":failure.getMessage());}}
private void meatTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_husbandry_turnin");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,"shadout_mapes").toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.husbandryTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Meat turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit Shadout Mapes on Arrakis.":failure.getMessage());}}
private void supplyTurnin(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_pol_supply");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,row.getAsJsonObject("supply").get("role").getAsString()).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.polSupplyTurnin(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Supply turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit the named quest contact.":failure.getMessage());}}
private void starter(Player p,String kind,String branch,int page,JsonObject row,String operation){try{var input=new JsonObject();input.addProperty("action","prepare_starter");input.addProperty("kind","personal");input.addProperty("definitionId",text(row,"id",""));input.addProperty("operation",operation);input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("access","journal");input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.starterKit(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Your equipment exchange remains available. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Open /start in Survival or Adventure mode.":failure.getMessage(),NamedTextColor.RED));}}
private void introduction(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){
var screen=panel(p,"Imperial Citizen briefing");
@ -100,9 +128,9 @@ final class QuestMenus implements Listener {
put(screen,30,"I understand","Confirm that you have read this briefing",Material.LIME_DYE,()->{try{bridge.citizenIntroduction(p);p.closeInventory();p.sendMessage(Component.text("Citizen briefing submitted. Refresh your mission journal in a few seconds to claim its verified reward.",NamedTextColor.GREEN));}catch(Exception unavailable){p.sendMessage("The briefing could not be recorded. Please reopen the journal.");}});
put(screen,32,"Back","Return without confirming",Material.ARROW,()->details(p,kind,data,branch,page,row));show(p,screen);
}
private void act(Player p,String kind,String branch,int page,JsonObject row,String action){var input=new JsonObject();input.addProperty("action",action);input.addProperty("kind",kind);input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);if(action.equals("claim"))input.add("revision",row.get("revision"));request(p,input,result->{p.sendMessage(Component.text(action.equals("claim")?"Verified quest reward recorded.":"Mission accepted.",NamedTextColor.GREEN));if(action.equals("claim")&&text(row,"id","").equals("S1-H-02"))try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your intact replacement remains queued for delivery.");}load(p,kind,branch,text(row,"id",""),page);});}
private void act(Player p,String kind,String branch,int page,JsonObject row,String action){var input=new JsonObject();input.addProperty("action",action);input.addProperty("kind",kind);input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);if(action.equals("claim"))input.add("revision",row.get("revision"));request(p,input,result->{p.sendMessage(Component.text(action.equals("claim")?"Verified quest reward recorded.":"Mission accepted.",NamedTextColor.GREEN));if(action.equals("claim")&&text(row,"id","").equals("S1-H-02"))try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your intact replacement remains queued for delivery.");}var role=roleScope.get(p.getUniqueId());if(action.equals("claim")&&role!=null&&kind.equals("pol")){var read=new JsonObject();read.addProperty("action","read");read.addProperty("kind","pol");read.addProperty("npcRole",role.key());request(p,read,data->roleThanks(p,data,role,row));return;}load(p,kind,branch,text(row,"id",""),page);});}
@EventHandler public void click(InventoryClickEvent e){if(!(e.getView().getTopInventory().getHolder() instanceof Panel panel))return;e.setCancelled(true);if(!(e.getWhoClicked() instanceof Player p)||!panel.owner.equals(p.getUniqueId())||e.getClickedInventory()!=panel.inventory||e.getClick()!=ClickType.LEFT)return;var action=panel.actions.get(e.getRawSlot());if(action!=null&&panel.gate.claim(p.getUniqueId()))Bukkit.getScheduler().runTask(plugin,()->{if(p.isOnline()&&p.getOpenInventory().getTopInventory()==panel.inventory)action.run();});}
@EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);}
@EventHandler public void closed(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Panel panel)panel.gate.expire();}
@EventHandler public void quit(PlayerQuitEvent e){pending.remove(e.getPlayer().getUniqueId());}
@EventHandler public void quit(PlayerQuitEvent e){pending.remove(e.getPlayer().getUniqueId());roleScope.remove(e.getPlayer().getUniqueId());}
}