From 15b4a6e9351f1725492619538d9c46b4077f94c9 Mon Sep 17 00:00:00 2001 From: libraryaddict Date: Thu, 13 Aug 2020 11:51:32 +1200 Subject: [PATCH] Clean a fair bit of reflection calls, still some left over.. Performance boost. Also fixed /disguise not spacing the disguises you can use --- .../packethandlers/PacketHandlerSpawn.java | 4 +- .../packetlisteners/PacketListenerSounds.java | 24 +- .../reflection/ReflectionManager.java | 560 +++++++++--------- .../utilities/translations/LibsMsg.java | 2 +- 4 files changed, 273 insertions(+), 317 deletions(-) diff --git a/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java b/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java index 6d452c1e..41761a34 100644 --- a/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java +++ b/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java @@ -24,6 +24,7 @@ import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import org.bukkit.Art; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.block.data.BlockData; import org.bukkit.entity.Damageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; @@ -305,13 +306,14 @@ public class PacketHandlerSpawn implements IPacketHandler { if (disguise.getType() == DisguiseType.FALLING_BLOCK) { if (NmsVersion.v1_13.isSupported()) { + BlockData block = ((FallingBlockWatcher) disguise.getWatcher()).getBlockData(); + data = ReflectionManager.getCombinedIdByBlockData(block); } else { ItemStack block = ((FallingBlockWatcher) disguise.getWatcher()).getBlock(); data = ReflectionManager.getCombinedIdByItemStack(block); } - if (((FallingBlockWatcher) disguise.getWatcher()).isGridLocked()) { // Center the block x = loc.getBlockX() + 0.5; diff --git a/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java b/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java index 0ab12b50..bda48bc6 100644 --- a/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java +++ b/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java @@ -22,6 +22,7 @@ import org.bukkit.block.Block; import org.bukkit.entity.*; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.Set; public class PacketListenerSounds extends PacketAdapter { @@ -31,6 +32,7 @@ public class PacketListenerSounds extends PacketAdapter { */ private static boolean cancelSound; private Object stepSoundEffect; + private Method getHealth, getSomething; public PacketListenerSounds(LibsDisguises plugin) { super(plugin, ListenerPriority.NORMAL, Server.NAMED_SOUND_EFFECT, Server.ENTITY_STATUS); @@ -95,25 +97,7 @@ public class PacketListenerSounds extends PacketAdapter { continue; } - Object obj = null; - - if (entity instanceof LivingEntity) { - try { - // Use reflection so that this works for either int or double methods - obj = LivingEntity.class.getMethod("getHealth").invoke(entity); - - if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) { - soundType = SoundType.DEATH; - } else { - obj = null; - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - if (obj == null) { + if ((!(entity instanceof LivingEntity)) || ((LivingEntity) entity).getHealth() > 0) { boolean hasInvun = false; Object nmsEntity = ReflectionManager.getNmsEntity(entity); @@ -134,6 +118,8 @@ public class PacketListenerSounds extends PacketAdapter { } soundType = entitySound.getType(soundEffectObj, !hasInvun); + } else { + soundType = SoundType.DEATH; } if (soundType != null) { diff --git a/src/main/java/me/libraryaddict/disguise/utilities/reflection/ReflectionManager.java b/src/main/java/me/libraryaddict/disguise/utilities/reflection/ReflectionManager.java index 267b6b81..af838f95 100644 --- a/src/main/java/me/libraryaddict/disguise/utilities/reflection/ReflectionManager.java +++ b/src/main/java/me/libraryaddict/disguise/utilities/reflection/ReflectionManager.java @@ -5,6 +5,7 @@ import com.comphenix.protocol.wrappers.*; import com.comphenix.protocol.wrappers.EnumWrappers.Direction; import com.comphenix.protocol.wrappers.WrappedDataWatcher.WrappedDataWatcherObject; import com.comphenix.protocol.wrappers.nbt.NbtWrapper; +import com.mojang.authlib.GameProfile; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.*; @@ -16,7 +17,6 @@ import me.libraryaddict.disguise.utilities.sounds.SoundGroup; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.bukkit.*; -import org.bukkit.block.BlockState; import org.bukkit.block.data.BlockData; import org.bukkit.command.Command; import org.bukkit.command.CommandMap; @@ -45,8 +45,10 @@ import java.util.jar.JarFile; import java.util.stream.Collectors; public class ReflectionManager { + private static final HashMap soundCategories = new HashMap<>(); private static String bukkitVersion; - private static Class craftItemClass; + private static Method itemAsCraftCopyMethod; + private static Method itemAsNmsCopyMethod; private static Method damageAndIdleSoundMethod; private static Constructor boundingBoxConstructor; private static Method setBoundingBoxMethod; @@ -63,43 +65,158 @@ public class ReflectionManager { @NmsRemovedIn(val = NmsVersion.v1_14) private static Field entitiesField; private static NmsVersion version; + private static Method itemAsBukkitMethod; + private static Method soundEffectMethod; + private static Method getServerMethod; + private static Method getEnumArtMethod; + private static Constructor blockPositionConstructor; + private static Method enumDirectionMethod; + private static Enum[] enumPlayerInfoAction; + private static Constructor chatComponentConstructor; + private static Constructor packetPlayOutConstructor; + private static Enum[] enumGamemode; + private static Method getNmsEntityMethod; + private static Enum[] enumItemSlots; + private static Method soundGetMethod; + private static Constructor vector3FConstructor; + private static Method enumDirectionFrom; + private static Constructor villagerDataConstructor; + private static Method bukkitKeyToNms; + private static Method registryBlocksGetMethod; + private static Object villagerTypeRegistry; + private static Object villagerProfessionRegistry; + private static Constructor dataWatcherItemConstructor; + private static Constructor vec3DConstructor; + private static Method entityTypesAMethod; + private static Class entityPoseClass; + private static Method craftBlockDataGetState; + private static Method getOldItemAsBlock; + private static Method magicGetBlock; + private static Method getNmsItem; + private static Method getBlockData; + private static Method getBlockDataAsId; + private static Method getNmsWorld; + private static Method deserializedItemMeta; + private static Method mobEffectList; + private static Constructor mobEffectConstructor; + private static Method boundingBoxMethod; + private static Method bukkitEntityMethod; public static void init() { // Sometimes it doesn't like me if I don't set this :\ // Weird characters in toLowerCase() for example Locale.setDefault(Locale.ENGLISH); + try { + boundingBoxConstructor = + getNmsConstructor("AxisAlignedBB", double.class, double.class, double.class, double.class, + double.class, double.class); + + setBoundingBoxMethod = getNmsMethod("Entity", "a", getNmsClass("AxisAlignedBB")); + entityCountField = getNmsField("Entity", "entityCount"); + + mobEffectConstructor = + getNmsConstructor("MobEffect", getNmsClass("MobEffectList"), Integer.TYPE, Integer.TYPE, + Boolean.TYPE, Boolean.TYPE); + mobEffectList = getNmsMethod("MobEffectList", "fromId", Integer.TYPE); + boundingBoxMethod = getNmsMethod("Entity", "getBoundingBox"); + bukkitEntityMethod = getNmsMethod("Entity", "getBukkitEntity"); + + Class craftItemClass = getCraftClass("inventory.CraftItemStack"); + itemAsCraftCopyMethod = getCraftMethod(craftItemClass, "asCraftCopy", ItemStack.class); + itemAsNmsCopyMethod = getCraftMethod(craftItemClass, "asNMSCopy", ItemStack.class); + itemAsBukkitMethod = getCraftMethod(craftItemClass, "asBukkitCopy", getNmsClass("ItemStack")); + soundEffectMethod = getCraftMethod("CraftSound", "getSoundEffect", String.class); + getServerMethod = getCraftMethod("CraftServer", "getServer"); + getEnumArtMethod = getCraftMethod("CraftArt", "BukkitToNotch", Art.class); + blockPositionConstructor = getNmsConstructor("BlockPosition", int.class, int.class, int.class); + enumDirectionMethod = getNmsMethod("EnumDirection", "fromType2", int.class); + enumPlayerInfoAction = + (Enum[]) getNmsClass("PacketPlayOutPlayerInfo$EnumPlayerInfoAction").getEnumConstants(); + chatComponentConstructor = getNmsConstructor("ChatComponentText", String.class); + packetPlayOutConstructor = + getNmsConstructor("PacketPlayOutPlayerInfo$PlayerInfoData", getNmsClass("PacketPlayOutPlayerInfo"), + GameProfile.class, int.class, getNmsClass("EnumGamemode"), + getNmsClass("IChatBaseComponent")); + enumGamemode = (Enum[]) getNmsClass("EnumGamemode").getEnumConstants(); + getNmsEntityMethod = getCraftMethod("entity.CraftEntity", "getHandle"); + enumItemSlots = (Enum[]) getNmsClass("EnumItemSlot").getEnumConstants(); + soundGetMethod = getCraftMethod("CraftSound", "getSound", Sound.class); + vector3FConstructor = getNmsConstructor("Vector3f", float.class, float.class, float.class); + enumDirectionFrom = getNmsMethod("EnumDirection", "fromType1", int.class); + + if (NmsVersion.v1_13.isSupported()) { + craftBlockDataGetState = getCraftMethod("block.data.CraftBlockData", "getState"); + magicGetBlock = getCraftMethod("util.CraftMagicNumbers", "getBlock", Material.class); + getBlockData = getNmsMethod(getNmsClass("Block"), "getBlockData"); + entityTypesAMethod = getNmsMethod("EntityTypes", "a", String.class); + + if (NmsVersion.v1_14.isSupported()) { + entityPoseClass = getNmsClass("EntityPose"); + registryBlocksGetMethod = getNmsMethod("RegistryBlocks", "get", getNmsClass("MinecraftKey")); + villagerDataConstructor = getNmsConstructor("VillagerData", getNmsClass("VillagerType"), + getNmsClass("VillagerProfession"), int.class); + villagerProfessionRegistry = getNmsField("IRegistry", "VILLAGER_PROFESSION").get(null); + villagerTypeRegistry = getNmsField("IRegistry", "VILLAGER_TYPE").get(null); + } else { + registryBlocksGetMethod = + getNmsMethod("RegistryBlocks", "getOrDefault", getNmsClass("MinecraftKey")); + } + } + + bukkitKeyToNms = getCraftMethod("util.CraftNamespacedKey", "toMinecraft", NamespacedKey.class); + dataWatcherItemConstructor = + getNmsConstructor("DataWatcher$Item", getNmsClass("DataWatcherObject"), Object.class); + vec3DConstructor = getNmsConstructor("Vec3D", double.class, double.class, double.class); + getOldItemAsBlock = getNmsMethod(getNmsClass("Block"), "asBlock", getNmsClass("Item")); + getNmsItem = getNmsMethod("ItemStack", "getItem"); + getBlockDataAsId = getNmsMethod("Block", "getCombinedId", getNmsClass("IBlockData")); + + getNmsWorld = getCraftMethod("CraftWorld", "getHandle"); + deserializedItemMeta = + getCraftMethod(getCraftClass("inventory.CraftMetaItem$SerializableMeta"), "deserialize", Map.class); + + Method method = getNmsMethod("SoundCategory", "a"); + + for (Enum anEnum : (Enum[]) getNmsClass("SoundCategory").getEnumConstants()) { + soundCategories.put((String) method.invoke(anEnum), anEnum); + } + } catch (Exception e) { + e.printStackTrace(); + } + try { Object entity = createEntityInstance(DisguiseType.COW, "Cow"); for (Method method : getNmsClass("EntityCow").getDeclaredMethods()) { - if (method.getReturnType() != float.class) + if (method.getReturnType() != float.class) { continue; + } - if (!Modifier.isProtected(method.getModifiers())) + if (!Modifier.isProtected(method.getModifiers())) { continue; + } - if (method.getParameterTypes().length != 0) + if (method.getParameterTypes().length != 0) { continue; + } method.setAccessible(true); float value = (Float) method.invoke(entity); - if ((float) method.invoke(entity) != 0.4f) + if ((float) method.invoke(entity) != 0.4f) { continue; + } damageAndIdleSoundMethod = getNmsClass("EntityLiving").getDeclaredMethod(method.getName()); damageAndIdleSoundMethod.setAccessible(true); break; } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } - craftItemClass = getCraftClass("inventory.CraftItemStack"); - pingField = getNmsField("EntityPlayer", "ping"); if (NmsVersion.v1_14.isSupported()) { @@ -117,15 +234,6 @@ public class ReflectionManager { entitiesField = getNmsField("EntityTracker", "trackedEntities"); ihmGet = getNmsMethod("IntHashMap", "get", int.class); } - - boundingBoxConstructor = getNmsConstructor("AxisAlignedBB", double.class, double.class, double.class, - double.class, double.class, double.class); - - setBoundingBoxMethod = getNmsMethod("Entity", "a", getNmsClass("AxisAlignedBB")); - - entityCountField = getNmsField("Entity", "entityCount"); - - entityCountField.setAccessible(true); } public static boolean isSupported(AccessibleObject obj) { @@ -164,8 +272,7 @@ public class ReflectionManager { return isSupported(method); } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -180,8 +287,7 @@ public class ReflectionManager { return new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)).lines() .collect(Collectors.joining("\n")); } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -204,8 +310,7 @@ public class ReflectionManager { config.loadFromString(getResourceAsString(file, "plugin.yml")); return config; - } - catch (InvalidConfigurationException e) { + } catch (InvalidConfigurationException e) { e.printStackTrace(); } @@ -233,8 +338,7 @@ public class ReflectionManager { } return entityCount.intValue(); - } - catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { e.printStackTrace(); } @@ -288,8 +392,7 @@ public class ReflectionManager { } return entityObject; - } - catch (Exception e) { + } catch (Exception e) { DisguiseUtilities.getLogger() .warning("Error while attempting to create entity instance for " + disguiseType.name()); e.printStackTrace(); @@ -299,12 +402,9 @@ public class ReflectionManager { } public static Object getMobEffectList(int id) { - Method nmsMethod = getNmsMethod("MobEffectList", "fromId", Integer.TYPE); - try { - return nmsMethod.invoke(null, id); - } - catch (IllegalAccessException | InvocationTargetException e) { + return mobEffectList.invoke(null, id); + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } @@ -318,12 +418,8 @@ public class ReflectionManager { public static Object createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { try { - return getNmsClass("MobEffect") - .getDeclaredConstructor(getNmsClass("MobEffectList"), Integer.TYPE, Integer.TYPE, Boolean.TYPE, - Boolean.TYPE) - .newInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - catch (Exception e) { + return mobEffectConstructor.newInstance(getMobEffectList(id), duration, amplification, ambient, particles); + } catch (Exception e) { e.printStackTrace(); } @@ -332,7 +428,7 @@ public class ReflectionManager { public static FakeBoundingBox getBoundingBox(Entity entity) { try { - Object boundingBox = getNmsMethod("Entity", "getBoundingBox").invoke(getNmsEntity(entity)); + Object boundingBox = boundingBoxMethod.invoke(getNmsEntity(entity)); double x = 0, y = 0, z = 0; int stage = 0; @@ -369,8 +465,7 @@ public class ReflectionManager { } return new FakeBoundingBox(x, y, z); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -379,9 +474,8 @@ public class ReflectionManager { public static Entity getBukkitEntity(Object nmsEntity) { try { - return (Entity) getNmsMethod("Entity", "getBukkitEntity").invoke(nmsEntity); - } - catch (Exception ex) { + return (Entity) bukkitEntityMethod.invoke(nmsEntity); + } catch (Exception ex) { ex.printStackTrace(); } @@ -390,9 +484,8 @@ public class ReflectionManager { public static ItemStack getBukkitItem(Object nmsItem) { try { - return (ItemStack) craftItemClass.getMethod("asBukkitCopy", getNmsClass("ItemStack")).invoke(null, nmsItem); - } - catch (Exception e) { + return (ItemStack) itemAsBukkitMethod.invoke(null, nmsItem); + } catch (Exception e) { e.printStackTrace(); } @@ -401,9 +494,8 @@ public class ReflectionManager { public static ItemStack getCraftItem(ItemStack bukkitItem) { try { - return (ItemStack) craftItemClass.getMethod("asCraftCopy", ItemStack.class).invoke(null, bukkitItem); - } - catch (Exception e) { + return (ItemStack) itemAsCraftCopyMethod.invoke(null, bukkitItem); + } catch (Exception e) { e.printStackTrace(); } @@ -438,8 +530,7 @@ public class ReflectionManager { public static Class getCraftClass(String className) { try { return Class.forName("org.bukkit.craftbukkit." + getBukkitVersion() + "." + className); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -451,8 +542,7 @@ public class ReflectionManager { Constructor declaredConstructor = clazz.getDeclaredConstructor(parameters); declaredConstructor.setAccessible(true); return declaredConstructor; - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { e.printStackTrace(); } @@ -465,10 +555,8 @@ public class ReflectionManager { public static Object getCraftSound(Sound sound) { try { - return getCraftClass("CraftSound").getMethod("getSoundEffect", String.class) - .invoke(null, getSoundString(sound)); - } - catch (Exception ex) { + return soundEffectMethod.invoke(null, getSoundString(sound)); + } catch (Exception ex) { ex.printStackTrace(); } @@ -500,9 +588,8 @@ public class ReflectionManager { public static Object getMinecraftServer() { try { - return getCraftMethod("CraftServer", "getServer").invoke(Bukkit.getServer()); - } - catch (IllegalAccessException | InvocationTargetException e) { + return getServerMethod.invoke(Bukkit.getServer()); + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; @@ -510,14 +597,13 @@ public class ReflectionManager { public static String getEnumArt(Art art) { try { - Object enumArt = getCraftClass("CraftArt").getMethod("BukkitToNotch", Art.class).invoke(null, art); + Object enumArt = getEnumArtMethod.invoke(null, art); for (Field field : enumArt.getClass().getDeclaredFields()) { if (field.getType() == String.class) { return (String) field.get(enumArt); } } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -526,10 +612,8 @@ public class ReflectionManager { public static Object getBlockPosition(int x, int y, int z) { try { - return getNmsClass("BlockPosition").getDeclaredConstructor(int.class, int.class, int.class) - .newInstance(x, y, z); - } - catch (Exception ex) { + return blockPositionConstructor.newInstance(x, y, z); + } catch (Exception ex) { ex.printStackTrace(); } @@ -538,9 +622,8 @@ public class ReflectionManager { public static Enum getEnumDirection(int direction) { try { - return (Enum) getNmsMethod("EnumDirection", "fromType2", int.class).invoke(null, direction); - } - catch (Exception ex) { + return (Enum) enumDirectionMethod.invoke(null, direction); + } catch (Exception ex) { ex.printStackTrace(); } @@ -549,9 +632,8 @@ public class ReflectionManager { public static Enum getEnumPlayerInfoAction(int action) { try { - return (Enum) getNmsClass("PacketPlayOutPlayerInfo$EnumPlayerInfoAction").getEnumConstants()[action]; - } - catch (Exception ex) { + return enumPlayerInfoAction[action]; + } catch (Exception ex) { ex.printStackTrace(); } @@ -560,16 +642,11 @@ public class ReflectionManager { public static Object getPlayerInfoData(Object playerInfoPacket, WrappedGameProfile gameProfile) { try { - Object playerListName = getNmsClass("ChatComponentText").getDeclaredConstructor(String.class) - .newInstance(gameProfile.getName()); + Object playerListName = chatComponentConstructor.newInstance(gameProfile.getName()); - return getNmsClass("PacketPlayOutPlayerInfo$PlayerInfoData") - .getDeclaredConstructor(getNmsClass("PacketPlayOutPlayerInfo"), gameProfile.getHandleType(), - int.class, getNmsClass("EnumGamemode"), getNmsClass("IChatBaseComponent")) - .newInstance(playerInfoPacket, gameProfile.getHandle(), 0, - getNmsClass("EnumGamemode").getEnumConstants()[1], playerListName); - } - catch (Exception ex) { + return packetPlayOutConstructor + .newInstance(playerInfoPacket, gameProfile.getHandle(), 0, enumGamemode[1], playerListName); + } catch (Exception ex) { ex.printStackTrace(); } @@ -583,8 +660,7 @@ public class ReflectionManager { public static WrappedGameProfile getGameProfile(UUID uuid, String playerName) { try { return new WrappedGameProfile(uuid != null ? uuid : getRandomUUID(), playerName); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } return null; @@ -595,7 +671,7 @@ public class ReflectionManager { } public static WrappedGameProfile getGameProfileWithThisSkin(UUID uuid, String playerName, - WrappedGameProfile profileWithSkin) { + WrappedGameProfile profileWithSkin) { try { WrappedGameProfile gameProfile = new WrappedGameProfile(uuid != null ? uuid : getRandomUUID(), playerName); @@ -604,8 +680,7 @@ public class ReflectionManager { } return gameProfile; - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -641,8 +716,7 @@ public class ReflectionManager { public static Class getNmsClass(String className) { try { return Class.forName("net.minecraft.server." + getBukkitVersion() + "." + className); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -652,8 +726,7 @@ public class ReflectionManager { public static Class getNmsClassIgnoreErrors(String className) { try { return Class.forName("net.minecraft.server." + getBukkitVersion() + "." + className); - } - catch (Exception ignored) { + } catch (Exception ignored) { } return null; @@ -664,8 +737,7 @@ public class ReflectionManager { Constructor declaredConstructor = clazz.getDeclaredConstructor(parameters); declaredConstructor.setAccessible(true); return declaredConstructor; - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { e.printStackTrace(); } @@ -678,9 +750,8 @@ public class ReflectionManager { public static Object getNmsEntity(Entity entity) { try { - return getCraftClass("entity.CraftEntity").getMethod("getHandle").invoke(entity); - } - catch (Exception ex) { + return getNmsEntityMethod.invoke(entity); + } catch (Exception ex) { ex.printStackTrace(); } @@ -693,8 +764,7 @@ public class ReflectionManager { declaredField.setAccessible(true); return declaredField; - } - catch (NoSuchFieldException e) { + } catch (NoSuchFieldException e) { e.printStackTrace(); } @@ -707,9 +777,8 @@ public class ReflectionManager { public static Object getNmsItem(ItemStack itemstack) { try { - return craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, itemstack); - } - catch (Exception e) { + return itemAsNmsCopyMethod.invoke(null, itemstack); + } catch (Exception e) { e.printStackTrace(); } @@ -726,8 +795,7 @@ public class ReflectionManager { declaredMethod.setAccessible(true); return declaredMethod; - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { e.printStackTrace(); } @@ -740,8 +808,7 @@ public class ReflectionManager { declaredMethod.setAccessible(true); return declaredMethod; - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { e.printStackTrace(); } @@ -755,8 +822,7 @@ public class ReflectionManager { public static double getPing(Player player) { try { return pingField.getInt(ReflectionManager.getNmsEntity(player)); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -780,8 +846,7 @@ public class ReflectionManager { float height = (Float) getNmsMethod("Entity", "getHeadHeight").invoke(getNmsEntity(entity)); return new float[]{width, height}; } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -801,8 +866,7 @@ public class ReflectionManager { .invoke(session, gameProfile.getHandle(), true)); } } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -812,8 +876,7 @@ public class ReflectionManager { public static Float getSoundModifier(Object entity) { try { return (Float) damageAndIdleSoundMethod.invoke(entity); - } - catch (Exception ignored) { + } catch (Exception ignored) { } return null; } @@ -843,8 +906,7 @@ public class ReflectionManager { return getGameProfile(null, playername); } } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -861,42 +923,29 @@ public class ReflectionManager { loc.getZ() + (newBox.getZ() / 2)); setBoundingBoxMethod.invoke(getNmsEntity(entity), boundingBox); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } } public static Enum getSoundCategory(String category) { - try { - Method method = getNmsMethod("SoundCategory", "a"); - - for (Enum anEnum : (Enum[]) getNmsClass("SoundCategory").getEnumConstants()) { - if (!category.equals(method.invoke(anEnum))) { - continue; - } - - return anEnum; - } - } - catch (Exception e) { - e.printStackTrace(); - } - - return null; + return soundCategories.get(category); } public static Enum getSoundCategory(DisguiseType disguiseType) { - if (disguiseType == DisguiseType.PLAYER) + if (disguiseType == DisguiseType.PLAYER) { return getSoundCategory("player"); + } Class entityClass = disguiseType.getEntityType().getEntityClass(); - if (Monster.class.isAssignableFrom(entityClass)) + if (Monster.class.isAssignableFrom(entityClass)) { return getSoundCategory("hostile"); + } - if (Ambient.class.isAssignableFrom(entityClass)) + if (Ambient.class.isAssignableFrom(entityClass)) { return getSoundCategory("ambient"); + } return getSoundCategory("neutral"); } @@ -908,26 +957,19 @@ public class ReflectionManager { * @return null if the equipment slot is null */ public static Enum createEnumItemSlot(EquipmentSlot slot) { - Class clazz = getNmsClass("EnumItemSlot"); - - Object[] enums = clazz != null ? clazz.getEnumConstants() : null; - - if (enums == null) - return null; - switch (slot) { case HAND: - return (Enum) enums[0]; + return enumItemSlots[0]; case OFF_HAND: - return (Enum) enums[1]; + return enumItemSlots[1]; case FEET: - return (Enum) enums[2]; + return enumItemSlots[2]; case LEGS: - return (Enum) enums[3]; + return enumItemSlots[3]; case CHEST: - return (Enum) enums[4]; + return enumItemSlots[4]; case HEAD: - return (Enum) enums[5]; + return enumItemSlots[5]; default: return null; } @@ -956,8 +998,7 @@ public class ReflectionManager { case "HEAD": return EquipmentSlot.HEAD; } - } - catch (Exception e) { + } catch (Exception ignored) { } return null; @@ -970,8 +1011,9 @@ public class ReflectionManager { * @return null if the disguisedEntity is not an instance of a living entity */ public static ItemStack getEquipment(EquipmentSlot slot, Entity disguisedEntity) { - if (!(disguisedEntity instanceof LivingEntity)) + if (!(disguisedEntity instanceof LivingEntity)) { return null; + } switch (slot) { case HAND: @@ -993,9 +1035,8 @@ public class ReflectionManager { public static Object getSoundString(Sound sound) { try { - return getCraftMethod("CraftSound", "getSound", Sound.class).invoke(null, sound); - } - catch (IllegalAccessException | InvocationTargetException e) { + return soundGetMethod.invoke(null, sound); + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } @@ -1020,7 +1061,7 @@ public class ReflectionManager { } else if (WrappedParticle.class.isAssignableFrom(cl)) { return getNmsClass("ParticleParam"); } else if (EntityPose.class.isAssignableFrom(cl)) { - return getNmsClass("EntityPose"); + return entityPoseClass; } else if (NbtWrapper.class.isAssignableFrom(cl)) { return getNmsClass("NBTTagCompound"); } @@ -1032,8 +1073,9 @@ public class ReflectionManager { if (value instanceof Optional) { Optional opt = (Optional) value; - if (!opt.isPresent()) + if (!opt.isPresent()) { return NmsVersion.v1_13.isSupported() ? value : com.google.common.base.Optional.absent(); + } Object val = opt.get(); @@ -1041,29 +1083,27 @@ public class ReflectionManager { BlockPosition pos = (BlockPosition) val; try { - Object obj = getNmsConstructor("BlockPosition", int.class, int.class, int.class) - .newInstance(pos.getX(), pos.getY(), pos.getZ()); + Object obj = blockPositionConstructor.newInstance(pos.getX(), pos.getY(), pos.getZ()); return NmsVersion.v1_13.isSupported() ? Optional.of(obj) : com.google.common.base.Optional.of(obj); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } } else if (val instanceof WrappedBlockData) { try { Object obj = ((WrappedBlockData) val).getHandle(); return NmsVersion.v1_13.isSupported() ? Optional.of(obj) : com.google.common.base.Optional.of(obj); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } } else if (val instanceof ItemStack) { val = getNmsItem((ItemStack) val); - if (val == null) + if (val == null) { return NmsVersion.v1_13.isSupported() ? Optional.empty() : com.google.common.base.Optional.absent(); - else + } else { return Optional.of(val); + } } else if (val instanceof WrappedChatComponent) { Object obj = ((WrappedChatComponent) val).getHandle(); @@ -1075,28 +1115,22 @@ public class ReflectionManager { Vector3F angle = (Vector3F) value; try { - return getNmsConstructor("Vector3f", float.class, float.class, float.class) - .newInstance(angle.getX(), angle.getY(), angle.getZ()); - } - catch (Exception ex) { + return vector3FConstructor.newInstance(angle.getX(), angle.getY(), angle.getZ()); + } catch (Exception ex) { ex.printStackTrace(); } } else if (value instanceof Direction) { try { - return getNmsMethod("EnumDirection", "fromType1", int.class) - .invoke(null, ((Direction) value).ordinal()); - } - catch (Exception ex) { + return enumDirectionFrom.invoke(null, ((Direction) value).ordinal()); + } catch (Exception ex) { ex.printStackTrace(); } } else if (value instanceof BlockPosition) { BlockPosition pos = (BlockPosition) value; try { - return getNmsConstructor("BlockPosition", int.class, int.class, int.class) - .newInstance(pos.getX(), pos.getY(), pos.getZ()); - } - catch (Exception ex) { + return blockPositionConstructor.newInstance(pos.getX(), pos.getY(), pos.getZ()); + } catch (Exception ex) { ex.printStackTrace(); } } else if (value instanceof ItemStack) { @@ -1121,8 +1155,8 @@ public class ReflectionManager { public static Material getMaterial(String name) { try { if (!NmsVersion.v1_13.isSupported()) { - Method toMinecraft = getCraftMethod("util.CraftMagicNumbers", "getMaterialFromInternalName", - String.class); + Method toMinecraft = + getCraftMethod("util.CraftMagicNumbers", "getMaterialFromInternalName", String.class); Object instance = toMinecraft.getDeclaringClass().getField("INSTANCE").get(null); @@ -1143,8 +1177,7 @@ public class ReflectionManager { Method getMaterial = getCraftMethod("util.CraftMagicNumbers", "getMaterial", getNmsClass("Item")); return (Material) getMaterial.invoke(null, item); - } - catch (Exception ex) { + } catch (Exception ex) { DisguiseUtilities.getLogger().severe("Error when trying to convert '" + name + "' into a Material"); ex.printStackTrace(); @@ -1172,8 +1205,8 @@ public class ReflectionManager { registry = getNmsField("Item", "REGISTRY").get(null); } - Method getMethod = getNmsMethod(registry.getClass(), NmsVersion.v1_13.isSupported() ? "getKey" : "b", - Object.class); + Method getMethod = + getNmsMethod(registry.getClass(), NmsVersion.v1_13.isSupported() ? "getKey" : "b", Object.class); Object mcKey = getMethod.invoke(registry, item); @@ -1182,8 +1215,7 @@ public class ReflectionManager { } return (String) getNmsMethod("MinecraftKey", "getKey").invoke(mcKey); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1195,10 +1227,8 @@ public class ReflectionManager { Object profession = getVillagerProfession(data.getProfession()); try { - return getNmsConstructor("VillagerData", getNmsClass("VillagerType"), profession.getClass(), int.class) - .newInstance(type, profession, data.getLevel()); - } - catch (Exception e) { + return villagerDataConstructor.newInstance(type, profession, data.getLevel()); + } catch (Exception e) { e.printStackTrace(); } @@ -1207,15 +1237,10 @@ public class ReflectionManager { public static Object getVillagerType(Villager.Type type) { try { - Object villagerType = getNmsField("IRegistry", "VILLAGER_TYPE").get(null); + Object mcKey = bukkitKeyToNms.invoke(null, type.getKey()); - Method toMinecraft = getCraftMethod("util.CraftNamespacedKey", "toMinecraft", NamespacedKey.class); - Object mcKey = toMinecraft.invoke(null, type.getKey()); - Method getField = getNmsMethod("RegistryBlocks", "get", mcKey.getClass()); - - return getField.invoke(villagerType, mcKey); - } - catch (Exception e) { + return registryBlocksGetMethod.invoke(villagerTypeRegistry, mcKey); + } catch (Exception e) { e.printStackTrace(); } @@ -1248,15 +1273,10 @@ public class ReflectionManager { public static Object getVillagerProfession(Villager.Profession profession) { try { - Object villagerProfession = getNmsField("IRegistry", "VILLAGER_PROFESSION").get(null); + Object mcKey = bukkitKeyToNms.invoke(null, profession.getKey()); - Method toMinecraft = getCraftMethod("util.CraftNamespacedKey", "toMinecraft", NamespacedKey.class); - Object mcKey = toMinecraft.invoke(null, profession.getKey()); - Method getField = getNmsMethod("RegistryBlocks", "get", mcKey.getClass()); - - return getField.invoke(villagerProfession, mcKey); - } - catch (Exception e) { + return registryBlocksGetMethod.invoke(villagerProfessionRegistry, mcKey); + } catch (Exception e) { e.printStackTrace(); } @@ -1270,8 +1290,9 @@ public class ReflectionManager { } public static WrappedDataWatcherObject createDataWatcherObject(MetaIndex index, Object value) { - if (value == null) + if (value == null) { return null; + } return new WrappedDataWatcherObject(index.getIndex(), index.getSerializer()); } @@ -1286,12 +1307,9 @@ public class ReflectionManager { public static Object createDataWatcherItem(MetaIndex id, Object value) { WrappedDataWatcherObject watcherObject = createDataWatcherObject(id, value); - Constructor construct = getNmsConstructor("DataWatcher$Item", getNmsClass("DataWatcherObject"), Object.class); - try { - return construct.newInstance(watcherObject.getHandle(), convertInvalidMeta(value)); - } - catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + return dataWatcherItemConstructor.newInstance(watcherObject.getHandle(), convertInvalidMeta(value)); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } @@ -1302,8 +1320,7 @@ public class ReflectionManager { try { return getNmsConstructor("SoundEffect", getNmsClass("MinecraftKey")) .newInstance(createMinecraftKey(minecraftKey)); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1312,9 +1329,8 @@ public class ReflectionManager { public static Object createMinecraftKey(String name) { try { - return getNmsClass("MinecraftKey").getConstructor(String.class).newInstance(name); - } - catch (Exception ex) { + return getNmsConstructor("MinecraftKey", String.class).newInstance(name); + } catch (Exception ex) { ex.printStackTrace(); } @@ -1323,11 +1339,8 @@ public class ReflectionManager { public static Object getVec3D(Vector vector) { try { - Constructor c = getNmsConstructor("Vec3D", double.class, double.class, double.class); - - return c.newInstance(vector.getX(), vector.getY(), vector.getZ()); - } - catch (Exception ex) { + return vec3DConstructor.newInstance(vector.getX(), vector.getY(), vector.getZ()); + } catch (Exception ex) { ex.printStackTrace(); } @@ -1336,8 +1349,7 @@ public class ReflectionManager { public static Object getEntityType(EntityType entityType) { try { - Method entityTypes = getNmsMethod("EntityTypes", "a", String.class); - Object val = entityTypes.invoke(null, + Object val = entityTypesAMethod.invoke(null, entityType.getName() == null ? entityType.name().toLowerCase() : entityType.getName()); if (NmsVersion.v1_14.isSupported()) { @@ -1345,8 +1357,7 @@ public class ReflectionManager { } return val; - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -1386,8 +1397,7 @@ public class ReflectionManager { .invoke(null, registry, mcKey, entityType); return entityType; - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -1401,8 +1411,7 @@ public class ReflectionManager { Object registry = typesClass.getField("ENTITY_TYPE").get(null); return (int) registry.getClass().getMethod("a", Object.class).invoke(registry, entityTypes); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1422,8 +1431,7 @@ public class ReflectionManager { } return entityType.getTypeId(); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1438,8 +1446,7 @@ public class ReflectionManager { Object mcKey = getNmsConstructor("MinecraftKey", String.class).newInstance(name.toString()); return registry.getClass().getMethod("a", mcKey.getClass()).invoke(registry, mcKey); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1447,7 +1454,7 @@ public class ReflectionManager { } public static Object getNmsEntityPose(EntityPose entityPose) { - return Enum.valueOf(getNmsClass("EntityPose"), + return Enum.valueOf(entityPoseClass, entityPose == EntityPose.SNEAKING && NmsVersion.v1_15.isSupported() ? "CROUCHING" : entityPose.name()); } @@ -1459,19 +1466,19 @@ public class ReflectionManager { public static WrappedWatchableObject createWatchable(MetaIndex index, Object obj) { Object watcherItem = createDataWatcherItem(index, obj); - if (watcherItem == null) + if (watcherItem == null) { return null; + } return new WrappedWatchableObject(watcherItem); } public static int getCombinedIdByBlockData(BlockData data) { try { - Object iBlockData = getCraftMethod("block.data.CraftBlockData", "getState").invoke(data); + Object iBlockData = craftBlockDataGetState.invoke(data); return (int) getNmsMethod("Block", "getCombinedId", getNmsClass("IBlockData")).invoke(null, iBlockData); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1481,24 +1488,21 @@ public class ReflectionManager { public static int getCombinedIdByItemStack(ItemStack itemStack) { try { Object nmsBlock; - Class blockClass = getNmsClass("Block"); if (NmsVersion.v1_13.isSupported()) { - nmsBlock = getCraftMethod("util.CraftMagicNumbers", "getBlock", Material.class) - .invoke(null, itemStack.getType()); + nmsBlock = magicGetBlock.invoke(null, itemStack.getType()); } else { Object nmsItem = getNmsItem(itemStack); - Object item = getNmsMethod("ItemStack", "getItem").invoke(nmsItem); + Object item = getNmsItem.invoke(nmsItem); - nmsBlock = getNmsMethod(blockClass, "asBlock", getNmsClass("Item")).invoke(null, item); + nmsBlock = getOldItemAsBlock.invoke(null, item); } - Object iBlockData = getNmsMethod(blockClass, "getBlockData").invoke(nmsBlock); + Object iBlockData = getBlockData.invoke(nmsBlock); - return (int) getNmsMethod("Block", "getCombinedId", getNmsClass("IBlockData")).invoke(null, iBlockData); - } - catch (Exception ex) { + return (int) getBlockDataAsId.invoke(null, iBlockData); + } catch (Exception ex) { ex.printStackTrace(); } @@ -1513,8 +1517,7 @@ public class ReflectionManager { return (BlockData) getCraftMethod("block.data.CraftBlockData", "fromData", iBlockClass) .invoke(null, iBlockData); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1533,8 +1536,7 @@ public class ReflectionManager { Method getItem = getNmsMethod("Block", "t", iBlockClass); return getBukkitItem(getItem.invoke(block, iBlockData)); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1543,22 +1545,8 @@ public class ReflectionManager { public static Object getWorldServer(World w) { try { - return getCraftMethod("CraftWorld", "getHandle").invoke(w); - } - catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - - return null; - } - - public static Object getPlayerInteractManager(World w) { - Object worldServer = getWorldServer(w); - - try { - return getNmsConstructor("PlayerInteractManager", getNmsClass("World")).newInstance(worldServer); - } - catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { + return getNmsWorld.invoke(w); + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } @@ -1567,12 +1555,8 @@ public class ReflectionManager { public static ItemMeta getDeserializedItemMeta(Map meta) { try { - Method method = getCraftMethod(getCraftClass("inventory.CraftMetaItem$SerializableMeta"), "deserialize", - Map.class); - - return (ItemMeta) method.invoke(null, meta); - } - catch (Exception e) { + return (ItemMeta) deserializedItemMeta.invoke(null, meta); + } catch (Exception e) { e.printStackTrace(); } @@ -1640,8 +1624,7 @@ public class ReflectionManager { "Watcher"); break; } - } - catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { // There is no explicit watcher for this entity. Class entityClass = disguiseType.getEntityType().getEntityClass(); @@ -1826,18 +1809,6 @@ public class ReflectionManager { Entity bukkitEntity = ReflectionManager.getBukkitEntity(nmsEntity); - int entitySize = 0; - - for (Field field : ReflectionManager.getNmsClass("Entity").getFields()) { - if (field.getType().getName().equals("EnumEntitySize")) { - Enum enumEntitySize = (Enum) field.get(nmsEntity); - - entitySize = enumEntitySize.ordinal(); - - break; - } - } - DisguiseValues disguiseValues = new DisguiseValues(disguiseType, bukkitEntity instanceof Damageable ? ((Damageable) bukkitEntity).getMaxHealth() : 0); @@ -1921,8 +1892,7 @@ public class ReflectionManager { disguiseValues.setBabyBox(ReflectionManager.getBoundingBox(bukkitEntity)); } - } - catch (SecurityException | IllegalArgumentException | IllegalAccessException | FieldAccessException ex) { + } catch (SecurityException | IllegalArgumentException | FieldAccessException ex) { DisguiseUtilities.getLogger() .severe("Uh oh! Trouble while making values for the disguise " + disguiseType.name() + "!"); DisguiseUtilities.getLogger().severe("Before reporting this error, " + @@ -1941,8 +1911,7 @@ public class ReflectionManager { field.setAccessible(true); return (Map) field.get(map); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } @@ -1955,8 +1924,7 @@ public class ReflectionManager { commandMap.setAccessible(true); return (SimpleCommandMap) commandMap.get(Bukkit.getPluginManager()); - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } diff --git a/src/main/java/me/libraryaddict/disguise/utilities/translations/LibsMsg.java b/src/main/java/me/libraryaddict/disguise/utilities/translations/LibsMsg.java index bcfee59f..0adfb14e 100644 --- a/src/main/java/me/libraryaddict/disguise/utilities/translations/LibsMsg.java +++ b/src/main/java/me/libraryaddict/disguise/utilities/translations/LibsMsg.java @@ -18,7 +18,7 @@ public enum LibsMsg { BLOWN_DISGUISE(ChatColor.RED + "Your disguise was blown!"), EXPIRED_DISGUISE(ChatColor.RED + "Your disguise has expired!"), CAN_USE_DISGS(ChatColor.DARK_GREEN + "You can use the disguises:" + ChatColor.GREEN + " %s"), - CAN_USE_DISGS_SEPERATOR(ChatColor.RED + "," + ChatColor.GREEN), + CAN_USE_DISGS_SEPERATOR(ChatColor.RED + ", " + ChatColor.GREEN), CANNOT_FIND_PLAYER(ChatColor.RED + "Cannot find the player/uuid '%s'"), CANNOT_FIND_PLAYER_NAME(ChatColor.RED + "Cannot find the player '%s'"), CANNOT_FIND_PLAYER_UUID(ChatColor.RED + "Cannot find the uuid '%s'"),