small optimizations and reformatting

This commit is contained in:
Pyr 2023-04-19 17:08:30 +01:00
parent 3fe6f73c32
commit 3fa94b4f31
5 changed files with 44 additions and 91 deletions

@ -1,7 +1,7 @@
package io.github.znetworkw.znpcservers.listeners; package io.github.znetworkw.znpcservers.listeners;
import io.github.znetworkw.znpcservers.utility.inventory.ZInventory;
import io.github.znetworkw.znpcservers.utility.inventory.ZInventoryHolder; import io.github.znetworkw.znpcservers.utility.inventory.ZInventoryHolder;
import io.github.znetworkw.znpcservers.utility.inventory.ZInventoryPage;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@ -15,17 +15,15 @@ public class InventoryListener implements Listener {
@EventHandler @EventHandler
public void onClick(InventoryClickEvent event) { public void onClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) if (!(event.getWhoClicked() instanceof Player player)) return;
return; if (event.getCurrentItem() == null) return;
if (event.getCurrentItem() == null) if (!(event.getInventory().getHolder() instanceof ZInventoryHolder holder)) return;
return;
if (!(event.getInventory().getHolder() instanceof ZInventoryHolder))
return;
event.setCancelled(true); event.setCancelled(true);
ZInventory zInventory = ((ZInventoryHolder) event.getInventory().getHolder()).getzInventory();
if (!zInventory.getPage().containsItem(event.getRawSlot())) ZInventoryPage page = holder.getzInventory().getPage();
return; if (!page.containsItem(event.getRawSlot())) return;
zInventory.getPage().findItem(event.getRawSlot()).getInventoryCallback().onClick(event);
((Player) event.getWhoClicked()).updateInventory(); page.findItem(event.getRawSlot()).getInventoryCallback().onClick(event);
player.updateInventory();
} }
} }

@ -5,6 +5,7 @@ import io.github.znetworkw.znpcservers.npc.event.NPCInteractEvent;
import io.github.znetworkw.znpcservers.user.EventService; import io.github.znetworkw.znpcservers.user.EventService;
import io.github.znetworkw.znpcservers.user.ZUser; import io.github.znetworkw.znpcservers.user.ZUser;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
@ -27,7 +28,7 @@ public class PlayerListener implements Listener {
ZUser.unregister(event.getPlayer()); ZUser.unregister(event.getPlayer());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onTalk(AsyncPlayerChatEvent event) { public void onTalk(AsyncPlayerChatEvent event) {
ZUser zUser = ZUser.find(event.getPlayer()); ZUser zUser = ZUser.find(event.getPlayer());
if (EventService.hasService(zUser, AsyncPlayerChatEvent.class)) { if (EventService.hasService(zUser, AsyncPlayerChatEvent.class)) {
@ -41,9 +42,7 @@ public class PlayerListener implements Listener {
@EventHandler @EventHandler
public void onConversation(NPCInteractEvent event) { public void onConversation(NPCInteractEvent event) {
ConversationModel conversationStorage = event.getNpc().getNpcPojo().getConversation(); ConversationModel conversationStorage = event.getNpc().getNpcPojo().getConversation();
if (conversationStorage == null || conversationStorage if (conversationStorage == null || conversationStorage.getConversationType() != ConversationModel.ConversationType.CLICK) return;
.getConversationType() != ConversationModel.ConversationType.CLICK)
return;
event.getNpc().tryStartConversation(event.getPlayer()); event.getNpc().tryStartConversation(event.getPlayer());
} }
} }

@ -22,41 +22,21 @@ import java.util.concurrent.ConcurrentMap;
public class NPC { public class NPC {
private static final ConcurrentMap<Integer, NPC> NPC_MAP = new ConcurrentHashMap<>(); private static final ConcurrentMap<Integer, NPC> NPC_MAP = new ConcurrentHashMap<>();
private static final String PROFILE_TEXTURES = "textures";
private static final String START_PREFIX = "[ZNPC] ";
private final Set<ZUser> viewers = new HashSet<>(); private final Set<ZUser> viewers = new HashSet<>();
private final PacketCache packets = new PacketCache(); private final PacketCache packets = new PacketCache();
private final NPCModel npcPojo; private final NPCModel npcPojo;
private final Hologram hologram; private final Hologram hologram;
private final String npcName; private final String npcName;
private final NPCSkin npcSkin; private final NPCSkin npcSkin;
private long lastMove = -1L; private long lastMove = -1L;
private int entityID; private int entityID;
private Object glowColor; private Object glowColor;
private Object tabConstructor; private Object tabConstructor;
private Object updateTabConstructor; private Object updateTabConstructor;
private Object nmsEntity; private Object nmsEntity;
private Object bukkitEntity; private Object bukkitEntity;
private UUID uuid; private UUID uuid;
private GameProfile gameProfile; private GameProfile gameProfile;
private NPCPath.PathInitializer npcPath; private NPCPath.PathInitializer npcPath;
public NPC(NPCModel npcModel, boolean load) { public NPC(NPCModel npcModel, boolean load) {
@ -155,8 +135,7 @@ public class NPC {
try { try {
if (this.npcPath == null) { if (this.npcPath == null) {
lookAt(null, location, true); lookAt(null, location, true);
if (updateTime) if (updateTime) this.lastMove = System.nanoTime();
this.lastMove = System.nanoTime();
this.npcPojo.setLocation(new ZLocation(location = new Location(location.getWorld(), location.getBlockX() + 0.5D, location.getY(), location.getBlockZ() + 0.5D, location.getYaw(), location.getPitch()))); this.npcPojo.setLocation(new ZLocation(location = new Location(location.getWorld(), location.getBlockX() + 0.5D, location.getY(), location.getBlockZ() + 0.5D, location.getYaw(), location.getPitch())));
} }
CacheRegistry.SET_LOCATION_METHOD.load().invoke(this.nmsEntity, location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); CacheRegistry.SET_LOCATION_METHOD.load().invoke(this.nmsEntity, location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
@ -172,8 +151,7 @@ public class NPC {
this.npcPojo.setSkin(skinFetch.getTexture()); this.npcPojo.setSkin(skinFetch.getTexture());
this.npcPojo.setSignature(skinFetch.getSignature()); this.npcPojo.setSignature(skinFetch.getSignature());
this.gameProfile.getProperties().clear(); this.gameProfile.getProperties().clear();
this.gameProfile.getProperties().put("textures", new Property("textures", this.npcPojo this.gameProfile.getProperties().put("textures", new Property("textures", this.npcPojo.getSkin(), this.npcPojo.getSignature()));
.getSkin(), this.npcPojo.getSignature()));
updateProfile(this.gameProfile.getProperties()); updateProfile(this.gameProfile.getProperties());
deleteViewers(); deleteViewers();
} }
@ -182,9 +160,9 @@ public class NPC {
try { try {
Object dataWatcherObject = CacheRegistry.GET_DATA_WATCHER_METHOD.load().invoke(this.nmsEntity); Object dataWatcherObject = CacheRegistry.GET_DATA_WATCHER_METHOD.load().invoke(this.nmsEntity);
if (Utils.versionNewer(9)) { if (Utils.versionNewer(9)) {
CacheRegistry.SET_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR CacheRegistry.SET_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject,
.load().newInstance(this.npcSkin.getLayerIndex(), CacheRegistry.DATA_WATCHER_REGISTER_FIELD CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR.load()
.load()), (byte) 127); .newInstance(this.npcSkin.getLayerIndex(), CacheRegistry.DATA_WATCHER_REGISTER_FIELD.load()), (byte) 127);
} else { } else {
CacheRegistry.WATCH_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, 10, (byte) 127); CacheRegistry.WATCH_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, 10, (byte) 127);
} }
@ -233,13 +211,11 @@ public class NPC {
scoreboardPackets.forEach(p -> Utils.sendPackets(user, p)); scoreboardPackets.forEach(p -> Utils.sendPackets(user, p));
} }
if (npcIsPlayer) { if (npcIsPlayer) {
if (FunctionFactory.isTrue(this, "mirror")) if (FunctionFactory.isTrue(this, "mirror")) updateProfile(user.getGameProfile().getProperties());
updateProfile(user.getGameProfile().getProperties());
Utils.sendPackets(user, this.tabConstructor, this.updateTabConstructor); Utils.sendPackets(user, this.tabConstructor, this.updateTabConstructor);
} }
Utils.sendPackets(user, this.packets.getProxyInstance().getSpawnPacket(this.nmsEntity, npcIsPlayer)); Utils.sendPackets(user, this.packets.getProxyInstance().getSpawnPacket(this.nmsEntity, npcIsPlayer));
if (FunctionFactory.isTrue(this, "holo")) if (FunctionFactory.isTrue(this, "holo")) this.hologram.spawn(user);
this.hologram.spawn(user);
updateMetadata(Collections.singleton(user)); updateMetadata(Collections.singleton(user));
sendEquipPackets(user); sendEquipPackets(user);
lookAt(user, getLocation(), true); lookAt(user, getLocation(), true);
@ -254,16 +230,14 @@ public class NPC {
} }
public synchronized void delete(ZUser user) { public synchronized void delete(ZUser user) {
if (!this.viewers.contains(user)) if (!this.viewers.contains(user)) throw new IllegalStateException(user.getUUID().toString() + " is not a viewer.");
throw new IllegalStateException(user.getUUID().toString() + " is not a viewer.");
this.viewers.remove(user); this.viewers.remove(user);
handleDelete(user); handleDelete(user);
} }
private void handleDelete(ZUser user) { private void handleDelete(ZUser user) {
try { try {
if (this.npcPojo.getNpcType() == NPCType.PLAYER) if (this.npcPojo.getNpcType() == NPCType.PLAYER) this.packets.getProxyInstance().getTabRemovePacket(this.nmsEntity);
this.packets.getProxyInstance().getTabRemovePacket(this.nmsEntity);
this.hologram.delete(user); this.hologram.delete(user);
Utils.sendPackets(user, this.packets.getProxyInstance().getDestroyPacket(this.entityID)); Utils.sendPackets(user, this.packets.getProxyInstance().getDestroyPacket(this.entityID));
} catch (ReflectiveOperationException operationException) { } catch (ReflectiveOperationException operationException) {
@ -273,34 +247,27 @@ public class NPC {
public void lookAt(ZUser player, Location location, boolean rotation) { public void lookAt(ZUser player, Location location, boolean rotation) {
long lastMoveNanos = System.nanoTime() - this.lastMove; long lastMoveNanos = System.nanoTime() - this.lastMove;
if (this.lastMove > 1L && lastMoveNanos < 1000000000L) if (this.lastMove > 1L && lastMoveNanos < 1000000000L) return;
return;
Location direction = rotation ? location : this.npcPojo.getLocation().bukkitLocation().clone().setDirection(location.clone().subtract(this.npcPojo.getLocation().bukkitLocation().clone()).toVector()); Location direction = rotation ? location : this.npcPojo.getLocation().bukkitLocation().clone().setDirection(location.clone().subtract(this.npcPojo.getLocation().bukkitLocation().clone()).toVector());
try { try {
Object lookPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_LOOK_CONSTRUCTOR.load().newInstance(this.entityID, (byte) (int) (direction.getYaw() * 256.0F / 360.0F), (byte) (int) (direction.getPitch() * 256.0F / 360.0F), true); Object lookPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_LOOK_CONSTRUCTOR.load().newInstance(this.entityID, (byte) (int) (direction.getYaw() * 256.0F / 360.0F), (byte) (int) (direction.getPitch() * 256.0F / 360.0F), true);
Object headRotationPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_HEAD_ROTATION_CONSTRUCTOR.load().newInstance(this.nmsEntity, (byte) (int) (direction.getYaw() * 256.0F / 360.0F)); Object headRotationPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_HEAD_ROTATION_CONSTRUCTOR.load().newInstance(this.nmsEntity, (byte) (int) (direction.getYaw() * 256.0F / 360.0F));
if (player != null) { if (player != null) Utils.sendPackets(player, lookPacket, headRotationPacket);
Utils.sendPackets(player, lookPacket, headRotationPacket); else this.viewers.forEach(players -> Utils.sendPackets(players, headRotationPacket));
} else {
this.viewers.forEach(players -> Utils.sendPackets(players, headRotationPacket));
}
} catch (ReflectiveOperationException operationException) { } catch (ReflectiveOperationException operationException) {
throw new UnexpectedCallException(operationException); throw new UnexpectedCallException(operationException);
} }
} }
public void deleteViewers() { public void deleteViewers() {
for (ZUser user : this.viewers) for (ZUser user : this.viewers) handleDelete(user);
handleDelete(user);
this.viewers.clear(); this.viewers.clear();
} }
protected void updateMetadata(Iterable<ZUser> users) { protected void updateMetadata(Iterable<ZUser> users) {
try { try {
Object metaData = this.packets.getProxyInstance().getMetadataPacket(this.entityID, this.nmsEntity); Object metaData = this.packets.getProxyInstance().getMetadataPacket(this.entityID, this.nmsEntity);
for (ZUser user : users) { for (ZUser user : users) Utils.sendPackets(user, metaData);
Utils.sendPackets(user, metaData);
}
} catch (ReflectiveOperationException operationException) { } catch (ReflectiveOperationException operationException) {
operationException.getCause().printStackTrace(); operationException.getCause().printStackTrace();
operationException.printStackTrace(); operationException.printStackTrace();
@ -308,8 +275,7 @@ public class NPC {
} }
public void updateProfile(PropertyMap propertyMap) { public void updateProfile(PropertyMap propertyMap) {
if (this.npcPojo.getNpcType() != NPCType.PLAYER) if (this.npcPojo.getNpcType() != NPCType.PLAYER) return;
return;
try { try {
Object gameProfileObj = CacheRegistry.GET_PROFILE_METHOD.load().invoke(this.nmsEntity); Object gameProfileObj = CacheRegistry.GET_PROFILE_METHOD.load().invoke(this.nmsEntity);
Utils.setValue(gameProfileObj, "name", this.gameProfile.getName()); Utils.setValue(gameProfileObj, "name", this.gameProfile.getName());
@ -321,8 +287,7 @@ public class NPC {
} }
public void sendEquipPackets(ZUser zUser) { public void sendEquipPackets(ZUser zUser) {
if (this.npcPojo.getNpcEquip().isEmpty()) if (this.npcPojo.getNpcEquip().isEmpty()) return;
return;
try { try {
ImmutableList<Object> equipPackets = this.packets.getProxyInstance().getEquipPackets(this); ImmutableList<Object> equipPackets = this.packets.getProxyInstance().getEquipPackets(this);
equipPackets.forEach(o -> Utils.sendPackets(zUser, o)); equipPackets.forEach(o -> Utils.sendPackets(zUser, o));
@ -343,13 +308,12 @@ public class NPC {
public void tryStartConversation(Player player) { public void tryStartConversation(Player player) {
ConversationModel conversation = this.npcPojo.getConversation(); ConversationModel conversation = this.npcPojo.getConversation();
if (conversation == null) if (conversation == null) throw new IllegalStateException("can't find conversation");
throw new IllegalStateException("can't find conversation");
conversation.startConversation(this, player); conversation.startConversation(this, player);
} }
public Location getLocation() { public Location getLocation() {
return (this.npcPath != null) ? return this.npcPath != null ?
this.npcPath.getLocation().bukkitLocation() : this.npcPath.getLocation().bukkitLocation() :
this.npcPojo.getLocation().bukkitLocation(); this.npcPojo.getLocation().bukkitLocation();
} }

@ -18,8 +18,7 @@ public class NPCManagerTask extends BukkitRunnable {
public void run() { public void run() {
for (NPC npc : NPC.all()) { for (NPC npc : NPC.all()) {
boolean hasPath = (npc.getNpcPath() != null); boolean hasPath = (npc.getNpcPath() != null);
if (hasPath) if (hasPath) npc.getNpcPath().handle();
npc.getNpcPath().handle();
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
ZUser zUser = ZUser.find(player); ZUser zUser = ZUser.find(player);
boolean canSeeNPC = (player.getWorld() == npc.getLocation().getWorld() && player.getLocation().distance(npc.getLocation()) <= ConfigurationConstants.VIEW_DISTANCE); boolean canSeeNPC = (player.getWorld() == npc.getLocation().getWorld() && player.getLocation().distance(npc.getLocation()) <= ConfigurationConstants.VIEW_DISTANCE);
@ -28,14 +27,11 @@ public class NPCManagerTask extends BukkitRunnable {
continue; continue;
} }
if (canSeeNPC) { if (canSeeNPC) {
if (!npc.getViewers().contains(zUser)) if (!npc.getViewers().contains(zUser)) npc.spawn(zUser);
npc.spawn(zUser); if (FunctionFactory.isTrue(npc, "look") && !hasPath) npc.lookAt(zUser, player.getLocation(), false);
if (FunctionFactory.isTrue(npc, "look") && !hasPath)
npc.lookAt(zUser, player.getLocation(), false);
npc.getHologram().updateNames(zUser); npc.getHologram().updateNames(zUser);
ConversationModel conversationStorage = npc.getNpcPojo().getConversation(); ConversationModel conversationStorage = npc.getNpcPojo().getConversation();
if (conversationStorage != null && conversationStorage.getConversationType() == ConversationModel.ConversationType.RADIUS) if (conversationStorage != null && conversationStorage.getConversationType() == ConversationModel.ConversationType.RADIUS) npc.tryStartConversation(player);
npc.tryStartConversation(player);
} }
} }
} }

@ -30,15 +30,14 @@ import java.util.Collections;
public class ZNPCsPlus extends JavaPlugin { public class ZNPCsPlus extends JavaPlugin {
public static final File PLUGIN_FOLDER = new File("plugins/ServersNPC"); public static final File PLUGIN_FOLDER = new File("plugins/ServersNPC");
public static final File PATH_FOLDER = new File("plugins/ServersNPC/paths"); public static final File PATH_FOLDER = new File("plugins/ServersNPC/paths");
public static final Gson GSON = (new GsonBuilder()) public static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(ZLocation.class, ZLocation.SERIALIZER) .registerTypeAdapter(ZLocation.class, ZLocation.SERIALIZER)
.registerTypeHierarchyAdapter(ItemStack.class, new ItemStackSerializer()) .registerTypeHierarchyAdapter(ItemStack.class, new ItemStackSerializer())
.setPrettyPrinting() .setPrettyPrinting()
.disableHtmlEscaping() .disableHtmlEscaping()
.create(); .create();
private static final int PLUGIN_ID = 8054; private static final int PLUGIN_ID = 18244;
public static SchedulerUtils SCHEDULER; public static SchedulerUtils SCHEDULER;
public static BungeeUtils BUNGEE_UTILS; public static BungeeUtils BUNGEE_UTILS;
@ -53,8 +52,7 @@ public class ZNPCsPlus extends JavaPlugin {
public static void deleteNPC(int npcID) { public static void deleteNPC(int npcID) {
NPC npc = NPC.find(npcID); NPC npc = NPC.find(npcID);
if (npc == null) if (npc == null) throw new IllegalStateException("can't find npc: " + npcID);
throw new IllegalStateException("can't find npc: " + npcID);
NPC.unregister(npcID); NPC.unregister(npcID);
ConfigurationConstants.NPC_LIST.remove(npc.getNpcPojo()); ConfigurationConstants.NPC_LIST.remove(npc.getNpcPojo());
} }
@ -82,14 +80,12 @@ public class ZNPCsPlus extends JavaPlugin {
} }
public void loadAllPaths() { public void loadAllPaths() {
File[] listFiles = PATH_FOLDER.listFiles(); File[] files = PATH_FOLDER.listFiles();
if (listFiles == null) if (files == null) return;
return; for (File file : files) {
for (File file : listFiles) { if (!file.getName().endsWith(".path")) continue;
if (file.getName().endsWith(".path")) {
NPCPath.AbstractTypeWriter abstractTypeWriter = NPCPath.AbstractTypeWriter.forFile(file, NPCPath.AbstractTypeWriter.TypeWriter.MOVEMENT); NPCPath.AbstractTypeWriter abstractTypeWriter = NPCPath.AbstractTypeWriter.forFile(file, NPCPath.AbstractTypeWriter.TypeWriter.MOVEMENT);
abstractTypeWriter.load(); abstractTypeWriter.load();
} }
} }
} }
}