forked from unimatrix/web
Make existing quest NPC persistence available to DuneMenus
This commit is contained in:
parent
c8fcf9d2e5
commit
53d2e211b3
1 changed files with 37 additions and 12 deletions
108
gui-common/src/main/java/com/dunerealms/npc/PolQuestNpc.java
Normal file
108
gui-common/src/main/java/com/dunerealms/npc/PolQuestNpc.java
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
package com.dunerealms.npc;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.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. */
|
||||
public final class PolQuestNpc implements Listener {
|
||||
public 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("war_marshal","War Marshal","caladan","*",Set.of(),-18),
|
||||
new Role("war_marshal","War Marshal","giedi_prime","*",Set.of(),-12),
|
||||
new Role("war_marshal","War Marshal","kaitain","*",Set.of(),-15),
|
||||
new Role("war_marshal","War Marshal","sigma_draconis_iv","*",Set.of(),-9),
|
||||
new Role("war_marshal","War Marshal","arrakis","*",Set.of(),-24),
|
||||
new Role("war_marshal","War Marshal","guild_lobby","*",Set.of(),-27),
|
||||
new Role("thufir_hawat","Thufir Hawat","caladan","atreides",Set.of("atreides"),-3),
|
||||
new Role("duncan_idaho","Duncan Idaho","caladan","*",Set.of("clan"),-6),
|
||||
new Role("piter_de_vries","Piter de Vries","giedi_prime","harkonnen",Set.of("harkonnen"),-3),
|
||||
new Role("glossu_rabban","Glossu Rabban","giedi_prime","harkonnen",Set.of(),-6),
|
||||
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("irulan_corrino","Princess Irulan Corrino","kaitain","corrino",Set.of(),-9),
|
||||
new Role("roma_atani","Roma Atani","sigma_draconis_iv","ordos",Set.of("ordos","company"),-3),
|
||||
new Role("stilgar","Stilgar","arrakis","fremen",Set.of("fremen"),-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),
|
||||
new Role("jessica_atreides","Lady Jessica Atreides","caladan","*",Set.of("bene"),-9),
|
||||
new Role("gaius_helen_mohiam","Gaius Helen Mohiam","caladan","*",Set.of("faith-sisterhood"),-12),
|
||||
new Role("alia_atreides","Alia Atreides","arrakis","*",Set.of("faith-church"),-15),
|
||||
new Role("thufir_hawat","Thufir Hawat · House introduction","guild_lobby","atreides",Set.of("prologue"),-9),
|
||||
new Role("piter_de_vries","Piter de Vries · House introduction","guild_lobby","harkonnen",Set.of("prologue"),-12),
|
||||
new Role("hasimir_fenring","Count Hasimir Fenring · House introduction","guild_lobby","corrino",Set.of("prologue"),-15),
|
||||
new Role("roma_atani","Roma Atani · House introduction","guild_lobby","ordos",Set.of("prologue"),-18),
|
||||
new Role("stilgar","Stilgar · House introduction","guild_lobby","fremen",Set.of("prologue"),-21),
|
||||
new Role("edric","Edric · Guild logistics","guild_lobby","*",Set.of("guild"),-3),
|
||||
new Role("esmar_tuek","Esmar Tuek · Smuggler contact","arrakis","*",Set.of("smugglers","spice-upgrading","elytra"),-18),
|
||||
new Role("esmar_tuek","Esmar Tuek · Smuggler contact","guild_lobby","*",Set.of("smugglers"),-6));
|
||||
private static final Set<String> SKINS=Set.of(
|
||||
"alia_atreides","chani","duncan_idaho","edric","esmar_tuek","gaius_helen_mohiam",
|
||||
"glossu_rabban","hasimir_fenring","imperial_attendant","irulan_corrino","jessica_atreides",
|
||||
"liet_kynes","piter_de_vries","roma_atani","shadout_mapes","staban_tuek","stilgar","thufir_hawat");
|
||||
private static final NamespacedKey SKIN=new NamespacedKey("dunerealms","quest_character_skin");
|
||||
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;
|
||||
public PolQuestNpc(JavaPlugin plugin){this(plugin,null);}
|
||||
public 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);}
|
||||
public static Role decisionContact(String id){return ROLES.stream().filter(r->r.key().equals(id)).findFirst().orElse(null);}
|
||||
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 boolean 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{Path target=file.toPath(),directory=target.getParent();Files.createDirectories(directory);Path temporary=Files.createTempFile(directory,"quest-npc-positions-",".yml");try{positions.save(temporary.toFile());try{Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException unsupported){Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);}}finally{Files.deleteIfExists(temporary);}return true;}catch(java.io.IOException failure){plugin.getLogger().warning("Quest NPC settings could not be saved: "+role.key());return false;}}
|
||||
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.key().equals("war_marshal")?"⚔ ":"✦ ")+role.name(),role.key().equals("war_marshal")?NamedTextColor.GOLD:NamedTextColor.AQUA));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(KEY,PersistentDataType.STRING,role.key());if(role.key().equals("esmar_tuek")&&role.world().equals("arrakis"))npc.getPersistentDataContainer().set(new NamespacedKey("dunecore","smuggler"),PersistentDataType.BYTE,(byte)1);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");String override=positions.getString(base(role)+".skin");Object appearance=skin(SKINS.contains(override==null?"":override)?override:role.key().equals("war_marshal")?"duncan_idaho":role.key());LivingEntity npc=at.getWorld().spawn(at,type,e->configure(role,e));try{profile(npc,appearance);if(override!=null&&SKINS.contains(override))npc.getPersistentDataContainer().set(SKIN,PersistentDataType.STRING,override);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);}}
|
||||
public 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){if(npc.getPersistentDataContainer().has(SKIN))return;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()||npc.getPersistentDataContainer().has(SKIN)||!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. */}});});
|
||||
}
|
||||
public void assignSkin(Player player,String value){
|
||||
if(!player.hasPermission("dune.admin")){player.sendMessage("Current NPC administration permission required.");return;}
|
||||
String id=value.startsWith("#")?value.substring(1).toLowerCase(Locale.ROOT):"";
|
||||
if(!SKINS.contains(id)){player.sendMessage("Available skins: #"+String.join(", #",new TreeSet<>(SKINS)));return;}
|
||||
if(!(player.getTargetEntity(6) instanceof LivingEntity npc)){player.sendMessage("Look at a quest NPC within six blocks.");return;}
|
||||
String roleKey=npc.getPersistentDataContainer().get(KEY,PersistentDataType.STRING);
|
||||
Role role=roleKey==null?null:role(roleKey,player.getWorld());
|
||||
if(role==null||existing(role,player.getWorld())!=npc){player.sendMessage("Look at a registered quest NPC.");return;}
|
||||
String key=base(role)+".skin",previous=positions.getString(key);
|
||||
try{
|
||||
Object original=npc.getClass().getMethod("getProfile").invoke(npc);
|
||||
profile(npc,skin(id));
|
||||
positions.set(key,id);
|
||||
if(!save(role,npc)){
|
||||
positions.set(key,previous);profile(npc,original);
|
||||
player.sendMessage("The skin could not be saved.");return;
|
||||
}
|
||||
npc.getPersistentDataContainer().set(SKIN,PersistentDataType.STRING,id);
|
||||
player.sendMessage("Equipped #"+id+" on "+role.name()+".");
|
||||
}catch(ReflectiveOperationException|LinkageError unavailable){
|
||||
player.sendMessage("This NPC does not support custom skins on this server.");
|
||||
}
|
||||
}
|
||||
public 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){if(open==null)return;String id=e.getRightClicked().getPersistentDataContainer().get(KEY,PersistentDataType.STRING);if(id==null)return;Role role=role(id,e.getPlayer().getWorld());if(role==null)return;if(id.equals("esmar_tuek")&&role.world().equals("arrakis")&&!e.getPlayer().isSneaking()){e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)e.getPlayer().performCommand("spice");return;}e.setCancelled(true);if(e.getHand()==EquipmentSlot.HAND)open.accept(e.getPlayer(),role);}
|
||||
public void nativeContact(Player p,String id){if(open==null)return;Role r=role(id,p.getWorld());if(r==null&&id.equals("guild_navigator"))r=new Role(id,"Guild Navigator",p.getWorld().getName(),"*",Set.of("guild","spice-harvesting"),0);if(r==null&&id.equals("gurney_halleck"))r=new Role(id,"Gurney Halleck · Bounty jobs",p.getWorld().getName(),"*",Set.of("bounty-jobs","war-service","repeatables"),0);if(r!=null)open.accept(p,r);}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff