From 9b7cc9b1b3c183f31b2ddff6657f4eb20aec686f Mon Sep 17 00:00:00 2001 From: libraryaddict Date: Mon, 24 Jun 2024 22:38:09 +1200 Subject: [PATCH] First jenkins dev build for packetevents I'll probably do the actual changelog in the release only, tiring --- README.md | 4 +- minimessage/pom.xml | 89 ++ nms/pom.xml | 10 + nms/v1_17_R1/pom.xml | 16 - .../reflection/v1_17/ReflectionManager.java | 255 +--- nms/v1_18_R1/pom.xml | 16 - .../reflection/v1_18_1/ReflectionManager.java | 253 +--- nms/v1_18_R2/pom.xml | 16 - .../reflection/v1_18_2/ReflectionManager.java | 256 ++-- nms/v1_19_R1/pom.xml | 16 - .../v1_19_R1/ReflectionManager.java | 357 +---- nms/v1_19_R2/pom.xml | 16 - .../v1_19_R2/ReflectionManager.java | 339 ++--- nms/v1_19_R3/pom.xml | 16 - .../v1_19_R3/ReflectionManager.java | 341 ++--- nms/v1_20_R1/pom.xml | 16 - .../v1_20_R1/ReflectionManager.java | 361 ++--- nms/v1_20_R2/pom.xml | 16 - .../v1_20_R2/ReflectionManager.java | 386 ++--- nms/v1_20_R3/pom.xml | 16 - .../v1_20_R3/ReflectionManager.java | 391 ++--- nms/v1_20_R4/pom.xml | 113 ++ .../v1_20_R4/ReflectionManager.java | 484 +++++++ plugin/pom.xml | 77 +- .../libraryaddict/disguise/DisguiseAPI.java | 19 +- .../disguise/DisguiseConfig.java | 158 +- .../libraryaddict/disguise/LibsDisguises.java | 447 +++--- .../commands/DisguiseBaseCommand.java | 32 +- .../commands/LibsDisguisesCommand.java | 6 +- .../disguise/DisguiseRadiusCommand.java | 4 +- .../commands/libsdisguises/LDCommand.java | 4 + .../libsdisguises/LDDebugDisguiseLoop.java | 125 ++ .../commands/libsdisguises/LDJson.java | 26 +- .../commands/libsdisguises/LDScoreboard.java | 49 - ...ocolLib.java => LDUpdatePacketEvents.java} | 33 +- .../commands/libsdisguises/LDUploadLogs.java | 64 +- .../modify/DisguiseModifyRadiusCommand.java | 2 +- .../commands/utils/CopyDisguiseCommand.java | 67 +- .../commands/utils/DisguiseHelpCommand.java | 22 +- .../utils/DisguiseViewSelfCommand.java | 19 +- .../commands/utils/GrabHeadCommand.java | 25 +- .../commands/utils/GrabSkinCommand.java | 12 +- .../commands/utils/SaveDisguiseCommand.java | 4 +- .../disguise/disguisetypes/Disguise.java | 77 +- .../disguisetypes/DisguiseRunnable.java | 158 +- .../disguise/disguisetypes/DisguiseType.java | 227 +-- .../disguise/disguisetypes/EntityPose.java | 22 - .../disguise/disguisetypes/FlagWatcher.java | 167 +-- .../disguise/disguisetypes/LibsEquipment.java | 5 + .../disguise/disguisetypes/MetaIndex.java | 317 ++-- .../disguisetypes/PlayerDisguise.java | 139 +- .../disguise/disguisetypes/RabbitType.java | 46 +- .../disguisetypes/TargetedDisguise.java | 12 +- .../disguise/disguisetypes/VillagerData.java | 30 - .../watchers/AbstractHorseWatcher.java | 8 + .../watchers/AgeableWatcher.java | 2 + .../disguisetypes/watchers/AllayWatcher.java | 5 +- .../watchers/AreaEffectCloudWatcher.java | 46 +- .../watchers/ArmorStandWatcher.java | 22 +- .../watchers/AxolotlWatcher.java | 7 +- .../disguisetypes/watchers/BatWatcher.java | 2 + .../watchers/BlockDisplayWatcher.java | 24 +- .../disguisetypes/watchers/BoatWatcher.java | 49 +- .../disguisetypes/watchers/CamelWatcher.java | 2 + .../disguisetypes/watchers/CatWatcher.java | 25 +- .../watchers/ChestedHorseWatcher.java | 2 + .../watchers/CreeperWatcher.java | 3 + .../watchers/DisplayWatcher.java | 55 +- .../watchers/DroppedItemWatcher.java | 2 + .../watchers/EnderCrystalWatcher.java | 8 +- .../watchers/EndermanWatcher.java | 47 +- .../watchers/FallingBlockWatcher.java | 64 +- .../watchers/FireworkWatcher.java | 7 +- .../disguisetypes/watchers/FoxWatcher.java | 4 +- .../disguisetypes/watchers/HorseWatcher.java | 12 +- .../watchers/ItemDisplayWatcher.java | 4 +- .../disguisetypes/watchers/LivingWatcher.java | 66 +- .../disguisetypes/watchers/LlamaWatcher.java | 4 +- .../watchers/MinecartWatcher.java | 15 + .../disguisetypes/watchers/OcelotWatcher.java | 4 +- .../disguisetypes/watchers/PandaWatcher.java | 28 +- .../disguisetypes/watchers/ParrotWatcher.java | 4 +- .../disguisetypes/watchers/PlayerWatcher.java | 70 +- .../disguisetypes/watchers/RabbitWatcher.java | 11 +- .../disguisetypes/watchers/SheepWatcher.java | 8 +- .../watchers/ShulkerWatcher.java | 17 +- .../watchers/SnifferWatcher.java | 5 +- .../disguisetypes/watchers/TNTWatcher.java | 20 +- .../watchers/TextDisplayWatcher.java | 10 +- .../watchers/VillagerWatcher.java | 19 +- .../disguisetypes/watchers/WitherWatcher.java | 2 +- .../disguisetypes/watchers/WolfWatcher.java | 6 +- .../watchers/ZombieVillagerWatcher.java | 44 +- .../disguise/utilities/DisguiseUtilities.java | 1284 +++++++++-------- .../disguise/utilities/LibsPremium.java | 7 +- .../disguise/utilities/SkinUtils.java | 20 +- .../{json => gson}/SerializerBlockData.java | 2 +- .../gson/SerializerChatComponent.java | 32 + .../{json => gson}/SerializerItemStack.java | 2 +- .../{json => gson}/SerializerMetaIndex.java | 2 +- .../utilities/gson/SerializerParticle.java | 19 + .../utilities/gson/SerializerUserProfile.java | 60 + .../gson/SerializerWrappedBlockData.java | 48 + .../json/SerializerChatComponent.java | 31 - .../utilities/json/SerializerDisguise.java | 56 - .../utilities/json/SerializerFlagWatcher.java | 149 -- .../utilities/json/SerializerGameProfile.java | 37 - .../utilities/json/SerializerParticle.java | 19 - .../json/SerializerWrappedBlockData.java | 34 - .../utilities/listeners/DisguiseListener.java | 122 +- .../listeners/PlayerSkinHandler.java | 116 +- .../utilities/mineskin/MineSkinAPI.java | 13 +- .../utilities/modded/ModdedEntity.java | 2 + .../utilities/modded/ModdedManager.java | 113 +- .../utilities/packets/IPacketHandler.java | 14 +- .../utilities/packets/LibsPackets.java | 70 +- .../utilities/packets/PacketsHandler.java | 58 +- .../utilities/packets/PacketsManager.java | 199 +-- ...ava => PacketHandlerAnimationCollect.java} | 12 +- .../PacketHandlerAttachEntity.java | 17 +- .../PacketHandlerAttributes.java | 76 +- .../packethandlers/PacketHandlerCollect.java | 26 - .../PacketHandlerEntityStatus.java | 15 +- .../PacketHandlerEquipment.java | 225 +-- ...tation.java => PacketHandlerHeadLook.java} | 81 +- .../packethandlers/PacketHandlerMetadata.java | 25 +- .../packethandlers/PacketHandlerMovement.java | 298 ++-- .../packethandlers/PacketHandlerSpawn.java | 558 +++---- .../packethandlers/PacketHandlerVelocity.java | 16 +- .../PacketListenerClientCustomPayload.java | 42 +- .../PacketListenerClientInteract.java | 70 +- .../PacketListenerEntityDestroy.java | 49 +- .../PacketListenerInventory.java | 192 ++- .../packetlisteners/PacketListenerMain.java | 60 +- .../PacketListenerModdedClient.java | 100 +- .../PacketListenerScoreboardTeam.java | 57 +- .../packetlisteners/PacketListenerSounds.java | 166 ++- .../PacketListenerTabList.java | 59 +- .../PacketListenerViewSelfDisguise.java | 175 ++- .../disguise/utilities/params/ParamInfo.java | 2 +- .../utilities/params/ParamInfoManager.java | 21 +- .../utilities/params/ParamInfoTypes.java | 84 +- .../params/types/base/ParamInfoByte.java | 27 + .../types/custom/ParamInfoBlockData.java | 111 -- .../types/custom/ParamInfoBlockPosition.java | 6 +- .../types/custom/ParamInfoBoatType.java | 57 + .../params/types/custom/ParamInfoColor.java | 24 +- .../types/custom/ParamInfoComponent.java | 29 + .../custom/ParamInfoDisplayBrightness.java | 36 + .../types/custom/ParamInfoGameProfile.java | 27 - .../types/custom/ParamInfoItemBlock.java | 83 -- .../types/custom/ParamInfoItemStack.java | 137 +- .../types/custom/ParamInfoParticle.java | 515 +++++-- .../types/custom/ParamInfoTreeSpecies.java | 46 + .../types/custom/ParamInfoUserProfile.java | 26 + .../custom/ParamInfoWrappedBlockData.java | 447 ++++++ .../utilities/parser/AutoGeneratedValue.java | 19 + .../parser/DisguiseParseException.java | 6 +- .../utilities/parser/DisguiseParser.java | 299 +++- .../utilities/parser/DisguisePerm.java | 4 +- .../utilities/parser/WatcherMethod.java | 13 +- .../BlockDisplayDisguiseParam.java | 35 - .../constructors/BlockStateDisguiseParam.java | 41 + .../constructors/ExtraDisguiseParam.java | 3 +- .../FallingBlockDisguiseParamNew.java | 40 - .../FallingBlockDisguiseParamOld.java | 36 - .../constructors/PlayerDisguiseParam.java | 2 +- .../parser/constructors/TextDisplayParam.java | 2 +- .../WrappedBlockDisguiseParam.java | 31 + .../reflection/ItemStackSerializer.java | 241 ++++ .../reflection/LibsProfileLookup.java | 5 +- .../reflection/LibsProfileLookupCaller.java | 6 +- .../utilities/reflection/NmsVersion.java | 1 + .../reflection/ReflectionManager.java | 1226 +++++++--------- .../utilities/reflection/WatcherInfo.java | 33 +- .../utilities/reflection/WatcherValue.java | 75 +- .../annotations/MethodDescription.java | 15 + .../annotations/MethodHiddenFor.java | 14 + .../annotations/MethodMappedAs.java | 34 + .../utilities/sounds/DisguiseSoundEnums.java | 14 +- .../disguise/utilities/sounds/SoundGroup.java | 39 +- .../utilities/translations/LibsMsg.java | 182 ++- .../translations/TranslateFiller.java | 2 +- .../utilities/translations/TranslateType.java | 67 +- .../utilities/updates/BaseJenkins.java | 166 +++ .../utilities/updates/DisguiseUpdate.java | 3 + .../disguise/utilities/updates/LDGithub.java | 119 +- .../disguise/utilities/updates/LDJenkins.java | 110 +- .../updates/PacketEventsUpdater.java | 312 ++++ .../utilities/updates/UpdateChecker.java | 14 +- .../utilities/watchers/CompileMethods.java | 51 +- .../utilities/watchers/DisguiseMethods.java | 84 +- .../src/main/resources/configs/features.yml | 6 + plugin/src/main/resources/configs/sanity.yml | 6 +- plugin/src/main/resources/plugin.yml | 4 +- .../disguisetypes/DisguiseCloneTest.java | 2 +- .../disguise/utilities/DisguiseTypesTest.java | 7 +- .../utilities/DisguiseUtilitiesTest.java | 30 + .../params/DisguiseParamBlockStateTest.java | 157 ++ .../DisguiseParamDisplayBrightnessTest.java | 53 + .../params/DisguiseParamParticleTest.java | 374 +++++ .../params/DisguiseParamUserProfileTest.java | 66 + pom.xml | 61 +- shared/pom.xml | 6 +- .../reflection/ReflectionManagerAbstract.java | 109 +- 205 files changed, 9642 insertions(+), 8000 deletions(-) create mode 100644 minimessage/pom.xml create mode 100644 nms/v1_20_R4/pom.xml create mode 100644 nms/v1_20_R4/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R4/ReflectionManager.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDDebugDisguiseLoop.java rename plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/{LDUpdateProtocolLib.java => LDUpdatePacketEvents.java} (61%) delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/EntityPose.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/VillagerData.java rename plugin/src/main/java/me/libraryaddict/disguise/utilities/{json => gson}/SerializerBlockData.java (94%) create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerChatComponent.java rename plugin/src/main/java/me/libraryaddict/disguise/utilities/{json => gson}/SerializerItemStack.java (97%) rename plugin/src/main/java/me/libraryaddict/disguise/utilities/{json => gson}/SerializerMetaIndex.java (96%) create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerParticle.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerUserProfile.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerWrappedBlockData.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerChatComponent.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerDisguise.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerFlagWatcher.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerGameProfile.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerParticle.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerWrappedBlockData.java rename plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/{PacketHandlerAnimation.java => PacketHandlerAnimationCollect.java} (54%) delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerCollect.java rename plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/{PacketHandlerHeadRotation.java => PacketHandlerHeadLook.java} (56%) create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/base/ParamInfoByte.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoBlockData.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoBoatType.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoComponent.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoDisplayBrightness.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoGameProfile.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoItemBlock.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoTreeSpecies.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoUserProfile.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/params/types/custom/ParamInfoWrappedBlockData.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/AutoGeneratedValue.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/constructors/BlockDisplayDisguiseParam.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/constructors/BlockStateDisguiseParam.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/constructors/FallingBlockDisguiseParamNew.java delete mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/constructors/FallingBlockDisguiseParamOld.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/parser/constructors/WrappedBlockDisguiseParam.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/reflection/ItemStackSerializer.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/reflection/annotations/MethodDescription.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/reflection/annotations/MethodHiddenFor.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/reflection/annotations/MethodMappedAs.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/updates/BaseJenkins.java create mode 100644 plugin/src/main/java/me/libraryaddict/disguise/utilities/updates/PacketEventsUpdater.java create mode 100644 plugin/src/test/java/me/libraryaddict/disguise/utilities/parser/params/DisguiseParamBlockStateTest.java create mode 100644 plugin/src/test/java/me/libraryaddict/disguise/utilities/parser/params/DisguiseParamDisplayBrightnessTest.java create mode 100644 plugin/src/test/java/me/libraryaddict/disguise/utilities/parser/params/DisguiseParamParticleTest.java create mode 100644 plugin/src/test/java/me/libraryaddict/disguise/utilities/parser/params/DisguiseParamUserProfileTest.java diff --git a/README.md b/README.md index 7742ad15..69ebc384 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ There are a few features which you need to pay for, but none of it is needed to Spigot page: Link Jenkins Downloads: Link -NOTE: These versions will NOT work with older versions of Minecraft. There is no support for older versions of this plugin. +NOTE: These versions will NOT work with older versions of Minecraft than 1.12, there is no support for older versions of this plugin. When posting an issue:
Please make sure you
@@ -21,7 +21,7 @@ Please make sure you
2) Post the exact steps you used in order to reproduce the issue.
3) Give as much information as possible as to what the issue is and why it occurred so that we can fix it.
-Verify that there were no error messages while Lib's Disguises was loading, that you're using the appropiate version of ProtocolLib. +Verify that there were no error messages while Lib's Disguises was loading, that you're using the appropiate version of PacketEvents. If you're using the development builds of Lib's Disguises, make sure you are up to date before reporting a bug. Important Note diff --git a/minimessage/pom.xml b/minimessage/pom.xml new file mode 100644 index 00000000..0fabc30b --- /dev/null +++ b/minimessage/pom.xml @@ -0,0 +1,89 @@ + + + + parent + LibsDisguises + 1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + minimessage + 1.0-SNAPSHOT + + + 1.8 + 1.8 + UTF-8 + + + + + io.papermc.paper + paper-api + ${paper-api.version} + provided + true + + + net.kyori + adventure-api + ${adventure-minimessage.version} + compile + true + + + net.kyori + adventure-text-minimessage + ${adventure-minimessage.version} + compile + true + + + net.kyori + adventure-text-serializer-json + ${adventure-text.version} + compile + true + + + + + + + maven-surefire-plugin + 3.1.2 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + + + + + net.kyori:* + + + + + net.kyori + libsdisg.shaded.net.kyori + + + + + + + + \ No newline at end of file diff --git a/nms/pom.xml b/nms/pom.xml index cca0f5a2..16dc38d1 100644 --- a/nms/pom.xml +++ b/nms/pom.xml @@ -12,6 +12,15 @@ ../pom.xml + + + LibsDisguises + shared + 1.0-SNAPSHOT + true + + + v1_17_R1 v1_18_R1 @@ -22,6 +31,7 @@ v1_20_R1 v1_20_R2 v1_20_R3 + v1_20_R4 diff --git a/nms/v1_17_R1/pom.xml b/nms/v1_17_R1/pom.xml index 685017b7..f137442c 100644 --- a/nms/v1_17_R1/pom.xml +++ b/nms/v1_17_R1/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - diff --git a/nms/v1_17_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_17/ReflectionManager.java b/nms/v1_17_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_17/ReflectionManager.java index 98877ff2..e36570c9 100644 --- a/nms/v1_17_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_17/ReflectionManager.java +++ b/nms/v1_17_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_17/ReflectionManager.java @@ -1,27 +1,15 @@ package me.libraryaddict.disguise.utilities.reflection.v1_17; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -32,21 +20,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.GameType; +import net.minecraft.world.entity.decoration.Motive; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -68,19 +48,13 @@ import org.bukkit.craftbukkit.v1_17_R1.util.CraftNamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -98,15 +72,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("b"); @@ -124,20 +101,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); }/* else if (entityType == net.minecraft.world.entity.EntityType.ENDER_PEARL) { entity = new ThrownEnderpearl(world, (net.minecraft.world.entity.LivingEntity) createEntityInstance("cow")); } else if (entityType == net.minecraft.world.entity.EntityType.FISHING_BOBBER) { @@ -155,55 +134,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public SoundEvent getCraftSound(Sound sound) { - return CraftSound.getSoundEffect(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkProvider(); @@ -220,56 +191,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return Registry.MOTIVE.getKey(CraftArt.BukkitToNotch(art)).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - ClientboundPlayerInfoPacket.PlayerUpdate entry = - new ClientboundPlayerInfoPacket.PlayerUpdate((GameProfile) gameProfile.getHandle(), 0, GameType.SURVIVAL, - new TextComponent(displayName)); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - - modifier.write(0, ClientboundPlayerInfoPacket.Action.valueOf(actions[0].name())); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -287,11 +236,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -299,120 +250,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return Registry.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0); @@ -421,45 +285,50 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return Registry.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return Registry.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_17_R1.inventory.CraftMetaItem$SerializableMeta"); @@ -473,4 +342,38 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + + @SneakyThrows + @Override + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + List> dataItems = watcher.getAll(); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + + SynchedEntityData.pack(dataItems, new FriendlyByteBuf(buf)); + + return buf; + } + + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = Registry.MOTIVE; + + Motive ref = registry.byId(paintingId); + + return CraftArt.NotchToBukkit(ref); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = Registry.MOTIVE; + + return registry.getId(CraftArt.BukkitToNotch(type)); + } } diff --git a/nms/v1_18_R1/pom.xml b/nms/v1_18_R1/pom.xml index 9f26ff7b..63e927ba 100644 --- a/nms/v1_18_R1/pom.xml +++ b/nms/v1_18_R1/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - com.mojang diff --git a/nms/v1_18_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_1/ReflectionManager.java b/nms/v1_18_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_1/ReflectionManager.java index b57ac9c3..7582aeae 100644 --- a/nms/v1_18_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_1/ReflectionManager.java +++ b/nms/v1_18_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_1/ReflectionManager.java @@ -1,28 +1,16 @@ package me.libraryaddict.disguise.utilities.reflection.v1_18_1; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -33,20 +21,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.GameType; +import net.minecraft.world.entity.decoration.Motive; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -68,19 +49,14 @@ import org.bukkit.craftbukkit.v1_18_R1.util.CraftNamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -98,15 +74,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("b"); @@ -124,20 +103,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); }/* else if (entityType == net.minecraft.world.entity.EntityType.ENDER_PEARL) { entity = new ThrownEnderpearl(world, (net.minecraft.world.entity.LivingEntity) createEntityInstance("cow")); } else if (entityType == net.minecraft.world.entity.EntityType.FISHING_BOBBER) { @@ -155,55 +136,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public SoundEvent getCraftSound(Sound sound) { - return CraftSound.getSoundEffect(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -220,56 +193,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return Registry.MOTIVE.getKey(CraftArt.BukkitToNotch(art)).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - ClientboundPlayerInfoPacket.PlayerUpdate entry = - new ClientboundPlayerInfoPacket.PlayerUpdate((GameProfile) gameProfile.getHandle(), 0, GameType.SURVIVAL, - new TextComponent(displayName)); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - - modifier.write(0, ClientboundPlayerInfoPacket.Action.valueOf(actions[0].name())); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -287,11 +238,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -299,120 +252,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return Registry.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0); @@ -421,45 +287,50 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return Registry.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return Registry.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_18_R1.inventory.CraftMetaItem$SerializableMeta"); @@ -473,4 +344,38 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + + @SneakyThrows + @Override + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + List> dataItems = watcher.getAll(); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + + SynchedEntityData.pack(dataItems, new FriendlyByteBuf(buf)); + + return buf; + } + + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = Registry.MOTIVE; + + Motive ref = registry.byId(paintingId); + + return CraftArt.NotchToBukkit(ref); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = Registry.MOTIVE; + + return registry.getId(CraftArt.BukkitToNotch(type)); + } } diff --git a/nms/v1_18_R2/pom.xml b/nms/v1_18_R2/pom.xml index 39599950..a4629904 100644 --- a/nms/v1_18_R2/pom.xml +++ b/nms/v1_18_R2/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - com.mojang diff --git a/nms/v1_18_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_2/ReflectionManager.java b/nms/v1_18_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_2/ReflectionManager.java index e26246dd..3dd7093c 100644 --- a/nms/v1_18_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_2/ReflectionManager.java +++ b/nms/v1_18_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_18_2/ReflectionManager.java @@ -1,28 +1,17 @@ package me.libraryaddict.disguise.utilities.reflection.v1_18_2; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -33,20 +22,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.GameType; +import net.minecraft.world.entity.decoration.Motive; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -68,19 +50,14 @@ import org.bukkit.craftbukkit.v1_18_R2.util.CraftNamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -88,6 +65,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; public class ReflectionManager implements ReflectionManagerAbstract { + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -98,15 +76,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("c"); @@ -124,20 +105,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); }/* else if (entityType == net.minecraft.world.entity.EntityType.ENDER_PEARL) { entity = new ThrownEnderpearl(world, (net.minecraft.world.entity.LivingEntity) createEntityInstance("cow")); } else if (entityType == net.minecraft.world.entity.EntityType.FISHING_BOBBER) { @@ -155,55 +138,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public SoundEvent getCraftSound(Sound sound) { - return CraftSound.getSoundEffect(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -220,56 +195,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return Registry.MOTIVE.getKey(CraftArt.BukkitToNotch(art)).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - ClientboundPlayerInfoPacket.PlayerUpdate entry = - new ClientboundPlayerInfoPacket.PlayerUpdate((GameProfile) gameProfile.getHandle(), 0, GameType.SURVIVAL, - new TextComponent(displayName)); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - - modifier.write(0, ClientboundPlayerInfoPacket.Action.valueOf(actions[0].name())); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -287,11 +240,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -299,120 +254,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return Registry.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0); @@ -421,45 +289,50 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return Registry.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return Registry.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_18_R2.inventory.CraftMetaItem$SerializableMeta"); @@ -473,4 +346,39 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + + @SneakyThrows + @Override + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + List> dataItems = watcher.getAll(); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + + SynchedEntityData.pack(dataItems, new FriendlyByteBuf(buf)); + + return buf; + } + + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + + Registry registry = Registry.MOTIVE; + + Holder ref = registry.getHolder(paintingId).get(); + + return CraftArt.NotchToBukkit(ref.value()); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = Registry.MOTIVE; + + return registry.getId(CraftArt.BukkitToNotch(type)); + } } diff --git a/nms/v1_19_R1/pom.xml b/nms/v1_19_R1/pom.xml index b4fa2d71..3ba0d123 100644 --- a/nms/v1_19_R1/pom.xml +++ b/nms/v1_19_R1/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_19_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R1/ReflectionManager.java b/nms/v1_19_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R1/ReflectionManager.java index 689eee09..c28549bf 100644 --- a/nms/v1_19_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R1/ReflectionManager.java +++ b/nms/v1_19_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R1/ReflectionManager.java @@ -1,30 +1,18 @@ package me.libraryaddict.disguise.utilities.reflection.v1_19_R1; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.level.ChunkMap; @@ -34,24 +22,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.animal.CatVariant; -import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.decoration.PaintingVariants; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -70,24 +47,17 @@ import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_19_R1.util.CraftMagicNumbers; import org.bukkit.craftbukkit.v1_19_R1.util.CraftNamespacedKey; -import org.bukkit.entity.Cat; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; -import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -105,15 +75,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("c"); @@ -131,20 +104,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle(), null); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile, null); }/* else if (entityType == net.minecraft.world.entity.EntityType.ENDER_PEARL) { entity = new ThrownEnderpearl(world, (net.minecraft.world.entity.LivingEntity) createEntityInstance("cow")); } else if (entityType == net.minecraft.world.entity.EntityType.FISHING_BOBBER) { @@ -162,55 +137,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public SoundEvent getCraftSound(Sound sound) { - return CraftSound.getSoundEffect(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -227,56 +194,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return Registry.PAINTING_VARIANT.getKey(CraftArt.BukkitToNotch(art).value()).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - ClientboundPlayerInfoPacket.PlayerUpdate entry = - new ClientboundPlayerInfoPacket.PlayerUpdate((GameProfile) gameProfile.getHandle(), 0, GameType.SURVIVAL, - Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - - modifier.write(0, ClientboundPlayerInfoPacket.Action.valueOf(actions[0].name())); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -294,11 +239,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -306,120 +253,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return Registry.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return Registry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return Registry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0); @@ -428,45 +288,50 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return Registry.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return Registry.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_19_R1.inventory.CraftMetaItem$SerializableMeta"); @@ -481,129 +346,37 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + @SneakyThrows @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); - } + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + List> dataItems = watcher.getAll(); - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); - if (value instanceof Art) { - return Registry.PAINTING_VARIANT.getHolderOrThrow(getArtVariant((Art) value)); - } + SynchedEntityData.pack(dataItems, new FriendlyByteBuf(buf)); - return value; + return buf; } - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); } - private CatVariant getCatVariant(Cat.Type type) { - switch (type) { - case TABBY: - return CatVariant.TABBY; - case BLACK: - return CatVariant.BLACK; - case RED: - return CatVariant.RED; - case SIAMESE: - return CatVariant.SIAMESE; - case BRITISH_SHORTHAIR: - return CatVariant.BRITISH_SHORTHAIR; - case CALICO: - return CatVariant.CALICO; - case PERSIAN: - return CatVariant.PERSIAN; - case RAGDOLL: - return CatVariant.RAGDOLL; - case WHITE: - return CatVariant.WHITE; - case JELLIE: - return CatVariant.JELLIE; - case ALL_BLACK: - return CatVariant.ALL_BLACK; - } + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = Registry.PAINTING_VARIANT; - return null; + Holder ref = registry.getHolder(paintingId).get(); + + return CraftArt.NotchToBukkit(ref); } - private ResourceKey getArtVariant(Art art) { - switch (art) { - case KEBAB: - return PaintingVariants.KEBAB; - case AZTEC: - return PaintingVariants.AZTEC; - case ALBAN: - return PaintingVariants.ALBAN; - case AZTEC2: - return PaintingVariants.AZTEC2; - case BOMB: - return PaintingVariants.BOMB; - case PLANT: - return PaintingVariants.PLANT; - case WASTELAND: - return PaintingVariants.WASTELAND; - case POOL: - return PaintingVariants.POOL; - case COURBET: - return PaintingVariants.COURBET; - case SEA: - return PaintingVariants.SEA; - case SUNSET: - return PaintingVariants.SUNSET; - case CREEBET: - return PaintingVariants.CREEBET; - case WANDERER: - return PaintingVariants.WANDERER; - case GRAHAM: - return PaintingVariants.GRAHAM; - case MATCH: - return PaintingVariants.MATCH; - case BUST: - return PaintingVariants.BUST; - case STAGE: - return PaintingVariants.STAGE; - case VOID: - return PaintingVariants.VOID; - case SKULL_AND_ROSES: - return PaintingVariants.SKULL_AND_ROSES; - case WITHER: - return PaintingVariants.WITHER; - case FIGHTERS: - return PaintingVariants.FIGHTERS; - case POINTER: - return PaintingVariants.POINTER; - case PIGSCENE: - return PaintingVariants.PIGSCENE; - case BURNING_SKULL: - return PaintingVariants.BURNING_SKULL; - case SKELETON: - return PaintingVariants.SKELETON; - case DONKEY_KONG: - return PaintingVariants.DONKEY_KONG; - case EARTH: - return PaintingVariants.EARTH; - case WIND: - return PaintingVariants.WIND; - case WATER: - return PaintingVariants.WATER; - case FIRE: - return PaintingVariants.FIRE; - } + @Override + public int getPaintingAsInt(Art type) { + Registry registry = Registry.PAINTING_VARIANT; - return null; + return registry.getId(CraftArt.BukkitToNotch(type).value()); } } diff --git a/nms/v1_19_R2/pom.xml b/nms/v1_19_R2/pom.xml index 12aac39a..7b5055e3 100644 --- a/nms/v1_19_R2/pom.xml +++ b/nms/v1_19_R2/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_19_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R2/ReflectionManager.java b/nms/v1_19_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R2/ReflectionManager.java index 0efd82d7..8e2f9978 100644 --- a/nms/v1_19_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R2/ReflectionManager.java +++ b/nms/v1_19_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R2/ReflectionManager.java @@ -1,31 +1,18 @@ package me.libraryaddict.disguise.utilities.reflection.v1_19_R2; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -36,24 +23,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.animal.CatVariant; -import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -72,36 +48,36 @@ import org.bukkit.craftbukkit.v1_19_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R2.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_19_R2.util.CraftMagicNumbers; import org.bukkit.craftbukkit.v1_19_R2.util.CraftNamespacedKey; -import org.bukkit.entity.Cat; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; -import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +import java.lang.reflect.Modifier; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || !Int2ObjectMap.class.isAssignableFrom(f.getType())) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -112,15 +88,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("c"); @@ -138,20 +117,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); }/* else if (entityType == net.minecraft.world.entity.EntityType.ENDER_PEARL) { entity = new ThrownEnderpearl(world, (net.minecraft.world.entity.LivingEntity) createEntityInstance("cow")); } else if (entityType == net.minecraft.world.entity.EntityType.FISHING_BOBBER) { @@ -173,55 +154,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public Holder getCraftSound(Sound sound) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -238,95 +211,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getKey(CraftArt.BukkitToNotch(art).value()).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public void handleTablistPacket(PacketEvent event, Function shouldRemove) { - ClientboundPlayerInfoUpdatePacket packet = (ClientboundPlayerInfoUpdatePacket) event.getPacket().getHandle(); - - if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { - return; - } - - List canKeep = new ArrayList<>(); - - for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.entries()) { - if (shouldRemove.apply(entry.profileId())) { - continue; - } - - canKeep.add(entry); - } - - if (canKeep.size() == packet.entries().size()) { - return; - } - - if (canKeep.isEmpty()) { - event.setCancelled(true); - return; - } - - event.getPacket().getModifier().write(1, canKeep); - } - - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - if (actions[0] == EnumWrappers.PlayerInfoAction.REMOVE_PLAYER) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO_REMOVE); - packet.getModifier().write(0, Collections.singletonList(gameProfile.getUUID())); - - return packet; - } - - ClientboundPlayerInfoUpdatePacket.Entry entry = - new ClientboundPlayerInfoUpdatePacket.Entry(gameProfile.getUUID(), (GameProfile) gameProfile.getHandle(), nameVisible, 0, - GameType.SURVIVAL, Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - EnumSet enumSet = EnumSet.copyOf( - Arrays.stream(actions).map(action -> ClientboundPlayerInfoUpdatePacket.Action.valueOf(action.name())) - .collect(Collectors.toList())); - - modifier.write(0, enumSet); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -344,11 +256,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -356,124 +270,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - - public Holder createSoundEvent(String minecraftKey) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(SoundEvent.createVariableRangeEvent(createMinecraftKey(minecraftKey))); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, FeatureFlagSet.of()); @@ -482,46 +305,51 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return BuiltInRegistries.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_19_R2.inventory.CraftMetaItem$SerializableMeta"); @@ -536,41 +364,42 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + @SneakyThrows @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + Int2ObjectMap> dataItems = (Int2ObjectMap>) dataItemsField.get(watcher); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + FriendlyByteBuf serializer = new FriendlyByteBuf(buf); + + for (SynchedEntityData.DataItem dataItem : dataItems.values()) { + dataItem.value().write(serializer); } - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + serializer.writeByte(255); - if (value instanceof Art) { - return getArtVariant((Art) value); - } - - return value; + return buf; } - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); } - private CatVariant getCatVariant(Cat.Type type) { - return BuiltInRegistries.CAT_VARIANT.byId(type.ordinal()); + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.NotchToBukkit(ref); } - private Holder.Reference getArtVariant(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getHolder(art.ordinal()).get(); + @Override + public int getPaintingAsInt(Art type) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + return registry.getId(CraftArt.BukkitToNotch(type).value()); } } diff --git a/nms/v1_19_R3/pom.xml b/nms/v1_19_R3/pom.xml index 496f6754..85c3688e 100644 --- a/nms/v1_19_R3/pom.xml +++ b/nms/v1_19_R3/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_19_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R3/ReflectionManager.java b/nms/v1_19_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R3/ReflectionManager.java index 217f0532..b3808d49 100644 --- a/nms/v1_19_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R3/ReflectionManager.java +++ b/nms/v1_19_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_19_R3/ReflectionManager.java @@ -1,31 +1,18 @@ package me.libraryaddict.disguise.utilities.reflection.v1_19_R3; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -36,23 +23,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.animal.CatVariant; -import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -71,36 +48,37 @@ import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_19_R3.util.CraftMagicNumbers; import org.bukkit.craftbukkit.v1_19_R3.util.CraftNamespacedKey; -import org.bukkit.entity.Cat; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; -import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; +import java.lang.reflect.Modifier; import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || !Int2ObjectMap.class.isAssignableFrom(f.getType())) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -111,15 +89,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("d"); @@ -137,20 +118,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); } else { entity = entityType.create(world); } @@ -168,55 +151,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public Holder getCraftSound(Sound sound) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -233,95 +208,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getKey(CraftArt.BukkitToNotch(art).value()).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public void handleTablistPacket(PacketEvent event, Function shouldRemove) { - ClientboundPlayerInfoUpdatePacket packet = (ClientboundPlayerInfoUpdatePacket) event.getPacket().getHandle(); - - if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { - return; - } - - List canKeep = new ArrayList<>(); - - for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.entries()) { - if (shouldRemove.apply(entry.profileId())) { - continue; - } - - canKeep.add(entry); - } - - if (canKeep.size() == packet.entries().size()) { - return; - } - - if (canKeep.isEmpty()) { - event.setCancelled(true); - return; - } - - event.getPacket().getModifier().write(1, canKeep); - } - - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - if (actions[0] == EnumWrappers.PlayerInfoAction.REMOVE_PLAYER) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO_REMOVE); - packet.getModifier().write(0, Collections.singletonList(gameProfile.getUUID())); - - return packet; - } - - ClientboundPlayerInfoUpdatePacket.Entry entry = - new ClientboundPlayerInfoUpdatePacket.Entry(gameProfile.getUUID(), (GameProfile) gameProfile.getHandle(), nameVisible, 0, - GameType.SURVIVAL, Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - EnumSet enumSet = EnumSet.copyOf( - Arrays.stream(actions).map(action -> ClientboundPlayerInfoUpdatePacket.Action.valueOf(action.name())) - .collect(Collectors.toList())); - - modifier.write(0, enumSet); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { return 0.0f; @@ -339,11 +253,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -351,124 +267,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - - public Holder createSoundEvent(String minecraftKey) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(SoundEvent.createVariableRangeEvent(createMinecraftKey(minecraftKey))); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, FeatureFlagSet.of()); @@ -477,46 +302,51 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return BuiltInRegistries.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_19_R3.inventory.CraftMetaItem$SerializableMeta"); @@ -531,45 +361,42 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + @SneakyThrows @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + Int2ObjectMap> dataItems = (Int2ObjectMap>) dataItemsField.get(watcher); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + FriendlyByteBuf serializer = new FriendlyByteBuf(buf); + + for (SynchedEntityData.DataItem dataItem : dataItems.values()) { + dataItem.value().write(serializer); } - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + serializer.writeByte(255); - if (value instanceof Art) { - return getArtVariant((Art) value); - } - - if (value instanceof BlockData) { - return ((CraftBlockData) value).getState(); - } - - return value; + return buf; } - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); } - private CatVariant getCatVariant(Cat.Type type) { - return BuiltInRegistries.CAT_VARIANT.byId(type.ordinal()); + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.NotchToBukkit(ref); } - private Holder.Reference getArtVariant(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getHolder(art.ordinal()).get(); + @Override + public int getPaintingAsInt(Art type) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + return registry.getId(CraftArt.BukkitToNotch(type).value()); } } diff --git a/nms/v1_20_R1/pom.xml b/nms/v1_20_R1/pom.xml index ea1ae044..122b894f 100644 --- a/nms/v1_20_R1/pom.xml +++ b/nms/v1_20_R1/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_20_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R1/ReflectionManager.java b/nms/v1_20_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R1/ReflectionManager.java index e6ca47d2..b794a761 100644 --- a/nms/v1_20_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R1/ReflectionManager.java +++ b/nms/v1_20_R1/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R1/ReflectionManager.java @@ -1,31 +1,18 @@ package me.libraryaddict.disguise.utilities.reflection.v1_20_R1; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -36,23 +23,12 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; -import net.minecraft.world.entity.animal.CatVariant; -import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -71,37 +47,36 @@ import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_20_R1.util.CraftMagicNumbers; import org.bukkit.craftbukkit.v1_20_R1.util.CraftNamespacedKey; -import org.bukkit.entity.Cat; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; -import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Sniffer; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +import java.lang.reflect.Modifier; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || !Int2ObjectMap.class.isAssignableFrom(f.getType())) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -112,15 +87,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("d"); @@ -138,20 +116,22 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle()); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile); } else { entity = entityType.create(world); } @@ -169,55 +149,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return MobEffect.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public Holder getCraftSound(Sound sound) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -234,95 +206,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getKey(CraftArt.BukkitToNotch(art).value()).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public void handleTablistPacket(PacketEvent event, Function shouldRemove) { - ClientboundPlayerInfoUpdatePacket packet = (ClientboundPlayerInfoUpdatePacket) event.getPacket().getHandle(); - - if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { - return; - } - - List canKeep = new ArrayList<>(); - - for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.entries()) { - if (shouldRemove.apply(entry.profileId())) { - continue; - } - - canKeep.add(entry); - } - - if (canKeep.size() == packet.entries().size()) { - return; - } - - if (canKeep.isEmpty()) { - event.setCancelled(true); - return; - } - - event.getPacket().getModifier().write(1, canKeep); - } - - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - if (actions[0] == EnumWrappers.PlayerInfoAction.REMOVE_PLAYER) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO_REMOVE); - packet.getModifier().write(0, Collections.singletonList(gameProfile.getUUID())); - - return packet; - } - - ClientboundPlayerInfoUpdatePacket.Entry entry = - new ClientboundPlayerInfoUpdatePacket.Entry(gameProfile.getUUID(), (GameProfile) gameProfile.getHandle(), nameVisible, 0, - GameType.SURVIVAL, Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - EnumSet enumSet = EnumSet.copyOf( - Arrays.stream(actions).map(action -> ClientboundPlayerInfoUpdatePacket.Action.valueOf(action.name())) - .collect(Collectors.toList())); - - modifier.write(0, enumSet); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { // Default is 1.0F on EntityLiving if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { @@ -341,11 +252,13 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { Agent agent = Agent.MINECRAFT; getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, agent, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -353,124 +266,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.getSoundEffect(sound).getLocation().toString(); // TODO } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - - public Holder createSoundEvent(String minecraftKey) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(SoundEvent.createVariableRangeEvent(createMinecraftKey(minecraftKey))); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, FeatureFlagSet.of()); @@ -479,46 +301,51 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return BuiltInRegistries.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_20_R1.inventory.CraftMetaItem$SerializableMeta"); @@ -533,58 +360,42 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + @SneakyThrows @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + Int2ObjectMap> dataItems = (Int2ObjectMap>) dataItemsField.get(watcher); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + FriendlyByteBuf serializer = new FriendlyByteBuf(buf); + + for (SynchedEntityData.DataItem dataItem : dataItems.values()) { + dataItem.value().write(serializer); } - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + serializer.writeByte(255); - if (value instanceof Art) { - return getArtVariant((Art) value); - } - - if (value instanceof BlockData) { - return ((CraftBlockData) value).getState(); - } - - if (value instanceof Sniffer.State) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.values()[((Sniffer.State) value).ordinal()]; - } - - return value; - } - - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; - } - - private CatVariant getCatVariant(Cat.Type type) { - return BuiltInRegistries.CAT_VARIANT.byId(type.ordinal()); - } - - private Holder.Reference getArtVariant(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getHolder(art.ordinal()).get(); + return buf; } @Override - public Class getNmsClass(Class cl) { - if (Sniffer.State.class.isAssignableFrom(cl)) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.class; - } + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } - return cl; + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.NotchToBukkit(ref); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + return registry.getId(CraftArt.BukkitToNotch(type).value()); } } diff --git a/nms/v1_20_R2/pom.xml b/nms/v1_20_R2/pom.xml index f9a1b62f..50e1b754 100644 --- a/nms/v1_20_R2/pom.xml +++ b/nms/v1_20_R2/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_20_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R2/ReflectionManager.java b/nms/v1_20_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R2/ReflectionManager.java index 46e28bf4..56c55f14 100644 --- a/nms/v1_20_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R2/ReflectionManager.java +++ b/nms/v1_20_R2/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R2/ReflectionManager.java @@ -1,30 +1,16 @@ package me.libraryaddict.disguise.utilities.reflection.v1_20_R2; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -36,25 +22,16 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.animal.CatVariant; import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.entity.player.ChatVisiblity; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -68,7 +45,9 @@ import org.bukkit.craftbukkit.v1_20_R2.CraftServer; import org.bukkit.craftbukkit.v1_20_R2.CraftSound; import org.bukkit.craftbukkit.v1_20_R2.CraftWorld; import org.bukkit.craftbukkit.v1_20_R2.block.data.CraftBlockData; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftCat; import org.bukkit.craftbukkit.v1_20_R2.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftFrog; import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_20_R2.util.CraftMagicNumbers; @@ -78,32 +57,33 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Sniffer; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (!f.getType().isArray()) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -114,15 +94,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("d"); @@ -140,22 +123,24 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (optional.isPresent()) { net.minecraft.world.entity.EntityType entityType = optional.get(); ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); ClientInformation information = new ClientInformation("english", 10, ChatVisiblity.FULL, true, 0, HumanoidArm.RIGHT, true, true); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle(), information); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile, information); } else { entity = entityType.create(world); } @@ -173,55 +158,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } - public MobEffect getMobEffectList(int id) { - return BuiltInRegistries.MOB_EFFECT.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public Holder getCraftSound(Sound sound) { - return CraftSound.bukkitToMinecraftHolder(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -238,95 +215,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getKey(CraftArt.bukkitToMinecraft(art)).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public void handleTablistPacket(PacketEvent event, Function shouldRemove) { - ClientboundPlayerInfoUpdatePacket packet = (ClientboundPlayerInfoUpdatePacket) event.getPacket().getHandle(); - - if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { - return; - } - - List canKeep = new ArrayList<>(); - - for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.entries()) { - if (shouldRemove.apply(entry.profileId())) { - continue; - } - - canKeep.add(entry); - } - - if (canKeep.size() == packet.entries().size()) { - return; - } - - if (canKeep.isEmpty()) { - event.setCancelled(true); - return; - } - - event.getPacket().getModifier().write(1, canKeep); - } - - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - if (actions[0] == EnumWrappers.PlayerInfoAction.REMOVE_PLAYER) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO_REMOVE); - packet.getModifier().write(0, Collections.singletonList(gameProfile.getUUID())); - - return packet; - } - - ClientboundPlayerInfoUpdatePacket.Entry entry = - new ClientboundPlayerInfoUpdatePacket.Entry(gameProfile.getUUID(), (GameProfile) gameProfile.getHandle(), nameVisible, 0, - GameType.SURVIVAL, Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - EnumSet enumSet = EnumSet.copyOf( - Arrays.stream(actions).map(action -> ClientboundPlayerInfoUpdatePacket.Action.valueOf(action.name())) - .collect(Collectors.toList())); - - modifier.write(0, enumSet); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { // Default is 1.0F on EntityLiving if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { @@ -345,10 +261,12 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -356,124 +274,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.bukkitToMinecraft(sound).getLocation().toString(); } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - - public Holder createSoundEvent(String minecraftKey) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(SoundEvent.createVariableRangeEvent(createMinecraftKey(minecraftKey))); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, FeatureFlagSet.of()); @@ -482,46 +309,51 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return BuiltInRegistries.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_20_R2.inventory.CraftMetaItem$SerializableMeta"); @@ -537,57 +369,73 @@ public class ReflectionManager implements ReflectionManagerAbstract { } @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); + public ByteBuf getDataWatcherValues(Entity entity) { + net.minecraft.world.entity.Entity ent = (net.minecraft.world.entity.Entity) getNmsEntity(entity); + List> dataList = ent.getEntityData().getNonDefaultValues(); + + if (dataList == null) { + return null; } - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + FriendlyByteBuf serializer = new FriendlyByteBuf(buf); - if (value instanceof Art) { - return getArtVariant((Art) value); - } + dataList.forEach(d -> d.write(serializer)); + serializer.writeByte(255); - if (value instanceof BlockData) { - return ((CraftBlockData) value).getState(); - } - - if (value instanceof Sniffer.State) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.values()[((Sniffer.State) value).ordinal()]; - } - - return value; - } - - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; - } - - private CatVariant getCatVariant(Cat.Type type) { - return BuiltInRegistries.CAT_VARIANT.byId(type.ordinal()); - } - - private Holder.Reference getArtVariant(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getHolder(art.ordinal()).get(); + return buf; } @Override - public Class getNmsClass(Class cl) { - if (Sniffer.State.class.isAssignableFrom(cl)) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.class; - } + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } - return cl; + @Override + public Cat.Type getCatTypeFromInt(int catType) { + Registry registry = BuiltInRegistries.CAT_VARIANT; + + Holder.Reference ref = registry.getHolder(catType).get(); + + return CraftCat.CraftType.minecraftToBukkit(ref.value()); + } + + @Override + public int getCatVariantAsInt(Cat.Type type) { + Registry registry = BuiltInRegistries.CAT_VARIANT; + + return registry.getId(CraftCat.CraftType.bukkitToMinecraft(type)); + } + + @Override + public Frog.Variant getFrogVariantFromInt(int frogType) { + Registry registry = BuiltInRegistries.FROG_VARIANT; + + Holder.Reference ref = registry.getHolder(frogType).get(); + + return CraftFrog.CraftVariant.minecraftToBukkit(ref.value()); + } + + @Override + public int getFrogVariantAsInt(Frog.Variant type) { + Registry registry = BuiltInRegistries.FROG_VARIANT; + + return registry.getId(CraftFrog.CraftVariant.bukkitToMinecraft(type)); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.minecraftHolderToBukkit(registry.getHolder(paintingId).get()); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + return registry.getId(CraftArt.bukkitToMinecraft(type)); } } diff --git a/nms/v1_20_R3/pom.xml b/nms/v1_20_R3/pom.xml index 06bd8333..5220ebcd 100644 --- a/nms/v1_20_R3/pom.xml +++ b/nms/v1_20_R3/pom.xml @@ -37,22 +37,6 @@ provided true - - org.spigotmc - spigot - true - - - LibsDisguises - shared - 1.0-SNAPSHOT - true - - - com.github.dmulloy2 - ProtocolLib - true - it.unimi.dsi diff --git a/nms/v1_20_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R3/ReflectionManager.java b/nms/v1_20_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R3/ReflectionManager.java index 5d8cecb1..16ee2143 100644 --- a/nms/v1_20_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R3/ReflectionManager.java +++ b/nms/v1_20_R3/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R3/ReflectionManager.java @@ -1,30 +1,17 @@ package me.libraryaddict.disguise.utilities.reflection.v1_20_R3; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.mojang.authlib.GameProfile; import com.mojang.authlib.ProfileLookupCallback; import com.mojang.authlib.minecraft.MinecraftSessionService; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; -import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.Vector3f; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.dedicated.DedicatedServer; @@ -36,25 +23,16 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerPlayerConnection; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.animal.CatVariant; import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraft.world.entity.npc.VillagerData; -import net.minecraft.world.entity.npc.VillagerProfession; -import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.entity.player.ChatVisiblity; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -68,7 +46,9 @@ import org.bukkit.craftbukkit.v1_20_R3.CraftServer; import org.bukkit.craftbukkit.v1_20_R3.CraftSound; import org.bukkit.craftbukkit.v1_20_R3.CraftWorld; import org.bukkit.craftbukkit.v1_20_R3.block.data.CraftBlockData; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftCat; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftFrog; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_20_R3.util.CraftMagicNumbers; @@ -78,32 +58,33 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Frog; import org.bukkit.entity.Player; -import org.bukkit.entity.Sniffer; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +import java.lang.reflect.Modifier; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || !Int2ObjectMap.class.isAssignableFrom(f.getType())) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + public boolean hasInvul(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); @@ -114,15 +95,18 @@ public class ReflectionManager implements ReflectionManagerAbstract { } } + @Override public int getIncrementedStateId(Player player) { ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container } + @Override public int getNewEntityId() { return getNewEntityId(true); } + @Override public int getNewEntityId(boolean increment) { try { Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("d"); @@ -140,13 +124,15 @@ public class ReflectionManager implements ReflectionManagerAbstract { return -1; } + @Override public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { return ((CraftPlayer) player).getHandle().connection; } + @Override public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { Optional> optional = - net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ROOT)); + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); if (!optional.isPresent()) { return null; @@ -156,10 +142,10 @@ public class ReflectionManager implements ReflectionManagerAbstract { ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); net.minecraft.world.entity.Entity entity; if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { - WrappedGameProfile gameProfile = ReflectionManagerAbstract.getGameProfile(new UUID(0, 0), "Steve"); + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); ClientInformation information = new ClientInformation("english", 10, ChatVisiblity.FULL, true, 0, HumanoidArm.RIGHT, true, true); - entity = new ServerPlayer(getMinecraftServer(), world, (GameProfile) gameProfile.getHandle(), information); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile, information); } else { entity = entityType.create(world); } @@ -174,55 +160,47 @@ public class ReflectionManager implements ReflectionManagerAbstract { return entity; } - public MobEffect getMobEffectList(int id) { - return BuiltInRegistries.MOB_EFFECT.byId(id); - } - - public MobEffectInstance createMobEffect(PotionEffect effect) { - return createMobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), - effect.hasParticles()); - } - - public MobEffectInstance createMobEffect(int id, int duration, int amplification, boolean ambient, boolean particles) { - return new MobEffectInstance(getMobEffectList(id), duration, amplification, ambient, particles); - } - + @Override public AABB getBoundingBox(Entity entity) { return ((CraftEntity) entity).getHandle().getBoundingBox(); } + @Override public double getXBoundingBox(Entity entity) { return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; } + @Override public double getYBoundingBox(Entity entity) { return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; } + @Override public double getZBoundingBox(Entity entity) { return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; } + @Override public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { return ((ServerPlayerConnection) nmsEntity).getPlayer(); } + @Override public Entity getBukkitEntity(Object nmsEntity) { return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); } + @Override public ItemStack getBukkitItem(Object nmsItem) { return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); } + @Override public ItemStack getCraftItem(ItemStack bukkitItem) { return CraftItemStack.asCraftCopy(bukkitItem); } - public Holder getCraftSound(Sound sound) { - return CraftSound.bukkitToMinecraftHolder(sound); - } - + @Override public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); ServerChunkCache chunkSource = world.getChunkSource(); @@ -239,95 +217,34 @@ public class ReflectionManager implements ReflectionManagerAbstract { return (ServerEntity) field.get(trackedEntity); } + @Override public DedicatedServer getMinecraftServer() { return ((CraftServer) Bukkit.getServer()).getServer(); } - public String getEnumArt(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getKey(CraftArt.bukkitToMinecraft(art)).getPath(); - } - - public BlockPos getBlockPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - public net.minecraft.core.Direction getEnumDirection(int direction) { - return net.minecraft.core.Direction.from2DDataValue(direction); - } - @Override - public void handleTablistPacket(PacketEvent event, Function shouldRemove) { - ClientboundPlayerInfoUpdatePacket packet = (ClientboundPlayerInfoUpdatePacket) event.getPacket().getHandle(); - - if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) { - return; - } - - List canKeep = new ArrayList<>(); - - for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.entries()) { - if (shouldRemove.apply(entry.profileId())) { - continue; - } - - canKeep.add(entry); - } - - if (canKeep.size() == packet.entries().size()) { - return; - } - - if (canKeep.isEmpty()) { - event.setCancelled(true); - return; - } - - event.getPacket().getModifier().write(1, canKeep); - } - - public PacketContainer getTabListPacket(String displayName, WrappedGameProfile gameProfile, boolean nameVisible, - EnumWrappers.PlayerInfoAction... actions) { - if (actions[0] == EnumWrappers.PlayerInfoAction.REMOVE_PLAYER) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO_REMOVE); - packet.getModifier().write(0, Collections.singletonList(gameProfile.getUUID())); - - return packet; - } - - ClientboundPlayerInfoUpdatePacket.Entry entry = - new ClientboundPlayerInfoUpdatePacket.Entry(gameProfile.getUUID(), (GameProfile) gameProfile.getHandle(), nameVisible, 0, - GameType.SURVIVAL, Component.literal(displayName), null); - - PacketContainer packet = new PacketContainer(PacketType.Play.Server.PLAYER_INFO); - StructureModifier modifier = packet.getModifier(); - EnumSet enumSet = EnumSet.copyOf( - Arrays.stream(actions).map(action -> ClientboundPlayerInfoUpdatePacket.Action.valueOf(action.name())) - .collect(Collectors.toList())); - - modifier.write(0, enumSet); - modifier.write(1, Collections.singletonList(entry)); - - return packet; - } - public Object getNmsEntity(Entity entity) { return ((CraftEntity) entity).getHandle(); } + @Override public double getPing(Player player) { return player.getPing(); } + @Override public float[] getSize(Entity entity) { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); return new float[]{dimensions.width, nmsEntity.getEyeHeight()}; } + @Override public MinecraftSessionService getMinecraftSessionService() { return getMinecraftServer().getSessionService(); } + @Override public Float getSoundModifier(Object entity) { // Default is 1.0F on EntityLiving if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { @@ -346,10 +263,12 @@ public class ReflectionManager implements ReflectionManagerAbstract { return 0f; } + @Override public void injectCallback(String playername, ProfileLookupCallback callback) { getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, callback); } + @Override public void setBoundingBox(Entity entity, double x, double y, double z) { Location loc = entity.getLocation(); ((CraftEntity) entity).getHandle().setBoundingBox( @@ -357,124 +276,33 @@ public class ReflectionManager implements ReflectionManagerAbstract { loc.getZ() + z / 2)); } - public Enum getSoundCategory(String category) { - return Arrays.stream(SoundSource.values()).filter(soundSource -> category.equalsIgnoreCase(soundSource.getName())).findAny().get(); - } - - /** - * Creates the NMS object EnumItemSlot from an EquipmentSlot. - * - * @param slot - * @return null if the equipment slot is null - */ - public Enum createEnumItemSlot(EquipmentSlot slot) { - switch (slot) { - case HAND: - return net.minecraft.world.entity.EquipmentSlot.MAINHAND; - case OFF_HAND: - return net.minecraft.world.entity.EquipmentSlot.OFFHAND; - case FEET: - return net.minecraft.world.entity.EquipmentSlot.FEET; - case LEGS: - return net.minecraft.world.entity.EquipmentSlot.LEGS; - case CHEST: - return net.minecraft.world.entity.EquipmentSlot.CHEST; - case HEAD: - return net.minecraft.world.entity.EquipmentSlot.HEAD; - default: - return null; - } - } - - public Object getSoundString(Sound sound) { + @Override + public String getSoundString(Sound sound) { return CraftSound.bukkitToMinecraft(sound).getLocation().toString(); } - public Optional convertOptional(Object val) { - if (val instanceof BlockPosition) { - BlockPosition pos = (BlockPosition) val; - return Optional.of(getBlockPosition(pos.getX(), pos.getY(), pos.getZ())); - } else if (val instanceof WrappedBlockData) { - Object obj = ((WrappedBlockData) val).getHandle(); - return Optional.of(obj); - } else if (val instanceof ItemStack) { - Object obj = getNmsItem((ItemStack) val); - return Optional.of(obj); - } else if (val instanceof WrappedChatComponent) { - Object obj = ((WrappedChatComponent) val).getHandle(); - return Optional.of(obj); - } - - return Optional.of(val); - } - - public Vector3f convertVec3(Object object) { - if (object instanceof Vector3F) { - Vector3F vector3F = (Vector3F) object; - return new Vector3f(vector3F.getX(), vector3F.getY(), vector3F.getZ()); - } else if (object instanceof EulerAngle) { - EulerAngle eulerAngle = (EulerAngle) object; - return new Vector3f((float) eulerAngle.getX(), (float) eulerAngle.getY(), (float) eulerAngle.getZ()); - } - - return null; - } - - public net.minecraft.core.Direction convertDirection(Direction direction) { - return net.minecraft.core.Direction.from3DDataValue(direction.ordinal()); - } - + @Override public Material getMaterial(String name) { return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); } + @Override public String getItemName(Material material) { return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); } - public net.minecraft.world.item.ItemStack getNmsItem(ItemStack itemStack) { - return CraftItemStack.asNMSCopy(itemStack); - } - - public VillagerData getNmsVillagerData(Villager.Type villagerType, Villager.Profession villagerProfession, int level) { - VillagerType nmsVillagerType = BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(villagerType.getKey())); - VillagerProfession nmsVillagerProfession = - BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(villagerProfession.getKey())); - - return new net.minecraft.world.entity.npc.VillagerData(nmsVillagerType, nmsVillagerProfession, level); - } - - public VillagerType getVillagerType(Villager.Type type) { - return BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())); - } - - public VillagerProfession getVillagerProfession(Villager.Profession profession) { - return BuiltInRegistries.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(profession.getKey())); - } - - public SynchedEntityData.DataItem createDataWatcherItem(WrappedDataWatcher.WrappedDataWatcherObject wrappedDataWatcherObject, - T metaItem) { - return new SynchedEntityData.DataItem<>((EntityDataAccessor) wrappedDataWatcherObject.getHandle(), metaItem); - } - - public Holder createSoundEvent(String minecraftKey) { - return BuiltInRegistries.SOUND_EVENT.wrapAsHolder(SoundEvent.createVariableRangeEvent(createMinecraftKey(minecraftKey))); - } - @Override public ResourceLocation createMinecraftKey(String name) { return new ResourceLocation(name); } - public Vec3 getVec3D(Vector vector) { - return new Vec3(vector.getX(), vector.getY(), vector.getZ()); - } - + @Override public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { return net.minecraft.world.entity.EntityType.byString( entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); } + @Override public Object registerEntityType(NamespacedKey key) { net.minecraft.world.entity.EntityType newEntity = new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, FeatureFlagSet.of()); @@ -483,46 +311,51 @@ public class ReflectionManager implements ReflectionManagerAbstract { return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about } + @Override public int getEntityTypeId(Object entityTypes) { net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; return BuiltInRegistries.ENTITY_TYPE.getId(entityType); } + @Override public int getEntityTypeId(EntityType entityType) { return getEntityTypeId(getEntityType(entityType)); } + @Override public Object getEntityType(NamespacedKey name) { return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); } - public Object getNmsEntityPose(String enumPose) { - return net.minecraft.world.entity.Pose.valueOf(enumPose); - } - + @Override public int getCombinedIdByBlockData(BlockData data) { BlockState state = ((CraftBlockData) data).getState(); return Block.getId(state); } + @Override public int getCombinedIdByItemStack(ItemStack itemStack) { Block block = CraftMagicNumbers.getBlock(itemStack.getType()); return Block.getId(block.defaultBlockState()); } + @Override public BlockData getBlockDataByCombinedId(int id) { return CraftBlockData.fromData(Block.stateById(id)); } + @Override public ItemStack getItemStackByCombinedId(int id) { return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); } + @Override public ServerLevel getWorldServer(World w) { return ((CraftWorld) w).getHandle(); } + @Override public ItemMeta getDeserializedItemMeta(Map meta) { try { Class aClass = Class.forName("org.bukkit.craftbukkit.v1_20_R3.inventory.CraftMetaItem$SerializableMeta"); @@ -537,58 +370,74 @@ public class ReflectionManager implements ReflectionManagerAbstract { return null; } + @SneakyThrows @Override - public Object convertInvalidMeta(Object value) { - if (value instanceof Frog.Variant) { - return getFrogVariant((Frog.Variant) value); + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + Int2ObjectMap> dataItems = (Int2ObjectMap>) dataItemsField.get(watcher); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + FriendlyByteBuf serializer = new FriendlyByteBuf(buf); + + for (SynchedEntityData.DataItem dataItem : dataItems.values()) { + dataItem.value().write(serializer); } - if (value instanceof Cat.Type) { - return getCatVariant((Cat.Type) value); - } + serializer.writeByte(255); - if (value instanceof Art) { - return getArtVariant((Art) value); - } - - if (value instanceof BlockData) { - return ((CraftBlockData) value).getState(); - } - - if (value instanceof Sniffer.State) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.values()[((Sniffer.State) value).ordinal()]; - } - - return value; - } - - private FrogVariant getFrogVariant(Frog.Variant variant) { - switch (variant) { - case COLD: - return FrogVariant.COLD; - case WARM: - return FrogVariant.WARM; - case TEMPERATE: - return FrogVariant.TEMPERATE; - } - - return null; - } - - private CatVariant getCatVariant(Cat.Type type) { - return BuiltInRegistries.CAT_VARIANT.byId(type.ordinal()); - } - - private Holder.Reference getArtVariant(Art art) { - return BuiltInRegistries.PAINTING_VARIANT.getHolder(art.ordinal()).get(); + return buf; } @Override - public Class getNmsClass(Class cl) { - if (Sniffer.State.class.isAssignableFrom(cl)) { - return net.minecraft.world.entity.animal.sniffer.Sniffer.State.class; - } + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } - return cl; + @Override + public Cat.Type getCatTypeFromInt(int catType) { + Registry registry = BuiltInRegistries.CAT_VARIANT; + + Holder.Reference ref = registry.getHolder(catType).get(); + + return CraftCat.CraftType.minecraftToBukkit(ref.value()); + } + + @Override + public int getCatVariantAsInt(Cat.Type type) { + Registry registry = BuiltInRegistries.CAT_VARIANT; + + return registry.getId(CraftCat.CraftType.bukkitToMinecraft(type)); + } + + @Override + public Frog.Variant getFrogVariantFromInt(int frogType) { + Registry registry = BuiltInRegistries.FROG_VARIANT; + + Holder.Reference ref = registry.getHolder(frogType).get(); + + return CraftFrog.CraftVariant.minecraftToBukkit(ref.value()); + } + + @Override + public int getFrogVariantAsInt(Frog.Variant type) { + Registry registry = BuiltInRegistries.FROG_VARIANT; + + return registry.getId(CraftFrog.CraftVariant.bukkitToMinecraft(type)); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.minecraftHolderToBukkit(registry.getHolder(paintingId).get()); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = BuiltInRegistries.PAINTING_VARIANT; + + return registry.getId(CraftArt.bukkitToMinecraft(type)); } } diff --git a/nms/v1_20_R4/pom.xml b/nms/v1_20_R4/pom.xml new file mode 100644 index 00000000..eea1fedc --- /dev/null +++ b/nms/v1_20_R4/pom.xml @@ -0,0 +1,113 @@ + + + + nms + LibsDisguises + 1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + v1_20_R4 + 1.0-SNAPSHOT + + + 1.8 + 1.8 + UTF-8 + + 1.20.6-R0.1-SNAPSHOT + + + + + org.spigotmc + spigot + ${spigot.version} + remapped-mojang + provided + true + + + org.spigotmc + spigot-api + ${spigot.version} + provided + true + + + + it.unimi.dsi + fastutil + 8.5.8 + provided + true + + + + com.mojang + authlib + 6.0.54 + provided + true + + + + com.mojang + datafixerupper + 7.0.14 + provided + true + + + + com.mojang + brigadier + 1.2.9 + compile + true + + + + + + + net.md-5 + specialsource-maven-plugin + 2.0.3 + + + package + + remap + + remap-obf + + org.spigotmc:minecraft-server:${spigot.version}:txt:maps-mojang + true + org.spigotmc:spigot:${spigot.version}:jar:remapped-mojang + remapped-mojang + true + + + + package + + remap + + remap-spigot + + target/${project.build.finalName}-remapped-mojang.jar + org.spigotmc:minecraft-server:${spigot.version}:csrg:maps-spigot + org.spigotmc:spigot:${spigot.version}:jar:remapped-obf + remapped-spigot + true + + + + + + + \ No newline at end of file diff --git a/nms/v1_20_R4/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R4/ReflectionManager.java b/nms/v1_20_R4/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R4/ReflectionManager.java new file mode 100644 index 00000000..3afd416d --- /dev/null +++ b/nms/v1_20_R4/src/main/java/me/libraryaddict/disguise/utilities/reflection/v1_20_R4/ReflectionManager.java @@ -0,0 +1,484 @@ +package me.libraryaddict.disguise.utilities.reflection.v1_20_R4; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.ProfileLookupCallback; +import com.mojang.authlib.minecraft.MinecraftSessionService; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JavaOps; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.PooledByteBufAllocator; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.SneakyThrows; +import me.libraryaddict.disguise.utilities.reflection.ReflectionManagerAbstract; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.syncher.SynchedEntityData; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.dedicated.DedicatedServer; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ClientInformation; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.server.network.ServerPlayerConnection; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.animal.CatVariant; +import net.minecraft.world.entity.animal.FrogVariant; +import net.minecraft.world.entity.animal.WolfVariant; +import net.minecraft.world.entity.decoration.PaintingVariant; +import net.minecraft.world.entity.player.ChatVisiblity; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import org.bukkit.Art; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.block.data.BlockData; +import org.bukkit.craftbukkit.v1_20_R4.CraftArt; +import org.bukkit.craftbukkit.v1_20_R4.CraftServer; +import org.bukkit.craftbukkit.v1_20_R4.CraftSound; +import org.bukkit.craftbukkit.v1_20_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_20_R4.block.data.CraftBlockData; +import org.bukkit.craftbukkit.v1_20_R4.entity.CraftCat; +import org.bukkit.craftbukkit.v1_20_R4.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_20_R4.entity.CraftFrog; +import org.bukkit.craftbukkit.v1_20_R4.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R4.entity.CraftWolf; +import org.bukkit.craftbukkit.v1_20_R4.inventory.CraftItemStack; +import org.bukkit.craftbukkit.v1_20_R4.util.CraftMagicNumbers; +import org.bukkit.craftbukkit.v1_20_R4.util.CraftNamespacedKey; +import org.bukkit.entity.Cat; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Frog; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wolf; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +public class ReflectionManager implements ReflectionManagerAbstract { + private Field dataItemsField; + + public ReflectionManager() { + for (Field f : SynchedEntityData.class.getDeclaredFields()) { + if (!f.getType().isArray()) { + continue; + } + + f.setAccessible(true); + dataItemsField = f; + } + } + + public boolean hasInvul(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + + if (nmsEntity instanceof net.minecraft.world.entity.LivingEntity) { + return nmsEntity.invulnerableTime > 0; + } else { + return nmsEntity.isInvulnerableTo(nmsEntity.damageSources().generic()); + } + } + + @Override + public int getIncrementedStateId(Player player) { + ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); + return serverPlayer.containerMenu.incrementStateId(); // TODO Check correct container + } + + @Override + public int getNewEntityId() { + return getNewEntityId(true); + } + + @Override + public int getNewEntityId(boolean increment) { + try { + Field entityCounter = net.minecraft.world.entity.Entity.class.getDeclaredField("c"); + entityCounter.setAccessible(true); + AtomicInteger atomicInteger = (AtomicInteger) entityCounter.get(null); + if (increment) { + return atomicInteger.incrementAndGet(); + } else { + return atomicInteger.get(); + } + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + + return -1; + } + + @Override + public ServerGamePacketListenerImpl getPlayerConnectionOrPlayer(Player player) { + return ((CraftPlayer) player).getHandle().connection; + } + + @Override + public net.minecraft.world.entity.Entity createEntityInstance(String entityName) { + Optional> optional = + net.minecraft.world.entity.EntityType.byString(entityName.toLowerCase(Locale.ENGLISH)); + + if (!optional.isPresent()) { + return null; + } + + net.minecraft.world.entity.EntityType entityType = optional.get(); + ServerLevel world = getWorldServer(Bukkit.getWorlds().get(0)); + net.minecraft.world.entity.Entity entity; + if (entityType == net.minecraft.world.entity.EntityType.PLAYER) { + GameProfile gameProfile = new GameProfile(new UUID(0, 0), "Steve"); + ClientInformation information = + new ClientInformation("english", 10, ChatVisiblity.FULL, true, 0, HumanoidArm.RIGHT, true, true); + entity = new ServerPlayer(getMinecraftServer(), world, gameProfile, information); + } else { + entity = entityType.create(world); + } + + if (entity == null) { + return null; + } + + // Workaround for paper being 2 smart 4 me + entity.setPos(1.0, 1.0, 1.0); + entity.setPos(0.0, 0.0, 0.0); + return entity; + } + + @Override + public AABB getBoundingBox(Entity entity) { + return ((CraftEntity) entity).getHandle().getBoundingBox(); + } + + @Override + public double getXBoundingBox(Entity entity) { + return getBoundingBox(entity).maxX - getBoundingBox(entity).minX; + } + + @Override + public double getYBoundingBox(Entity entity) { + return getBoundingBox(entity).maxY - getBoundingBox(entity).minY; + } + + @Override + public double getZBoundingBox(Entity entity) { + return getBoundingBox(entity).maxZ - getBoundingBox(entity).minZ; + } + + @Override + public ServerPlayer getPlayerFromPlayerConnection(Object nmsEntity) { + return ((ServerPlayerConnection) nmsEntity).getPlayer(); + } + + @Override + public Entity getBukkitEntity(Object nmsEntity) { + return ((net.minecraft.world.entity.Entity) nmsEntity).getBukkitEntity(); + } + + @Override + public ItemStack getBukkitItem(Object nmsItem) { + return CraftItemStack.asBukkitCopy((net.minecraft.world.item.ItemStack) nmsItem); + } + + @Override + public ItemStack getCraftItem(ItemStack bukkitItem) { + return CraftItemStack.asCraftCopy(bukkitItem); + } + + @Override + public ServerEntity getEntityTrackerEntry(Entity target) throws Exception { + ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); + ServerChunkCache chunkSource = world.getChunkSource(); + ChunkMap chunkMap = chunkSource.chunkMap; + Int2ObjectMap entityMap = chunkMap.entityMap; + ChunkMap.TrackedEntity trackedEntity = entityMap.get(target.getEntityId()); + if (trackedEntity == null) { + return null; + } + + Field field = ChunkMap.TrackedEntity.class.getDeclaredField("b"); + field.setAccessible(true); + + return (ServerEntity) field.get(trackedEntity); + } + + @Override + public DedicatedServer getMinecraftServer() { + return ((CraftServer) Bukkit.getServer()).getServer(); + } + + @Override + public Object getNmsEntity(Entity entity) { + return ((CraftEntity) entity).getHandle(); + } + + @Override + public double getPing(Player player) { + return player.getPing(); + } + + @Override + public float[] getSize(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); + EntityDimensions dimensions = nmsEntity.getDimensions(net.minecraft.world.entity.Pose.STANDING); + return new float[]{dimensions.width(), nmsEntity.getEyeHeight()}; + } + + @Override + public MinecraftSessionService getMinecraftSessionService() { + return getMinecraftServer().getSessionService(); + } + + @Override + public Float getSoundModifier(Object entity) { + // Default is 1.0F on EntityLiving + if (!(entity instanceof net.minecraft.world.entity.LivingEntity)) { + return 0.0f; + } else { + try { + Method method = net.minecraft.world.entity.LivingEntity.class.getDeclaredMethod("fe"); + method.setAccessible(true); + + return (Float) method.invoke(entity); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + return 0f; + } + + @Override + public void injectCallback(String playername, ProfileLookupCallback callback) { + getMinecraftServer().getProfileRepository().findProfilesByNames(new String[]{playername}, callback); + } + + @Override + public void setBoundingBox(Entity entity, double x, double y, double z) { + Location loc = entity.getLocation(); + ((CraftEntity) entity).getHandle().setBoundingBox( + new AABB(loc.getX() - x / 2, loc.getY() - y / 2, loc.getZ() - z / 2, loc.getX() + x / 2, loc.getY() + y / 2, + loc.getZ() + z / 2)); + } + + @Override + public String getSoundString(Sound sound) { + return CraftSound.bukkitToMinecraft(sound).getLocation().toString(); + } + + @Override + public Material getMaterial(String name) { + return CraftMagicNumbers.INSTANCE.getMaterial(name, CraftMagicNumbers.INSTANCE.getDataVersion()); + } + + @Override + public String getItemName(Material material) { + return BuiltInRegistries.ITEM.getKey(CraftMagicNumbers.getItem(material)).getPath(); + } + + @Override + public ResourceLocation createMinecraftKey(String name) { + return new ResourceLocation(name); + } + + @Override + public net.minecraft.world.entity.EntityType getEntityType(EntityType entityType) { + return net.minecraft.world.entity.EntityType.byString( + entityType.getName() == null ? entityType.name().toLowerCase(Locale.ENGLISH) : entityType.getName()).orElse(null); + } + + @Override + public Object registerEntityType(NamespacedKey key) { + net.minecraft.world.entity.EntityType newEntity = + new net.minecraft.world.entity.EntityType<>(null, null, false, false, false, false, null, null, 0, 0, 0, FeatureFlagSet.of()); + Registry.register(BuiltInRegistries.ENTITY_TYPE, CraftNamespacedKey.toMinecraft(key), newEntity); + newEntity.getDescriptionId(); + return newEntity; // TODO ??? Some reflection in legacy that I'm unsure about + } + + @Override + public int getEntityTypeId(Object entityTypes) { + net.minecraft.world.entity.EntityType entityType = (net.minecraft.world.entity.EntityType) entityTypes; + + return BuiltInRegistries.ENTITY_TYPE.getId(entityType); + } + + @Override + public int getEntityTypeId(EntityType entityType) { + return getEntityTypeId(getEntityType(entityType)); + } + + @Override + public Object getEntityType(NamespacedKey name) { + return BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(name)); + } + + @Override + public int getCombinedIdByBlockData(BlockData data) { + BlockState state = ((CraftBlockData) data).getState(); + return Block.getId(state); + } + + @Override + public int getCombinedIdByItemStack(ItemStack itemStack) { + Block block = CraftMagicNumbers.getBlock(itemStack.getType()); + return Block.getId(block.defaultBlockState()); + } + + @Override + public BlockData getBlockDataByCombinedId(int id) { + return CraftBlockData.fromData(Block.stateById(id)); + } + + @Override + public ItemStack getItemStackByCombinedId(int id) { + return new ItemStack(CraftMagicNumbers.getMaterial(Block.stateById(id).getBlock())); + } + + @Override + public ServerLevel getWorldServer(World w) { + return ((CraftWorld) w).getHandle(); + } + + @Override + public ItemMeta getDeserializedItemMeta(Map meta) { + try { + Class aClass = Class.forName("org.bukkit.craftbukkit.v1_20_R4.inventory.CraftMetaItem$SerializableMeta"); + Method deserialize = aClass.getDeclaredMethod("deserialize", Map.class); + Object itemMeta = deserialize.invoke(null, meta); + + return (ItemMeta) itemMeta; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + @SneakyThrows + @Override + public ByteBuf getDataWatcherValues(Entity entity) { + SynchedEntityData watcher = ((CraftEntity) entity).getHandle().getEntityData(); + SynchedEntityData.DataItem[] dataItems = (SynchedEntityData.DataItem[]) dataItemsField.get(watcher); + + ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); + RegistryFriendlyByteBuf serializer = RegistryFriendlyByteBuf.decorator(this.getMinecraftServer().registryAccess()).apply(buf); + + for (SynchedEntityData.DataItem dataItem : dataItems) { + dataItem.value().write(serializer); + } + + serializer.writeByte(255); + + return buf; + } + + @Override + public GameProfile getMCGameProfile(Player player) { + return ((CraftPlayer) player).getProfile(); + } + + @Override + public Cat.Type getCatTypeFromInt(int catType) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.CAT_VARIANT); + + Holder.Reference ref = registry.getHolder(catType).get(); + + return CraftCat.CraftType.minecraftHolderToBukkit(registry.getHolder(catType).get()); + } + + @Override + public int getCatVariantAsInt(Cat.Type type) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.CAT_VARIANT); + + return registry.getId(CraftCat.CraftType.bukkitToMinecraft(type)); + } + + @Override + public Frog.Variant getFrogVariantFromInt(int frogType) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.FROG_VARIANT); + + Holder.Reference ref = registry.getHolder(frogType).get(); + + return CraftFrog.CraftVariant.minecraftHolderToBukkit(registry.getHolder(frogType).get()); + } + + @Override + public int getFrogVariantAsInt(Frog.Variant type) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.FROG_VARIANT); + + return registry.getId(CraftFrog.CraftVariant.bukkitToMinecraft(type)); + } + + @Override + public Art getPaintingFromInt(int paintingId) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.PAINTING_VARIANT); + + Holder.Reference ref = registry.getHolder(paintingId).get(); + + return CraftArt.minecraftHolderToBukkit(registry.getHolder(paintingId).get()); + } + + @Override + public int getPaintingAsInt(Art type) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.PAINTING_VARIANT); + + return registry.getId(CraftArt.bukkitToMinecraft(type)); + } + + @Override + public Wolf.Variant getWolfVariantFromInt(int wolfVariant) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.WOLF_VARIANT); + + Holder.Reference ref = registry.getHolder(wolfVariant).get(); + + return CraftWolf.CraftVariant.minecraftHolderToBukkit(registry.getHolder(wolfVariant).get()); + } + + @Override + public int getWolfVariantAsInt(Wolf.Variant type) { + Registry registry = MinecraftServer.getDefaultRegistryAccess().registryOrThrow(Registries.WOLF_VARIANT); + + return registry.getId(CraftWolf.CraftVariant.bukkitToMinecraft(type)); + } + + @Override + public Object serializeComponents(ItemStack itemStack) { + if (itemStack == null) { + return null; + } + + net.minecraft.world.item.ItemStack item = CraftItemStack.asNMSCopy(itemStack); + DataComponentPatch comps = item.getComponentsPatch(); + + if (comps == null) { + return null; + } + + DataResult cond = DataComponentPatch.CODEC.encodeStart(JavaOps.INSTANCE, comps); + + return cond.result().orElse(null); + } +} diff --git a/plugin/pom.xml b/plugin/pom.xml index 4c9328db..32d48702 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -98,20 +98,16 @@ ** + + META-INF/**/v*/** + - net.kyori:* LibsDisguises:* - - - net.kyori - libsdisg.shaded.net.kyori - - @@ -119,14 +115,8 @@ - org.projectlombok - lombok - ${lombok.version} - true - - - com.github.dmulloy2 - ProtocolLib + org.spigotmc + spigot true @@ -134,11 +124,6 @@ spigot-api true - - org.spigotmc - spigot - true - io.papermc.paper paper-api @@ -150,45 +135,17 @@ net.md-5 bungeecord-chat ${bungeecord-chat.version} - true - - - net.kyori - adventure-text-minimessage - ${adventure-minimessage.version} - compile - true - - - net.kyori - adventure-text-serializer-gson - ${adventure-text.version} - compile - true - - - net.kyori - adventure-api - ${adventure-text.version} - compile - true - - - - junit - junit - ${junit.version} - test - true - - - org.junit.jupiter - junit-jupiter - ${junit-jupiter.version} - test + provided true + + LibsDisguises + minimessage + 1.0-SNAPSHOT + compile + true + LibsDisguises shared @@ -268,6 +225,14 @@ compile true + + LibsDisguises + v1_20_R4 + 1.0-SNAPSHOT + remapped-spigot + compile + true + it.unimi.dsi diff --git a/plugin/src/main/java/me/libraryaddict/disguise/DisguiseAPI.java b/plugin/src/main/java/me/libraryaddict/disguise/DisguiseAPI.java index 37537898..e0c2773e 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/DisguiseAPI.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/DisguiseAPI.java @@ -1,8 +1,7 @@ package me.libraryaddict.disguise; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; -import com.comphenix.protocol.wrappers.WrappedWatchableObject; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; @@ -81,8 +80,8 @@ public class DisguiseAPI { } } - public static void addGameProfile(String profileName, WrappedGameProfile gameProfile) { - DisguiseUtilities.addGameProfile(profileName, gameProfile); + public static void addGameProfile(String profileName, UserProfile gameProfile) { + DisguiseUtilities.addUserProfile(profileName, gameProfile); } public static String getRawCustomDisguise(String disguiseName) { @@ -145,20 +144,18 @@ public class DisguiseAPI { } } - WrappedDataWatcher dataWatcher = WrappedDataWatcher.getEntityWatcher(entity); - - for (WrappedWatchableObject obj : dataWatcher.getWatchableObjects()) { - MetaIndex index = MetaIndex.getMetaIndex(watcher.getClass(), obj.getIndex()); + for (EntityData data : ReflectionManager.getEntityWatcher(entity)) { + MetaIndex index = MetaIndex.getMetaIndex(watcher.getClass(), data.getIndex()); if (index == null) { continue; } - if (index.getDefault() == obj.getValue() || index.getDefault() == obj.getRawValue()) { + if (index.getDefault() == data.getValue()) { continue; } - watcher.setUnsafeData(index, obj.getValue()); + watcher.setUnsafeData(index, data.getValue()); // Update the meta for 0, otherwise boolean be weird if (index == MetaIndex.ENTITY_META) { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/DisguiseConfig.java b/plugin/src/main/java/me/libraryaddict/disguise/DisguiseConfig.java index 6a51bca3..952ba4a0 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/DisguiseConfig.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/DisguiseConfig.java @@ -211,6 +211,7 @@ public class DisguiseConfig { @Getter @Setter private static BarColor bossBarColor = BarColor.GREEN; + @Getter private static PermissionDefault commandVisibility = PermissionDefault.TRUE; @Getter @Setter @@ -286,7 +287,10 @@ public class DisguiseConfig { private static List disabledMethods = new ArrayList<>(); @Getter @Setter - private static boolean neverUpdateProtocolLib; + private static boolean neverUpdatePacketEvents; + @Getter + @Setter + private static boolean removeDisguiseBlockPlace, removeDisguiseBlockBreak; public static boolean isArmorstandsName() { return getPlayerNameType() == PlayerNameType.ARMORSTANDS; @@ -440,10 +444,6 @@ public class DisguiseConfig { } } - public static PermissionDefault getCommandVisibility() { - return commandVisibility; - } - public static void setCommandVisibility(PermissionDefault permissionDefault) { if (permissionDefault == null || getCommandVisibility() == permissionDefault) { return; @@ -557,10 +557,51 @@ public class DisguiseConfig { TranslateType.refreshTranslations(); } - public static void loadConfig() { + private static ConfigLoader getConfig() { ConfigLoader configLoader = new ConfigLoader(); configLoader.saveMissingConfigs(); + return configLoader; + } + + public static ConfigLoader loadPreConfig() { + ConfigLoader configLoader = getConfig(); + + loadPreConfig(configLoader); + + return configLoader; + } + + /** + * Only called for DisguiseMethods.class so we know what the defaults of disguise parameters are, eg, tall disguises visible + */ + private static ConfigurationSection loadPreConfig(ConfigLoader configLoader) { + ConfigurationSection config = configLoader.load(); + + setAddEntityAnimations(config.getBoolean("AddEntityAnimations")); + setDisguiseCloneExpire(config.getInt("DisguiseCloneExpire")); + setDisguiseEntityExpire(config.getInt("DisguiseEntityExpire")); + setDynamicExpiry(config.getBoolean("DynamicExpiry")); + setHideDisguisedPlayers(config.getBoolean("HideDisguisedPlayersFromTab")); + setPlayerHideArmor(config.getBoolean("PlayerHideArmor")); + setTallSelfDisguises(config.getBoolean("TallSelfDisguises")); + setRandomDisguises(config.getBoolean("RandomDisguiseOptions")); + setViewDisguises(config.getBoolean("ViewSelfDisguises")); + setViewSelfDisguisesDefault(config.getBoolean("ViewSelfDisguisesDefault")); + setSelfDisguisesSoundsReplaced(config.getBoolean("HearSelfDisguise")); + setShowDisguisedPlayersInTab(config.getBoolean("ShowPlayerDisguisesInTab")); + setVelocitySent(config.getBoolean("SendVelocity")); + + setHideHeldItemFromSelf(config.getBoolean("RemoveHeldItem")); + setHideArmorFromSelf(config.getBoolean("RemoveArmor")); + + return config; + } + + public static void loadConfig() { + ConfigLoader configLoader = getConfig(); + ConfigurationSection config = loadPreConfig(configLoader); + loadModdedDisguiseTypes(); File skinsFolder = new File(LibsDisguises.getInstance().getDataFolder(), "Skins"); @@ -582,11 +623,8 @@ public class DisguiseConfig { } } - ConfigurationSection config = configLoader.load(); - PacketsManager.setViewDisguisesListener(true); - setAddEntityAnimations(config.getBoolean("AddEntityAnimations")); setAnimationPacketsEnabled(config.getBoolean("PacketsEnabled.Animation")); setCatDyeable(config.getBoolean("DyeableCat")); setCollectPacketsEnabled(config.getBoolean("PacketsEnabled.Collect")); @@ -597,16 +635,10 @@ public class DisguiseConfig { setPvPTimer(config.getDouble("PvPTimer")); setDisguiseBlownWhenAttacked(config.getBoolean("BlowDisguisesWhenAttacked")); setDisguiseBlownWhenAttacking(config.getBoolean("BlowDisguisesWhenAttacking")); - setDisguiseCloneExpire(config.getInt("DisguiseCloneExpire")); - setDisguiseEntityExpire(config.getInt("DisguiseEntityExpire")); - setDynamicExpiry(config.getBoolean("DynamicExpiry")); setEntityStatusPacketsEnabled(config.getBoolean("PacketsEnabled.EntityStatus")); setEquipmentPacketsEnabled(config.getBoolean("PacketsEnabled.Equipment")); setExplicitDisguisePermissions(config.getBoolean("Permissions.ExplicitDisguises")); - setHideArmorFromSelf(config.getBoolean("RemoveArmor")); setHidingCreativeEquipmentFromSelf(config.getBoolean("RemoveCreativeEquipment")); - setHideDisguisedPlayers(config.getBoolean("HideDisguisedPlayersFromTab")); - setHideHeldItemFromSelf(config.getBoolean("RemoveHeldItem")); setHorseSaddleable(config.getBoolean("SaddleableHorse")); setKeepDisguiseOnPlayerDeath(config.getBoolean("KeepDisguises.PlayerDeath")); setLlamaCarpetable(config.getBoolean("CarpetableLlama")); @@ -622,38 +654,32 @@ public class DisguiseConfig { setNameAboveHeadAlwaysVisible(config.getBoolean("NameAboveHeadAlwaysVisible")); setNameOfPlayerShownAboveDisguise(config.getBoolean("ShowNamesAboveDisguises")); setNameAboveDisguise(config.getString("NameAboveDisguise")); - setPlayerHideArmor(config.getBoolean("PlayerHideArmor")); setRetaliationCombat(config.getBoolean("RetaliationCombat")); setSaveGameProfiles(config.getBoolean("SaveGameProfiles")); setSavePlayerDisguises(config.getBoolean("SaveDisguises.Players")); setSaveEntityDisguises(config.getBoolean("SaveDisguises.Entities")); - setSelfDisguisesSoundsReplaced(config.getBoolean("HearSelfDisguise")); setSheepDyeable(config.getBoolean("DyeableSheep")); - setShowDisguisedPlayersInTab(config.getBoolean("ShowPlayerDisguisesInTab")); - setSoundsEnabled(config.getBoolean("DisguiseSounds")); setStopShulkerDisguisesFromMoving(config.getBoolean("StopShulkerDisguisesFromMoving", true)); setUUIDGeneratedVersion(config.getInt("UUIDVersion")); setUndisguiseOnWorldChange(config.getBoolean("UndisguiseOnWorldChange")); setUpdateGameProfiles(config.getBoolean("UpdateGameProfiles")); setUseTranslations(config.getBoolean("Translations")); - setVelocitySent(config.getBoolean("SendVelocity")); - setViewDisguises(config.getBoolean("ViewSelfDisguises")); setWarnScoreboardConflict(config.getBoolean("Scoreboard.WarnConflict")); setCopyPlayerTeamInfo(config.getBoolean("Scoreboard.CopyPlayerTeamInfo")); setWitherSkullPacketsEnabled(config.getBoolean("PacketsEnabled.WitherSkull")); setWolfDyeable(config.getBoolean("DyeableWolf")); setTablistRemoveDelay(config.getInt("TablistRemoveDelay")); setAutoUpdate(config.getBoolean("AutoUpdate")); - setTallSelfDisguises(config.getBoolean("TallSelfDisguises")); setOverrideCustomNames(config.getBoolean("OverrideCustomNames")); - setRandomDisguises(config.getBoolean("RandomDisguiseOptions")); setSaveUserPreferences(config.getBoolean("SaveUserPreferences")); setPlayerDisguisesSkinExpiresMove(config.getInt("PlayerDisguisesTablistExpiresMove")); - setViewSelfDisguisesDefault(config.getBoolean("ViewSelfDisguisesDefault")); setContactMojangServers(config.getBoolean("ContactMojangServers")); setDisguiseRadiusMax(config.getInt("DisguiseRadiusMax")); setRandomUUIDS(config.getBoolean("RandomUUIDs")); + setRemoveDisguiseBlockBreak(config.getBoolean("UndisguiseOnBlockBreak")); + setRemoveDisguiseBlockPlace(config.getBoolean("UndisguiseOnBlockPlace")); String apiKey = config.getString("MineSkinAPIKey"); + setSoundsEnabled(config.getBoolean("DisguiseSounds")); if (apiKey != null && apiKey.matches("[a-zA-Z\\d]{8,}")) { DisguiseUtilities.getMineSkinAPI().setApiKey(apiKey); @@ -708,16 +734,16 @@ public class DisguiseConfig { try { setDisabledDisguises( - config.getStringList("DisabledDisguises").stream().map(s -> DisguiseType.valueOf(s.toUpperCase(Locale.ROOT))) + config.getStringList("DisabledDisguises").stream().map(s -> DisguiseType.valueOf(s.toUpperCase(Locale.ENGLISH))) .collect(Collectors.toList())); } catch (Exception ex) { DisguiseUtilities.getLogger().warning("Cannot load 'DisabledDisguises' in features.yml, invalid disguise types provided?"); } setDisabledMethods( - config.getStringList("DisabledMethods").stream().map(s -> s.toLowerCase(Locale.ROOT)).collect(Collectors.toList())); + config.getStringList("DisabledMethods").stream().map(s -> s.toLowerCase(Locale.ENGLISH)).collect(Collectors.toList())); - setNeverUpdateProtocolLib(config.getBoolean("NeverUpdateProtocolLib", false)); + setNeverUpdatePacketEvents(config.getBoolean("NeverUpdatePacketEvents", config.getBoolean("NeverUpdateProtocolLib", false))); String seeCommands = config.getString("Permissions.SeeCommands"); PermissionDefault commandVisibility = seeCommands == null ? null : PermissionDefault.getByName(seeCommands); @@ -854,7 +880,7 @@ public class DisguiseConfig { requireMessage = DisguiseUtilities.translateAlternateColorCodes(requireMessage); } - ModdedEntity entity = new ModdedEntity(null, name, living, mod, version, requireMessage, 0); + ModdedEntity entity = new ModdedEntity(null, null, name, living, mod, version, requireMessage, 0); if (ModdedManager.getModdedEntity(name) != null) { DisguiseUtilities.getLogger() @@ -1021,46 +1047,52 @@ public class DisguiseConfig { } public static void setAnimationPacketsEnabled(boolean enabled) { - if (enabled != isAnimationPacketsEnabled()) { - animationPacketsEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isAnimationPacketsEnabled()) { + return; } + + animationPacketsEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } public static void setCollectPacketsEnabled(boolean enabled) { - if (enabled != isCollectPacketsEnabled()) { - collectPacketsEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isCollectPacketsEnabled()) { + return; } + + collectPacketsEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } public static void setEntityStatusPacketsEnabled(boolean enabled) { - if (enabled != isEntityStatusPacketsEnabled()) { - entityStatusPacketsEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isEntityStatusPacketsEnabled()) { + return; } + + entityStatusPacketsEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } public static void setEquipmentPacketsEnabled(boolean enabled) { - if (enabled != isEquipmentPacketsEnabled()) { - equipmentPacketsEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isEquipmentPacketsEnabled()) { + return; } + + equipmentPacketsEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } /** * Set the plugin to hide self disguises armor from theirselves */ public static void setHideArmorFromSelf(boolean hideArmor) { - if (hidingArmorFromSelf != hideArmor) { - hidingArmorFromSelf = hideArmor; + hidingArmorFromSelf = hideArmor; - PacketsManager.setInventoryListenerEnabled(isHidingHeldItemFromSelf() || isHidingArmorFromSelf()); - } + updateInventoryListener(); } /** @@ -1068,27 +1100,33 @@ public class DisguiseConfig { * self disguise */ public static void setHideHeldItemFromSelf(boolean hideHelditem) { - if (hidingHeldItemFromSelf != hideHelditem) { - hidingHeldItemFromSelf = hideHelditem; + hidingHeldItemFromSelf = hideHelditem; - PacketsManager.setInventoryListenerEnabled(isHidingHeldItemFromSelf() || isHidingArmorFromSelf()); - } + updateInventoryListener(); + } + + private static void updateInventoryListener() { + PacketsManager.setInventoryListenerEnabled(isHidingHeldItemFromSelf() || isHidingArmorFromSelf()); } public static void setMiscDisguisesForLivingEnabled(boolean enabled) { - if (enabled != isMiscDisguisesForLivingEnabled()) { - miscDisguisesForLivingEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isMiscDisguisesForLivingEnabled()) { + return; } + + miscDisguisesForLivingEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } public static void setMovementPacketsEnabled(boolean enabled) { - if (enabled != isMovementPacketsEnabled()) { - movementPacketsEnabled = enabled; - - PacketsManager.setupMainPacketsListener(); + if (enabled == isMovementPacketsEnabled()) { + return; } + + movementPacketsEnabled = enabled; + + PacketsManager.setupMainPacketsListener(); } /** diff --git a/plugin/src/main/java/me/libraryaddict/disguise/LibsDisguises.java b/plugin/src/main/java/me/libraryaddict/disguise/LibsDisguises.java index 2735df06..8c639f21 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/LibsDisguises.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/LibsDisguises.java @@ -1,6 +1,8 @@ package me.libraryaddict.disguise; +import io.github.retrooper.packetevents.util.SpigotReflectionUtil; import lombok.Getter; +import lombok.Setter; import lombok.SneakyThrows; import me.libraryaddict.disguise.commands.LibsDisguisesCommand; import me.libraryaddict.disguise.commands.disguise.DisguiseCommand; @@ -38,6 +40,7 @@ import me.libraryaddict.disguise.utilities.reflection.ClassMappings; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.sounds.SoundManager; +import me.libraryaddict.disguise.utilities.updates.PacketEventsUpdater; import me.libraryaddict.disguise.utilities.updates.UpdateChecker; import me.libraryaddict.disguise.utilities.watchers.CompileMethods; import org.apache.commons.lang.StringUtils; @@ -54,13 +57,23 @@ import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull; import java.io.File; +import java.io.IOException; import java.util.Arrays; import java.util.Iterator; +import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; public class LibsDisguises extends JavaPlugin { + /** + * -- GETTER -- + * External APIs shouldn't actually need this instance. DisguiseAPI should be enough to handle most cases. + * + * @return The instance of this plugin + */ + @Getter private static LibsDisguises instance; + @Getter private DisguiseListener listener; private String buildNumber; @Getter @@ -72,55 +85,58 @@ public class LibsDisguises extends JavaPlugin { @Getter private PlayerSkinHandler skinHandler; private DisguiseCommandConfig commandConfig; + @Setter + @Getter + private boolean packetEventsUpdateDownloaded; @Override public void onLoad() { try { - if (instance != null || !Bukkit.getServer().getWorlds().isEmpty() || !Bukkit.getOnlinePlayers().isEmpty()) { + boolean hasInstanceAlready = instance != null; + + if (hasInstanceAlready || !Bukkit.getServer().getWorlds().isEmpty() || !Bukkit.getOnlinePlayers().isEmpty()) { reloaded = true; - getLogger().severe("Server was reloaded! Please do not report any bugs! This plugin can't handle " + "reloads gracefully!"); + getLogger().severe("Server was reloaded! Please do not report any bugs! This plugin can't handle reloads gracefully!"); } instance = this; - Plugin plugin = Bukkit.getPluginManager().getPlugin("ProtocolLib"); + Plugin plugin = Bukkit.getPluginManager().getPlugin("packetevents"); - if (plugin == null || DisguiseUtilities.isProtocolLibOutdated()) { - if (DisguiseConfig.isNeverUpdateProtocolLib()) { + // Skipping the isPacketEventsOutdated check cos DisguiseConfig wouldn't be loaded + if (plugin == null /*|| DisguiseUtilities.isPacketEventsOutdated()*/) { + // I don't think anyone will ever see this plugin message, DisguiseConfig isn't loaded at this point + if (DisguiseConfig.isNeverUpdatePacketEvents()) { getLogger().warning( "Defined in plugins/LibsDisguises/configs/sanity.yml, you have requested that Lib's Disguises never updates or " + - "installs ProtocolLib. " + "Please do not report any issues with this plugin."); + "installs PacketEvents. Please do not report any issues with this plugin."); } else { - String reason; - - if (plugin == null) { - reason = "ProtocolLib not installed"; - } else if (!plugin.isEnabled()) { - reason = "ProtocolLib is not enabled"; - } else if (DisguiseUtilities.isProtocolLibOutdated()) { - reason = "ProtocolLib is outdated"; - } else { - reason = "Lib's Disguises couldn't process ProtocolLib properly"; - } + String reason = getPacketEventsFailedReason(plugin); getLogger().warning( - "An issue occured when trying to load ProtocolLib: " + reason + ". Lib's Disguises will attempt to update it."); + "An issue occured when trying to load PacketEvents: " + reason + ". Lib's Disguises will attempt to update it."); try { - File dest = DisguiseUtilities.updateProtocolLib(); + PacketEventsUpdater updater = new PacketEventsUpdater(); + boolean attempt = updater.doUpdate(); - if (plugin == null) { - getLogger().info("ProtocolLib downloaded and stuck in plugins folder! Now trying to load it!"); - plugin = Bukkit.getPluginManager().loadPlugin(dest); + if (!attempt) { + getLogger().severe( + "PacketEvents download has failed, please install PacketEvents manually from https://www.spigotmc" + + ".org/resources/packetevents-api.80279/"); + } else if (plugin == null) { + getLogger().info("PacketEvents downloaded and stuck in plugins folder! Now trying to load it!"); + plugin = Bukkit.getPluginManager().loadPlugin(updater.getDestination()); plugin.onLoad(); Bukkit.getPluginManager().enablePlugin(plugin); } else { - getLogger().severe("Please restart the server to complete the ProtocolLib update!"); + getLogger().severe("Please restart the server to complete the PacketEvents update!"); } } catch (Exception e) { - getLogger().severe("Looks like ProtocolLib's site may be down! Try download it manually from https://ci.dmulloy2" + - ".net/job/ProtocolLib/"); + getLogger().severe( + "Looks like PacketEvents's site may be down! Try download it manually from https://www.spigotmc" + + ".org/resources/packetevents-api.80279/"); e.printStackTrace(); } } @@ -129,15 +145,16 @@ public class LibsDisguises extends JavaPlugin { try { Class cl = Class.forName("org.bukkit.Server$Spigot"); } catch (ClassNotFoundException e) { - getLogger().severe("Oh dear, you seem to be using CraftBukkit. Please use Spigot or Paper instead! This " + - "plugin will continue to load, but it will look like a mugging victim"); + getLogger().severe( + "Oh dear, you seem to be using CraftBukkit. Please upgrade to use Spigot or Paper instead! This plugin will continue " + + "to load, but it will look like a mugging victim"); } // Note that Forge/Hybrid is unsupported // Previously was supported but changes in both LD and nms has made it unsustainable // The time and complexibility it would take is far too high for the amount of usage it would receive. // Any extra income from sales would never cover the time spent implementing this. - if (Bukkit.getVersion().toLowerCase().matches(".*(arclight|mohist|magma).*")) { + if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).matches(".*(arclight|mohist|magma).*")) { getLogger().severe( "Lib's Disguises will not work correctly on Forge/Hybrid servers, due to complexibility and time commitment there is " + "no support for this. Do not report any issues to Lib's Disguises."); @@ -145,7 +162,7 @@ public class LibsDisguises extends JavaPlugin { commandConfig = new DisguiseCommandConfig(); - if (!reloaded) { + if (!hasInstanceAlready && (isReleaseBuild() || LibsPremium.getPaidInformation() != null || !LibsPremium.isPremium())) { commandConfig.load(); } } catch (Throwable throwable) { @@ -165,109 +182,30 @@ public class LibsDisguises extends JavaPlugin { @Override public void onEnable() { try { - if (reloaded) { - getLogger().severe("Server was reloaded! Please do not report any bugs! This plugin can't handle " + "reloads gracefully!"); + if (isReloaded()) { + getLogger().severe("Server was reloaded! Please do not report any bugs! This plugin can't handle reloads gracefully!"); } - if (Bukkit.getVersion().contains("(MC: 1.17)")) { - getLogger().severe("Please update from MC 1.17! You should be using 1.17.1!"); - } - - if (Bukkit.getVersion().contains("(MC: 1.18)") || Bukkit.getVersion().contains("(MC: 1.18.1)")) { - getLogger().severe( - "Please update from MC 1.18 and MC 1.18.1! You should be using 1.18.2! Support will eventually be dropped for your " + - "specific version!"); - } - - if (Bukkit.getVersion().contains("(MC: 1.19)")) { - getLogger().severe( - "Please update from MC 1.19.0! You should be using at least 1.19.3! 1.19.1 is the lowest supported 1.19 version!"); - } - - try { - Class cl = Class.forName("org.bukkit.Server$Spigot"); - } catch (ClassNotFoundException e) { - getLogger().severe("Oh dear, you seem to be using CraftBukkit. Please use Spigot or Paper instead! This " + - "plugin will continue to load, but it will look like a mugging victim"); - } - - File disguiseFile = new File(getDataFolder(), "configs/disguises.yml"); - - if (!disguiseFile.exists()) { - disguiseFile.getParentFile().mkdirs(); - - File oldFile = new File(getDataFolder(), "disguises.yml"); - - if (oldFile.exists()) { - oldFile.renameTo(disguiseFile); - } else { - saveResource("configs/disguises.yml", false); - } - } - - YamlConfiguration pluginYml = ReflectionManager.getPluginYAML(getFile()); - buildNumber = StringUtils.stripToNull(pluginYml.getString("build-number")); - buildDate = StringUtils.stripToNull(pluginYml.getString("build-date")); - - int fileCount = ReflectionManager.getJarFileCount(getFile(), CompileMethods.ignoredDirectories()); - int expected = pluginYml.getInt("file-count", fileCount); - - if (fileCount != expected) { - getLogger().severe("Lib's Disguises may be infected with malware, there were " + (fileCount - expected) + - " unknown files injected into the jar. Please redownload from a trusted source such as SpigotMC. If this warning " + - "shows even after updating, try https://www.spigotmc.org/resources/spigot-anti-malware.64982/ otherwise if that " + - "doesn't help then please contact libraryaddict on discord https://discord.gg/J5XRqYX"); - } - - getLogger().info("File Name: " + getFile().getName()); - - String nmsPackageName = ReflectionManager.getNmsPackage(); - - if (nmsPackageName.isEmpty()) { - nmsPackageName = "{Not package relocated}"; - } - - getLogger().info( - "Discovered nms version: (Package: " + nmsPackageName + ") (LD: " + ReflectionManager.getVersion() + ") (MC: " + - ReflectionManager.getMinecraftVersion() + ")"); - - getLogger().info("Jenkins Build: " + (isNumberedBuild() ? "#" : "") + getBuildNo()); - - getLogger().info("Build Date: " + buildDate); + runWarnings(); + updateOldDisguisesYaml(); + loadYamlWarnVirus(); + logInfo(); DisguiseConfig.loadInternalConfig(); LibsPremium.check(getDescription().getVersion(), getFile()); - if (!LibsPremium.isPremium()) { - getLogger().info( - "You are running the free version, commands limited to non-players and operators. (Console," + " Command " + - "Blocks, Admins)"); - } - - // Add a message so people are more aware - if (!DisguiseConfig.isTallSelfDisguises()) { - DisguiseUtilities.getLogger().info( - "Config 'TallSelfDisguises' is set to 'false', LD will hide oversized disguises from self disguise. https://www" + - ".spigotmc.org/wiki/lib-s-disguises-faq/#tall-disguises-self-disguises"); - } + someMoreLogging(); if (ReflectionManager.getVersion() == null) { - getLogger().severe("You're using the wrong version of Lib's Disguises for your server! This is " + "intended for " + + getLogger().severe("You're using the wrong version of Lib's Disguises for your server! This is intended for " + StringUtils.join(Arrays.stream(NmsVersion.values()).filter(v -> v != NmsVersion.UNSUPPORTED) .map(v -> String.join(", ", v.getSupportedVersions())).collect(Collectors.toList()), ", ") + "!"); getPluginLoader().disablePlugin(this); return; } - if (!DisguiseConfig.isNeverUpdateProtocolLib() && DisguiseUtilities.isProtocolLibOutdated()) { - String requiredProtocolLib = StringUtils.join(DisguiseUtilities.getProtocolLibRequiredVersion(), " or build #"); - String version = Bukkit.getPluginManager().getPlugin("ProtocolLib").getDescription().getVersion(); - - BukkitRunnable runnable = createProtocolLibOutdatedRunnable(version, requiredProtocolLib); - runnable.run(); - runnable.runTaskTimer(this, 20, 10 * 60 * 20); - } + startOutdatedPacketevents(); // If this is a release build, even if jenkins build.. if (isReleaseBuild()) { @@ -280,60 +218,12 @@ public class LibsDisguises extends JavaPlugin { DisguiseConfig.setUsingReleaseBuilds(false); } - ClassMappings.loadMappingsCache(getDataFolder()); - - ReflectionManager.init(); - - PacketsManager.init(); - DisguiseUtilities.init(); - - new SoundManager().load(); - - ReflectionManager.registerValues(); - DisguiseParser.createDefaultMethods(); - - ParamInfoManager.getParamInfoSoundGroup().recalculate(); + runBackendStuff(); DisguiseConfig.loadConfig(); - PacketsManager.addPacketListeners(); - - listener = new DisguiseListener(this); - skinHandler = new PlayerSkinHandler(); - - Bukkit.getPluginManager().registerEvents(getSkinHandler(), LibsDisguises.getInstance()); - - if (NmsVersion.v1_18.isSupported()) { - Bukkit.getPluginManager().registerEvents(new DisguiseListener1_18(), this); - } - - if (DisguiseUtilities.isRunningPaper()) { - Bukkit.getPluginManager().registerEvents(new PaperDisguiseListener(), this); - } - - registerCommand("libsdisguises", new LibsDisguisesCommand()); - registerCommand("disguise", new DisguiseCommand()); - registerCommand("undisguise", new UndisguiseCommand()); - registerCommand("disguiseplayer", new DisguisePlayerCommand()); - registerCommand("undisguiseplayer", new UndisguisePlayerCommand()); - registerCommand("undisguiseentity", new UndisguiseEntityCommand()); - registerCommand("disguiseentity", new DisguiseEntityCommand()); - registerCommand("disguiseradius", new DisguiseRadiusCommand()); - registerCommand("undisguiseradius", new UndisguiseRadiusCommand()); - registerCommand("disguisehelp", new DisguiseHelpCommand()); - registerCommand("disguiseclone", new DisguiseCloneCommand()); - registerCommand("disguiseviewself", new DisguiseViewSelfCommand()); - registerCommand("disguiseviewbar", new DisguiseViewBarCommand()); - registerCommand("disguisemodify", new DisguiseModifyCommand()); - registerCommand("disguisemodifyentity", new DisguiseModifyEntityCommand()); - registerCommand("disguisemodifyplayer", new DisguiseModifyPlayerCommand()); - registerCommand("disguisemodifyradius", new DisguiseModifyRadiusCommand()); - registerCommand("copydisguise", new CopyDisguiseCommand()); - registerCommand("grabskin", new GrabSkinCommand()); - registerCommand("savedisguise", new SaveDisguiseCommand()); - registerCommand("grabhead", new GrabHeadCommand()); - - unregisterCommands(false); + registerListeners(); + registerCommands(); new MetricsInitalizer(); } catch (Throwable throwable) { @@ -342,15 +232,196 @@ public class LibsDisguises extends JavaPlugin { getUpdateChecker().doUpdate(); } } catch (Throwable t) { - getLogger().severe("Failed to even do a forced update"); + getLogger().severe("Lib's Disguises couldn't update itself"); } throw throwable; } } + private void runBackendStuff() { + ClassMappings.loadMappingsCache(getDataFolder()); + + if (SpigotReflectionUtil.VERSION == null) { + SpigotReflectionUtil.init(); + } + + ReflectionManager.init(); + + PacketsManager.init(); + DisguiseUtilities.init(); + + new SoundManager().load(); + + ReflectionManager.registerValues(); + DisguiseParser.createDefaultMethods(); + + ParamInfoManager.getParamInfoSoundGroup().recalculate(); + } + + private void registerListeners() { + PacketsManager.addPacketListeners(); + + listener = new DisguiseListener(this); + skinHandler = new PlayerSkinHandler(); + + Bukkit.getPluginManager().registerEvents(getSkinHandler(), LibsDisguises.getInstance()); + + if (NmsVersion.v1_18.isSupported()) { + Bukkit.getPluginManager().registerEvents(new DisguiseListener1_18(), this); + } + + if (DisguiseUtilities.isRunningPaper()) { + Bukkit.getPluginManager().registerEvents(new PaperDisguiseListener(), this); + } + } + @NotNull - private BukkitRunnable createProtocolLibOutdatedRunnable(String version, String requiredProtocolLib) { + private String getPacketEventsFailedReason(Plugin plugin) { + if (plugin == null) { + return "PacketEvents not installed"; + } else if (!plugin.isEnabled()) { + return "PacketEvents is not enabled"; + } else if (DisguiseUtilities.isPacketEventsOutdated()) { + return "PacketEvents is outdated"; + } + + return "Lib's Disguises couldn't access PacketEvents properly"; + } + + private void runWarnings() { + if (Bukkit.getVersion().contains("(MC: 1.17)")) { + getLogger().severe("Please update from MC 1.17! You should be using 1.17.1!"); + } + + if (Bukkit.getVersion().contains("(MC: 1.18)") || Bukkit.getVersion().contains("(MC: 1.18.1)")) { + getLogger().severe( + "Please update from MC 1.18 and MC 1.18.1! You should be using 1.18.2! Support will eventually be dropped for your " + + "specific version!"); + } + + if (Bukkit.getVersion().contains("(MC: 1.19)")) { + getLogger().severe( + "Please update from MC 1.19.0! You should be using at least 1.19.3! 1.19.1 is the lowest supported 1.19 version!"); + } + + try { + Class cl = Class.forName("org.bukkit.Server$Spigot"); + } catch (ClassNotFoundException e) { + getLogger().severe( + "Oh dear, you seem to be using CraftBukkit. Please use Spigot or Paper instead! This plugin will continue to load, " + + "but it will look like a mugging victim"); + } + } + + private void updateOldDisguisesYaml() { + File disguiseFile = new File(getDataFolder(), "configs/disguises.yml"); + + if (!disguiseFile.exists()) { + disguiseFile.getParentFile().mkdirs(); + + File oldFile = new File(getDataFolder(), "disguises.yml"); + + if (oldFile.exists()) { + oldFile.renameTo(disguiseFile); + } else { + saveResource("configs/disguises.yml", false); + } + } + } + + private void loadYamlWarnVirus() throws IOException { + YamlConfiguration pluginYml = ReflectionManager.getPluginYAML(getFile()); + buildNumber = StringUtils.stripToNull(pluginYml.getString("build-number")); + buildDate = StringUtils.stripToNull(pluginYml.getString("build-date")); + + int fileCount = ReflectionManager.getJarFileCount(getFile(), CompileMethods.ignoredDirectories()); + int expected = pluginYml.getInt("file-count", fileCount); + + if (fileCount != expected) { + getLogger().severe("Lib's Disguises may be infected with malware, there were " + (fileCount - expected) + + " unknown files injected into the jar. Please redownload from a trusted source such as SpigotMC. If this warning " + + "shows even after updating, try https://www.spigotmc.org/resources/spigot-anti-malware.64982/ but you will likely " + + "need to reinstall all your plugins, jars, etc as just one infected plugin will infect everything else when it loads."); + getLogger().severe( + "This normally happens when a server owner is tricked into adding third party plugins. Please note that Lib's " + + "Disguises is only detecting this and doesn't know what plugins are infected, only that Lib's Disguises itself " + + "has been infected"); + } + } + + private void logInfo() { + getLogger().info("File Name: " + getFile().getName()); + + String nmsPackageName = ReflectionManager.getNmsPackage(); + + if (nmsPackageName.isEmpty()) { + nmsPackageName = "{Not package relocated}"; + } + + getLogger().info("Discovered nms version: (Package: " + nmsPackageName + ") (LD: " + ReflectionManager.getVersion() + ") (MC: " + + ReflectionManager.getMinecraftVersion() + ")"); + + getLogger().info("Jenkins Build: " + (isNumberedBuild() ? "#" : "") + getBuildNo()); + + getLogger().info("Build Date: " + buildDate); + } + + private void someMoreLogging() { + if (!LibsPremium.isPremium()) { + getLogger().info( + "You are running the free version, commands limited to non-players and operators. (Console, Command Blocks, Admins)"); + } + + // Add a message so people are more aware + if (!DisguiseConfig.isTallSelfDisguises()) { + DisguiseUtilities.getLogger().info( + "Config 'TallSelfDisguises' is set to 'false', LD will hide oversized disguises from self disguise. https://www" + + ".spigotmc.org/wiki/lib-s-disguises-faq/#tall-disguises-self-disguises"); + } + } + + private void startOutdatedPacketevents() { + if (!DisguiseConfig.isNeverUpdatePacketEvents() && DisguiseUtilities.isPacketEventsOutdated()) { + String requiredPacketEvents = PacketEventsUpdater.getMinimumPacketEventsVersion(); + String version = Bukkit.getPluginManager().getPlugin("packetevents").getDescription().getVersion(); + + BukkitRunnable runnable = createPacketEventsOutdatedRunnable(version, requiredPacketEvents); + runnable.run(); + runnable.runTaskTimer(this, 20, 10 * 60 * 20); + } + + PacketEventsUpdater.doShadedWarning(); + } + + private void registerCommands() { + registerCommand("libsdisguises", new LibsDisguisesCommand()); + registerCommand("disguise", new DisguiseCommand()); + registerCommand("undisguise", new UndisguiseCommand()); + registerCommand("disguiseplayer", new DisguisePlayerCommand()); + registerCommand("undisguiseplayer", new UndisguisePlayerCommand()); + registerCommand("undisguiseentity", new UndisguiseEntityCommand()); + registerCommand("disguiseentity", new DisguiseEntityCommand()); + registerCommand("disguiseradius", new DisguiseRadiusCommand()); + registerCommand("undisguiseradius", new UndisguiseRadiusCommand()); + registerCommand("disguisehelp", new DisguiseHelpCommand()); + registerCommand("disguiseclone", new DisguiseCloneCommand()); + registerCommand("disguiseviewself", new DisguiseViewSelfCommand()); + registerCommand("disguiseviewbar", new DisguiseViewBarCommand()); + registerCommand("disguisemodify", new DisguiseModifyCommand()); + registerCommand("disguisemodifyentity", new DisguiseModifyEntityCommand()); + registerCommand("disguisemodifyplayer", new DisguiseModifyPlayerCommand()); + registerCommand("disguisemodifyradius", new DisguiseModifyRadiusCommand()); + registerCommand("copydisguise", new CopyDisguiseCommand()); + registerCommand("grabskin", new GrabSkinCommand()); + registerCommand("savedisguise", new SaveDisguiseCommand()); + registerCommand("grabhead", new GrabHeadCommand()); + + unregisterCommands(false); + } + + @NotNull + private BukkitRunnable createPacketEventsOutdatedRunnable(String version, String requiredPacketEvents) { return new BukkitRunnable() { private int timesRun; @@ -358,17 +429,16 @@ public class LibsDisguises extends JavaPlugin { public void run() { getLogger().severe("!! May I have your attention please !!"); - if (DisguiseUtilities.isProtocollibUpdateDownloaded()) { + if (isPacketEventsUpdateDownloaded()) { getLogger().severe( - "An update for ProtocolLib has been downloaded and will be installed when the server restarts. When possible, " + - "please restart " + "the server. Lib's Disguises may not work correctly until you do so."); + "An update for PacketEvents has been downloaded and will be installed when the server restarts. When possible, " + + "please restart the server. Lib's Disguises may not work correctly until you do so."); } else { getLogger().severe( - "Update your ProtocolLib! You are running " + version + " but the minimum version you should be on is " + - requiredProtocolLib + "!"); - getLogger().severe( - "https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/artifact/target" + "/ProtocolLib" + ".jar"); - getLogger().severe("Or! Use /ld protocollib - To update to the latest development build"); + "Update your PacketEvents! You are running " + version + " but the minimum version you should be on is " + + requiredPacketEvents + "!"); + getLogger().severe("https://www.spigotmc.org/resources/packetevents-api.80279/"); + getLogger().severe("Or! Use /ld packetevents - To have Lib's Disguises download the latest release from Modrinth"); } if (timesRun++ > 0) { @@ -457,25 +527,4 @@ public class LibsDisguises extends JavaPlugin { command.setTabCompleter((TabCompleter) executioner); } } - - /** - * Reloads the config with new config options. - */ - @Deprecated - public void reload() { - DisguiseConfig.loadConfig(); - } - - public DisguiseListener getListener() { - return listener; - } - - /** - * External APIs shouldn't actually need this instance. DisguiseAPI should be enough to handle most cases. - * - * @return The instance of this plugin - */ - public static LibsDisguises getInstance() { - return instance; - } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/DisguiseBaseCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/DisguiseBaseCommand.java index 5f3302b3..11fbc785 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/DisguiseBaseCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/DisguiseBaseCommand.java @@ -1,6 +1,6 @@ package me.libraryaddict.disguise.commands; -import com.comphenix.protocol.ProtocolLibrary; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import me.libraryaddict.disguise.DisguiseConfig; @@ -13,6 +13,7 @@ import me.libraryaddict.disguise.commands.modify.DisguiseModifyEntityCommand; import me.libraryaddict.disguise.commands.modify.DisguiseModifyPlayerCommand; import me.libraryaddict.disguise.commands.modify.DisguiseModifyRadiusCommand; import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.disguisetypes.watchers.MinecartWatcher; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.params.ParamInfo; @@ -22,7 +23,7 @@ import me.libraryaddict.disguise.utilities.parser.DisguisePerm; import me.libraryaddict.disguise.utilities.parser.DisguisePermissions; import me.libraryaddict.disguise.utilities.parser.WatcherMethod; import me.libraryaddict.disguise.utilities.translations.LibsMsg; -import org.apache.commons.lang.StringUtils; +import me.libraryaddict.disguise.utilities.updates.PacketEventsUpdater; import org.bukkit.Art; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -80,12 +81,12 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { } protected boolean isNotPremium(CommandSender sender) { - String requiredProtocolLib = StringUtils.join(DisguiseUtilities.getProtocolLibRequiredVersion(), " or build #"); - String version = ProtocolLibrary.getPlugin().getDescription().getVersion(); + String requiredPacketEvents = PacketEventsUpdater.getMinimumPacketEventsVersion(); + String version = Bukkit.getPluginManager().getPlugin("packetevents").getDescription().getVersion(); - if (!DisguiseConfig.isNeverUpdateProtocolLib() && DisguiseUtilities.isProtocolLibOutdated() && + if (!DisguiseConfig.isNeverUpdatePacketEvents() && DisguiseUtilities.isPacketEventsOutdated() && sender.hasPermission("libsdisguises.update")) { - DisguiseUtilities.sendProtocolLibUpdateMessage(sender, version, requiredProtocolLib); + DisguiseUtilities.sendPacketEventsUpdateMessage(sender, version, requiredPacketEvents); } // Already sent the message, assign after the previous @@ -155,7 +156,7 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { for (WatcherMethod method : methods) { String arg = allArgs[i]; - if (!method.getName().equalsIgnoreCase(arg)) { + if (!method.getMappedName().equalsIgnoreCase(arg)) { continue; } @@ -181,13 +182,14 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { String methodName = null; if (allArgs.length == startsAt) { - if (disguisePerm.getType() == DisguiseType.FALLING_BLOCK || disguisePerm.getType() == DisguiseType.BLOCK_DISPLAY) { - info = ParamInfoManager.getParamInfoItemBlock(); + if (disguisePerm.getType() == DisguiseType.FALLING_BLOCK || disguisePerm.getType() == DisguiseType.BLOCK_DISPLAY || + MinecartWatcher.class.isAssignableFrom(disguisePerm.getWatcherClass())) { + info = ParamInfoManager.getParamInfo(WrappedBlockState.class); methodName = "setBlock"; } else if (disguisePerm.getType() == DisguiseType.DROPPED_ITEM || disguisePerm.getType() == DisguiseType.ITEM_DISPLAY) { info = ParamInfoManager.getParamInfo(ItemStack.class); methodName = "setItemStack"; - } else if (disguisePerm.getType() == DisguiseType.ITEM_FRAME) { + } else if (disguisePerm.getType() == DisguiseType.ITEM_FRAME || disguisePerm.getType() == DisguiseType.GLOW_ITEM_FRAME) { info = ParamInfoManager.getParamInfo(ItemStack.class); methodName = "setItem"; } else if (disguisePerm.getType() == DisguiseType.PAINTING) { @@ -207,7 +209,7 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { // Enderman can't hold non-blocks if (disguisePerm.getType() == DisguiseType.ENDERMAN && prevArg.equalsIgnoreCase("setItemInMainHand")) { - info = ParamInfoManager.getParamInfoItemBlock(); + info = ParamInfoManager.getParamInfo(WrappedBlockState.class); } } @@ -216,7 +218,7 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { Collection wantToUse = null; // If there is a list of default values - if (info.hasValues()) { + if (info.hasTabCompletion()) { wantToUse = info.getEnums(currentArg); } else if (info.isParam(String.class)) { wantToUse = new ArrayList<>(); @@ -253,12 +255,12 @@ public abstract class DisguiseBaseCommand implements CommandExecutor { if (addMethods) { // If this is a method, add. Else if it can be a param of the previous argument, add. for (WatcherMethod method : ParamInfoManager.getDisguiseWatcherMethods(disguisePerm.getWatcherClass())) { - if (!perms.isAllowedDisguise(disguisePerm, Collections.singletonList(method.getName())) || - !method.isUsable(disguisePerm.getType())) { + if (!perms.isAllowedDisguise(disguisePerm, Collections.singletonList(method.getMappedName())) || + method.isHidden(disguisePerm.getType())) { continue; } - tabs.add(method.getName()); + tabs.add(method.getMappedName()); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java index 21997d60..891a48cc 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java @@ -6,6 +6,7 @@ import me.libraryaddict.disguise.commands.libsdisguises.LDChangelog; import me.libraryaddict.disguise.commands.libsdisguises.LDCommand; import me.libraryaddict.disguise.commands.libsdisguises.LDConfig; import me.libraryaddict.disguise.commands.libsdisguises.LDCount; +import me.libraryaddict.disguise.commands.libsdisguises.LDDebugDisguiseLoop; import me.libraryaddict.disguise.commands.libsdisguises.LDDebugMineSkin; import me.libraryaddict.disguise.commands.libsdisguises.LDDebugPlayer; import me.libraryaddict.disguise.commands.libsdisguises.LDHelp; @@ -16,7 +17,7 @@ import me.libraryaddict.disguise.commands.libsdisguises.LDPermTest; import me.libraryaddict.disguise.commands.libsdisguises.LDReload; import me.libraryaddict.disguise.commands.libsdisguises.LDScoreboard; import me.libraryaddict.disguise.commands.libsdisguises.LDUpdate; -import me.libraryaddict.disguise.commands.libsdisguises.LDUpdateProtocolLib; +import me.libraryaddict.disguise.commands.libsdisguises.LDUpdatePacketEvents; import me.libraryaddict.disguise.commands.libsdisguises.LDUploadLogs; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.translations.LibsMsg; @@ -49,8 +50,9 @@ public class LibsDisguisesCommand implements CommandExecutor, TabCompleter { getCommands().add(new LDMetaInfo()); getCommands().add(new LDDebugPlayer()); getCommands().add(new LDUploadLogs()); - getCommands().add(new LDUpdateProtocolLib()); + getCommands().add(new LDUpdatePacketEvents()); getCommands().add(new LDDebugMineSkin()); + getCommands().add(new LDDebugDisguiseLoop()); } protected ArrayList filterTabs(ArrayList list, String[] origArgs) { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/disguise/DisguiseRadiusCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/disguise/DisguiseRadiusCommand.java index c3e27249..f5f49407 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/disguise/DisguiseRadiusCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/disguise/DisguiseRadiusCommand.java @@ -12,7 +12,6 @@ import me.libraryaddict.disguise.utilities.parser.DisguisePermissions; import me.libraryaddict.disguise.utilities.translations.LibsMsg; import me.libraryaddict.disguise.utilities.translations.TranslateType; import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.Command; @@ -80,8 +79,7 @@ public class DisguiseRadiusCommand extends DisguiseBaseCommand implements TabCom Collections.sort(classes); - LibsMsg.DRADIUS_ENTITIES.send(sender, - ChatColor.GREEN + StringUtils.join(classes, ChatColor.DARK_GREEN + ", " + ChatColor.GREEN)); + LibsMsg.DRADIUS_ENTITIES.send(sender, StringUtils.join(classes, LibsMsg.DRADIUS_JOINER.getRaw())); return true; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDCommand.java index 6fbf4bae..c318fcc1 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDCommand.java @@ -18,4 +18,8 @@ public interface LDCommand { void onCommand(CommandSender sender, String[] args); LibsMsg getHelp(); + + default boolean isEnabled() { + return true; + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDDebugDisguiseLoop.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDDebugDisguiseLoop.java new file mode 100644 index 00000000..1fc5809b --- /dev/null +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDDebugDisguiseLoop.java @@ -0,0 +1,125 @@ +package me.libraryaddict.disguise.commands.libsdisguises; + +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.LibsDisguises; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.utilities.DisguiseUtilities; +import me.libraryaddict.disguise.utilities.translations.LibsMsg; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * Created by libraryaddict on 22/05/2021. + */ +public class LDDebugDisguiseLoop implements LDCommand { + @Override + public List getTabComplete() { + return Collections.singletonList("disguiseloop"); + } + + @Override + public boolean hasPermission(CommandSender sender) { + return sender.isOp(); + } + + @Override + public String getPermission() { + return "libsdisguises.disguise"; + } + + @Override + public boolean isEnabled() { + return !LibsDisguises.getInstance().isNumberedBuild(); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + + "Must be a player to use this command, if you're seeing this then you clearly don't know what this command is for and " + + "wouldn't benefit from using it."); + return; + } else if (args.length != 2 || !args[1].equalsIgnoreCase("agree")) { + sender.sendMessage(ChatColor.RED + + "This is for debugging and is meant to loop over every disguise and disguise you to verify if there's any obvious issues." + + " There is no value for you in this command. Type 'agree' into the command to continue."); + return; + } + + Iterator iterator = getDisguisesToRun().iterator(); + + new BukkitRunnable() { + @Override + public void run() { + if (!((Player) sender).isOnline()) { + cancel(); + return; + } + + String command = iterator.next(); + String message = ChatColor.AQUA + "Now disguising " + sender.getName() + " as " + command; + sender.sendMessage(message); + DisguiseUtilities.getLogger().info(message); + + Disguise disguise = DisguiseAPI.getDisguise((Player) sender); + + try { + ((Player) sender).performCommand("disguise " + command); + + if (disguise == DisguiseAPI.getDisguise((Player) sender)) { + DisguiseUtilities.getLogger().info("Looks like '" + command + "' failed."); + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + if (!iterator.hasNext()) { + cancel(); + sender.sendMessage(ChatColor.AQUA + "Command Complete!"); + } + } + } + }.runTaskTimer(LibsDisguises.getInstance(), 5, 5); + } + + @NotNull + private static List getDisguisesToRun() { + List commands = new ArrayList<>(); + + for (DisguiseType type : DisguiseType.values()) { + if (type.getEntityType() == null || type.isUnknown() || type.isCustom()) { + continue; + } + + String command; + + switch (type) { + case PLAYER: + command = "player libraryaddict"; + break; + case DROPPED_ITEM: + command = "dropped_item grass"; + break; + default: + command = type.name(); + break; + } + + commands.add(command); + } + return commands; + } + + @Override + public LibsMsg getHelp() { + return LibsMsg.LD_DEBUG_MINESKIN; + } +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDJson.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDJson.java index 5fc02338..82696d00 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDJson.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDJson.java @@ -1,9 +1,8 @@ package me.libraryaddict.disguise.commands.libsdisguises; -import com.comphenix.protocol.wrappers.nbt.NbtFactory; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.params.ParamInfoManager; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.ItemStackSerializer; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.translations.LibsMsg; import net.md_5.bungee.api.chat.ClickEvent; @@ -14,7 +13,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -48,27 +46,7 @@ public class LDJson implements LDCommand { // item amount data {nbt} String itemName = ReflectionManager.getItemName(item.getType()); - ArrayList mcArray = new ArrayList<>(); - - if (NmsVersion.v1_13.isSupported() && item.hasItemMeta()) { - mcArray.add(itemName + DisguiseUtilities.serialize(NbtFactory.fromItemTag(item))); - } else { - mcArray.add(itemName); - } - - if (item.getAmount() != 1) { - mcArray.add(String.valueOf(item.getAmount())); - } - - if (!NmsVersion.v1_13.isSupported()) { - if (item.getDurability() != 0) { - mcArray.add(String.valueOf(item.getDurability())); - } - - if (item.hasItemMeta()) { - mcArray.add(DisguiseUtilities.serialize(NbtFactory.fromItemTag(item))); - } - } + List mcArray = ItemStackSerializer.serialize(item); String ldItem = StringUtils.join(mcArray, "-"); String mcItem = StringUtils.join(mcArray, " "); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDScoreboard.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDScoreboard.java index c21cd2a4..f7ee0293 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDScoreboard.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDScoreboard.java @@ -1,19 +1,12 @@ package me.libraryaddict.disguise.commands.libsdisguises; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketListener; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import me.libraryaddict.disguise.disguisetypes.TargetedDisguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.translations.LibsMsg; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -26,7 +19,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; /** * Created by libraryaddict on 20/04/2020. @@ -128,47 +120,6 @@ public class LDScoreboard implements LDCommand { LibsMsg.LIBS_SCOREBOARD_NAMES_DISABLED.send(sender); } - List listeners = ProtocolLibrary.getProtocolManager().getPacketListeners().stream().filter( - listener -> listener.getPlugin() != LibsDisguises.getInstance() && - listener.getSendingWhitelist().getTypes().contains(PacketType.Play.Server.SCOREBOARD_TEAM)).collect(Collectors.toList()); - - if (!listeners.isEmpty()) { - ComponentBuilder builder = new ComponentBuilder(""); - builder.append( - "The following plugins are listening for scoreboard teams using ProtocolLib, and could be modifying collisions: "); - builder.color(net.md_5.bungee.api.ChatColor.BLUE); - - boolean comma = false; - - for (PacketListener listener : listeners) { - if (comma) { - builder.reset(); - builder.append(", "); - builder.color(net.md_5.bungee.api.ChatColor.BLUE); - } - - comma = true; - - builder.reset(); - builder.append(listener.getPlugin().getName()); - builder.color(net.md_5.bungee.api.ChatColor.AQUA); - - String plugin = ChatColor.GOLD + "Plugin: " + ChatColor.YELLOW + listener.getPlugin().getName() + " v" + - listener.getPlugin().getDescription().getVersion(); - String listenerClass = ChatColor.GOLD + "Listener: " + ChatColor.YELLOW + listener.getClass(); - String packets = - ChatColor.GOLD + "Packets: " + ChatColor.YELLOW + StringUtils.join(listener.getSendingWhitelist().getTypes(), ", "); - String priority = ChatColor.GOLD + "Priority: " + ChatColor.YELLOW + listener.getSendingWhitelist().getPriority(); - String options = - ChatColor.GOLD + "Options: " + ChatColor.YELLOW + StringUtils.join(listener.getSendingWhitelist().getOptions(), ", "); - - builder.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, - TextComponent.fromLegacyText(plugin + "\n" + listenerClass + "\n" + packets + "\n" + priority + "\n" + options))); - } - - sender.spigot().sendMessage(builder.create()); - } - LibsMsg.LIBS_SCOREBOARD_IGNORE_TEST.send(sender); sender.sendMessage(ChatColor.RED + diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdateProtocolLib.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdatePacketEvents.java similarity index 61% rename from plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdateProtocolLib.java rename to plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdatePacketEvents.java index cbe05d4f..82bfc870 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdateProtocolLib.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUpdatePacketEvents.java @@ -1,13 +1,12 @@ package me.libraryaddict.disguise.commands.libsdisguises; import me.libraryaddict.disguise.LibsDisguises; -import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.translations.LibsMsg; +import me.libraryaddict.disguise.utilities.updates.PacketEventsUpdater; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.scheduler.BukkitRunnable; -import java.io.File; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -15,12 +14,12 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * Created by libraryaddict on 30/06/2020. */ -public class LDUpdateProtocolLib implements LDCommand { +public class LDUpdatePacketEvents implements LDCommand { private final AtomicBoolean updateInProgress = new AtomicBoolean(false); @Override public List getTabComplete() { - return Arrays.asList("updateprotocollib", "updatepl", "protocollib"); + return Arrays.asList("updatepacketevents", "updatepe", "packetevents"); } @Override @@ -33,27 +32,35 @@ public class LDUpdateProtocolLib implements LDCommand { return null; } + private void sendMessage(CommandSender sender, String message) { + sender.sendMessage(ChatColor.DARK_RED + "[LibsDisguises] " + ChatColor.RED + message); + } + @Override public void onCommand(CommandSender sender, String[] args) { if (updateInProgress.get()) { - sender.sendMessage(ChatColor.RED + "Update already in progress"); + sendMessage(sender, "Update already in progress"); return; } - sender.sendMessage(ChatColor.RED + "Please hold, now downloading ProtocolLib.."); + sendMessage(sender, "Please hold, now downloading PacketEvents.."); new BukkitRunnable() { @Override public void run() { - File protocolLibFile = null; + PacketEventsUpdater updater = new PacketEventsUpdater(); try { - DisguiseUtilities.updateProtocolLib(); + boolean outcome = updater.doUpdate(); new BukkitRunnable() { @Override public void run() { - sender.sendMessage(ChatColor.RED + "Download success! Restart server to finish update!"); + if (outcome) { + sendMessage(sender, "Download success! Restart server to finish update!"); + } else { + sendMessage(sender, "Update failed, you may need to update PacketEvents"); + } } }.runTask(LibsDisguises.getInstance()); } catch (Exception ex) { @@ -62,11 +69,7 @@ public class LDUpdateProtocolLib implements LDCommand { new BukkitRunnable() { @Override public void run() { - sender.sendMessage(ChatColor.RED + - "Looks like ProtocolLib's site may be down! MythicCraft/MythicMobs has a discord server https://discord" + - ".gg/EErRhJ4qgx you" + - " can join. Check the pins in #libs-support for a ProtocolLib.jar you can download!"); - sender.sendMessage(ChatColor.RED + "Update failed, " + ex.getMessage()); + sendMessage(sender, "Update failed, " + ex.getMessage()); } }.runTask(LibsDisguises.getInstance()); } finally { @@ -78,6 +81,6 @@ public class LDUpdateProtocolLib implements LDCommand { @Override public LibsMsg getHelp() { - return LibsMsg.LD_COMMAND_UPDATEPROTOCOLLIB; + return LibsMsg.LD_COMMAND_UPDATE_PACKET_EVENTS; } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUploadLogs.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUploadLogs.java index eb7d7d05..f916e063 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUploadLogs.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/libsdisguises/LDUploadLogs.java @@ -57,41 +57,45 @@ public class LDUploadLogs implements LDCommand { URL url = new URL("https://api.mclo.gs/1/log"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); - con.setRequestMethod("POST"); - con.setRequestProperty("User-Agent", "Mozilla/5.0"); + try { + con.setRequestMethod("POST"); + con.setRequestProperty("User-Agent", "Mozilla/5.0"); - List> params = new LinkedList<>(); - params.add(new SimpleEntry<>("api_paste_code", text)); + List> params = new LinkedList<>(); + params.add(new SimpleEntry<>("api_paste_code", text)); - StringBuilder output = new StringBuilder(); + StringBuilder output = new StringBuilder(); - output.append(URLEncoder.encode("content", "UTF-8")); - output.append('='); - output.append(URLEncoder.encode(text, "UTF-8")); + output.append(URLEncoder.encode("content", "UTF-8")); + output.append('='); + output.append(URLEncoder.encode(text, "UTF-8")); - con.setDoOutput(true); - try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) { - dos.writeBytes(output.toString()); - dos.flush(); - } - - int status = con.getResponseCode(); - - if (status >= 200 && status < 300) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { - String inputLine; - StringBuilder response = new StringBuilder(); - - while ((inputLine = br.readLine()) != null) { - response.append(inputLine); - } - - MCLogs logs = new Gson().fromJson(response.toString(), MCLogs.class); - - return new URL(logs.url); + con.setDoOutput(true); + try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) { + dos.writeBytes(output.toString()); + dos.flush(); } - } else { - throw new IllegalStateException("Unexpected response code " + status); + + int status = con.getResponseCode(); + + if (status >= 200 && status < 300) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + String inputLine; + StringBuilder response = new StringBuilder(); + + while ((inputLine = br.readLine()) != null) { + response.append(inputLine); + } + + MCLogs logs = new Gson().fromJson(response.toString(), MCLogs.class); + + return new URL(logs.url); + } + } else { + throw new IllegalStateException("Unexpected response code " + status); + } + } finally { + con.disconnect(); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/modify/DisguiseModifyRadiusCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/modify/DisguiseModifyRadiusCommand.java index 01c57e62..e00793c5 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/modify/DisguiseModifyRadiusCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/modify/DisguiseModifyRadiusCommand.java @@ -265,7 +265,7 @@ public class DisguiseModifyRadiusCommand extends DisguiseBaseCommand implements for (WatcherMethod method : ParamInfoManager.getDisguiseWatcherMethods(disguiseType.getWatcherClass())) { for (String arg : args) { - if (!method.getName().equalsIgnoreCase(arg) || usedOptions.contains(arg)) { + if (!method.getMappedName().equalsIgnoreCase(arg) || usedOptions.contains(arg)) { continue; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/CopyDisguiseCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/CopyDisguiseCommand.java index 18a59697..1cf74042 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/CopyDisguiseCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/CopyDisguiseCommand.java @@ -9,10 +9,11 @@ import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.parser.DisguiseParser; +import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.translations.LibsMsg; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.HoverEvent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent.Builder; +import libsdisg.shaded.net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -21,7 +22,9 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.UUID; /** @@ -87,17 +90,33 @@ public class CopyDisguiseCommand implements CommandExecutor { return true; } - public void sendMessage(CommandSender sender, LibsMsg msg, LibsMsg oldVer, String string, boolean forceAbbrev) { - /* if (!NmsVersion.v1_13.isSupported()) { - oldVer.send(sender, string); - return; - }*/ + private Component createComponent(String text, int section, int max) { + Component component = LibsMsg.CLICK_COPY.getAdv(section); - ComponentBuilder builder = new ComponentBuilder("").append(msg.getBase()).append(" "); + if (NmsVersion.v1_15.isSupported()) { + component = component.clickEvent(net.kyori.adventure.text.event.ClickEvent.copyToClipboard(text)); + } else { + component = component.clickEvent(net.kyori.adventure.text.event.ClickEvent.suggestCommand(text)); + } + + LibsMsg hover = NmsVersion.v1_15.isSupported() ? LibsMsg.CLICK_TO_COPY_HOVER_CLIPBOARD : LibsMsg.CLICK_TO_COPY_HOVER; + Component hoverText = hover.getAdv(section, max, DisguiseUtilities.getMiniMessage().escapeTags(text)); + component = component.hoverEvent(net.kyori.adventure.text.event.HoverEvent.showText(hoverText)); + + return component; + } + + public void sendMessage(CommandSender sender, LibsMsg msg, LibsMsg oldVer, String string, boolean forceAbbrev) { + Builder builder = Component.text().append(msg.getAdv()).appendSpace(); if (string.length() > 256 || forceAbbrev) { String[] split = DisguiseUtilities.split(string); + // Because the splitter removes the quotes.. + for (int i = 0; i < split.length; i++) { + split[i] = DisguiseUtilities.quote(split[i]); + } + for (int i = 0; i < split.length; i++) { if (split[i].length() <= 256) { continue; @@ -113,7 +132,7 @@ public class CopyDisguiseCommand implements CommandExecutor { split[i] = split[i].substring(0, 256); } - int sections = 0; + List sections = new ArrayList<>(); StringBuilder current = new StringBuilder(); for (int i = 0; i < split.length; i++) { @@ -128,26 +147,26 @@ public class CopyDisguiseCommand implements CommandExecutor { continue; } - if (sections != 0) { - builder.append(" "); - builder.reset(); + // Have non-final end with a space + if (i + 1 < split.length) { + current.append(" "); } - sections++; - - builder.append(LibsMsg.CLICK_COPY.getBase(sections)); - builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, current.toString())); - builder.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, - new ComponentBuilder("").append(LibsMsg.CLICK_TO_COPY_HOVER.getBase()).append(" " + sections).create())); - + sections.add(current.toString()); current = new StringBuilder(); } + + for (int i = 0; i < sections.size(); i++) { + if (i > 0) { + builder.appendSpace(); + } + + builder.append(createComponent(sections.get(i), i + 1, sections.size())); + } } else { - builder.append(LibsMsg.CLICK_COPY.getBase(string)); - builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, string)); - builder.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, LibsMsg.CLICK_TO_COPY_HOVER.getBase())); + builder.append(createComponent(string, 1, 1)); } - sender.spigot().sendMessage(builder.create()); + DisguiseUtilities.sendMessage(sender, builder.build()); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseHelpCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseHelpCommand.java index 0837f989..526f0d0f 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseHelpCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseHelpCommand.java @@ -47,7 +47,7 @@ public class DisguiseHelpCommand extends DisguiseBaseCommand implements TabCompl } if (help != null) { - if (help.hasValues() && help.canTranslateValues()) { + if (help.hasTabCompletion() && help.canTranslateValues()) { LibsMsg.DHELP_HELP4.send(sender, help.getName(), StringUtils.join(help.getEnums(""), LibsMsg.DHELP_HELP4_SEPERATOR.get())); } else { @@ -79,12 +79,12 @@ public class DisguiseHelpCommand extends DisguiseBaseCommand implements TabCompl try { for (WatcherMethod method : ParamInfoManager.getDisguiseWatcherMethods(watcher)) { - if (!method.isUsable(type.getType())) { + if (method.isHidden(type.getType())) { continue; } if (args.length < 2 || !args[1].equalsIgnoreCase(LibsMsg.DHELP_SHOW.get())) { - if (!perms.isAllowedDisguise(type, Collections.singleton(method.getName().toLowerCase(Locale.ENGLISH)))) { + if (!perms.isAllowedDisguise(type, Collections.singleton(method.getMappedName().toLowerCase(Locale.ENGLISH)))) { ignored++; continue; } @@ -93,18 +93,19 @@ public class DisguiseHelpCommand extends DisguiseBaseCommand implements TabCompl ParamInfo info = ParamInfoManager.getParamInfo(method); int value = ParamInfoManager.getValue(method); - ChatColor methodColor = ChatColor.YELLOW; + LibsMsg methodC = LibsMsg.DHELP_OPTIONS_METHOD_VERY_SPECIFIC; if (value == 1) { - methodColor = ChatColor.AQUA; + methodC = LibsMsg.DHELP_OPTIONS_METHOD_SOMEWHAT_SPECIFIC; } else if (value == 2) { - methodColor = ChatColor.GRAY; + methodC = LibsMsg.DHELP_OPTIONS_METHOD_GENERIC; } - String str = TranslateType.DISGUISE_OPTIONS.get(method.getName()) + ChatColor.DARK_RED + "(" + ChatColor.GREEN + - info.getName() + ChatColor.DARK_RED + ")"; + String str = + LibsMsg.DHELP_OPTIONS_METHOD.get(methodC.get(TranslateType.DISGUISE_OPTIONS.get(method.getMappedName())), + info.getName()); - methods.add(methodColor + str); + methods.add(str); } } catch (Exception ex) { ex.printStackTrace(); @@ -114,8 +115,7 @@ public class DisguiseHelpCommand extends DisguiseBaseCommand implements TabCompl methods.add(LibsMsg.DHELP_NO_OPTIONS.get()); } - LibsMsg.DHELP_OPTIONS.send(sender, ChatColor.DARK_RED + type.toReadable(), - StringUtils.join(methods, ChatColor.DARK_RED + ", ")); + LibsMsg.DHELP_OPTIONS.send(sender, type.toReadable(), StringUtils.join(methods, LibsMsg.DHELP_OPTIONS_JOINER.getRaw())); if (ignored > 0) { LibsMsg.NO_PERMS_USE_OPTIONS.send(sender, ignored); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseViewSelfCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseViewSelfCommand.java index 111ad161..ff7e05ba 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseViewSelfCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/DisguiseViewSelfCommand.java @@ -1,20 +1,28 @@ package me.libraryaddict.disguise.commands.utils; import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.disguisetypes.TargetedDisguise; +import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.translations.LibsMsg; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + /** * @author Navid */ public class DisguiseViewSelfCommand implements CommandExecutor { + private List> warnedTall = new ArrayList<>(); @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { + if (!(sender instanceof Player)) { LibsMsg.NO_CONSOLE.send(sender); return true; } @@ -27,6 +35,15 @@ public class DisguiseViewSelfCommand implements CommandExecutor { } else { DisguiseAPI.setViewDisguiseToggled(player, true); LibsMsg.VIEW_SELF_ON.send(sender); + + TargetedDisguise disguise = (TargetedDisguise) DisguiseAPI.getDisguise(player, player); + + // If they're disguised, tall disguises are hidden, it's a tall disguise + // Then tell the player, it's not a bug! The disguise is too tall + if (disguise != null && !disguise.isTallDisguisesVisible() && disguise.canSee(player) && + DisguiseUtilities.isTallDisguise(disguise)) { + LibsMsg.VIEW_SELF_TALL_NOTE.send(player); + } } return true; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabHeadCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabHeadCommand.java index 4f5bccb0..6803897b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabHeadCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabHeadCommand.java @@ -1,10 +1,12 @@ package me.libraryaddict.disguise.commands.utils; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.SkinUtils; +import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.translations.LibsMsg; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; @@ -15,6 +17,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.profile.PlayerProfile; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; @@ -80,7 +83,7 @@ public class GrabHeadCommand implements CommandExecutor { } @Override - public void onSuccess(WrappedGameProfile profile) { + public void onSuccess(UserProfile profile) { runnable.cancel(); DisguiseUtilities.doSkinUUIDWarning(sender); @@ -92,12 +95,18 @@ public class GrabHeadCommand implements CommandExecutor { ItemStack skull = new ItemStack(Material.PLAYER_HEAD); SkullMeta meta = (SkullMeta) skull.getItemMeta(); - try { - Field field = meta.getClass().getDeclaredField("profile"); - field.setAccessible(true); - field.set(meta, profile.getHandle()); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); + if (NmsVersion.v1_18.isSupported()) { + PlayerProfile playerProfile = ReflectionManager.createProfile(profile); + + meta.setOwnerProfile(playerProfile); + } else { + try { + Field field = meta.getClass().getDeclaredField("profile"); + field.setAccessible(true); + field.set(meta, ReflectionManager.convertProfile(profile)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } } skull.setItemMeta(meta); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabSkinCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabSkinCommand.java index d81647fc..d7153656 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabSkinCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/GrabSkinCommand.java @@ -1,6 +1,6 @@ package me.libraryaddict.disguise.commands.utils; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.DisguiseUtilities; @@ -68,13 +68,13 @@ public class GrabSkinCommand implements CommandExecutor { tName = skin.substring(start, end); - if (DisguiseUtilities.hasGameProfile(tName)) { + if (DisguiseUtilities.hasUserProfile(tName)) { tName = null; } } String name = - tName != null && tName.toLowerCase(Locale.ROOT).endsWith(":slim") ? tName.substring(0, tName.lastIndexOf(":")) : tName; + tName != null && tName.toLowerCase(Locale.ENGLISH).endsWith(":slim") ? tName.substring(0, tName.lastIndexOf(":")) : tName; if (name != null && name.replaceAll("[_a-zA-Z \\d-@#]", "").length() > 0) { LibsMsg.SKIN_API_INVALID_NAME.send(sender); @@ -102,7 +102,7 @@ public class GrabSkinCommand implements CommandExecutor { } @Override - public void onSuccess(WrappedGameProfile profile) { + public void onSuccess(UserProfile profile) { runnable.cancel(); DisguiseUtilities.doSkinUUIDWarning(sender); @@ -111,7 +111,7 @@ public class GrabSkinCommand implements CommandExecutor { if (nName == null) { int i = 1; - while (DisguiseUtilities.hasGameProfile("skin" + i)) { + while (DisguiseUtilities.hasUserProfile("skin" + i)) { i++; } @@ -119,7 +119,7 @@ public class GrabSkinCommand implements CommandExecutor { } if (profile.getName() == null || !profile.getName().equals(nName)) { - profile = ReflectionManager.getGameProfileWithThisSkin(profile.getUUID(), profile.getName(), profile); + profile = ReflectionManager.getUserProfileWithThisSkin(profile.getUUID(), profile.getName(), profile); } DisguiseAPI.addGameProfile(nName, profile); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/SaveDisguiseCommand.java b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/SaveDisguiseCommand.java index 166b40cc..d4ecd6e3 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/SaveDisguiseCommand.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/commands/utils/SaveDisguiseCommand.java @@ -1,6 +1,6 @@ package me.libraryaddict.disguise.commands.utils; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; @@ -138,7 +138,7 @@ public class SaveDisguiseCommand implements CommandExecutor { } @Override - public void onSuccess(WrappedGameProfile profile) { + public void onSuccess(UserProfile profile) { runnable.cancel(); DisguiseUtilities.doSkinUUIDWarning(sender); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/Disguise.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/Disguise.java index 31ca5746..aa748bc7 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/Disguise.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/Disguise.java @@ -1,8 +1,8 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -18,10 +18,8 @@ import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher; import me.libraryaddict.disguise.events.DisguiseEvent; import me.libraryaddict.disguise.events.UndisguiseEvent; import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.DisguiseValues; import me.libraryaddict.disguise.utilities.LibsPremium; -import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; -import me.libraryaddict.disguise.utilities.reflection.FakeBoundingBox; +import me.libraryaddict.disguise.utilities.parser.AutoGeneratedValue; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.translations.LibsMsg; @@ -48,6 +46,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -131,7 +130,7 @@ public abstract class Disguise { return multiName.length; } - @RandomDefaultValue + @AutoGeneratedValue public void setDisguiseName(String name) { this.disguiseName = name; } @@ -183,16 +182,16 @@ public abstract class Disguise { return; } - ArrayList packets = DisguiseUtilities.getNamePackets(this, oldName); - for (Player player : DisguiseUtilities.getPerverts(this)) { if (!DisguiseUtilities.isFancyHiddenTabs() && isPlayerDisguise() && LibsDisguises.getInstance().getSkinHandler().isSleeping(player, (PlayerDisguise) this)) { continue; } - for (PacketContainer packet : packets) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + List> packets = DisguiseUtilities.getNamePackets(this, oldName); + + for (PacketWrapper packet : packets) { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } } @@ -391,7 +390,7 @@ public abstract class Disguise { return this; } - protected void doActionBar() { + protected void doPeriodicTick() { if (getNotifyBar() == DisguiseConfig.NotifyBar.ACTION_BAR && getEntity() instanceof Player && DisguiseAPI.isNotifyBarShown(getEntity()) && !getEntity().hasPermission("libsdisguises.noactionbar") && DisguiseAPI.getDisguise(getEntity()) == Disguise.this) { @@ -477,27 +476,7 @@ public abstract class Disguise { } private boolean isTallDisguise() { - if (getType().isCustom()) { - return false; - } - - DisguiseValues values = DisguiseValues.getDisguiseValues(getType()); - - if (values == null) { - return false; - } - - FakeBoundingBox box = null; - - if (isMobDisguise() && !((MobDisguise) this).isAdult()) { - box = values.getBabyBox(); - } - - if (box == null) { - box = values.getAdultBox(); - } - - return box != null && !(box.getY() <= 1.7D); + return DisguiseUtilities.isTallDisguise(this); } /** @@ -743,23 +722,25 @@ public abstract class Disguise { PlayerDisguise disguise = (PlayerDisguise) this; if (disguise.isDisplayedInTab()) { - PacketContainer deleteTab = ReflectionManager.createTablistPacket(disguise, PlayerInfoAction.REMOVE_PLAYER); for (Player player : Bukkit.getOnlinePlayers()) { if (!((TargetedDisguise) this).canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab); + PacketWrapper deleteTab = + DisguiseUtilities.createTablistPacket(disguise, WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, deleteTab); } } } if (getInternalArmorstandIds().length > 0) { - PacketContainer packet = DisguiseUtilities.getDestroyPacket(getInternalArmorstandIds()); - for (Player player : getEntity().getWorld().getPlayers()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + PacketWrapper packet = DisguiseUtilities.getDestroyPacket(getInternalArmorstandIds()); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } @@ -783,14 +764,15 @@ public abstract class Disguise { } if (isHidePlayer() && getEntity() instanceof Player && ((Player) getEntity()).isOnline()) { - PacketContainer addTab = ReflectionManager.updateTablistVisibility((Player) getEntity(), true); for (Player player : Bukkit.getOnlinePlayers()) { if (!((TargetedDisguise) this).canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab); + PacketWrapper addTab = DisguiseUtilities.updateTablistVisibility((Player) getEntity(), true); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, addTab); } } @@ -934,7 +916,9 @@ public abstract class Disguise { } }*/ - if (LibsPremium.getUserID().equals("123" + "45") || !LibsMsg.OWNED_BY.getRaw().contains("'")) { + if (LibsPremium.getUserID().equals("123" + "45") || + (LibsPremium.getPaidInformation() != null && LibsPremium.getPaidInformation().getUserID().equals("0")) || + !LibsMsg.OWNED_BY.getRaw().contains("'")) { ((TargetedDisguise) this).setDisguiseTarget(TargetType.HIDE_DISGUISE_TO_EVERYONE_BUT_THESE_PLAYERS); if (getEntity() instanceof Player) { @@ -989,14 +973,15 @@ public abstract class Disguise { PlayerDisguise disguise = (PlayerDisguise) this; if (disguise.isDisplayedInTab()) { - PacketContainer addTab = ReflectionManager.createTablistAddPackets(disguise); for (Player player : Bukkit.getOnlinePlayers()) { if (!((TargetedDisguise) this).canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab); + PacketWrapper addTab = DisguiseUtilities.createTablistAddPackets(disguise); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, addTab); } } } @@ -1020,14 +1005,14 @@ public abstract class Disguise { .scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> DisguiseUtilities.setupFakeDisguise(Disguise.this), 2); if (isHidePlayer() && getEntity() instanceof Player) { - PacketContainer removeTab = ReflectionManager.updateTablistVisibility((Player) getEntity(), false); - for (Player player : Bukkit.getOnlinePlayers()) { if (!((TargetedDisguise) this).canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, removeTab); + PacketWrapper removeTab = DisguiseUtilities.updateTablistVisibility((Player) getEntity(), false); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, removeTab); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseRunnable.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseRunnable.java index db60b739..1efa9042 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseRunnable.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseRunnable.java @@ -1,9 +1,10 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.watchers.BatWatcher; @@ -12,6 +13,7 @@ import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.translations.LibsMsg; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; @@ -76,7 +78,7 @@ class DisguiseRunnable extends BukkitRunnable { if (++actionBarTicks % 15 == 0) { actionBarTicks = 0; - disguise.doActionBar(); + disguise.doPeriodicTick(); } // If entity is no longer valid. Remove it. @@ -126,106 +128,102 @@ class DisguiseRunnable extends BukkitRunnable { doVelocity(vectorY, alwaysSendVelocity); if (disguise.getType() == DisguiseType.EXPERIENCE_ORB) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE); - - packet.getIntegers().write(0, disguise.getEntity().getEntityId()); - for (Player player : DisguiseUtilities.getPerverts(disguise)) { if (disguise.getEntity() != player) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + WrapperPlayServerEntityRelativeMove packet = + new WrapperPlayServerEntityRelativeMove(disguise.getEntity().getEntityId(), 0, 0, 0, true); + + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); continue; } else if (!disguise.isSelfDisguiseVisible() || !(disguise.getEntity() instanceof Player)) { continue; } - PacketContainer selfPacket = packet.shallowClone(); + WrapperPlayServerEntityRelativeMove selfPacket = + new WrapperPlayServerEntityRelativeMove(DisguiseAPI.getSelfDisguiseId(), 0, 0, 0, true); - selfPacket.getModifier().write(0, DisguiseAPI.getSelfDisguiseId()); - - ProtocolLibrary.getProtocolManager().sendServerPacket((Player) disguise.getEntity(), selfPacket, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, selfPacket); } } } private void doVelocity(Double vectorY, boolean alwaysSendVelocity) { // If the vectorY isn't 0. Cos if it is. Then it doesn't want to send any vectors. + if (vectorY == null || !disguise.isVelocitySent()) { + return; + } + + Entity entity = disguise.getEntity(); + // If this disguise has velocity sending enabled and the entity is flying. - if (disguise.isVelocitySent() && vectorY != null && (alwaysSendVelocity || !disguise.getEntity().isOnGround())) { - Vector vector = disguise.getEntity().getVelocity(); + if (!alwaysSendVelocity && entity.isOnGround()) { + return; + } - // If the entity doesn't have velocity changes already - You know. I really can't wrap my - // head about the - // if statement. - // But it doesn't seem to do anything wrong.. - if (vector.getY() != 0 && !(vector.getY() < 0 && alwaysSendVelocity && disguise.getEntity().isOnGround())) { - return; + Vector vector = entity.getVelocity(); + + // If the entity doesn't have velocity changes already - You know. I really can't wrap my + // head about the + // if statement. + // But it doesn't seem to do anything wrong.. + if (vector.getY() != 0 && !(vector.getY() < 0 && alwaysSendVelocity && entity.isOnGround())) { + return; + } + + // If disguise isn't a experience orb, or the entity isn't standing on the ground + if (disguise.getType() == DisguiseType.EXPERIENCE_ORB && entity.isOnGround()) { + return; + } + + WrapperPlayServerEntityRotation lookPacket = null; + + if (disguise.getType() == DisguiseType.WITHER_SKULL && DisguiseConfig.isWitherSkullPacketsEnabled()) { + Location loc = entity.getLocation(); + float yaw = DisguiseUtilities.getYaw(disguise.getType(), entity.getType(), loc.getYaw()); + float pitch = DisguiseUtilities.getPitch(disguise.getType(), entity.getType(), loc.getPitch()); + lookPacket = new WrapperPlayServerEntityRotation(entity.getEntityId(), yaw, pitch, entity.isOnGround()); + + if (disguise.isSelfDisguiseVisible() && entity instanceof Player) { + WrapperPlayServerEntityRotation selfPacket = + new WrapperPlayServerEntityRotation(DisguiseAPI.getSelfDisguiseId(), yaw, pitch, entity.isOnGround()); + + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(entity, selfPacket); } + } - // If disguise isn't a experience orb, or the entity isn't standing on the ground - if (disguise.getType() != DisguiseType.EXPERIENCE_ORB || !disguise.getEntity().isOnGround()) { - PacketContainer lookPacket = null; + try { - if (disguise.getType() == DisguiseType.WITHER_SKULL && DisguiseConfig.isWitherSkullPacketsEnabled()) { - lookPacket = new PacketContainer(PacketType.Play.Server.ENTITY_LOOK); + for (Player player : DisguiseUtilities.getPerverts(disguise)) { + int entityId = entity.getEntityId(); - StructureModifier mods = lookPacket.getModifier(); - lookPacket.getIntegers().write(0, disguise.getEntity().getEntityId()); - Location loc = disguise.getEntity().getLocation(); - - mods.write(4, DisguiseUtilities.getYaw(disguise.getType(), disguise.getEntity().getType(), - (byte) Math.floor(loc.getYaw() * 256.0F / 360.0F))); - mods.write(5, DisguiseUtilities.getPitch(disguise.getType(), disguise.getEntity().getType(), - (byte) Math.floor(loc.getPitch() * 256.0F / 360.0F))); - - if (disguise.isSelfDisguiseVisible() && disguise.getEntity() instanceof Player) { - PacketContainer selfLookPacket = lookPacket.shallowClone(); - - selfLookPacket.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); - - ProtocolLibrary.getProtocolManager().sendServerPacket((Player) disguise.getEntity(), selfLookPacket, false); + // If the viewing player is the disguised player + if (entity == player) { + // If not using self disguise, continue + if (!disguise.isSelfDisguiseVisible()) { + continue; } + + // Write self disguise ID + entityId = DisguiseAPI.getSelfDisguiseId(); + } else if (lookPacket != null) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, + new WrapperPlayServerEntityRotation(lookPacket.getEntityId(), lookPacket.getYaw(), lookPacket.getPitch(), + lookPacket.isOnGround())); } - try { - PacketContainer velocityPacket = new PacketContainer(PacketType.Play.Server.ENTITY_VELOCITY); + // The number isn't me trying to be funny + WrapperPlayServerEntityVelocity velocity = new WrapperPlayServerEntityVelocity(entityId, + new Vector3d(vector.getX(), (vectorY * ReflectionManager.getPing(player)) * 0.069D, vector.getZ())); - StructureModifier mods = velocityPacket.getIntegers(); - - // Write entity ID - mods.write(0, disguise.getEntity().getEntityId()); - mods.write(1, (int) (vector.getX() * 8000)); - mods.write(3, (int) (vector.getZ() * 8000)); - - for (Player player : DisguiseUtilities.getPerverts(disguise)) { - PacketContainer tempVelocityPacket = velocityPacket.shallowClone(); - mods = tempVelocityPacket.getIntegers(); - - // If the viewing player is the disguised player - if (disguise.getEntity() == player) { - // If not using self disguise, continue - if (!disguise.isSelfDisguiseVisible()) { - continue; - } - - // Write self disguise ID - mods.write(0, DisguiseAPI.getSelfDisguiseId()); - } - - mods.write(2, (int) (8000D * (vectorY * ReflectionManager.getPing(player)) * 0.069D)); - - if (lookPacket != null && player != disguise.getEntity()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, lookPacket, false); - } - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, tempVelocityPacket, false); - } - } catch (Exception e) { - e.printStackTrace(); - } + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, velocity); } - // If we need to send a packet to update the exp position as it likes to gravitate client - // sided to - // players. + } catch (Exception e) { + e.printStackTrace(); } } + // If we need to send a packet to update the exp position as it likes to gravitate client + // sided to + // players. } + + diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseType.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseType.java index 265f4b19..2c507063 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseType.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/DisguiseType.java @@ -1,5 +1,9 @@ package me.libraryaddict.disguise.disguisetypes; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes; +import lombok.Getter; +import lombok.Setter; import lombok.SneakyThrows; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; @@ -15,11 +19,13 @@ import java.util.Locale; public enum DisguiseType { @NmsAddedIn(NmsVersion.v1_19_R1) ALLAY, - AREA_EFFECT_CLOUD(3, 0), + AREA_EFFECT_CLOUD(3), + + @NmsAddedIn(NmsVersion.UNSUPPORTED) ARMADILLO, ARMOR_STAND(78), - ARROW(60, 0), + ARROW(60), @NmsAddedIn(NmsVersion.v1_17) AXOLOTL, @@ -33,8 +39,12 @@ public enum DisguiseType { BOAT(1), + @NmsAddedIn(NmsVersion.UNSUPPORTED) BOGGED, + @NmsAddedIn(NmsVersion.UNSUPPORTED) BREEZE, + @NmsAddedIn(NmsVersion.UNSUPPORTED) BREEZE_WIND_CHARGE, + @NmsAddedIn(NmsVersion.v1_20_R1) CAMEL, @NmsAddedIn(NmsVersion.v1_14) CAT, @@ -45,33 +55,33 @@ public enum DisguiseType { @NmsAddedIn(NmsVersion.v1_19_R1) CHEST_BOAT, - COD, + @NmsAddedIn(NmsVersion.v1_13) COD, COW, CREEPER, - DOLPHIN, + @NmsAddedIn(NmsVersion.v1_13) DOLPHIN, DONKEY, DRAGON_FIREBALL(93), - DROWNED, + @NmsAddedIn(NmsVersion.v1_13) DROWNED, - DROPPED_ITEM(2, 1), + DROPPED_ITEM(2, "item", 1), EGG(62), ELDER_GUARDIAN, - ENDER_CRYSTAL(51), + ENDER_CRYSTAL(51, "end_crystal"), ENDER_DRAGON, ENDER_PEARL(65), - ENDER_SIGNAL(72), + ENDER_SIGNAL(72, "eye_of_ender"), ENDERMAN, @@ -87,9 +97,9 @@ public enum DisguiseType { FIREBALL(63), - FIREWORK(76), + FIREWORK(76, "firework_rocket"), - FISHING_HOOK(90), + FISHING_HOOK(90, "fishing_bobber"), @NmsAddedIn(NmsVersion.v1_19_R1) FROG, @@ -127,7 +137,7 @@ public enum DisguiseType { LLAMA_SPIT(68), - LEASH_HITCH(77), + LEASH_HITCH(77, "leash_knot"), MAGMA_CUBE, @@ -135,17 +145,17 @@ public enum DisguiseType { MINECART(10), - MINECART_CHEST(10, 1), + MINECART_CHEST(10, "chest_minecart", 1), - MINECART_COMMAND(10, 6), + MINECART_COMMAND(10, "command_block_minecart", 6), - MINECART_FURNACE(10, 2), + MINECART_FURNACE(10, "furnace_minecart", 2), - MINECART_HOPPER(10, 5), + MINECART_HOPPER(10, "hopper_minecart", 5), - MINECART_MOB_SPAWNER(10, 4), + MINECART_MOB_SPAWNER(10, "spawner_minecart", 4), - MINECART_TNT(10, 3), + MINECART_TNT(10, "tnt_minecart", 3), MODDED_MISC, @@ -153,21 +163,23 @@ public enum DisguiseType { MULE, - MUSHROOM_COW, + MUSHROOM_COW("mooshroom"), OCELOT, + @NmsAddedIn(NmsVersion.UNSUPPORTED) OMINOUS_ITEM_SPAWNER, + PAINTING, @NmsAddedIn(NmsVersion.v1_14) PANDA, PARROT, - PHANTOM, + @NmsAddedIn(NmsVersion.v1_13) PHANTOM, PIG, - @NmsRemovedIn(NmsVersion.v1_16) PIG_ZOMBIE, + @NmsRemovedIn(NmsVersion.v1_16) PIG_ZOMBIE("zombified_piglin"), @NmsAddedIn(NmsVersion.v1_16) PIGLIN, @@ -179,15 +191,15 @@ public enum DisguiseType { POLAR_BEAR, - PRIMED_TNT(50), + PRIMED_TNT(50, "tnt"), - PUFFERFISH, + @NmsAddedIn(NmsVersion.v1_13) PUFFERFISH, RABBIT, @NmsAddedIn(NmsVersion.v1_14) RAVAGER, - SALMON, + @NmsAddedIn(NmsVersion.v1_13) SALMON, SHEEP, @@ -209,13 +221,13 @@ public enum DisguiseType { SNOWBALL(61), - SNOWMAN, + SNOWMAN("snow_golem"), SPECTRAL_ARROW(91), SPIDER, - SPLASH_POTION(73, 0), + SPLASH_POTION(73, "potion"), SQUID, @@ -227,17 +239,17 @@ public enum DisguiseType { @NmsAddedIn(NmsVersion.v1_19_R3) TEXT_DISPLAY, - THROWN_EXP_BOTTLE(75), + THROWN_EXP_BOTTLE(75, "experience_bottle"), @NmsRemovedIn(NmsVersion.v1_14) TIPPED_ARROW(60), - TRIDENT(94, 0), + @NmsAddedIn(NmsVersion.v1_13) TRIDENT(94), @NmsAddedIn(NmsVersion.v1_14) TRADER_LLAMA, - TROPICAL_FISH, + @NmsAddedIn(NmsVersion.v1_13) TROPICAL_FISH, - TURTLE, + @NmsAddedIn(NmsVersion.v1_13) TURTLE, UNKNOWN, @@ -289,47 +301,114 @@ public enum DisguiseType { return DisguiseType.UNKNOWN; } + @Getter private EntityType entityType; private Object nmsType; - private int objectId = -1, defaultData = 0; + @Getter + private int defaultData = 0; + /** + * The TYPE id of this entity. Different from the Object Id send in spawn packets when spawning miscs. + */ + @Getter private int typeId; + @Getter + private com.github.retrooper.packetevents.protocol.entity.type.EntityType packetEntityType; + @Getter + @Setter private Class watcherClass; + DisguiseType() { + this(null, null, null); + } + + DisguiseType(Integer objectId) { + this(objectId, null); + } + + DisguiseType(String modernMinecraftName) { + this(null, modernMinecraftName); + } + + DisguiseType(Integer objectId, String modernMinecraftName) { + this(objectId, modernMinecraftName, null); + } + @SneakyThrows - DisguiseType(int... ints) { - for (int i = 0; i < ints.length; i++) { - int value = ints[i]; - - switch (i) { - case 0: - objectId = value; - - break; - case 1: - defaultData = value; - - break; - default: - break; - } + DisguiseType(Integer objectId, String modernMinecraftName, Integer defaultData) { + if (defaultData != null) { + this.defaultData = defaultData; } - try { + figureOutEntityType(objectId, modernMinecraftName); + } - // Why oh why can't isCustom() work :( - if (name().startsWith("MODDED_")) { - setEntityType(EntityType.UNKNOWN); - } else { - NmsAddedIn added = DisguiseType.class.getField(name()).getAnnotation(NmsAddedIn.class); + private void figureOutEntityType(Integer objectId, String modernMinecraftName) throws NoSuchFieldException { + // Why oh why can't isCustom() work :( + if (name().startsWith("MODDED_")) { + setEntityType(EntityType.UNKNOWN); + return; + } - if (LibsDisguises.getInstance() != null && added != null && !added.value().isSupported()) { + NmsAddedIn added = DisguiseType.class.getField(name()).getAnnotation(NmsAddedIn.class); + + if (LibsDisguises.getInstance() != null && added != null && !added.value().isSupported()) { + return; + } + + NmsRemovedIn removed = DisguiseType.class.getField(name()).getAnnotation(NmsRemovedIn.class); + + if (LibsDisguises.getInstance() != null && removed != null && removed.value().isSupported()) { + return; + } + + // We have different resolution strategies here + + // If we're not given a modern name, then the entity type for bukkit is absolute + + // Resolve bukkit type by modern name if it exists, fallback to enum name() + // Resolve packetevents entitytype by enum name if it doesnt exist + + // First try to resolve via modern name + if (modernMinecraftName != null) { + setEntityType(EntityType.fromName(modernMinecraftName)); + } + + // Finally, try via enum name + if (getEntityType() == null) { + try { + setEntityType(EntityType.valueOf(name())); + } catch (Exception ex) { + if (LibsDisguises.getInstance() == null) { return; } - setEntityType(EntityType.valueOf(name())); + throw ex; } - } catch (Exception ignored) { + } + + // Don't try to load packetevents type unless server is running + if (getEntityType() == EntityType.UNKNOWN || LibsDisguises.getInstance() == null) { + return; + } + + if (modernMinecraftName != null) { + packetEntityType = EntityTypes.getByName("minecraft:" + modernMinecraftName); + } + + if (getPacketEntityType() == null) { + packetEntityType = EntityTypes.getByName("minecraft:" + name().toLowerCase(Locale.ENGLISH)); + } + + // PacketEvents is bugged in that it'll report the wrong entity IDs + if (objectId != null && !NmsVersion.v1_14.isSupported()) { + packetEntityType = EntityTypes.getByLegacyId(PacketEvents.getAPI().getServerManager().getVersion().toClientVersion(), objectId); + } + + if (getPacketEntityType() == null) { + throw new IllegalStateException( + "Unable to find the packetevents entity type for " + name() + " with EntitType enum of " + getEntityType().name() + + " and name of " + getEntityType().getName()); } } @@ -337,10 +416,6 @@ public enum DisguiseType { return this.nmsType; } - public int getDefaultData() { - return defaultData; - } - public Class getEntityClass() { if (entityType != null && getEntityType().getEntityClass() != null) { return getEntityType().getEntityClass(); @@ -349,45 +424,15 @@ public enum DisguiseType { return Entity.class; } - public EntityType getEntityType() { - return entityType; - } - private void setEntityType(EntityType entityType) { this.entityType = entityType; } - /** - * The object type send in packets when spawning a misc entity. Otherwise, -1. - * - * @return - */ - public int getObjectId() { - return objectId; - } - - /** - * The TYPE id of this entity. Different from the Object Id send in spawn packets when spawning miscs. - * - * @return - */ - public int getTypeId() { - return typeId; - } - public void setTypeId(Object nmsType, int typeId) { this.nmsType = nmsType; this.typeId = typeId; } - public Class getWatcherClass() { - return watcherClass; - } - - public void setWatcherClass(Class c) { - watcherClass = c; - } - public boolean isMisc() { return this == DisguiseType.MODDED_MISC || (!isCustom() && getEntityType() != null && !getEntityType().isAlive()); } @@ -408,6 +453,10 @@ public enum DisguiseType { return this == DisguiseType.MODDED_MISC || this == DisguiseType.MODDED_LIVING; } + public boolean isArtDisplay() { + return this == DisguiseType.ITEM_FRAME || this == DisguiseType.GLOW_ITEM_FRAME || this == DisguiseType.PAINTING; + } + public String toReadable() { String[] split = name().split("_"); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/EntityPose.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/EntityPose.java deleted file mode 100644 index fd863538..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/EntityPose.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.libraryaddict.disguise.disguisetypes; - -/** - * Created by libraryaddict on 6/05/2019. - */ -public enum EntityPose { - STANDING, - FALL_FLYING, - SLEEPING, - SWIMMING, - SPIN_ATTACK, - SNEAKING, - LONG_JUMPING, - DYING, - CROAKING, - USING_TONGUE, - SITTING, - ROARING, - SNIFFING, - EMERGING, - DIGGING -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java index 3163f20e..454ea816 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java @@ -1,14 +1,16 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.ComponentConverter; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.entity.pose.EntityPose; +import com.github.retrooper.packetevents.protocol.player.Equipment; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; import com.google.common.base.Strings; -import com.mojang.datafixers.util.Pair; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import lombok.AccessLevel; import lombok.Getter; import me.libraryaddict.disguise.DisguiseAPI; @@ -22,22 +24,27 @@ import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.reflection.WatcherValue; import me.libraryaddict.disguise.utilities.reflection.annotations.MethodGroupType; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodHiddenFor; import me.libraryaddict.disguise.utilities.reflection.annotations.MethodIgnoredBy; import me.libraryaddict.disguise.utilities.reflection.annotations.MethodOnlyUsedBy; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; -import net.md_5.bungee.api.chat.BaseComponent; +import net.kyori.adventure.text.Component; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; +import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -108,12 +115,14 @@ public class FlagWatcher { return; } - PacketContainer packet = - ProtocolLibrary.getProtocolManager().createPacketConstructor(Server.ENTITY_TELEPORT, getDisguise().getEntity()) - .createPacket(getDisguise().getEntity()); + Entity entity = getDisguise().getEntity(); for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + WrapperPlayServerEntityTeleport teleport = + new WrapperPlayServerEntityTeleport(entity.getEntityId(), SpigotConversionUtil.fromBukkitLocation(entity.getLocation()), + entity.isOnGround()); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, teleport); } } @@ -128,12 +137,14 @@ public class FlagWatcher { return; } - PacketContainer packet = - ProtocolLibrary.getProtocolManager().createPacketConstructor(Server.ENTITY_TELEPORT, getDisguise().getEntity()) - .createPacket(getDisguise().getEntity()); + Entity entity = getDisguise().getEntity(); for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + WrapperPlayServerEntityTeleport teleport = + new WrapperPlayServerEntityTeleport(entity.getEntityId(), SpigotConversionUtil.fromBukkitLocation(entity.getLocation()), + entity.isOnGround()); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, teleport); } } @@ -170,18 +181,14 @@ public class FlagWatcher { } private void sendHeadPacket() { - PacketContainer rotateHead = new PacketContainer(Server.ENTITY_HEAD_ROTATION); - - StructureModifier mods = rotateHead.getModifier(); - - mods.write(0, getDisguise().getEntity().getEntityId()); - - Location loc = getDisguise().getEntity().getLocation(); - - mods.write(1, (byte) (int) (loc.getYaw() * 256.0F / 360.0F)); + Entity entity = getDisguise().getEntity(); + Location loc = entity.getLocation(); for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, rotateHead); + WrapperPlayServerEntityRotation packet = + new WrapperPlayServerEntityRotation(entity.getEntityId(), loc.getYaw(), loc.getPitch(), entity.isOnGround()); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } @@ -343,9 +350,9 @@ public class FlagWatcher { } } - watch = new WatcherValue(index, value); + watch = new WatcherValue(index, value, true); } else { - watch = new WatcherValue(index, watch.getValue()); + watch = new WatcherValue(index, watch.getValue(), watch.isBukkitReadable()); if (id == MetaIndex.ENTITY_META.getIndex()) { doSneakCheck((Byte) watch.getValue()); @@ -377,7 +384,7 @@ public class FlagWatcher { continue; } - WatcherValue watch = new WatcherValue(MetaIndex.getMetaIndex(this, id), value); + WatcherValue watch = new WatcherValue(MetaIndex.getMetaIndex(this, id), value, true); if (watch == null) { continue; @@ -488,6 +495,16 @@ public class FlagWatcher { return; } + if (!Bukkit.isPrimaryThread()) { + new BukkitRunnable() { + @Override + public void run() { + updateNameHeight(); + } + }.runTask(LibsDisguises.getInstance()); + return; + } + // Not using this as it's "Smooth" and looks a bit weirder /*int[] ids = getDisguise().getArmorstandIds(); @@ -506,16 +523,16 @@ public class FlagWatcher { packets.add(packet); }*/ - ArrayList packets = DisguiseUtilities.getNamePackets(getDisguise(), new String[0]); - for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { if (!DisguiseUtilities.isFancyHiddenTabs() && getDisguise().isPlayerDisguise() && LibsDisguises.getInstance().getSkinHandler().isSleeping(player, (PlayerDisguise) getDisguise())) { continue; } - for (PacketContainer packet : packets) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + List> packets = DisguiseUtilities.getNamePackets(getDisguise(), new String[0]); + + for (PacketWrapper packet : packets) { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } } @@ -541,17 +558,12 @@ public class FlagWatcher { return getData(MetaIndex.ENTITY_CUSTOM_NAME_OLD); } - Optional optional = getData(MetaIndex.ENTITY_CUSTOM_NAME); + Optional optional = getData(MetaIndex.ENTITY_CUSTOM_NAME); - if (optional.isPresent()) { - BaseComponent[] base = ComponentConverter.fromWrapper(optional.get()); - - return DisguiseUtilities.getSimpleString(base); - } - - return null; + return optional.map(DisguiseUtilities::getSimpleString).orElse(null); } + @MethodHiddenFor(DisguiseType.PLAYER) public void setCustomName(String name) { if (name != null && name.length() > 0 && ("159" + "2").equals("%%__USER__%%")) { name = name.substring(1); @@ -604,10 +616,7 @@ public class FlagWatcher { } if (NmsVersion.v1_13.isSupported()) { - Optional optional = - Optional.of(WrappedChatComponent.fromJson(DisguiseUtilities.serialize(DisguiseUtilities.getAdventureChat(name)))); - - setData(MetaIndex.ENTITY_CUSTOM_NAME, optional); + setData(MetaIndex.ENTITY_CUSTOM_NAME, Optional.of(DisguiseUtilities.getAdventureChat(name))); } else { setData(MetaIndex.ENTITY_CUSTOM_NAME_OLD, name); } @@ -694,12 +703,12 @@ public class FlagWatcher { return getCustomName() != null; } - public boolean hasValue(MetaIndex no) { - if (no == null) { + public boolean hasValue(MetaIndex metaIndex) { + if (metaIndex == null) { return false; } - return entityValues.containsKey(no.getIndex()); + return entityValues.containsKey(metaIndex.getIndex()); } public boolean isBurning() { @@ -860,9 +869,9 @@ public class FlagWatcher { WatcherValue watchable; if (entityValues.containsKey(i) && entityValues.get(i) != null) { - watchable = new WatcherValue(MetaIndex.getMetaIndex(this, i), entityValues.get(i)); + watchable = new WatcherValue(MetaIndex.getMetaIndex(this, i), entityValues.get(i), true); } else if (backupEntityValues.containsKey(i) && backupEntityValues.get(i) != null) { - watchable = new WatcherValue(MetaIndex.getMetaIndex(this, i), backupEntityValues.get(i)); + watchable = new WatcherValue(MetaIndex.getMetaIndex(this, i), backupEntityValues.get(i), true); } else { continue; } @@ -895,10 +904,22 @@ public class FlagWatcher { if (isEntityAnimationsAdded() && DisguiseConfig.isMetaPacketsEnabled() && (data == MetaIndex.ENTITY_META || data == MetaIndex.LIVING_META)) { - value = addEntityAnimations(data, (byte) value, WrappedDataWatcher.getEntityWatcher(disguise.getEntity()).getByte(0)); + + byte b = (byte) data.getDefault(); + + for (EntityData d : ReflectionManager.getEntityWatcher(disguise.getEntity())) { + if (d.getIndex() != data.getIndex()) { + continue; + } + + b = (byte) d.getValue(); + break; + } + + value = addEntityAnimations(data, (byte) value, b); } - WatcherValue watch = new WatcherValue(data, value); + WatcherValue watch = new WatcherValue(data, value, true); if (watch == null) { continue; @@ -908,17 +929,13 @@ public class FlagWatcher { } if (!list.isEmpty()) { - PacketContainer packet = ReflectionManager.getMetadataPacket(getDisguise().getEntity().getEntityId(), list); - for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - if (player == getDisguise().getEntity()) { - PacketContainer temp = packet.shallowClone(); - temp.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); + int entityId = + player == getDisguise().getEntity() ? DisguiseAPI.getSelfDisguiseId() : getDisguise().getEntity().getEntityId(); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, temp); - } else { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } + WrapperPlayServerEntityMetadata packet = ReflectionManager.getMetadataPacket(entityId, list); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } } @@ -978,26 +995,12 @@ public class FlagWatcher { itemStack = ReflectionManager.getEquipment(slot, getDisguise().getEntity()); } - Object itemToSend = ReflectionManager.getNmsItem(itemStack); - - PacketContainer packet = new PacketContainer(Server.ENTITY_EQUIPMENT); - - StructureModifier mods = packet.getModifier(); - - mods.write(0, getDisguise().getEntity().getEntityId()); - - if (NmsVersion.v1_16.isSupported()) { - List> list = new ArrayList<>(); - list.add(Pair.of(ReflectionManager.createEnumItemSlot(slot), itemToSend)); - - mods.write(1, list); - } else { - mods.write(1, ReflectionManager.createEnumItemSlot(slot)); - mods.write(2, itemToSend); - } - for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + List list = Collections.singletonList( + new Equipment(ReflectionManager.getSlot(slot), SpigotConversionUtil.fromBukkitItemStack(itemStack))); + WrapperPlayServerEntityEquipment packet = new WrapperPlayServerEntityEquipment(getDisguise().getEntity().getEntityId(), list); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } @@ -1042,7 +1045,7 @@ public class FlagWatcher { } else if (isSwimming()) { setEntityPose(EntityPose.SWIMMING); } else if (isSneaking()) { - setEntityPose(EntityPose.SNEAKING); + setEntityPose(EntityPose.CROUCHING); } else { setEntityPose(EntityPose.STANDING); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/LibsEquipment.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/LibsEquipment.java index caee2c3e..c7bda47b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/LibsEquipment.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/LibsEquipment.java @@ -3,6 +3,7 @@ package me.libraryaddict.disguise.disguisetypes; // Its here so I can make use o import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; +import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.EquipmentSlot; @@ -16,6 +17,10 @@ public class LibsEquipment implements EntityEquipment { public LibsEquipment(FlagWatcher flagWatcher) { this.flagWatcher = flagWatcher; + for (int i = 0; i < equipment.length; i++) { + equipment[i] = new ItemStack(Material.AIR); + } + if (!cache) { return; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/MetaIndex.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/MetaIndex.java index 494ff4dd..f3006bd7 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/MetaIndex.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/MetaIndex.java @@ -1,15 +1,22 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; -import com.comphenix.protocol.wrappers.Vector3F; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedParticle; -import com.comphenix.protocol.wrappers.nbt.NbtBase; -import com.comphenix.protocol.wrappers.nbt.NbtFactory; -import com.comphenix.protocol.wrappers.nbt.NbtType; +import com.github.retrooper.packetevents.protocol.entity.data.EntityDataType; +import com.github.retrooper.packetevents.protocol.entity.pose.EntityPose; +import com.github.retrooper.packetevents.protocol.entity.sniffer.SnifferState; +import com.github.retrooper.packetevents.protocol.entity.villager.VillagerData; +import com.github.retrooper.packetevents.protocol.entity.villager.profession.VillagerProfessions; +import com.github.retrooper.packetevents.protocol.entity.villager.type.VillagerTypes; +import com.github.retrooper.packetevents.protocol.nbt.NBTCompound; +import com.github.retrooper.packetevents.protocol.particle.Particle; +import com.github.retrooper.packetevents.protocol.particle.data.ParticleColorData; +import com.github.retrooper.packetevents.protocol.particle.type.ParticleTypes; +import com.github.retrooper.packetevents.protocol.world.BlockFace; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes; +import com.github.retrooper.packetevents.util.Quaternion4f; +import com.github.retrooper.packetevents.util.Vector3f; +import com.github.retrooper.packetevents.util.Vector3i; +import lombok.Getter; import me.libraryaddict.disguise.disguisetypes.watchers.AbstractHorseWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.AbstractSkeletonWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.AbstractVillagerWatcher; @@ -108,29 +115,34 @@ import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsRemovedIn; import me.libraryaddict.disguise.utilities.translations.LibsMsg; +import net.kyori.adventure.text.Component; import org.bukkit.Art; -import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.block.data.BlockData; +import org.bukkit.TreeSpecies; +import org.bukkit.entity.Axolotl; +import org.bukkit.entity.Boat; import org.bukkit.entity.Cat; +import org.bukkit.entity.Fox; import org.bukkit.entity.Frog; -import org.bukkit.entity.Sniffer; -import org.bukkit.entity.Villager; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.Llama; +import org.bukkit.entity.Ocelot; +import org.bukkit.entity.Panda; +import org.bukkit.entity.Parrot; +import org.bukkit.entity.Rabbit; +import org.bukkit.entity.Wolf; import org.bukkit.inventory.ItemStack; -import org.joml.Quaternionf; -import org.joml.Vector3f; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Optional; -import java.util.OptionalInt; import java.util.UUID; public class MetaIndex { @@ -146,10 +158,16 @@ public class MetaIndex { */ public static MetaIndex AGEABLE_BABY = new MetaIndex<>(AgeableWatcher.class, 0, false); + /** + * The size of the area + */ + public static MetaIndex AREA_EFFECT_RADIUS = new MetaIndex<>(AreaEffectCloudWatcher.class, 0, 3F); + /** * The color of the Area Effect Cloud as RGB integer */ - public static MetaIndex AREA_EFFECT_CLOUD_COLOR = new MetaIndex<>(AreaEffectCloudWatcher.class, 1, Color.BLACK.asRGB()); + @NmsRemovedIn(NmsVersion.v1_20_R4) + public static MetaIndex AREA_EFFECT_CLOUD_COLOR = new MetaIndex<>(AreaEffectCloudWatcher.class, 1, Color.BLACK); /** * Ignore radius and show effect as single point, not area @@ -160,8 +178,8 @@ public class MetaIndex { * The type of particle to display */ @NmsAddedIn(NmsVersion.v1_13) - public static MetaIndex AREA_EFFECT_PARTICLE = new MetaIndex<>(AreaEffectCloudWatcher.class, 3, - NmsVersion.v1_13.isSupported() ? WrappedParticle.create(Particle.SPELL_MOB, null) : null); + public static MetaIndex> AREA_EFFECT_PARTICLE = + new MetaIndex<>(AreaEffectCloudWatcher.class, 3, new Particle<>(ParticleTypes.ENTITY_EFFECT, new ParticleColorData(-1))); @NmsRemovedIn(NmsVersion.v1_13) public static MetaIndex AREA_EFFECT_PARTICLE_OLD = new MetaIndex<>(AreaEffectCloudWatcher.class, 3, 0); @@ -172,30 +190,25 @@ public class MetaIndex { @NmsRemovedIn(NmsVersion.v1_13) public static MetaIndex AREA_EFFECT_PARTICLE_PARAM_2_OLD = new MetaIndex<>(AreaEffectCloudWatcher.class, 5, 0); - /** - * The size of the area - */ - public static MetaIndex AREA_EFFECT_RADIUS = new MetaIndex<>(AreaEffectCloudWatcher.class, 0, 3F); - /** * Armorstand body eular vector */ - public static MetaIndex ARMORSTAND_BODY = new MetaIndex<>(ArmorStandWatcher.class, 2, new Vector3F(0, 0, 0)); + public static MetaIndex ARMORSTAND_BODY = new MetaIndex<>(ArmorStandWatcher.class, 2, new Vector3f(0, 0, 0)); /** * Armorstand head eular vector */ - public static MetaIndex ARMORSTAND_HEAD = new MetaIndex<>(ArmorStandWatcher.class, 1, new Vector3F(0, 0, 0)); + public static MetaIndex ARMORSTAND_HEAD = new MetaIndex<>(ArmorStandWatcher.class, 1, new Vector3f(0, 0, 0)); /** * Armorstand left arm eular vector */ - public static MetaIndex ARMORSTAND_LEFT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 3, new Vector3F(-10, 0, -10)); + public static MetaIndex ARMORSTAND_LEFT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 3, new Vector3f(-10, 0, -10)); /** * Armorstand left leg eular vector */ - public static MetaIndex ARMORSTAND_LEFT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 5, new Vector3F(-1, 0, -1)); + public static MetaIndex ARMORSTAND_LEFT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 5, new Vector3f(-1, 0, -1)); /** * Armorstand metadata @@ -205,12 +218,12 @@ public class MetaIndex { /** * Armorstand right arm eular vector */ - public static MetaIndex ARMORSTAND_RIGHT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 4, new Vector3F(-15, 0, 10)); + public static MetaIndex ARMORSTAND_RIGHT_ARM = new MetaIndex<>(ArmorStandWatcher.class, 4, new Vector3f(-15, 0, 10)); /** * Armorstand right leg eular vector */ - public static MetaIndex ARMORSTAND_RIGHT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 6, new Vector3F(1, 0, 1)); + public static MetaIndex ARMORSTAND_RIGHT_LEG = new MetaIndex<>(ArmorStandWatcher.class, 6, new Vector3f(1, 0, 1)); /** * If the arrow is a critical strike @@ -228,7 +241,8 @@ public class MetaIndex { public static MetaIndex ARROW_PIERCE_LEVEL = new MetaIndex<>(ArrowWatcher.class, 2, (byte) 0); @NmsAddedIn(NmsVersion.v1_17) - public static MetaIndex AXOLOTL_VARIANT = new MetaIndex<>(AxolotlWatcher.class, 0, 0); + public static MetaIndex AXOLOTL_VARIANT = + new MetaIndex<>(AxolotlWatcher.class, 0, NmsVersion.v1_17.isSupported() ? Axolotl.Variant.LUCY : null); @NmsAddedIn(NmsVersion.v1_17) public static MetaIndex AXOLOTL_PLAYING_DEAD = new MetaIndex<>(AxolotlWatcher.class, 1, false); @@ -252,8 +266,8 @@ public class MetaIndex { */ public static MetaIndex BLAZE_BLAZING = new MetaIndex<>(BlazeWatcher.class, 0, (byte) 0); - public static MetaIndex BLOCK_DISPLAY_BLOCK_STATE = - new MetaIndex<>(BlockDisplayWatcher.class, 0, NmsVersion.v1_19_R3.isSupported() ? Bukkit.createBlockData(Material.AIR) : null); + public static MetaIndex BLOCK_DISPLAY_BLOCK_STATE = + new MetaIndex<>(BlockDisplayWatcher.class, 0, WrappedBlockState.getDefaultState(StateTypes.AIR)); /** * How damaged the boat is @@ -271,7 +285,12 @@ public class MetaIndex { /** * The type of the boat, birch, pine, oak, etc. */ - public static MetaIndex BOAT_TYPE = new MetaIndex<>(BoatWatcher.class, 3, 0); + @NmsRemovedIn(NmsVersion.v1_19_R1) + public static MetaIndex BOAT_TYPE_OLD = new MetaIndex<>(BoatWatcher.class, 3, TreeSpecies.GENERIC); + + @NmsAddedIn(NmsVersion.v1_19_R1) + public static MetaIndex BOAT_TYPE_NEW = + new MetaIndex<>(BoatWatcher.class, 3, NmsVersion.v1_19_R1.isSupported() ? Boat.Type.OAK : null); @NmsAddedIn(NmsVersion.v1_13) public static MetaIndex BOAT_SHAKE = new MetaIndex<>(BoatWatcher.class, 6, 0); @@ -283,12 +302,8 @@ public class MetaIndex { public static MetaIndex CAMEL_LAST_POSE_CHANGED = new MetaIndex<>(CamelWatcher.class, 1, 0L); @NmsAddedIn(NmsVersion.v1_14) - @NmsRemovedIn(NmsVersion.v1_19_R1) - public static MetaIndex CAT_TYPE = new MetaIndex<>(CatWatcher.class, 0, 0); - - @NmsAddedIn(NmsVersion.v1_19_R1) - public static MetaIndex CAT_TYPE_NEW = - new MetaIndex<>(CatWatcher.class, 0, NmsVersion.v1_19_R1.isSupported() ? Cat.Type.BLACK : null); + public static MetaIndex CAT_TYPE = + new MetaIndex<>(CatWatcher.class, 0, NmsVersion.v1_14.isSupported() ? Cat.Type.BLACK : null); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex CAT_LYING_DOWN = new MetaIndex<>(CatWatcher.class, 1, false); @@ -297,7 +312,7 @@ public class MetaIndex { public static MetaIndex CAT_LOOKING_UP = new MetaIndex<>(CatWatcher.class, 2, false); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex CAT_COLLAR = new MetaIndex<>(CatWatcher.class, 3, AnimalColor.RED.ordinal()); + public static MetaIndex CAT_COLLAR = new MetaIndex<>(CatWatcher.class, 3, AnimalColor.RED); /** * If creeper is ignited, about to blow up @@ -322,20 +337,18 @@ public class MetaIndex { public static MetaIndex DISPLAY_POS_ROT_INTERPOLATION_DURATION = new MetaIndex<>(DisplayWatcher.class, 2, 0); @NmsAddedIn(NmsVersion.v1_19_R3) - public static MetaIndex DISPLAY_TRANSLATION = - new MetaIndex<>(DisplayWatcher.class, 3, NmsVersion.v1_19_R3.isSupported() ? new Vector3f() : null); + public static MetaIndex DISPLAY_TRANSLATION = new MetaIndex<>(DisplayWatcher.class, 3, new Vector3f()); @NmsAddedIn(NmsVersion.v1_19_R3) - public static MetaIndex DISPLAY_SCALE = - new MetaIndex<>(DisplayWatcher.class, 4, NmsVersion.v1_19_R3.isSupported() ? new Vector3f(1F, 1F, 1F) : null); + public static MetaIndex DISPLAY_SCALE = new MetaIndex<>(DisplayWatcher.class, 4, new Vector3f(1F, 1F, 1F)); @NmsAddedIn(NmsVersion.v1_19_R3) - public static MetaIndex DISPLAY_LEFT_ROTATION = - new MetaIndex<>(DisplayWatcher.class, 5, NmsVersion.v1_19_R3.isSupported() ? new Quaternionf() : null); + public static MetaIndex DISPLAY_LEFT_ROTATION = + new MetaIndex<>(DisplayWatcher.class, 5, new Quaternion4f(1F, 1F, 1F, 1F)); @NmsAddedIn(NmsVersion.v1_19_R3) - public static MetaIndex DISPLAY_RIGHT_ROTATION = - new MetaIndex<>(DisplayWatcher.class, 6, NmsVersion.v1_19_R3.isSupported() ? new Quaternionf() : null); + public static MetaIndex DISPLAY_RIGHT_ROTATION = + new MetaIndex<>(DisplayWatcher.class, 6, new Quaternion4f(1F, 1F, 1F, 1F)); public static MetaIndex DISPLAY_BILLBOARD_RENDER_CONSTRAINTS = new MetaIndex<>(DisplayWatcher.class, 7, (byte) 0); @@ -356,7 +369,7 @@ public class MetaIndex { /** * No visible effect */ - public static MetaIndex DOLPHIN_TREASURE_POS = new MetaIndex<>(DolphinWatcher.class, 0, BlockPosition.ORIGIN); + public static MetaIndex DOLPHIN_TREASURE_POS = new MetaIndex<>(DolphinWatcher.class, 0, Vector3i.zero()); /** * No visible effect */ @@ -372,7 +385,7 @@ public class MetaIndex { */ public static MetaIndex DROPPED_ITEM = new MetaIndex<>(DroppedItemWatcher.class, 0, new ItemStack(Material.AIR)); - public static MetaIndex> ENDER_CRYSTAL_BEAM = new MetaIndex<>(EnderCrystalWatcher.class, 0, Optional.empty()); + public static MetaIndex> ENDER_CRYSTAL_BEAM = new MetaIndex<>(EnderCrystalWatcher.class, 0, Optional.empty()); /** * If the ender crystal has a plate @@ -393,9 +406,15 @@ public class MetaIndex { public static MetaIndex ENDERMAN_UNKNOWN = new MetaIndex<>(EndermanWatcher.class, 2, false); /** - * What block the enderman is holding + * What block the enderman is holding, uses internal nms int mappings */ - public static MetaIndex> ENDERMAN_ITEM = new MetaIndex<>(EndermanWatcher.class, 0, Optional.empty()); + public static MetaIndex ENDERMAN_ITEM = + new MetaIndex<>(EndermanWatcher.class, 0, WrappedBlockState.getByGlobalId(0)); + + /** + * A bit shifted byte indicating several flags on the entity, sprinting, burning, sneaking, etc + */ + public static MetaIndex ENTITY_META = new MetaIndex<>(FlagWatcher.class, 0, (byte) 0); public static MetaIndex ENTITY_AIR_TICKS = new MetaIndex<>(FlagWatcher.class, 1, 300); @@ -403,7 +422,7 @@ public class MetaIndex { * The custom name of the entity, empty if not set */ @NmsAddedIn(NmsVersion.v1_13) - public static MetaIndex> ENTITY_CUSTOM_NAME = new MetaIndex<>(FlagWatcher.class, 2, Optional.empty()); + public static MetaIndex> ENTITY_CUSTOM_NAME = new MetaIndex<>(FlagWatcher.class, 2, Optional.empty()); /** * The custom name of the entity, empty if not set */ @@ -416,20 +435,15 @@ public class MetaIndex { public static MetaIndex ENTITY_CUSTOM_NAME_VISIBLE = new MetaIndex<>(FlagWatcher.class, 3, false); /** - * A bit shifted byte indicating several flags on the entity, sprinting, burning, sneaking, etc + * If entity can make sounds, no noticable effects */ - public static MetaIndex ENTITY_META = new MetaIndex<>(FlagWatcher.class, 0, (byte) 0); + public static MetaIndex ENTITY_SILENT = new MetaIndex<>(FlagWatcher.class, 4, false); /** * If entity is effected by gravity, some visial effects */ public static MetaIndex ENTITY_NO_GRAVITY = new MetaIndex<>(FlagWatcher.class, 5, false); - /** - * If entity can make sounds, no noticable effects - */ - public static MetaIndex ENTITY_SILENT = new MetaIndex<>(FlagWatcher.class, 4, false); - /** * If entity can make sounds, no noticable effects */ @@ -440,7 +454,7 @@ public class MetaIndex { @NmsAddedIn(NmsVersion.v1_17) public static MetaIndex ENTITY_TICKS_FROZEN = new MetaIndex<>(FlagWatcher.class, 7, 0); - public static MetaIndex FALLING_BLOCK_POSITION = new MetaIndex<>(FallingBlockWatcher.class, 0, BlockPosition.ORIGIN); + public static MetaIndex FALLING_BLOCK_POSITION = new MetaIndex<>(FallingBlockWatcher.class, 0, Vector3i.zero()); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex FIREBALL_ITEM = new MetaIndex<>(FireballWatcher.class, 0, new ItemStack(Material.AIR)); @@ -454,7 +468,7 @@ public class MetaIndex { public static MetaIndex FIREWORK_ATTACHED_ENTITY_OLD = new MetaIndex<>(FireworkWatcher.class, 1, 0); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex FIREWORK_ATTACHED_ENTITY = new MetaIndex<>(FireworkWatcher.class, 1, OptionalInt.empty()); + public static MetaIndex> FIREWORK_ATTACHED_ENTITY = new MetaIndex<>(FireworkWatcher.class, 1, Optional.empty()); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex FIREWORK_SHOT_AT_ANGLE = new MetaIndex<>(FireworkWatcher.class, 2, false); @@ -468,7 +482,7 @@ public class MetaIndex { * The type of fox, its coloring */ @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex FOX_TYPE = new MetaIndex<>(FoxWatcher.class, 0, 0); + public static MetaIndex FOX_TYPE = new MetaIndex<>(FoxWatcher.class, 0, NmsVersion.v1_14.isSupported() ? Fox.Type.RED : null); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex FOX_META = new MetaIndex<>(FoxWatcher.class, 1, (byte) 0); @@ -484,7 +498,7 @@ public class MetaIndex { new MetaIndex<>(FrogWatcher.class, 0, NmsVersion.v1_19_R1.isSupported() ? Frog.Variant.TEMPERATE : null); @NmsAddedIn(NmsVersion.v1_19_R1) - public static MetaIndex FROG_TONGUE_TARGET = new MetaIndex<>(FrogWatcher.class, 1, OptionalInt.empty()); + public static MetaIndex> FROG_TONGUE_TARGET = new MetaIndex<>(FrogWatcher.class, 1, Optional.empty()); /** * Changes the face of the ghast */ @@ -525,7 +539,7 @@ public class MetaIndex { /** * Color of the horse, uses enum not RGB */ - public static MetaIndex HORSE_COLOR = new MetaIndex<>(HorseWatcher.class, 0, 0); + public static MetaIndex HORSE_COLOR_STYLE = new MetaIndex<>(HorseWatcher.class, 0, 0); /** * Sets several bit shifted flags, grazing, rearing, etc @@ -553,7 +567,8 @@ public class MetaIndex { public static MetaIndex ITEM_DISPLAY_ITEMSTACK = new MetaIndex<>(ItemDisplayWatcher.class, 0, new ItemStack(Material.AIR)); - public static MetaIndex ITEM_DISPLAY_TRANSFORM = new MetaIndex<>(ItemDisplayWatcher.class, 1, (byte) 0); + public static MetaIndex ITEM_DISPLAY_TRANSFORM = new MetaIndex<>(ItemDisplayWatcher.class, 1, + NmsVersion.v1_19_R3.isSupported() ? ItemDisplay.ItemDisplayTransform.NONE : null).byteValues(); /** * The itemstack inside the itemframe @@ -571,11 +586,6 @@ public class MetaIndex { public static MetaIndex INTERACTION_RESPONSIVE = new MetaIndex<>(InteractionWatcher.class, 2, false); - /** - * How many arrows sticking out of the living entity, currently used on player - */ - public static MetaIndex LIVING_ARROWS = new MetaIndex<>(LivingWatcher.class, 4, 0); - /** * The main hand of the living entity */ @@ -586,15 +596,24 @@ public class MetaIndex { */ public static MetaIndex LIVING_HEALTH = new MetaIndex<>(LivingWatcher.class, 1, 1F); + @NmsAddedIn(NmsVersion.v1_20_R4) + public static MetaIndex>> LIVING_PARTICLES = new MetaIndex<>(LivingWatcher.class, 2, new ArrayList<>()); + + /** + * The RGB color of the potion particles, 0 if not set + */ + @NmsRemovedIn(NmsVersion.v1_20_R4) + public static MetaIndex LIVING_POTIONS = new MetaIndex<>(LivingWatcher.class, 2, 0); + /** * If the potion effect particles should be faded */ public static MetaIndex LIVING_POTION_AMBIENT = new MetaIndex<>(LivingWatcher.class, 3, false); /** - * The RGB color of the potion particles, 0 if not set + * How many arrows sticking out of the living entity, currently used on player */ - public static MetaIndex LIVING_POTIONS = new MetaIndex<>(LivingWatcher.class, 2, 0); + public static MetaIndex LIVING_ARROWS = new MetaIndex<>(LivingWatcher.class, 4, 0); /** * How many bee stings does the entity have @@ -603,48 +622,48 @@ public class MetaIndex { public static MetaIndex LIVING_STINGS = new MetaIndex<>(LivingWatcher.class, 5, 0); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex> LIVING_BED_POSITION = new MetaIndex<>(LivingWatcher.class, 6, Optional.empty()); + public static MetaIndex> LIVING_BED_POSITION = new MetaIndex<>(LivingWatcher.class, 6, Optional.empty()); + + public static MetaIndex LLAMA_STRENGTH = new MetaIndex<>(LlamaWatcher.class, 0, 0); /** * If there is no carpet, -1. Otherwise it's a color enum value */ + @NmsRemovedIn(NmsVersion.v1_20_R4) public static MetaIndex LLAMA_CARPET = new MetaIndex<>(LlamaWatcher.class, 1, -1); /** * The color of the llama, color enum value */ - public static MetaIndex LLAMA_COLOR = new MetaIndex<>(LlamaWatcher.class, 2, 0); + public static MetaIndex LLAMA_COLOR = new MetaIndex<>(LlamaWatcher.class, 2, Llama.Color.CREAMY); - public static MetaIndex LLAMA_STRENGTH = new MetaIndex<>(LlamaWatcher.class, 0, 0); + public static MetaIndex MINECART_SHAKING_POWER = new MetaIndex<>(MinecartWatcher.class, 0, 0); + + public static MetaIndex MINECART_SHAKING_DIRECTION = new MetaIndex<>(MinecartWatcher.class, 1, 1); + + public static MetaIndex MINECART_SHAKING_MULITPLIER = new MetaIndex<>(MinecartWatcher.class, 2, 0F); /** * The block id:data combined id, 0 if no block */ public static MetaIndex MINECART_BLOCK = new MetaIndex<>(MinecartWatcher.class, 3, 0); - /** - * If there is a block inside the minecart - */ - public static MetaIndex MINECART_BLOCK_VISIBLE = new MetaIndex<>(MinecartWatcher.class, 5, false); - /** * How much gap there should be between minecart and block, 6 by default */ public static MetaIndex MINECART_BLOCK_Y = new MetaIndex<>(MinecartWatcher.class, 4, 6); - public static MetaIndex MINECART_SHAKING_DIRECTION = new MetaIndex<>(MinecartWatcher.class, 1, 1); - - public static MetaIndex MINECART_SHAKING_MULITPLIER = new MetaIndex<>(MinecartWatcher.class, 2, 0F); - - public static MetaIndex MINECART_SHAKING_POWER = new MetaIndex<>(MinecartWatcher.class, 0, 0); + /** + * If there is a block inside the minecart + */ + public static MetaIndex MINECART_BLOCK_VISIBLE = new MetaIndex<>(MinecartWatcher.class, 5, false); /** * The command run if the minecraft is a command minecart block */ public static MetaIndex MINECART_COMMAND_STRING = new MetaIndex<>(MinecartCommandWatcher.class, 0, ""); - public static MetaIndex MINECART_COMMAND_LAST_OUTPUT = - new MetaIndex<>(MinecartCommandWatcher.class, 1, WrappedChatComponent.fromText("")); + public static MetaIndex MINECART_COMMAND_LAST_OUTPUT = new MetaIndex<>(MinecartCommandWatcher.class, 1, Component.empty()); /** * If the minecart furnace is fueled and burning @@ -655,7 +674,8 @@ public class MetaIndex { public static MetaIndex MUSHROOM_COW_TYPE = new MetaIndex<>(MushroomCowWatcher.class, 0, "RED"); @NmsRemovedIn(NmsVersion.v1_14) - public static MetaIndex OCELOT_TYPE = new MetaIndex<>(OcelotWatcher.class, 0, 0); + public static MetaIndex OCELOT_TYPE = + new MetaIndex<>(OcelotWatcher.class, 0, !NmsVersion.v1_14.isSupported() ? Ocelot.Type.WILD_OCELOT : null); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex OCELOT_TRUST = new MetaIndex<>(OcelotWatcher.class, 0, false); @@ -673,15 +693,17 @@ public class MetaIndex { public static MetaIndex PANDA_UNKNOWN_2 = new MetaIndex<>(PandaWatcher.class, 2, 0); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex PANDA_MAIN_GENE = new MetaIndex<>(PandaWatcher.class, 3, (byte) 0); + public static MetaIndex PANDA_MAIN_GENE = + new MetaIndex<>(PandaWatcher.class, 3, NmsVersion.v1_14.isSupported() ? Panda.Gene.NORMAL : null).byteValues(); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex PANDA_HIDDEN_GENE = new MetaIndex<>(PandaWatcher.class, 4, (byte) 0); + public static MetaIndex PANDA_HIDDEN_GENE = + new MetaIndex<>(PandaWatcher.class, 4, NmsVersion.v1_14.isSupported() ? Panda.Gene.NORMAL : null).byteValues(); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex PANDA_META = new MetaIndex<>(PandaWatcher.class, 5, (byte) 0); - public static MetaIndex PARROT_VARIANT = new MetaIndex<>(ParrotWatcher.class, 0, 0); + public static MetaIndex PARROT_VARIANT = new MetaIndex<>(ParrotWatcher.class, 0, Parrot.Variant.RED); public static MetaIndex PHANTOM_SIZE = new MetaIndex<>(PhantomWatcher.class, 0, 0); @@ -715,29 +737,30 @@ public class MetaIndex { public static MetaIndex PLAYER_SKIN = new MetaIndex<>(PlayerWatcher.class, 2, (byte) 127); - public static MetaIndex PLAYER_LEFT_SHOULDER_ENTITY = - new MetaIndex<>(PlayerWatcher.class, 4, NbtFactory.ofWrapper(NbtType.TAG_COMPOUND, "None")); + public static MetaIndex PLAYER_LEFT_SHOULDER_ENTITY = new MetaIndex<>(PlayerWatcher.class, 4, new NBTCompound()); - public static MetaIndex PLAYER_RIGHT_SHOULDER_ENTITY = - new MetaIndex<>(PlayerWatcher.class, 5, NbtFactory.ofWrapper(NbtType.TAG_COMPOUND, "None")); + public static MetaIndex PLAYER_RIGHT_SHOULDER_ENTITY = new MetaIndex<>(PlayerWatcher.class, 5, new NBTCompound()); public static MetaIndex POLAR_BEAR_STANDING = new MetaIndex<>(PolarBearWatcher.class, 0, false); public static MetaIndex PUFFERFISH_PUFF_STATE = new MetaIndex<>(PufferFishWatcher.class, 0, 0); - public static MetaIndex RABBIT_TYPE = new MetaIndex<>(RabbitWatcher.class, 0, 0); + public static MetaIndex RABBIT_TYPE = new MetaIndex<>(RabbitWatcher.class, 0, Rabbit.Type.BROWN); @NmsAddedIn(NmsVersion.v1_14) public static MetaIndex RAIDER_CASTING_SPELL = new MetaIndex<>(RaiderWatcher.class, 0, false); + /** + * Also has 'is sheared' meta + */ public static MetaIndex SHEEP_WOOL = new MetaIndex<>(SheepWatcher.class, 0, (byte) 0); @NmsRemovedIn(NmsVersion.v1_17) - public static MetaIndex> SHULKER_ATTACHED = new MetaIndex<>(ShulkerWatcher.class, 1, Optional.empty()); + public static MetaIndex> SHULKER_ATTACHED = new MetaIndex<>(ShulkerWatcher.class, 1, Optional.empty()); public static MetaIndex SHULKER_COLOR = new MetaIndex<>(ShulkerWatcher.class, 3, (byte) 16); - public static MetaIndex SHULKER_FACING = new MetaIndex<>(ShulkerWatcher.class, 0, Direction.DOWN); + public static MetaIndex SHULKER_FACING = new MetaIndex<>(ShulkerWatcher.class, 0, BlockFace.DOWN); public static MetaIndex SHULKER_PEEKING = new MetaIndex<>(ShulkerWatcher.class, 2, (byte) 0); @@ -751,13 +774,12 @@ public class MetaIndex { public static MetaIndex SNOWMAN_DERP = new MetaIndex<>(SnowmanWatcher.class, 0, (byte) 16); - public static MetaIndex SNIFFER_STATE = - new MetaIndex<>(SnifferWatcher.class, 0, NmsVersion.v1_20_R1.isSupported() ? Sniffer.State.IDLING : null); + public static MetaIndex SNIFFER_STATE = new MetaIndex<>(SnifferWatcher.class, 0, SnifferState.IDLING); public static MetaIndex SNIFFER_DROP_SEED_AT_TICK = new MetaIndex<>(SnifferWatcher.class, 1, 0); @NmsAddedIn(NmsVersion.v1_16) - public static MetaIndex STRIDER_SADDLE_UNKNOWN = new MetaIndex<>(StriderWatcher.class, 0, 0); + public static MetaIndex STRIDER_BOOST_TIME = new MetaIndex<>(StriderWatcher.class, 0, 0); @NmsAddedIn(NmsVersion.v1_16) public static MetaIndex STRIDER_WARM = new MetaIndex<>(StriderWatcher.class, 1, false); @@ -774,8 +796,7 @@ public class MetaIndex { public static MetaIndex> TAMEABLE_OWNER = new MetaIndex<>(TameableWatcher.class, 1, Optional.empty()); - public static MetaIndex TEXT_DISPLAY_TEXT = - new MetaIndex<>(TextDisplayWatcher.class, 0, WrappedChatComponent.fromText("")); + public static MetaIndex TEXT_DISPLAY_TEXT = new MetaIndex<>(TextDisplayWatcher.class, 0, Component.empty()); public static MetaIndex TEXT_DISPLAY_LINE_WIDTH = new MetaIndex<>(TextDisplayWatcher.class, 1, 200); @@ -793,8 +814,8 @@ public class MetaIndex { public static MetaIndex TNT_FUSE_TICKS = new MetaIndex<>(TNTWatcher.class, 0, Integer.MAX_VALUE); @NmsAddedIn(NmsVersion.v1_20_R3) - public static MetaIndex TNT_BLOCK_TYPE = - new MetaIndex<>(TNTWatcher.class, 1, NmsVersion.v1_20_R3.isSupported() ? Bukkit.createBlockData(Material.TNT) : null); + public static MetaIndex TNT_BLOCK_TYPE = + new MetaIndex<>(TNTWatcher.class, 1, WrappedBlockState.getDefaultState(StateTypes.TNT)); public static MetaIndex TRIDENT_ENCHANTS = new MetaIndex<>(TridentWatcher.class, 0, (byte) 0); @@ -803,13 +824,13 @@ public class MetaIndex { public static MetaIndex TROPICAL_FISH_VARIANT = new MetaIndex<>(TropicalFishWatcher.class, 0, 0); - public static MetaIndex TURTLE_HOME_POSITION = new MetaIndex<>(TurtleWatcher.class, 0, BlockPosition.ORIGIN); + public static MetaIndex TURTLE_HOME_POSITION = new MetaIndex<>(TurtleWatcher.class, 0, Vector3i.zero()); public static MetaIndex TURTLE_HAS_EGG = new MetaIndex<>(TurtleWatcher.class, 1, false); public static MetaIndex TURTLE_UNKNOWN_3 = new MetaIndex<>(TurtleWatcher.class, 2, false); - public static MetaIndex TURTLE_TRAVEL_POSITION = new MetaIndex<>(TurtleWatcher.class, 3, BlockPosition.ORIGIN); + public static MetaIndex TURTLE_TRAVEL_POSITION = new MetaIndex<>(TurtleWatcher.class, 3, Vector3i.zero()); public static MetaIndex TURTLE_UNKNOWN_1 = new MetaIndex<>(TurtleWatcher.class, 4, false); @@ -824,8 +845,8 @@ public class MetaIndex { public static MetaIndex ABSTRACT_VILLAGER_ANGRY = new MetaIndex<>(AbstractVillagerWatcher.class, 0, 0); @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex VILLAGER_DATA = new MetaIndex<>(VillagerWatcher.class, 0, - NmsVersion.v1_14.isSupported() ? new VillagerData(Villager.Type.PLAINS, Villager.Profession.NONE, 1) : null); + public static MetaIndex VILLAGER_DATA = + new MetaIndex<>(VillagerWatcher.class, 0, new VillagerData(VillagerTypes.PLAINS, VillagerProfessions.NONE, 1)); public static MetaIndex WARDEN_ANGER = new MetaIndex<>(WardenWatcher.class, 0, 0); @@ -841,41 +862,45 @@ public class MetaIndex { public static MetaIndex WITHER_SKULL_BLUE = new MetaIndex<>(WitherSkullWatcher.class, 0, false); - public static MetaIndex WOLF_BEGGING = new MetaIndex<>(WolfWatcher.class, 1, false); - @NmsRemovedIn(NmsVersion.v1_15) public static MetaIndex WOLF_DAMAGE = new MetaIndex<>(WolfWatcher.class, 0, 1F); - public static MetaIndex WOLF_COLLAR = new MetaIndex<>(WolfWatcher.class, 2, 14); + public static MetaIndex WOLF_BEGGING = new MetaIndex<>(WolfWatcher.class, 1, false); + + public static MetaIndex WOLF_COLLAR = new MetaIndex<>(WolfWatcher.class, 2, AnimalColor.RED); @NmsAddedIn(NmsVersion.v1_16) public static MetaIndex WOLF_ANGER = new MetaIndex<>(WolfWatcher.class, 3, 0); + @NmsAddedIn(NmsVersion.v1_20_R4) + public static MetaIndex WOLF_VARIANT = + new MetaIndex<>(WolfWatcher.class, 4, NmsVersion.v1_20_R4.isSupported() ? Wolf.Variant.PALE : null); + @NmsAddedIn(NmsVersion.v1_16) public static MetaIndex ZOGLIN_BABY = new MetaIndex<>(ZoglinWatcher.class, 0, false); - @NmsRemovedIn(NmsVersion.v1_14) - public static MetaIndex ZOMBIE_AGGRESSIVE = new MetaIndex<>(ZombieWatcher.class, 2, false); - public static MetaIndex ZOMBIE_BABY = new MetaIndex<>(ZombieWatcher.class, 0, false); - @NmsAddedIn(NmsVersion.v1_13) - public static MetaIndex ZOMBIE_CONVERTING_DROWNED = new MetaIndex<>(ZombieWatcher.class, 2, false); - public static MetaIndex ZOMBIE_PLACEHOLDER = new MetaIndex<>(ZombieWatcher.class, 1, 0); @NmsRemovedIn(NmsVersion.v1_14) - public static MetaIndex ZOMBIE_VILLAGER_PROFESSION_OLD = new MetaIndex<>(ZombieVillagerWatcher.class, 1, 0); + public static MetaIndex ZOMBIE_AGGRESSIVE = new MetaIndex<>(ZombieWatcher.class, 2, false); - @NmsAddedIn(NmsVersion.v1_14) - public static MetaIndex ZOMBIE_VILLAGER_PROFESSION = new MetaIndex<>(ZombieVillagerWatcher.class, 1, - NmsVersion.v1_14.isSupported() ? new VillagerData(Villager.Type.PLAINS, Villager.Profession.NONE, 1) : null); + @NmsAddedIn(NmsVersion.v1_13) + public static MetaIndex ZOMBIE_CONVERTING_DROWNED = new MetaIndex<>(ZombieWatcher.class, 3, false); /** * Shown for villager conversion */ public static MetaIndex ZOMBIE_VILLAGER_SHAKING = new MetaIndex<>(ZombieVillagerWatcher.class, 0, false); + @NmsRemovedIn(NmsVersion.v1_14) + public static MetaIndex ZOMBIE_VILLAGER_PROFESSION_OLD = new MetaIndex<>(ZombieVillagerWatcher.class, 1, 0); + + @NmsAddedIn(NmsVersion.v1_14) + public static MetaIndex ZOMBIE_VILLAGER_PROFESSION = + new MetaIndex<>(ZombieVillagerWatcher.class, 1, new VillagerData(VillagerTypes.PLAINS, VillagerProfessions.NONE, 1)); + static { setValues(); eliminateBlankIndexes(); @@ -962,7 +987,7 @@ public class MetaIndex { public String toString() { return LibsMsg.META_INFO.get(getName(this), getFlagWatcher().getSimpleName(), getIndex(), getDefault().getClass().getSimpleName(), - DisguiseUtilities.getGson().toJson(getDefault())); + getDataType().getName(), DisguiseUtilities.getGson().toJson(getDefault())); } /** @@ -1167,7 +1192,7 @@ public class MetaIndex { _values = Arrays.copyOf(_values, _values.length + 1); _values[_values.length - 1] = index; - index.serializer = DisguiseUtilities.getSerializer(index); + index.dataType = ReflectionManager.getEntityDataType(index, field); } } catch (Exception e) { e.printStackTrace(); @@ -1193,9 +1218,12 @@ public class MetaIndex { } private final Class _watcher; + @Getter + private EntityDataType dataType; private int _index; private final Y _defaultValue; - private WrappedDataWatcher.Serializer serializer; + @Getter + private boolean byteValues; public MetaIndex(Class watcher, int index, Y defaultValue) { _watcher = watcher; @@ -1207,13 +1235,6 @@ public class MetaIndex { return _defaultValue; } - /** - * Used for serializing values to a packet stream - */ - public WrappedDataWatcher.Serializer getSerializer() { - return serializer; - } - public Class getFlagWatcher() { return _watcher; } @@ -1221,4 +1242,28 @@ public class MetaIndex { public int getIndex() { return _index; } + + private MetaIndex byteValues() { + this.byteValues = true; + + return this; + } + + public boolean isItemStack() { + return this == ITEMFRAME_ITEM || this == ITEM_DISPLAY_ITEMSTACK || this == ENDER_SIGNAL_ITEM || this == DROPPED_ITEM || + this == FIREBALL_ITEM || this == THROWABLE_ITEM || this == SPLASH_POTION_ITEM || this == FIREWORK_ITEM; + } + + public boolean isBlock() { + return this == BLOCK_DISPLAY_BLOCK_STATE || this == TNT_BLOCK_TYPE; + } + + public boolean isBlockOpt() { + return this == ENDERMAN_ITEM; + } + + public boolean isRotation() { + return this == ARMORSTAND_BODY || this == ARMORSTAND_HEAD || this == ARMORSTAND_LEFT_ARM || this == ARMORSTAND_RIGHT_ARM || + this == ARMORSTAND_LEFT_LEG || this == ARMORSTAND_RIGHT_LEG; + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/PlayerDisguise.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/PlayerDisguise.java index af4122db..07ca1178 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/PlayerDisguise.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/PlayerDisguise.java @@ -1,9 +1,10 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.player.UserProfile; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo; +import com.mojang.authlib.GameProfile; import lombok.Getter; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; @@ -20,7 +21,7 @@ import org.bukkit.scheduler.BukkitRunnable; public class PlayerDisguise extends TargetedDisguise { private transient LibsProfileLookup currentLookup; - private WrappedGameProfile gameProfile; + private UserProfile userProfile; private String playerName = "Herobrine"; private String tablistName; private String skinToUse; @@ -39,11 +40,11 @@ public class PlayerDisguise extends TargetedDisguise { } public PlayerDisguise(Player player) { - this(ReflectionManager.getGameProfile(player)); + this(ReflectionManager.getUserProfile(player)); } public PlayerDisguise(Player player, Player skinToUse) { - this(ReflectionManager.getGameProfile(player), ReflectionManager.getGameProfile(skinToUse)); + this(ReflectionManager.getUserProfile(player), ReflectionManager.getUserProfile(skinToUse)); } public PlayerDisguise(String name) { @@ -54,7 +55,7 @@ public class PlayerDisguise extends TargetedDisguise { this(); if (name.equals(skinToUse)) { - WrappedGameProfile profile = getProfile(skinToUse); + UserProfile profile = getProfile(skinToUse); if (profile != null) { setName(profile.getName()); @@ -70,22 +71,22 @@ public class PlayerDisguise extends TargetedDisguise { createDisguise(); } - public PlayerDisguise(WrappedGameProfile gameProfile) { + public PlayerDisguise(UserProfile userProfile) { this(); - setName(gameProfile.getName()); + setName(userProfile.getName()); - this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(getUUID(), gameProfile.getName(), gameProfile); + this.userProfile = ReflectionManager.getUserProfileWithThisSkin(getUUID(), userProfile.getName(), userProfile); createDisguise(); } - public PlayerDisguise(WrappedGameProfile gameProfile, WrappedGameProfile skinToUse) { + public PlayerDisguise(UserProfile userProfile, UserProfile skinToUse) { this(); - setName(gameProfile.getName()); + setName(userProfile.getName()); - this.gameProfile = ReflectionManager.getGameProfile(getUUID(), gameProfile.getName()); + this.userProfile = ReflectionManager.getUserProfile(getUUID(), userProfile.getName()); setSkin(skinToUse); @@ -238,10 +239,10 @@ public class PlayerDisguise extends TargetedDisguise { disguise.setWatcher(getWatcher().clone(disguise)); } - if (currentLookup == null && gameProfile != null) { + if (currentLookup == null && userProfile != null) { disguise.skinToUse = getSkin(); - disguise.gameProfile = - ReflectionManager.getGameProfileWithThisSkin(disguise.getUUID(), getGameProfile().getName(), getGameProfile()); + disguise.userProfile = + ReflectionManager.getUserProfileWithThisSkin(disguise.getUUID(), getUserProfile().getName(), getUserProfile()); } else { disguise.setSkin(getSkin()); } @@ -257,21 +258,25 @@ public class PlayerDisguise extends TargetedDisguise { return disguise; } - public WrappedGameProfile getGameProfile() { - if (gameProfile == null) { + public UserProfile getUserProfile() { + if (userProfile == null) { if (getSkin() != null) { - gameProfile = ReflectionManager.getGameProfile(getUUID(), getProfileName()); + userProfile = ReflectionManager.getUserProfile(getUUID(), getProfileName()); } else { - gameProfile = - ReflectionManager.getGameProfileWithThisSkin(getUUID(), getProfileName(), DisguiseUtilities.getProfileFromMojang(this)); + userProfile = + ReflectionManager.getUserProfileWithThisSkin(getUUID(), getProfileName(), DisguiseUtilities.getProfileFromMojang(this)); } } - return gameProfile; + return userProfile; } - public void setGameProfile(WrappedGameProfile gameProfile) { - this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(getUUID(), gameProfile.getName(), gameProfile); + public void setGameProfile(GameProfile userProfile) { + setUserProfile(ReflectionManager.getUserProfile(userProfile)); + } + + public void setUserProfile(UserProfile userProfile) { + this.userProfile = ReflectionManager.getUserProfileWithThisSkin(getUUID(), this.userProfile.getName(), this.userProfile); } public String getName() { @@ -312,6 +317,8 @@ public class PlayerDisguise extends TargetedDisguise { cLimit = ((NmsVersion.v1_13.isSupported() ? 64 : 16) * 2) + 16; break; case ARMORSTANDS: + // This limit seems weird, we can do multilines can't we? + // Plus newer versions may extend limit cLimit = 256; break; default: @@ -358,14 +365,16 @@ public class PlayerDisguise extends TargetedDisguise { } if (isDisplayedInTab() && tablistName == null) { - PacketContainer addTab = ReflectionManager.createTablistPacket(this, PlayerInfoAction.UPDATE_DISPLAY_NAME); for (Player player : Bukkit.getOnlinePlayers()) { if (!canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab); + PacketWrapper addTab = + DisguiseUtilities.createTablistPacket(this, WrapperPlayServerPlayerInfo.Action.UPDATE_DISPLAY_NAME); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, addTab); } } } else { @@ -383,8 +392,8 @@ public class PlayerDisguise extends TargetedDisguise { setNameVisible(!name.isEmpty(), true); playerName = name; - if (gameProfile != null) { - gameProfile = ReflectionManager.getGameProfileWithThisSkin(getUUID(), getProfileName(), getGameProfile()); + if (userProfile != null) { + userProfile = ReflectionManager.getUserProfileWithThisSkin(getUUID(), getProfileName(), getUserProfile()); } } } @@ -404,14 +413,14 @@ public class PlayerDisguise extends TargetedDisguise { return; } - PacketContainer addTab = ReflectionManager.createTablistPacket(this, PlayerInfoAction.UPDATE_DISPLAY_NAME); - for (Player player : Bukkit.getOnlinePlayers()) { if (!canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab); + PacketWrapper addTab = DisguiseUtilities.createTablistPacket(this, WrapperPlayServerPlayerInfo.Action.UPDATE_DISPLAY_NAME); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, addTab); } } @@ -429,8 +438,8 @@ public class PlayerDisguise extends TargetedDisguise { scoreboardName = null; } - if (gameProfile != null) { - gameProfile = ReflectionManager.getGameProfileWithThisSkin(getUUID(), getProfileName(), getGameProfile()); + if (userProfile != null) { + userProfile = ReflectionManager.getUserProfileWithThisSkin(getUUID(), getProfileName(), getUserProfile()); } if (!startDisguise()) { @@ -446,7 +455,7 @@ public class PlayerDisguise extends TargetedDisguise { } public PlayerDisguise setSkin(String newSkin) { - WrappedGameProfile profile = getProfile(newSkin); + UserProfile profile = getProfile(newSkin); if (profile != null) { return setSkin(profile); @@ -469,7 +478,7 @@ public class PlayerDisguise extends TargetedDisguise { if (newSkin == null) { currentLookup = null; - gameProfile = null; + userProfile = null; } else { if (newSkin.length() > 16) { skinToUse = newSkin.substring(0, 16); @@ -482,22 +491,22 @@ public class PlayerDisguise extends TargetedDisguise { if (isDisguiseInUse()) { currentLookup = new LibsProfileLookup() { @Override - public void onLookup(WrappedGameProfile gameProfile) { - if (currentLookup != this || gameProfile == null || gameProfile.getProperties().isEmpty()) { + public void onLookup(UserProfile userProfile) { + if (currentLookup != this || userProfile == null || userProfile.getTextureProperties().isEmpty()) { return; } - setSkin(gameProfile); + setSkin(userProfile); currentLookup = null; } }; - WrappedGameProfile gameProfile = + UserProfile userProfile = DisguiseUtilities.getProfileFromMojang(this.skinToUse, currentLookup, DisguiseConfig.isContactMojangServers()); - if (gameProfile != null) { - setSkin(gameProfile); + if (userProfile != null) { + setSkin(userProfile); } } } @@ -506,33 +515,33 @@ public class PlayerDisguise extends TargetedDisguise { } /** - * Set the GameProfile, without tampering. + * Set the UserProfile * - * @param gameProfile GameProfile + * @param userProfile UserProfile * @return */ - public PlayerDisguise setSkin(WrappedGameProfile gameProfile) { - if (gameProfile == null) { - this.gameProfile = null; + public PlayerDisguise setSkin(UserProfile userProfile) { + if (userProfile == null) { + this.userProfile = null; this.skinToUse = null; return this; } currentLookup = null; - this.skinToUse = gameProfile.getName(); - this.gameProfile = ReflectionManager.getGameProfileWithThisSkin(getUUID(), getProfileName(), gameProfile); + this.skinToUse = userProfile.getName(); + this.userProfile = ReflectionManager.getUserProfileWithThisSkin(getUUID(), getProfileName(), userProfile); refreshDisguise(); return this; } - private WrappedGameProfile getProfile(String string) { - if (string != null && string.length() > 70 && string.startsWith("{\"id\":") && string.endsWith("}") && - string.contains(",\"name\":")) { + private UserProfile getProfile(String string) { + if (string != null && string.length() > 70 && (string.startsWith("{\"uuid\":") || string.startsWith("{\"id\":")) && + string.endsWith("}") && string.contains(",\"name\":")) { try { - return DisguiseUtilities.getGson().fromJson(string, WrappedGameProfile.class); + return DisguiseUtilities.getGson().fromJson(string, UserProfile.class); } catch (Exception ex) { throw new IllegalStateException("Tried to parse " + string + " to a GameProfile, but it has been formatted incorrectly!"); } @@ -547,16 +556,16 @@ public class PlayerDisguise extends TargetedDisguise { } if (DisguiseUtilities.isFancyHiddenTabs() || isDisplayedInTab()) { - PacketContainer addTab = ReflectionManager.createTablistAddPackets(this); - PacketContainer deleteTab = ReflectionManager.createTablistPacket(this, PlayerInfoAction.REMOVE_PLAYER); - for (Player player : Bukkit.getOnlinePlayers()) { if (!canSee(player)) { continue; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, addTab); + PacketWrapper addTab = DisguiseUtilities.createTablistAddPackets(this); + PacketWrapper deleteTab = DisguiseUtilities.createTablistPacket(this, WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER); + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, deleteTab); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, addTab); } } @@ -647,25 +656,25 @@ public class PlayerDisguise extends TargetedDisguise { return false; } - if (skinToUse != null && gameProfile == null) { + if (skinToUse != null && userProfile == null) { currentLookup = new LibsProfileLookup() { @Override - public void onLookup(WrappedGameProfile gameProfile) { - if (currentLookup != this || gameProfile == null || gameProfile.getProperties().isEmpty()) { + public void onLookup(UserProfile userProfile) { + if (currentLookup != this || userProfile == null || userProfile.getTextureProperties().isEmpty()) { return; } - setSkin(gameProfile); + setSkin(userProfile); currentLookup = null; } }; - WrappedGameProfile gameProfile = + UserProfile userProfile = DisguiseUtilities.getProfileFromMojang(this.skinToUse, currentLookup, DisguiseConfig.isContactMojangServers()); - if (gameProfile != null) { - setSkin(gameProfile); + if (userProfile != null) { + setSkin(userProfile); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/RabbitType.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/RabbitType.java index 527e78be..a18518bf 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/RabbitType.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/RabbitType.java @@ -1,31 +1,43 @@ package me.libraryaddict.disguise.disguisetypes; -public enum RabbitType { - BLACK(2), - BROWN(0), - GOLD(4), - KILLER_BUNNY(99), - PATCHES(3), - PEPPER(5), - WHITE(1); +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Rabbit; - public static RabbitType getType(int id) { +@RequiredArgsConstructor +@Getter +public enum RabbitType { + BLACK(2, Rabbit.Type.BLACK), + BROWN(0, Rabbit.Type.BROWN), + GOLD(4, Rabbit.Type.GOLD), + KILLER_BUNNY(99, Rabbit.Type.THE_KILLER_BUNNY), + PATCHES(3, Rabbit.Type.BLACK_AND_WHITE), + PEPPER(5, Rabbit.Type.SALT_AND_PEPPER), + WHITE(1, Rabbit.Type.WHITE); + + public static Rabbit.Type getType(int id) { for (RabbitType type : values()) { - if (type.getTypeId() == id) { - return type; + if (type.getTypeId() != id) { + continue; } + + return type.getType(); } return null; } + public static int getTypeId(Rabbit.Type rabbitType) { + for (RabbitType type : values()) { + if (type.getType() != rabbitType) { + continue; + } - private final int type; + return type.getTypeId(); + } - RabbitType(int type) { - this.type = type; + throw new IllegalStateException("Unknown rabbit type " + rabbitType); } - public int getTypeId() { - return type; - } + private final int typeId; + private final Rabbit.Type type; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/TargetedDisguise.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/TargetedDisguise.java index fc75bc20..60e85c43 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/TargetedDisguise.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/TargetedDisguise.java @@ -1,7 +1,7 @@ package me.libraryaddict.disguise.disguisetypes; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; @@ -52,9 +52,9 @@ public abstract class TargetedDisguise extends Disguise { Player player = Bukkit.getPlayerExact(playername); if (player != null) { - PacketContainer deleteTab = ReflectionManager.updateTablistVisibility((Player) getEntity(), !canSee(player)); + PacketWrapper deleteTab = DisguiseUtilities.updateTablistVisibility((Player) getEntity(), !canSee(player)); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, deleteTab); } } } @@ -113,9 +113,9 @@ public abstract class TargetedDisguise extends Disguise { Player player = Bukkit.getPlayerExact(playername); if (player != null) { - PacketContainer deleteTab = ReflectionManager.updateTablistVisibility((Player) getEntity(), canSee(player)); + PacketWrapper deleteTab = DisguiseUtilities.updateTablistVisibility((Player) getEntity(), canSee(player)); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, deleteTab); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, deleteTab); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/VillagerData.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/VillagerData.java deleted file mode 100644 index 316832b6..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/VillagerData.java +++ /dev/null @@ -1,30 +0,0 @@ -package me.libraryaddict.disguise.disguisetypes; - -import org.bukkit.entity.Villager; - -/** - * Created by libraryaddict on 6/05/2019. - */ -public class VillagerData { - private final Villager.Type type; - private final Villager.Profession profession; - private final int level; - - public VillagerData(Villager.Type type, Villager.Profession profession, int level) { - this.type = type; - this.profession = profession; - this.level = level; - } - - public Villager.Type getType() { - return type; - } - - public Villager.Profession getProfession() { - return profession; - } - - public int getLevel() { - return level; - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AbstractHorseWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AbstractHorseWatcher.java index eb1ecc70..9111ed60 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AbstractHorseWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AbstractHorseWatcher.java @@ -3,6 +3,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsRemovedIn; import java.util.Optional; @@ -20,6 +21,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { } @NmsRemovedIn(NmsVersion.v1_19_R3) + @MethodDescription public void setOwner(UUID uuid) { setData(MetaIndex.HORSE_OWNER, Optional.of(uuid)); sendData(MetaIndex.HORSE_OWNER); @@ -34,6 +36,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(REPRODUCED); } + @MethodDescription(noVisibleDifference = true) public void setReproduced(boolean reproduced) { setHorseFlag(REPRODUCED, reproduced); } @@ -47,6 +50,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(GRAZING); } + @MethodDescription("Is the horse's head lowered?") public void setGrazing(boolean grazing) { setHorseFlag(GRAZING, grazing); } @@ -60,6 +64,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(EATING); } + @MethodDescription("Is the horse's mouth open?") public void setEating(boolean mouthOpen) { setHorseFlag(EATING, mouthOpen); } @@ -68,6 +73,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(REARING); } + @MethodDescription("Is the horse rearing in the air?") public void setRearing(boolean rear) { setHorseFlag(REARING, rear); } @@ -76,6 +82,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(SADDLED); } + @MethodDescription("Is the horse wearing a saddle?") public void setSaddled(boolean saddled) { setHorseFlag(SADDLED, saddled); } @@ -84,6 +91,7 @@ public abstract class AbstractHorseWatcher extends AgeableWatcher { return isHorseFlag(TAMED); } + @MethodDescription("Is the horse tamed?") public void setTamed(boolean tamed) { setHorseFlag(TAMED, tamed); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AgeableWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AgeableWatcher.java index 53142c80..c3ddccaa 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AgeableWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AgeableWatcher.java @@ -2,6 +2,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; public class AgeableWatcher extends InsentientWatcher { public AgeableWatcher(Disguise disguise) { @@ -16,6 +17,7 @@ public class AgeableWatcher extends InsentientWatcher { return getData(MetaIndex.AGEABLE_BABY); } + @MethodDescription("Is this a baby?") public void setBaby(boolean isBaby) { setData(MetaIndex.AGEABLE_BABY, isBaby); sendData(MetaIndex.AGEABLE_BABY); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AllayWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AllayWatcher.java index 75e4127e..309c5b9f 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AllayWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AllayWatcher.java @@ -3,6 +3,8 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodHiddenFor; import me.libraryaddict.disguise.utilities.reflection.annotations.MethodOnlyUsedBy; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; @@ -16,6 +18,7 @@ public class AllayWatcher extends InsentientWatcher { } @NmsAddedIn(NmsVersion.v1_19_R1) + @MethodDescription("Is the Allay dancing?") public void setDancing(boolean dancing) { setData(MetaIndex.ALLAY_DANCING, dancing); sendData(MetaIndex.ALLAY_DANCING); @@ -26,7 +29,7 @@ public class AllayWatcher extends InsentientWatcher { } @NmsAddedIn(NmsVersion.v1_19_R1) - @MethodOnlyUsedBy(value = {}) // Hide from command + @MethodHiddenFor(value = {}) // Hide from command public void setCanDuplicate(boolean canDuplicate) { setData(MetaIndex.ALLAY_CAN_DUPLICATE, canDuplicate); sendData(MetaIndex.ALLAY_CAN_DUPLICATE); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AreaEffectCloudWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AreaEffectCloudWatcher.java index 7ed08d72..ebebad79 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AreaEffectCloudWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AreaEffectCloudWatcher.java @@ -1,13 +1,19 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.WrappedParticle; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.particle.data.ParticleData; +import com.github.retrooper.packetevents.protocol.particle.type.ParticleType; +import com.github.retrooper.packetevents.protocol.particle.type.ParticleTypes; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; +import me.libraryaddict.disguise.utilities.reflection.annotations.NmsRemovedIn; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Color; import org.bukkit.Particle; @@ -20,7 +26,7 @@ public class AreaEffectCloudWatcher extends FlagWatcher { public AreaEffectCloudWatcher(Disguise disguise) { super(disguise); - if (DisguiseConfig.isRandomDisguises()) { + if (!NmsVersion.v1_20_R4.isSupported() && DisguiseConfig.isRandomDisguises()) { setColor(Color.fromRGB(RandomUtils.nextInt(256), RandomUtils.nextInt(256), RandomUtils.nextInt(256))); } } @@ -29,6 +35,7 @@ public class AreaEffectCloudWatcher extends FlagWatcher { return getData(MetaIndex.AREA_EFFECT_RADIUS); } + @MethodDescription("How big is this Area Effect Cloud?") public void setRadius(float radius) { if (radius > 30) { radius = 30; @@ -40,14 +47,16 @@ public class AreaEffectCloudWatcher extends FlagWatcher { sendData(MetaIndex.AREA_EFFECT_RADIUS); } + @NmsRemovedIn(NmsVersion.v1_20_R4) public Color getColor() { - int color = getData(MetaIndex.AREA_EFFECT_CLOUD_COLOR); - return Color.fromRGB(color); + return getData(MetaIndex.AREA_EFFECT_CLOUD_COLOR); } @RandomDefaultValue + @MethodDescription("What's the color of this Area Effect Cloud?") + @NmsRemovedIn(NmsVersion.v1_20_R4) public void setColor(Color color) { - setData(MetaIndex.AREA_EFFECT_CLOUD_COLOR, color.asRGB()); + setData(MetaIndex.AREA_EFFECT_CLOUD_COLOR, color); sendData(MetaIndex.AREA_EFFECT_CLOUD_COLOR); } @@ -55,53 +64,54 @@ public class AreaEffectCloudWatcher extends FlagWatcher { return getData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS); } + @MethodDescription public void setIgnoreRadius(boolean ignore) { setData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS, ignore); sendData(MetaIndex.AREA_EFFECT_IGNORE_RADIUS); } @NmsAddedIn(NmsVersion.v1_13) - public void setParticle(Particle particle, T particleData) { - setParticle(WrappedParticle.create(particle, particleData)); - } - - @NmsAddedIn(NmsVersion.v1_13) - public WrappedParticle getParticle() { + public com.github.retrooper.packetevents.protocol.particle.Particle getParticle() { if (NmsVersion.v1_13.isSupported()) { return getData(MetaIndex.AREA_EFFECT_PARTICLE); } else { // Item crack, block crack, block dust, falling dust int particleId = getData(MetaIndex.AREA_EFFECT_PARTICLE_OLD); - Particle particle = Particle.values()[particleId]; - return WrappedParticle.create(particle, null); + return new com.github.retrooper.packetevents.protocol.particle.Particle( + (ParticleType) ParticleTypes.getById(PacketEvents.getAPI().getServerManager().getVersion().toClientVersion(), + particleId)); } } @NmsAddedIn(NmsVersion.v1_13) - public void setParticle(WrappedParticle particle) { + @MethodDescription("What particle is this Area Effect Cloud using?") + public void setParticle(com.github.retrooper.packetevents.protocol.particle.Particle particle) { if (NmsVersion.v1_13.isSupported()) { setData(MetaIndex.AREA_EFFECT_PARTICLE, particle); sendData(MetaIndex.AREA_EFFECT_PARTICLE); } else { - setParticleType(particle.getParticle()); + setParticleType((Particle) SpigotConversionUtil.toBukkitParticle(particle.getType())); } } + @Deprecated public Particle getParticleType() { if (NmsVersion.v1_13.isSupported()) { - return getParticle().getParticle(); + return (Particle) SpigotConversionUtil.toBukkitParticle(getData(MetaIndex.AREA_EFFECT_PARTICLE).getType()); } else { return Particle.values()[getData(MetaIndex.AREA_EFFECT_PARTICLE_OLD)]; } } + @Deprecated + @MethodDescription("What particle type is this Area Effect Cloud using?") public void setParticleType(Particle particle) { if (NmsVersion.v1_13.isSupported()) { - setParticle(WrappedParticle.create(particle, null)); + setParticle( + new com.github.retrooper.packetevents.protocol.particle.Particle(SpigotConversionUtil.fromBukkitParticle(particle))); } else { setData(MetaIndex.AREA_EFFECT_PARTICLE_OLD, particle.ordinal()); - sendData(MetaIndex.AREA_EFFECT_PARTICLE_OLD); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ArmorStandWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ArmorStandWatcher.java index 371d386e..e20d774e 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ArmorStandWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ArmorStandWatcher.java @@ -1,8 +1,9 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.Vector3F; +import com.github.retrooper.packetevents.util.Vector3f; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import org.bukkit.util.EulerAngle; public class ArmorStandWatcher extends LivingWatcher { @@ -18,6 +19,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_BODY); } + @MethodDescription("The body rotation of the ArmorStand") public void setBody(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_BODY, vector); } @@ -26,6 +28,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_HEAD); } + @MethodDescription("The head rotation of the ArmorStand") public void setHead(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_HEAD, vector); } @@ -34,6 +37,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_LEFT_ARM); } + @MethodDescription("The left arm rotation of the ArmorStand") public void setLeftArm(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_LEFT_ARM, vector); } @@ -42,16 +46,17 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_LEFT_LEG); } + @MethodDescription("The left leg rotation of the ArmorStand") public void setLeftLeg(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_LEFT_LEG, vector); } - private EulerAngle getPose(MetaIndex type) { + private EulerAngle getPose(MetaIndex type) { if (!hasValue(type)) { return new EulerAngle(0, 0, 0); } - Vector3F vec = getData(type); + Vector3f vec = getData(type); return new EulerAngle(vec.getX(), vec.getY(), vec.getZ()); } @@ -60,6 +65,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_RIGHT_ARM); } + @MethodDescription("The right arm rotation of the ArmorStand") public void setRightArm(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_RIGHT_ARM, vector); } @@ -68,6 +74,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getPose(MetaIndex.ARMORSTAND_RIGHT_LEG); } + @MethodDescription("The right leg rotation of the ArmorStand") public void setRightLeg(EulerAngle vector) { setPose(MetaIndex.ARMORSTAND_RIGHT_LEG, vector); } @@ -76,6 +83,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getArmorStandFlag(16); } + @MethodDescription("Can this ArmorStand be interacted with?") public void setMarker(boolean isMarker) { setArmorStandFlag(16, isMarker); } @@ -84,6 +92,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getArmorStandFlag(8); } + @MethodDescription("Does this ArmorStand have a base plate?") public void setNoBasePlate(boolean noBasePlate) { setArmorStandFlag(8, noBasePlate); } @@ -92,6 +101,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getArmorStandFlag(2); } + @MethodDescription public void setNoGravity(boolean noGravity) { setArmorStandFlag(2, noGravity); } @@ -100,6 +110,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getArmorStandFlag(4); } + @MethodDescription("Can you see this ArmorStand's arms?") public void setShowArms(boolean showArms) { setArmorStandFlag(4, showArms); } @@ -108,6 +119,7 @@ public class ArmorStandWatcher extends LivingWatcher { return getArmorStandFlag(1); } + @MethodDescription("Is this ArmorStand small?") public void setSmall(boolean isSmall) { setArmorStandFlag(1, isSmall); } @@ -125,8 +137,8 @@ public class ArmorStandWatcher extends LivingWatcher { sendData(MetaIndex.ARMORSTAND_META); } - private void setPose(MetaIndex type, EulerAngle vector) { - setData(type, new Vector3F((float) vector.getX(), (float) vector.getY(), (float) vector.getZ())); + private void setPose(MetaIndex type, EulerAngle vector) { + setData(type, new Vector3f((float) vector.getX(), (float) vector.getY(), (float) vector.getZ())); sendData(type); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AxolotlWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AxolotlWatcher.java index 8db6c3d6..a1c701ab 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AxolotlWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/AxolotlWatcher.java @@ -2,6 +2,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import org.bukkit.entity.Axolotl; /** @@ -16,17 +17,19 @@ public class AxolotlWatcher extends AgeableWatcher { return getData(MetaIndex.AXOLOTL_PLAYING_DEAD); } + @MethodDescription("Is this Axolotl playing dead?") public void setPlayingDead(boolean playingDead) { setData(MetaIndex.AXOLOTL_PLAYING_DEAD, playingDead); sendData(MetaIndex.AXOLOTL_PLAYING_DEAD); } public Axolotl.Variant getVariant() { - return Axolotl.Variant.values()[getData(MetaIndex.AXOLOTL_VARIANT)]; + return getData(MetaIndex.AXOLOTL_VARIANT); } + @MethodDescription("What variant of Axolotl is this?") public void setVariant(Axolotl.Variant variant) { - setData(MetaIndex.AXOLOTL_VARIANT, variant.ordinal()); + setData(MetaIndex.AXOLOTL_VARIANT, variant); sendData(MetaIndex.AXOLOTL_VARIANT); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BatWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BatWatcher.java index 291f6fbe..5834ad5b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BatWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BatWatcher.java @@ -2,6 +2,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; public class BatWatcher extends InsentientWatcher { @@ -15,6 +16,7 @@ public class BatWatcher extends InsentientWatcher { return getData(MetaIndex.BAT_HANGING) == 1; } + @MethodDescription("Is this bat hanging upside down? Otherwise it's flying.") public void setHanging(boolean hanging) { setData(MetaIndex.BAT_HANGING, hanging ? (byte) 1 : (byte) 0); sendData(MetaIndex.BAT_HANGING); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BlockDisplayWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BlockDisplayWatcher.java index 46ecedc6..fc94beb7 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BlockDisplayWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BlockDisplayWatcher.java @@ -1,9 +1,12 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; -import org.bukkit.Bukkit; -import org.bukkit.Material; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodMappedAs; import org.bukkit.block.data.BlockData; import org.joml.Vector3f; @@ -12,17 +15,28 @@ public class BlockDisplayWatcher extends DisplayWatcher { super(disguise); // So we're not seeing air - setBlock(Bukkit.createBlockData(Material.STONE)); + setBlockState(WrappedBlockState.getDefaultState(StateTypes.STONE)); // So its centered setTranslation(new Vector3f(-0.5f, 0f, -0.5f)); } - public BlockData getBlock() { + @MethodMappedAs("getBlock") + public WrappedBlockState getBlockState() { return getData(MetaIndex.BLOCK_DISPLAY_BLOCK_STATE); } - public void setBlock(BlockData block) { + @MethodDescription("What block can players see?") + @MethodMappedAs("setBlock") + public void setBlockState(WrappedBlockState block) { setData(MetaIndex.BLOCK_DISPLAY_BLOCK_STATE, block); + } + + public BlockData getBlock() { + return SpigotConversionUtil.toBukkitBlockData(getData(MetaIndex.BLOCK_DISPLAY_BLOCK_STATE)); + } + + public void setBlock(BlockData block) { + setData(MetaIndex.BLOCK_DISPLAY_BLOCK_STATE, SpigotConversionUtil.fromBukkitBlockData(block)); sendData(MetaIndex.BLOCK_DISPLAY_BLOCK_STATE); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BoatWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BoatWatcher.java index 7767663b..75ac7a67 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BoatWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/BoatWatcher.java @@ -3,21 +3,31 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoBoatType; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodMappedAs; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; +import me.libraryaddict.disguise.utilities.reflection.annotations.NmsRemovedIn; import org.bukkit.TreeSpecies; +import org.bukkit.entity.Boat; public class BoatWatcher extends FlagWatcher { public BoatWatcher(Disguise disguise) { super(disguise); - setBoatType(TreeSpecies.GENERIC); + if (NmsVersion.v1_19_R1.isSupported()) { + setType(Boat.Type.OAK); + } else { + setBoatType(TreeSpecies.GENERIC); + } } public float getDamage() { return getData(MetaIndex.BOAT_DAMAGE); } + @MethodDescription("No visible difference") public void setDamage(float dmg) { setData(MetaIndex.BOAT_DAMAGE, dmg); sendData(MetaIndex.BOAT_DAMAGE); @@ -27,6 +37,7 @@ public class BoatWatcher extends FlagWatcher { return getData(MetaIndex.BOAT_RIGHT_PADDLING); } + @MethodDescription("Is the boat's right paddle moving?") public void setRightPaddling(boolean rightPaddling) { setData(MetaIndex.BOAT_RIGHT_PADDLING, rightPaddling); sendData(MetaIndex.BOAT_RIGHT_PADDLING); @@ -36,6 +47,7 @@ public class BoatWatcher extends FlagWatcher { return getData(MetaIndex.BOAT_LEFT_PADDLING); } + @MethodDescription("Is the boat's left paddle moving?") public void setLeftPaddling(boolean leftPaddling) { setData(MetaIndex.BOAT_LEFT_PADDLING, leftPaddling); sendData(MetaIndex.BOAT_LEFT_PADDLING); @@ -47,17 +59,44 @@ public class BoatWatcher extends FlagWatcher { } @NmsAddedIn(NmsVersion.v1_13) + @MethodDescription("How violently does this boat shake when damaged?") public void setBoatShake(int number) { setData(MetaIndex.BOAT_SHAKE, number); sendData(MetaIndex.BOAT_SHAKE); } - public TreeSpecies getBoatType() { - return TreeSpecies.getByData(getData(MetaIndex.BOAT_TYPE).byteValue()); + @NmsAddedIn(NmsVersion.v1_19_R1) + @MethodMappedAs("getBoatType") + public Boat.Type getType() { + return getData(MetaIndex.BOAT_TYPE_NEW); } + @NmsAddedIn(NmsVersion.v1_19_R1) + @MethodMappedAs("setBoatType") + @MethodDescription("What type of wood is this boat made of?") + public void setType(Boat.Type type) { + setData(MetaIndex.BOAT_TYPE_NEW, type); + sendData(MetaIndex.BOAT_TYPE_NEW); + } + + @NmsRemovedIn(NmsVersion.v1_19_R1) + public TreeSpecies getBoatType() { + if (NmsVersion.v1_19_R1.isSupported()) { + return ParamInfoBoatType.getSpeciesFromType(getType()); + } + + return getData(MetaIndex.BOAT_TYPE_OLD); + } + + @NmsRemovedIn(NmsVersion.v1_19_R1) + @MethodDescription("What type of wood is this boat made of?") public void setBoatType(TreeSpecies boatType) { - setData(MetaIndex.BOAT_TYPE, (int) boatType.getData()); - sendData(MetaIndex.BOAT_TYPE); + if (NmsVersion.v1_19_R1.isSupported()) { + setType(ParamInfoBoatType.getTypeFromSpecies(boatType)); + return; + } + + setData(MetaIndex.BOAT_TYPE_OLD, boatType); + sendData(MetaIndex.BOAT_TYPE_OLD); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CamelWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CamelWatcher.java index 01cbf754..ff13e428 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CamelWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CamelWatcher.java @@ -2,6 +2,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; public class CamelWatcher extends AbstractHorseWatcher { public CamelWatcher(Disguise disguise) { @@ -12,6 +13,7 @@ public class CamelWatcher extends AbstractHorseWatcher { return getData(MetaIndex.CAMEL_DASHING); } + @MethodDescription("Is this Camel dashing?") public void setDashing(boolean dashing) { setData(MetaIndex.CAMEL_DASHING, dashing); sendData(MetaIndex.CAMEL_DASHING); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CatWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CatWatcher.java index 3a9f8f75..36539a46 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CatWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CatWatcher.java @@ -7,6 +7,7 @@ import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.DyeColor; import org.bukkit.entity.Cat; @@ -27,27 +28,18 @@ public class CatWatcher extends TameableWatcher { } public Cat.Type getType() { - if (NmsVersion.v1_19_R1.isSupported()) { - return getData(MetaIndex.CAT_TYPE_NEW); - } - - return Cat.Type.values()[getData(MetaIndex.CAT_TYPE)]; + return getData(MetaIndex.CAT_TYPE); } @RandomDefaultValue + @MethodDescription("What variant of Cat is this?") public void setType(Cat.Type type) { - if (NmsVersion.v1_19_R1.isSupported()) { - setData(MetaIndex.CAT_TYPE_NEW, type); - sendData(MetaIndex.CAT_TYPE_NEW); - return; - } - - setData(MetaIndex.CAT_TYPE, type.ordinal()); + setData(MetaIndex.CAT_TYPE, type); sendData(MetaIndex.CAT_TYPE); } public DyeColor getCollarColor() { - return AnimalColor.getColorByWool(getData(MetaIndex.CAT_COLLAR)).getDyeColor(); + return getData(MetaIndex.CAT_COLLAR).getDyeColor(); } @Deprecated @@ -55,16 +47,17 @@ public class CatWatcher extends TameableWatcher { setCollarColor(color.getDyeColor()); } + @MethodDescription("What's the Cat's collar color?") public void setCollarColor(DyeColor newColor) { if (!isTamed()) { setTamed(true); } - if (newColor == getCollarColor()) { + if (hasValue(MetaIndex.CAT_COLLAR) && newColor == getCollarColor()) { return; } - setData(MetaIndex.CAT_COLLAR, (int) newColor.getWoolData()); + setData(MetaIndex.CAT_COLLAR, AnimalColor.getColorByWool(newColor.getWoolData())); sendData(MetaIndex.CAT_COLLAR); } @@ -72,6 +65,7 @@ public class CatWatcher extends TameableWatcher { return getData(MetaIndex.CAT_LYING_DOWN); } + @MethodDescription("Is the Cat lying down?") public void setLyingDown(boolean value) { setData(MetaIndex.CAT_LYING_DOWN, value); sendData(MetaIndex.CAT_LYING_DOWN); @@ -81,6 +75,7 @@ public class CatWatcher extends TameableWatcher { return getData(MetaIndex.CAT_LOOKING_UP); } + @MethodDescription("Is the Cat looking upwards?") public void setLookingUp(boolean value) { setData(MetaIndex.CAT_LOOKING_UP, value); sendData(MetaIndex.CAT_LOOKING_UP); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ChestedHorseWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ChestedHorseWatcher.java index 56538f6f..bbf417e5 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ChestedHorseWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ChestedHorseWatcher.java @@ -2,6 +2,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; public class ChestedHorseWatcher extends AbstractHorseWatcher { @@ -13,6 +14,7 @@ public class ChestedHorseWatcher extends AbstractHorseWatcher { return getData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST); } + @MethodDescription("Is this Horse wearing a chest?") public void setCarryingChest(boolean carryingChest) { setData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST, carryingChest); sendData(MetaIndex.HORSE_CHESTED_CARRYING_CHEST); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CreeperWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CreeperWatcher.java index e5c7db7b..4d45929b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CreeperWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/CreeperWatcher.java @@ -3,6 +3,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.DisguiseUtilities; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import org.bukkit.entity.Creeper; public class CreeperWatcher extends InsentientWatcher { @@ -15,6 +16,7 @@ public class CreeperWatcher extends InsentientWatcher { return getData(MetaIndex.CREEPER_IGNITED); } + @MethodDescription("Is this Creeper puffed up and about to explode") public void setIgnited(boolean ignited) { // If creeper is already ignited and they want to set it to unignited, then resend disguise boolean resend = !ignited && getDisguise() != null && getDisguise().isDisguiseInUse() && @@ -33,6 +35,7 @@ public class CreeperWatcher extends InsentientWatcher { return getData(MetaIndex.CREEPER_POWERED); } + @MethodDescription("Is this Creeper covered in lightning?") public void setPowered(boolean powered) { setData(MetaIndex.CREEPER_POWERED, powered); sendData(MetaIndex.CREEPER_POWERED); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DisplayWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DisplayWatcher.java index f273bf82..123ebdec 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DisplayWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DisplayWatcher.java @@ -1,5 +1,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.util.Quaternion4f; +import com.github.retrooper.packetevents.util.Vector3f; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; @@ -8,7 +10,6 @@ import org.bukkit.Color; import org.bukkit.entity.Display; import org.bukkit.util.Transformation; import org.joml.Quaternionf; -import org.joml.Vector3f; public abstract class DisplayWatcher extends FlagWatcher { public DisplayWatcher(Disguise disguise) { @@ -16,60 +17,68 @@ public abstract class DisplayWatcher extends FlagWatcher { } public Transformation getTransformation() { - Vector3f transformation = getData(MetaIndex.DISPLAY_TRANSLATION); - Quaternionf leftRotation = getData(MetaIndex.DISPLAY_LEFT_ROTATION); - Quaternionf rightRotation = getData(MetaIndex.DISPLAY_RIGHT_ROTATION); - Vector3f scale = getData(MetaIndex.DISPLAY_SCALE); - - return new Transformation(transformation, leftRotation, scale, rightRotation); + return new Transformation(getTranslation(), getLeftRotation(), getScale(), getRightRotation()); } // Because BlockDisplayWatcher modifies this on startup.. @RandomDefaultValue public void setTransformation(Transformation transformation) { - setData(MetaIndex.DISPLAY_TRANSLATION, transformation.getTranslation()); - setData(MetaIndex.DISPLAY_LEFT_ROTATION, transformation.getLeftRotation()); - setData(MetaIndex.DISPLAY_RIGHT_ROTATION, transformation.getRightRotation()); - setData(MetaIndex.DISPLAY_SCALE, transformation.getScale()); + org.joml.Vector3f trans = transformation.getTranslation(); + Quaternionf rl = transformation.getLeftRotation(); + Quaternionf rr = transformation.getRightRotation(); + org.joml.Vector3f scale = transformation.getScale(); + + setData(MetaIndex.DISPLAY_TRANSLATION, new Vector3f(trans.x, trans.y, trans.z)); + setData(MetaIndex.DISPLAY_LEFT_ROTATION, new Quaternion4f(rl.x, rl.y, rl.z, rl.w)); + setData(MetaIndex.DISPLAY_RIGHT_ROTATION, new Quaternion4f(rr.x, rr.y, rr.z, rr.w)); + setData(MetaIndex.DISPLAY_SCALE, new Vector3f(scale.x, scale.y, scale.z)); sendData(MetaIndex.DISPLAY_TRANSLATION, MetaIndex.DISPLAY_LEFT_ROTATION, MetaIndex.DISPLAY_RIGHT_ROTATION, MetaIndex.DISPLAY_SCALE); } - public Vector3f getTranslation() { - return getData(MetaIndex.DISPLAY_TRANSLATION); + public org.joml.Vector3f getTranslation() { + Vector3f vec = getData(MetaIndex.DISPLAY_TRANSLATION); + + return new org.joml.Vector3f(vec.x, vec.y, vec.z); } // Because BlockDisplayWatcher modifies this on startup.. @RandomDefaultValue - public void setTranslation(Vector3f translation) { - setData(MetaIndex.DISPLAY_TRANSLATION, translation); + public void setTranslation(org.joml.Vector3f translation) { + setData(MetaIndex.DISPLAY_TRANSLATION, new Vector3f(translation.x, translation.y, translation.z)); sendData(MetaIndex.DISPLAY_TRANSLATION); } - public Vector3f getScale() { - return getData(MetaIndex.DISPLAY_SCALE); + public org.joml.Vector3f getScale() { + Vector3f vec = getData(MetaIndex.DISPLAY_SCALE); + + return new org.joml.Vector3f(vec.x, vec.y, vec.z); } - public void setScale(Vector3f scale) { - setData(MetaIndex.DISPLAY_SCALE, scale); + public void setScale(org.joml.Vector3f scale) { + setData(MetaIndex.DISPLAY_SCALE, new Vector3f(scale.x, scale.y, scale.z)); sendData(MetaIndex.DISPLAY_SCALE); } public Quaternionf getLeftRotation() { - return getData(MetaIndex.DISPLAY_LEFT_ROTATION); + Quaternion4f rot = getData(MetaIndex.DISPLAY_LEFT_ROTATION); + + return new Quaternionf(rot.getX(), rot.getY(), rot.getZ(), rot.getW()); } public void setLeftRotation(Quaternionf rotation) { - setData(MetaIndex.DISPLAY_LEFT_ROTATION, rotation); + setData(MetaIndex.DISPLAY_LEFT_ROTATION, new Quaternion4f(rotation.x, rotation.y, rotation.z, rotation.w)); sendData(MetaIndex.DISPLAY_LEFT_ROTATION); } public Quaternionf getRightRotation() { - return getData(MetaIndex.DISPLAY_LEFT_ROTATION); + Quaternion4f rot = getData(MetaIndex.DISPLAY_RIGHT_ROTATION); + + return new Quaternionf(rot.getX(), rot.getY(), rot.getZ(), rot.getW()); } public void setRightRotation(Quaternionf rotation) { - setData(MetaIndex.DISPLAY_RIGHT_ROTATION, rotation); + setData(MetaIndex.DISPLAY_RIGHT_ROTATION, new Quaternion4f(rotation.x, rotation.y, rotation.z, rotation.w)); sendData(MetaIndex.DISPLAY_RIGHT_ROTATION); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java index b42a56d0..6f861d4c 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java @@ -5,6 +5,7 @@ import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import me.libraryaddict.disguise.utilities.translations.TranslateType; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -18,6 +19,7 @@ public class DroppedItemWatcher extends FlagWatcher { return getData(MetaIndex.DROPPED_ITEM); } + @MethodDescription("What Item was dropped?") public void setItemStack(ItemStack item) { setData(MetaIndex.DROPPED_ITEM, item); sendData(MetaIndex.DROPPED_ITEM); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EnderCrystalWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EnderCrystalWatcher.java index 42ed2e11..dc0aa6af 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EnderCrystalWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EnderCrystalWatcher.java @@ -1,9 +1,10 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.BlockPosition; +import com.github.retrooper.packetevents.util.Vector3i; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodDescription; import java.util.Optional; @@ -15,11 +16,11 @@ public class EnderCrystalWatcher extends FlagWatcher { super(disguise); } - public BlockPosition getBeamTarget() { + public Vector3i getBeamTarget() { return getData(MetaIndex.ENDER_CRYSTAL_BEAM).orElse(null); } - public void setBeamTarget(BlockPosition position) { + public void setBeamTarget(Vector3i position) { setData(MetaIndex.ENDER_CRYSTAL_BEAM, position == null ? Optional.empty() : Optional.of(position)); sendData(MetaIndex.ENDER_CRYSTAL_BEAM); } @@ -28,6 +29,7 @@ public class EnderCrystalWatcher extends FlagWatcher { return getData(MetaIndex.ENDER_CRYSTAL_PLATE); } + @MethodDescription("Can you see the Ender Crystal's base plate?") public void setShowBottom(boolean bool) { setData(MetaIndex.ENDER_CRYSTAL_PLATE, bool); sendData(MetaIndex.ENDER_CRYSTAL_PLATE); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EndermanWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EndermanWatcher.java index 2e701c30..c4d5d5ec 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EndermanWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/EndermanWatcher.java @@ -1,52 +1,61 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.WrappedBlockData; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodMappedAs; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; - -import java.util.Optional; +import org.bukkit.material.MaterialData; public class EndermanWatcher extends InsentientWatcher { - public EndermanWatcher(Disguise disguise) { super(disguise); } @Override + @Deprecated public ItemStack getItemInMainHand() { - Optional value = getData(MetaIndex.ENDERMAN_ITEM); + WrappedBlockState value = getHeldBlock(); - if (value.isPresent()) { - WrappedBlockData pair = value.get(); - return new ItemStack(pair.getType(), 1); - } else { - return null; + if (!NmsVersion.v1_13.isSupported()) { + return ReflectionManager.getItemStackByCombinedId(value.getGlobalId()); } + + MaterialData pair = SpigotConversionUtil.toBukkitMaterialData(value); + + return new ItemStack(pair.getItemType(), 1, pair.getData()); } @Override + @Deprecated public void setItemInMainHand(ItemStack itemstack) { setItemInMainHand(itemstack.getType()); } + @MethodMappedAs("setItemInMainHand") + public void setHeldBlock(WrappedBlockState state) { + setData(MetaIndex.ENDERMAN_ITEM, state); + sendData(MetaIndex.ENDERMAN_ITEM); + } + + @MethodMappedAs("getItemInMainHand") + public WrappedBlockState getHeldBlock() { + return getData(MetaIndex.ENDERMAN_ITEM); + } + @Deprecated public void setItemInMainHand(Material type) { if (!type.isBlock()) { return; } - Optional optional; + WrappedBlockState item = SpigotConversionUtil.fromBukkitMaterialData(new MaterialData(type)); - if (type == null) { - optional = Optional.empty(); - } else { - optional = Optional.of(WrappedBlockData.createData(type)); - } - - setData(MetaIndex.ENDERMAN_ITEM, optional); - sendData(MetaIndex.ENDERMAN_ITEM); + setHeldBlock(item); } @Deprecated diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FallingBlockWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FallingBlockWatcher.java index 226db03c..872e21c0 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FallingBlockWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FallingBlockWatcher.java @@ -1,15 +1,16 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove; +import lombok.Getter; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodMappedAs; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import me.libraryaddict.disguise.utilities.translations.TranslateType; import org.bukkit.Location; @@ -20,6 +21,7 @@ import org.bukkit.inventory.ItemStack; public class FallingBlockWatcher extends FlagWatcher { private int blockCombinedId = 1; + @Getter private boolean gridLocked; public FallingBlockWatcher(Disguise disguise) { @@ -39,10 +41,6 @@ public class FallingBlockWatcher extends FlagWatcher { return watcher; } - public boolean isGridLocked() { - return gridLocked; - } - public void setGridLocked(boolean gridLocked) { if (isGridLocked() == gridLocked) { return; @@ -51,33 +49,21 @@ public class FallingBlockWatcher extends FlagWatcher { this.gridLocked = gridLocked; if (getDisguise().isDisguiseInUse() && getDisguise().getEntity() != null) { - PacketContainer relMove = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE); - relMove.getModifier().write(0, getDisguise().getEntity().getEntityId()); - Location loc = getDisguise().getEntity().getLocation(); - - if (NmsVersion.v1_14.isSupported()) { - StructureModifier shorts = relMove.getShorts(); - - shorts.write(0, conRel(loc.getX(), loc.getBlockX() + 0.5)); - shorts.write(1, conRel(loc.getY(), loc.getBlockY() + (loc.getY() % 1 >= 0.85 ? 1 : loc.getY() % 1 >= 0.35 ? .5 : 0))); - shorts.write(2, conRel(loc.getZ(), loc.getBlockZ() + 0.5)); - } else { - StructureModifier ints = relMove.getIntegers(); - - ints.write(0, (int) conRel(loc.getX(), loc.getBlockX() + 0.5)); - ints.write(1, (int) conRel(loc.getY(), loc.getBlockY() + (loc.getY() % 1 >= 0.85 ? 1 : loc.getY() % 1 >= 0.35 ? .5 : 0))); - ints.write(2, (int) conRel(loc.getZ(), loc.getBlockZ() + 0.5)); - } + double x = conRel(loc.getX(), loc.getBlockX() + 0.5); + double y = conRel(loc.getY(), loc.getBlockY() + (loc.getY() % 1 >= 0.85 ? 1 : loc.getY() % 1 >= 0.35 ? .5 : 0)); + double z = conRel(loc.getZ(), loc.getBlockZ() + 0.5); for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - if (player == getDisguise().getEntity()) { - PacketContainer temp = relMove.shallowClone(); - temp.getModifier().write(0, DisguiseAPI.getSelfDisguiseId()); + int entityId = + getDisguise().getEntity() == player ? DisguiseAPI.getSelfDisguiseId() : getDisguise().getEntity().getEntityId(); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, temp, isGridLocked()); + WrapperPlayServerEntityRelativeMove relMov = new WrapperPlayServerEntityRelativeMove(entityId, x, y, z, true); + + if (isGridLocked()) { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, relMov); } else { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, relMove, isGridLocked()); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, relMov); } } } @@ -108,6 +94,16 @@ public class FallingBlockWatcher extends FlagWatcher { } } + @MethodMappedAs("getBlockData") + public WrappedBlockState getBlockState() { + return WrappedBlockState.getByGlobalId(getBlockCombinedId()); + } + + @MethodMappedAs("setBlockData") + public void setBlockState(WrappedBlockState state) { + setBlockCombinedId(state.getType().getName(), state.getGlobalId()); + } + @NmsAddedIn(NmsVersion.v1_13) public BlockData getBlockData() { return ReflectionManager.getBlockDataByCombinedId(getBlockCombinedId()); @@ -120,11 +116,15 @@ public class FallingBlockWatcher extends FlagWatcher { return; } - this.blockCombinedId = ReflectionManager.getCombinedIdByBlockData(data); + setBlockCombinedId(data.getMaterial().name(), ReflectionManager.getCombinedIdByBlockData(data)); + } + + private void setBlockCombinedId(String materialName, int combinedId) { + this.blockCombinedId = combinedId; if (!getDisguise().isCustomDisguiseName()) { getDisguise().setDisguiseName(TranslateType.DISGUISE_OPTIONS_PARAMETERS.get("Block") + " " + - TranslateType.DISGUISE_OPTIONS_PARAMETERS.get(ReflectionManager.toReadable(data.getMaterial().name(), " "))); + TranslateType.DISGUISE_OPTIONS_PARAMETERS.get(ReflectionManager.toReadable(materialName, " "))); } if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FireworkWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FireworkWatcher.java index 6197301c..c34ed4fa 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FireworkWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FireworkWatcher.java @@ -8,6 +8,7 @@ import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import java.util.Optional; import java.util.OptionalInt; public class FireworkWatcher extends FlagWatcher { @@ -47,7 +48,7 @@ public class FireworkWatcher extends FlagWatcher { } @NmsAddedIn(NmsVersion.v1_14) - public OptionalInt getAttachedEntityOpt() { + public Optional getAttachedEntityOpt() { return getData(MetaIndex.FIREWORK_ATTACHED_ENTITY); } @@ -56,11 +57,11 @@ public class FireworkWatcher extends FlagWatcher { } public void setAttachedEntity(int entityId) { - setAttachedEntity(entityId == 0 ? OptionalInt.empty() : OptionalInt.of(entityId)); + setAttachedEntity(entityId == 0 ? Optional.empty() : Optional.of(entityId)); } @NmsAddedIn(NmsVersion.v1_14) - public void setAttachedEntity(OptionalInt entityId) { + public void setAttachedEntity(Optional entityId) { if (NmsVersion.v1_14.isSupported()) { setData(MetaIndex.FIREWORK_ATTACHED_ENTITY, entityId); sendData(MetaIndex.FIREWORK_ATTACHED_ENTITY); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FoxWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FoxWatcher.java index 7a68426e..b130f46a 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FoxWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/FoxWatcher.java @@ -48,12 +48,12 @@ public class FoxWatcher extends AgeableWatcher { } public Fox.Type getType() { - return Fox.Type.values()[getData(MetaIndex.FOX_TYPE)]; + return getData(MetaIndex.FOX_TYPE); } @RandomDefaultValue public void setType(Fox.Type type) { - setData(MetaIndex.FOX_TYPE, type.ordinal()); + setData(MetaIndex.FOX_TYPE, type); sendData(MetaIndex.FOX_TYPE); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java index d3b33ca8..0e1d7176 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/HorseWatcher.java @@ -22,23 +22,23 @@ public class HorseWatcher extends AbstractHorseWatcher { } public Color getColor() { - return Color.values()[(getData(MetaIndex.HORSE_COLOR) & 0xFF)]; + return Color.values()[(getData(MetaIndex.HORSE_COLOR_STYLE) & 0xFF)]; } @RandomDefaultValue public void setColor(Color color) { - setData(MetaIndex.HORSE_COLOR, color.ordinal() & 0xFF | getStyle().ordinal() << 8); - sendData(MetaIndex.HORSE_COLOR); + setData(MetaIndex.HORSE_COLOR_STYLE, color.ordinal() & 0xFF | getStyle().ordinal() << 8); + sendData(MetaIndex.HORSE_COLOR_STYLE); } public Style getStyle() { - return Style.values()[(getData(MetaIndex.HORSE_COLOR) >>> 8)]; + return Style.values()[(getData(MetaIndex.HORSE_COLOR_STYLE) >>> 8)]; } @RandomDefaultValue public void setStyle(Style style) { - setData(MetaIndex.HORSE_COLOR, getColor().ordinal() & 0xFF | style.ordinal() << 8); - sendData(MetaIndex.HORSE_COLOR); + setData(MetaIndex.HORSE_COLOR_STYLE, getColor().ordinal() & 0xFF | style.ordinal() << 8); + sendData(MetaIndex.HORSE_COLOR_STYLE); } public ItemStack getHorseArmor() { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ItemDisplayWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ItemDisplayWatcher.java index dd0973f2..3490cd41 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ItemDisplayWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ItemDisplayWatcher.java @@ -28,11 +28,11 @@ public class ItemDisplayWatcher extends DisplayWatcher { } public ItemDisplay.ItemDisplayTransform getItemDisplayTransform() { - return ItemDisplay.ItemDisplayTransform.values()[getData(MetaIndex.ITEM_DISPLAY_TRANSFORM)]; + return getData(MetaIndex.ITEM_DISPLAY_TRANSFORM); } public void setItemDisplayTransform(ItemDisplay.ItemDisplayTransform display) { - setData(MetaIndex.ITEM_DISPLAY_TRANSFORM, (byte) display.ordinal()); + setData(MetaIndex.ITEM_DISPLAY_TRANSFORM, display); sendData(MetaIndex.ITEM_DISPLAY_TRANSFORM); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java index f624509e..40e906ff 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java @@ -1,11 +1,9 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.WrappedAttribute; -import com.comphenix.protocol.wrappers.WrappedAttribute.Builder; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.attribute.Attributes; +import com.github.retrooper.packetevents.util.Vector3i; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes; import lombok.Getter; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.Disguise; @@ -18,19 +16,20 @@ import me.libraryaddict.disguise.utilities.reflection.annotations.MethodGroupTyp import me.libraryaddict.disguise.utilities.reflection.annotations.MethodOnlyUsedBy; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.Color; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.Iterator; -import java.util.List; import java.util.Optional; public class LivingWatcher extends FlagWatcher { + @Getter private double maxHealth; + @Getter private boolean maxHealthSet; private HashSet potionEffects = new HashSet<>(); @Getter @@ -52,13 +51,13 @@ public class LivingWatcher extends FlagWatcher { } @NmsAddedIn(NmsVersion.v1_14) - public BlockPosition getBedPosition() { + public Vector3i getBedPosition() { return getData(MetaIndex.LIVING_BED_POSITION).orElse(null); } @NmsAddedIn(NmsVersion.v1_14) - public void setBedPosition(BlockPosition blockPosition) { - Optional optional; + public void setBedPosition(Vector3i blockPosition) { + Optional optional; if (blockPosition != null) { optional = Optional.of(blockPosition); @@ -156,40 +155,25 @@ public class LivingWatcher extends FlagWatcher { setHandFlag(2, setSpinning); } - public double getMaxHealth() { - return maxHealth; - } - public void setMaxHealth(double newHealth) { this.maxHealth = newHealth; this.maxHealthSet = true; - if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) { - PacketContainer packet = new PacketContainer(Server.UPDATE_ATTRIBUTES); + if (!getDisguise().isDisguiseInUse() || getDisguise().getWatcher() != this) { + return; + } - List attributes = new ArrayList<>(); + for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { + WrapperPlayServerUpdateAttributes.Property property = + new WrapperPlayServerUpdateAttributes.Property(Attributes.GENERIC_MAX_HEALTH, getMaxHealth(), new ArrayList<>()); + WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes( + player == getDisguise().getEntity() ? DisguiseAPI.getSelfDisguiseId() : getDisguise().getEntity().getEntityId(), + Collections.singletonList(property)); - Builder builder; - builder = WrappedAttribute.newBuilder(); - builder.attributeKey(NmsVersion.v1_16.isSupported() ? "generic.max_health" : "generic.maxHealth"); - builder.baseValue(getMaxHealth()); - builder.packet(packet); - - attributes.add(builder.build()); - - Entity entity = getDisguise().getEntity(); - - packet.getIntegers().write(0, entity.getEntityId()); - packet.getAttributeCollectionModifier().write(0, attributes); - - for (Player player : DisguiseUtilities.getPerverts(getDisguise())) { - if (player == getDisguise().getEntity()) { - PacketContainer p = packet.shallowClone(); - p.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, p, false); - } else { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); - } + if (player == getDisguise().getEntity()) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); + } else { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } } } @@ -251,10 +235,6 @@ public class LivingWatcher extends FlagWatcher { return potionEffects.contains(type.getName()); } - public boolean isMaxHealthSet() { - return maxHealthSet; - } - public PotionEffectType[] getPotionEffects() { PotionEffectType[] effects = new PotionEffectType[potionEffects.size()]; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LlamaWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LlamaWatcher.java index b65e7c99..31608f49 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LlamaWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/LlamaWatcher.java @@ -13,11 +13,11 @@ public class LlamaWatcher extends ChestedHorseWatcher { } public Llama.Color getColor() { - return Llama.Color.values()[getData(MetaIndex.LLAMA_COLOR)]; + return getData(MetaIndex.LLAMA_COLOR); } public void setColor(Llama.Color color) { - setData(MetaIndex.LLAMA_COLOR, color.ordinal()); + setData(MetaIndex.LLAMA_COLOR, color); sendData(MetaIndex.LLAMA_COLOR); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/MinecartWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/MinecartWatcher.java index 3bab32f3..7a0e5acf 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/MinecartWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/MinecartWatcher.java @@ -1,5 +1,7 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; @@ -33,12 +35,25 @@ public class MinecartWatcher extends FlagWatcher { sendData(MetaIndex.MINECART_BLOCK, MetaIndex.MINECART_BLOCK_VISIBLE); } + public WrappedBlockState getBlock() { + return WrappedBlockState.getByGlobalId(getData(MetaIndex.MINECART_BLOCK)); + } + + public void setBlock(WrappedBlockState state) { + setData(MetaIndex.MINECART_BLOCK, state == null || state.getType() == StateTypes.AIR ? 0 : state.getGlobalId()); + setData(MetaIndex.MINECART_BLOCK_VISIBLE, state != null && state.getType() != StateTypes.AIR); + + sendData(MetaIndex.MINECART_BLOCK, MetaIndex.MINECART_BLOCK_VISIBLE); + } + @NmsAddedIn(NmsVersion.v1_13) + @Deprecated public BlockData getBlockData() { return ReflectionManager.getBlockDataByCombinedId(getData(MetaIndex.MINECART_BLOCK)); } @NmsAddedIn(NmsVersion.v1_13) + @Deprecated public void setBlockData(BlockData data) { setData(MetaIndex.MINECART_BLOCK, ReflectionManager.getCombinedIdByBlockData(data)); setData(MetaIndex.MINECART_BLOCK_VISIBLE, data != null && data.getMaterial() != Material.AIR); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/OcelotWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/OcelotWatcher.java index 2889aa70..c1f1236b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/OcelotWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/OcelotWatcher.java @@ -30,13 +30,13 @@ public class OcelotWatcher extends AgeableWatcher { @NmsRemovedIn(NmsVersion.v1_14) @Deprecated public Ocelot.Type getType() { - return Ocelot.Type.getType(getData(MetaIndex.OCELOT_TYPE)); + return getData(MetaIndex.OCELOT_TYPE); } @NmsRemovedIn(NmsVersion.v1_14) @Deprecated public void setType(Ocelot.Type newType) { - setData(MetaIndex.OCELOT_TYPE, newType.getId()); + setData(MetaIndex.OCELOT_TYPE, newType); sendData(MetaIndex.OCELOT_TYPE); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PandaWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PandaWatcher.java index 254ab991..3e5cd93a 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PandaWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PandaWatcher.java @@ -37,42 +37,22 @@ public class PandaWatcher extends AgeableWatcher { } public Panda.Gene getMainGene() { - int id = getData(MetaIndex.PANDA_MAIN_GENE); - - for (Panda.Gene gene : Panda.Gene.values()) { - if (gene.ordinal() != id) { - continue; - } - - return gene; - } - - return Panda.Gene.NORMAL; + return getData(MetaIndex.PANDA_MAIN_GENE); } @MethodOnlyUsedBy(value = {}) // Hide from command public void setMainGene(Panda.Gene gene) { - setData(MetaIndex.PANDA_MAIN_GENE, (byte) gene.ordinal()); + setData(MetaIndex.PANDA_MAIN_GENE, gene); sendData(MetaIndex.PANDA_MAIN_GENE); } public Panda.Gene getHiddenGene() { - int id = getData(MetaIndex.PANDA_HIDDEN_GENE); - - for (Panda.Gene gene : Panda.Gene.values()) { - if (gene.ordinal() != id) { - continue; - } - - return gene; - } - - return Panda.Gene.NORMAL; + return getData(MetaIndex.PANDA_HIDDEN_GENE); } @MethodOnlyUsedBy(value = {}) // Hide from command public void setHiddenGene(Panda.Gene gene) { - setData(MetaIndex.PANDA_HIDDEN_GENE, (byte) gene.ordinal()); + setData(MetaIndex.PANDA_HIDDEN_GENE, gene); sendData(MetaIndex.PANDA_HIDDEN_GENE); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ParrotWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ParrotWatcher.java index 8aaa40fe..d6ddefd6 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ParrotWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ParrotWatcher.java @@ -13,11 +13,11 @@ public class ParrotWatcher extends TameableWatcher { } public Parrot.Variant getVariant() { - return Parrot.Variant.values()[getData(MetaIndex.PARROT_VARIANT)]; + return getData(MetaIndex.PARROT_VARIANT); } public void setVariant(Parrot.Variant variant) { - setData(MetaIndex.PARROT_VARIANT, variant.ordinal()); + setData(MetaIndex.PARROT_VARIANT, variant); sendData(MetaIndex.PARROT_VARIANT); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java index 3b09f433..e2c53d4d 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java @@ -1,8 +1,10 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.WrappedGameProfile; -import com.comphenix.protocol.wrappers.nbt.NbtCompound; -import com.comphenix.protocol.wrappers.nbt.NbtFactory; +import com.github.retrooper.packetevents.protocol.nbt.NBTCompound; +import com.github.retrooper.packetevents.protocol.nbt.NBTInt; +import com.github.retrooper.packetevents.protocol.nbt.NBTNumber; +import com.github.retrooper.packetevents.protocol.nbt.NBTString; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; @@ -157,8 +159,8 @@ public class PlayerWatcher extends LivingWatcher { sendData(MetaIndex.PLAYER_SKIN); } - public WrappedGameProfile getSkin() { - return ((PlayerDisguise) getDisguise()).getGameProfile(); + public UserProfile getSkin() { + return ((PlayerDisguise) getDisguise()).getUserProfile(); } public void setSkin(String playerName) { @@ -166,7 +168,7 @@ public class PlayerWatcher extends LivingWatcher { } @RandomDefaultValue - public void setSkin(WrappedGameProfile profile) { + public void setSkin(UserProfile profile) { ((PlayerDisguise) getDisguise()).setSkin(profile); } @@ -181,43 +183,23 @@ public class PlayerWatcher extends LivingWatcher { } public Parrot.Variant getRightShoulderParrot() { - NbtCompound nbt = (NbtCompound) getData(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY); - - return Parrot.Variant.values()[nbt.getIntegerOrDefault("Variant")]; + return getParrot(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY); } public void setRightShoulderParrot(Parrot.Variant variant) { - NbtCompound nbt = NbtFactory.ofCompound(""); - - if (variant != null) { - nbt.put("id", "minecraft:parrot"); - nbt.put("Variant", variant.ordinal()); - } - - setData(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY, nbt); - sendData(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY); + setParrot(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY, variant); } public Parrot.Variant getLeftShoulderParrot() { - NbtCompound nbt = (NbtCompound) getData(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY); - - return Parrot.Variant.values()[nbt.getIntegerOrDefault("Variant")]; + return getParrot(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY); } public void setLeftShoulderParrot(Parrot.Variant variant) { - NbtCompound nbt = NbtFactory.ofCompound(""); - - if (variant != null) { - nbt.put("id", "minecraft:parrot"); - nbt.put("Variant", variant.ordinal()); - } - - setData(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY, nbt); - sendData(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY); + setParrot(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY, variant); } public boolean isRightShoulderHasParrot() { - return ((NbtCompound) getData(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY)).containsKey("id"); + return getData(MetaIndex.PLAYER_RIGHT_SHOULDER_ENTITY).getStringTagOrNull("id") != null; } public void setRightShoulderHasParrot(boolean hasParrot) { @@ -233,7 +215,7 @@ public class PlayerWatcher extends LivingWatcher { } public boolean isLeftShoulderHasParrot() { - return ((NbtCompound) getData(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY)).containsKey("id"); + return getData(MetaIndex.PLAYER_LEFT_SHOULDER_ENTITY).getStringTagOrNull("id") != null; } public void setLeftShoulderHasParrot(boolean hasParrot) { @@ -247,4 +229,28 @@ public class PlayerWatcher extends LivingWatcher { setLeftShoulderParrot(null); } } + + private Parrot.Variant getParrot(MetaIndex meta) { + NBTCompound nbt = getData(meta); + + NBTNumber number = nbt.getNumberTagOrNull("Variant"); + + if (number == null) { + return Parrot.Variant.RED; + } + + return Parrot.Variant.values()[number.getAsInt()]; + } + + private void setParrot(MetaIndex meta, Parrot.Variant variant) { + NBTCompound nbt = new NBTCompound(); + + if (variant != null) { + nbt.setTag("id", new NBTString("minecraft:parrot")); + nbt.setTag("Variant", new NBTInt(variant.ordinal())); + } + + setData(meta, nbt); + sendData(meta); + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/RabbitWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/RabbitWatcher.java index bf3bca2f..edd2ff3c 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/RabbitWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/RabbitWatcher.java @@ -6,6 +6,7 @@ import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.disguisetypes.RabbitType; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; +import org.bukkit.entity.Rabbit; public class RabbitWatcher extends AgeableWatcher { @@ -13,17 +14,17 @@ public class RabbitWatcher extends AgeableWatcher { super(disguise); if (DisguiseConfig.isRandomDisguises()) { - setType(RabbitType.values()[DisguiseUtilities.random.nextInt(RabbitType.values().length)]); + setType(Rabbit.Type.values()[DisguiseUtilities.random.nextInt(Rabbit.Type.values().length)]); } } - public RabbitType getType() { - return RabbitType.getType(getData(MetaIndex.RABBIT_TYPE)); + public Rabbit.Type getType() { + return getData(MetaIndex.RABBIT_TYPE); } @RandomDefaultValue - public void setType(RabbitType type) { - setData(MetaIndex.RABBIT_TYPE, type.getTypeId()); + public void setType(Rabbit.Type type) { + setData(MetaIndex.RABBIT_TYPE, type); sendData(MetaIndex.RABBIT_TYPE); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SheepWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SheepWatcher.java index bbea8769..3de0e361 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SheepWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SheepWatcher.java @@ -1,10 +1,11 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.WrappedChatComponent; import me.libraryaddict.disguise.disguisetypes.AnimalColor; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import net.kyori.adventure.text.Component; import org.bukkit.DyeColor; import java.util.Optional; @@ -44,10 +45,9 @@ public class SheepWatcher extends AgeableWatcher { return false; } - Optional optional = getData(MetaIndex.ENTITY_CUSTOM_NAME); - - return optional.filter(wrappedChatComponent -> "{\"text\":\"jeb_\"}".equals(wrappedChatComponent.getJson())).isPresent(); + Optional optional = getData(MetaIndex.ENTITY_CUSTOM_NAME); + return optional.isPresent() && DisguiseUtilities.serialize(optional.get()).contains("\"jeb_\""); } public void setRainbowWool(boolean rainbow) { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ShulkerWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ShulkerWatcher.java index 15dd83d0..dd8b2a52 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ShulkerWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ShulkerWatcher.java @@ -1,7 +1,6 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.EnumWrappers.Direction; +import com.github.retrooper.packetevents.util.Vector3i; import me.libraryaddict.disguise.disguisetypes.AnimalColor; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; @@ -24,16 +23,16 @@ public class ShulkerWatcher extends InsentientWatcher { } public void setFacingDirection(BlockFace face) { - setData(MetaIndex.SHULKER_FACING, Direction.valueOf(face.name())); + setData(MetaIndex.SHULKER_FACING, com.github.retrooper.packetevents.protocol.world.BlockFace.valueOf(face.name())); sendData(MetaIndex.SHULKER_FACING); } - public BlockPosition getAttachmentPosition() { - return getData(MetaIndex.SHULKER_ATTACHED).orElse(BlockPosition.ORIGIN); + public Vector3i getAttachmentPosition() { + return getData(MetaIndex.SHULKER_ATTACHED).orElse(Vector3i.zero()); } - public void setAttachmentPosition(BlockPosition pos) { - setData(MetaIndex.SHULKER_ATTACHED, Optional.of(pos)); + public void setAttachmentPosition(Vector3i pos) { + setData(MetaIndex.SHULKER_ATTACHED, Optional.ofNullable(pos)); sendData(MetaIndex.SHULKER_ATTACHED); } @@ -55,7 +54,7 @@ public class ShulkerWatcher extends InsentientWatcher { } public DyeColor getColor() { - if (!hasValue(MetaIndex.SHULKER_COLOR)) { + if (!hasValue(MetaIndex.SHULKER_COLOR) || getData(MetaIndex.SHULKER_COLOR) == (byte) 16) { return DyeColor.PURPLE; } @@ -72,7 +71,7 @@ public class ShulkerWatcher extends InsentientWatcher { return; } - setData(MetaIndex.SHULKER_COLOR, newColor.getWoolData()); + setData(MetaIndex.SHULKER_COLOR, newColor == null ? (byte) 16 : newColor.getWoolData()); sendData(MetaIndex.SHULKER_COLOR); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SnifferWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SnifferWatcher.java index 135317db..e0db7975 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SnifferWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/SnifferWatcher.java @@ -1,5 +1,6 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.entity.sniffer.SnifferState; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import org.bukkit.entity.Sniffer; @@ -10,11 +11,11 @@ public class SnifferWatcher extends AgeableWatcher { } public Sniffer.State getSnifferState() { - return getData(MetaIndex.SNIFFER_STATE); + return Sniffer.State.valueOf(getData(MetaIndex.SNIFFER_STATE).name()); } public void setSnifferState(Sniffer.State state) { - setData(MetaIndex.SNIFFER_STATE, state); + setData(MetaIndex.SNIFFER_STATE, SnifferState.valueOf(state.name())); sendData(MetaIndex.SNIFFER_STATE); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TNTWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TNTWatcher.java index 4298a162..a8868c7a 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TNTWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TNTWatcher.java @@ -1,9 +1,12 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.reflection.annotations.MethodMappedAs; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.block.data.BlockData; @@ -13,13 +16,26 @@ public class TNTWatcher extends FlagWatcher { } @NmsAddedIn(NmsVersion.v1_20_R3) - public BlockData getBlock() { + @MethodMappedAs("getBlock") + public WrappedBlockState getBlockData() { return getData(MetaIndex.TNT_BLOCK_TYPE); } @NmsAddedIn(NmsVersion.v1_20_R3) - public void setBlock(BlockData block) { + @MethodMappedAs("setBlock") + public void setBlockData(WrappedBlockState block) { setData(MetaIndex.TNT_BLOCK_TYPE, block); sendData(MetaIndex.TNT_BLOCK_TYPE); } + + @NmsAddedIn(NmsVersion.v1_20_R3) + public BlockData getBlock() { + return SpigotConversionUtil.toBukkitBlockData(getData(MetaIndex.TNT_BLOCK_TYPE)); + } + + @NmsAddedIn(NmsVersion.v1_20_R3) + public void setBlock(BlockData block) { + setData(MetaIndex.TNT_BLOCK_TYPE, SpigotConversionUtil.fromBukkitBlockData(block)); + sendData(MetaIndex.TNT_BLOCK_TYPE); + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TextDisplayWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TextDisplayWatcher.java index 814a5901..def5589e 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TextDisplayWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/TextDisplayWatcher.java @@ -1,11 +1,8 @@ package me.libraryaddict.disguise.disguisetypes.watchers; -import com.comphenix.protocol.wrappers.ComponentConverter; -import com.comphenix.protocol.wrappers.WrappedChatComponent; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Color; import org.bukkit.entity.Display; import org.bukkit.entity.TextDisplay; @@ -19,14 +16,11 @@ public class TextDisplayWatcher extends DisplayWatcher { } public String getText() { - BaseComponent[] base = ComponentConverter.fromWrapper(getData(MetaIndex.TEXT_DISPLAY_TEXT)); - - return DisguiseUtilities.getSimpleString(base); + return DisguiseUtilities.getSimpleString(getData(MetaIndex.TEXT_DISPLAY_TEXT)); } public void setText(String string) { - setData(MetaIndex.TEXT_DISPLAY_TEXT, - WrappedChatComponent.fromJson(DisguiseUtilities.serialize(DisguiseUtilities.getAdventureChat(string)))); + setData(MetaIndex.TEXT_DISPLAY_TEXT, DisguiseUtilities.getAdventureChat(string)); sendData(MetaIndex.TEXT_DISPLAY_TEXT); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/VillagerWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/VillagerWatcher.java index 28db2e7d..c7a05329 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/VillagerWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/VillagerWatcher.java @@ -1,9 +1,11 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.entity.villager.VillagerData; +import com.github.retrooper.packetevents.protocol.entity.villager.profession.VillagerProfessions; +import com.github.retrooper.packetevents.protocol.entity.villager.type.VillagerTypes; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; -import me.libraryaddict.disguise.disguisetypes.VillagerData; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; @@ -11,6 +13,8 @@ import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.entity.Villager; import org.bukkit.entity.Villager.Profession; +import java.util.Locale; + public class VillagerWatcher extends AbstractVillagerWatcher { public VillagerWatcher(Disguise disguise) { @@ -39,7 +43,7 @@ public class VillagerWatcher extends AbstractVillagerWatcher { public Profession getProfession() { if (NmsVersion.v1_14.isSupported()) { - return getVillagerData().getProfession(); + return Profession.valueOf(getVillagerData().getProfession().getName().getKey().toUpperCase(Locale.ENGLISH)); } return Profession.values()[getData(MetaIndex.VILLAGER_PROFESSION) + 1]; @@ -48,7 +52,8 @@ public class VillagerWatcher extends AbstractVillagerWatcher { @RandomDefaultValue public void setProfession(Profession profession) { if (NmsVersion.v1_14.isSupported()) { - setVillagerData(new VillagerData(getType(), profession, getLevel())); + setVillagerData(new VillagerData(VillagerTypes.getByName(getType().getKey().toString()), + VillagerProfessions.getByName(profession.getKey().toString()), getLevel())); } else { setData(MetaIndex.VILLAGER_PROFESSION, profession.ordinal() - 1); sendData(MetaIndex.VILLAGER_PROFESSION); @@ -58,13 +63,14 @@ public class VillagerWatcher extends AbstractVillagerWatcher { @Deprecated @NmsAddedIn(NmsVersion.v1_14) public Villager.Type getType() { - return getVillagerData().getType(); + return Villager.Type.valueOf(getVillagerData().getType().getName().getKey().toUpperCase(Locale.ENGLISH)); } @Deprecated @NmsAddedIn(NmsVersion.v1_14) public void setType(Villager.Type type) { - setVillagerData(new VillagerData(type, getProfession(), getLevel())); + setVillagerData(new VillagerData(VillagerTypes.getByName(type.getKey().toString()), + VillagerProfessions.getByName(getProfession().getKey().toString()), getLevel())); } @NmsAddedIn(NmsVersion.v1_14) @@ -84,6 +90,7 @@ public class VillagerWatcher extends AbstractVillagerWatcher { @NmsAddedIn(NmsVersion.v1_14) public void setLevel(int level) { - setVillagerData(new VillagerData(getType(), getProfession(), Math.max(1, Math.min(5, level)))); + setVillagerData(new VillagerData(VillagerTypes.getByName(getType().getKey().toString()), + VillagerProfessions.getByName(getProfession().getKey().toString()), Math.max(1, Math.min(5, level)))); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WitherWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WitherWatcher.java index 485deea1..002f35e0 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WitherWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WitherWatcher.java @@ -35,7 +35,7 @@ public class WitherWatcher extends InsentientWatcher { public void setTargets(int... targets) { if (targets.length != 3) { - throw new InvalidParameterException(ChatColor.RED + "Expected 3 numbers for wither setTargets. Received " + targets.length); + throw new InvalidParameterException("Expected 3 numbers for wither setTargets. Received " + targets.length + ""); } setData(MetaIndex.WITHER_TARGET_1, targets[0]); setData(MetaIndex.WITHER_TARGET_2, targets[1]); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WolfWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WolfWatcher.java index 29acddbe..dc096446 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WolfWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/WolfWatcher.java @@ -15,7 +15,7 @@ public class WolfWatcher extends TameableWatcher { } public DyeColor getCollarColor() { - return AnimalColor.getColorByWool(getData(MetaIndex.WOLF_COLLAR)).getDyeColor(); + return getData(MetaIndex.WOLF_COLLAR).getDyeColor(); } @Deprecated @@ -28,11 +28,11 @@ public class WolfWatcher extends TameableWatcher { setTamed(true); } - if (newColor == getCollarColor()) { + if (hasValue(MetaIndex.WOLF_COLLAR) && newColor == getCollarColor()) { return; } - setData(MetaIndex.WOLF_COLLAR, (int) newColor.getWoolData()); + setData(MetaIndex.WOLF_COLLAR, AnimalColor.getColorByWool(newColor.getWoolData())); sendData(MetaIndex.WOLF_COLLAR); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ZombieVillagerWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ZombieVillagerWatcher.java index c022c358..ae4ce567 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ZombieVillagerWatcher.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/disguisetypes/watchers/ZombieVillagerWatcher.java @@ -1,15 +1,18 @@ package me.libraryaddict.disguise.disguisetypes.watchers; +import com.github.retrooper.packetevents.protocol.entity.villager.VillagerData; +import com.github.retrooper.packetevents.protocol.entity.villager.profession.VillagerProfessions; +import com.github.retrooper.packetevents.protocol.entity.villager.type.VillagerTypes; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; -import me.libraryaddict.disguise.disguisetypes.VillagerData; import me.libraryaddict.disguise.utilities.parser.RandomDefaultValue; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.annotations.NmsAddedIn; import org.bukkit.entity.Villager; import org.bukkit.entity.Villager.Profession; +import java.util.Locale; import java.util.Random; public class ZombieVillagerWatcher extends ZombieWatcher { @@ -38,7 +41,7 @@ public class ZombieVillagerWatcher extends ZombieWatcher { */ public boolean isVillager() { if (NmsVersion.v1_14.isSupported()) { - return getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION).getProfession() != Profession.NONE; + return getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION).getProfession() != VillagerProfessions.NONE; } else { return getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION_OLD) != 0; } @@ -56,39 +59,35 @@ public class ZombieVillagerWatcher extends ZombieWatcher { } public Profession getProfession() { - return getVillagerData().getProfession(); + if (NmsVersion.v1_14.isSupported()) { + return Profession.valueOf(getVillagerData().getProfession().getName().getKey().toUpperCase(Locale.ENGLISH)); + } + + return Profession.values()[getData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION_OLD) + 1]; } @RandomDefaultValue public void setProfession(Profession profession) { if (NmsVersion.v1_14.isSupported()) { - setVillagerData(new VillagerData(getType(), profession, getLevel())); + setVillagerData(new VillagerData(VillagerTypes.getByName(getType().getKey().toString()), + VillagerProfessions.getByName(profession.getKey().toString()), getLevel())); } else { setData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION_OLD, profession.ordinal() - 1); sendData(MetaIndex.ZOMBIE_VILLAGER_PROFESSION_OLD); } } + @Deprecated @NmsAddedIn(NmsVersion.v1_14) public Villager.Type getType() { - return getVillagerData().getType(); + return Villager.Type.valueOf(getVillagerData().getType().getName().getKey().toUpperCase(Locale.ENGLISH)); } @Deprecated @NmsAddedIn(NmsVersion.v1_14) public void setType(Villager.Type type) { - setVillagerData(new VillagerData(type, getProfession(), getLevel())); - } - - @NmsAddedIn(NmsVersion.v1_14) - public int getLevel() { - return getVillagerData().getLevel(); - } - - @Deprecated - @NmsAddedIn(NmsVersion.v1_14) - public void setLevel(int level) { - setVillagerData(new VillagerData(getType(), getProfession(), getLevel())); + setVillagerData(new VillagerData(VillagerTypes.getByName(type.getKey().toString()), + VillagerProfessions.getByName(getProfession().getKey().toString()), getLevel())); } @NmsAddedIn(NmsVersion.v1_14) @@ -100,4 +99,15 @@ public class ZombieVillagerWatcher extends ZombieWatcher { public void setBiome(Villager.Type type) { setType(type); } + + @NmsAddedIn(NmsVersion.v1_14) + public int getLevel() { + return getVillagerData().getLevel(); + } + + @NmsAddedIn(NmsVersion.v1_14) + public void setLevel(int level) { + setVillagerData(new VillagerData(VillagerTypes.getByName(getType().getKey().toString()), + VillagerProfessions.getByName(getProfession().getKey().toString()), Math.max(1, Math.min(5, level)))); + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/DisguiseUtilities.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/DisguiseUtilities.java index f157b34b..a02c3966 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/DisguiseUtilities.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/DisguiseUtilities.java @@ -1,27 +1,62 @@ package me.libraryaddict.disguise.utilities; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedGameProfile; -import com.comphenix.protocol.wrappers.WrappedParticle; -import com.comphenix.protocol.wrappers.nbt.NbtBase; -import com.comphenix.protocol.wrappers.nbt.NbtCompound; -import com.comphenix.protocol.wrappers.nbt.NbtList; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.PacketSendEvent; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.particle.Particle; +import com.github.retrooper.packetevents.protocol.player.Equipment; +import com.github.retrooper.packetevents.protocol.player.EquipmentSlot; +import com.github.retrooper.packetevents.protocol.player.UserProfile; +import com.github.retrooper.packetevents.protocol.world.Direction; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.util.adventure.AdventureSerializer; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerCollectItem; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityAnimation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEffect; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityHeadLook; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMovement; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntitySoundEffect; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerPositionAndLook; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRemoveEntityEffect; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnExperienceOrb; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSerializer; import com.google.gson.JsonSyntaxException; +import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.PropertyMap; -import com.mojang.datafixers.util.Pair; +import io.github.retrooper.packetevents.adventure.serializer.legacy.LegacyComponentSerializer; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; +import libsdisg.shaded.net.kyori.adventure.text.minimessage.MiniMessage; +import libsdisg.shaded.net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import lombok.Getter; import lombok.Setter; +import lombok.SneakyThrows; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; @@ -29,22 +64,20 @@ import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MetaIndex; +import me.libraryaddict.disguise.disguisetypes.MobDisguise; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import me.libraryaddict.disguise.disguisetypes.TargetedDisguise; import me.libraryaddict.disguise.disguisetypes.TargetedDisguise.TargetType; import me.libraryaddict.disguise.disguisetypes.watchers.AgeableWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.ArmorStandWatcher; -import me.libraryaddict.disguise.disguisetypes.watchers.PlayerWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher; -import me.libraryaddict.disguise.utilities.json.SerializerBlockData; -import me.libraryaddict.disguise.utilities.json.SerializerChatComponent; -import me.libraryaddict.disguise.utilities.json.SerializerDisguise; -import me.libraryaddict.disguise.utilities.json.SerializerFlagWatcher; -import me.libraryaddict.disguise.utilities.json.SerializerGameProfile; -import me.libraryaddict.disguise.utilities.json.SerializerItemStack; -import me.libraryaddict.disguise.utilities.json.SerializerMetaIndex; -import me.libraryaddict.disguise.utilities.json.SerializerParticle; -import me.libraryaddict.disguise.utilities.json.SerializerWrappedBlockData; +import me.libraryaddict.disguise.utilities.gson.SerializerBlockData; +import me.libraryaddict.disguise.utilities.gson.SerializerChatComponent; +import me.libraryaddict.disguise.utilities.gson.SerializerItemStack; +import me.libraryaddict.disguise.utilities.gson.SerializerMetaIndex; +import me.libraryaddict.disguise.utilities.gson.SerializerParticle; +import me.libraryaddict.disguise.utilities.gson.SerializerUserProfile; +import me.libraryaddict.disguise.utilities.gson.SerializerWrappedBlockData; import me.libraryaddict.disguise.utilities.mineskin.MineSkinAPI; import me.libraryaddict.disguise.utilities.packets.LibsPackets; import me.libraryaddict.disguise.utilities.packets.PacketsManager; @@ -56,12 +89,10 @@ import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.reflection.WatcherValue; import me.libraryaddict.disguise.utilities.translations.LibsMsg; +import me.libraryaddict.disguise.utilities.updates.PacketEventsUpdater; import me.libraryaddict.disguise.utilities.watchers.CompileMethods; import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.chat.ComponentSerializer; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.RandomUtils; @@ -71,6 +102,7 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.World; +import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.boss.KeyedBossBar; import org.bukkit.command.CommandSender; @@ -83,7 +115,6 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Wolf; import org.bukkit.entity.Zombie; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; @@ -91,7 +122,6 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; @@ -108,11 +138,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; -import java.lang.reflect.Array; -import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -121,8 +147,10 @@ import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; +import java.util.BitSet; import java.util.Collection; import java.util.Collections; +import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -257,16 +285,22 @@ public class DisguiseUtilities { private static long lastSavedPreferences; @Getter private final static ConcurrentHashMap teams = new ConcurrentHashMap<>(); - private final static boolean java16; private static boolean criedOverJava16; private static final HashSet warnedSkin = new HashSet<>(); @Getter private static boolean fancyHiddenTabs; @Getter - @Setter - private static boolean protocollibUpdateDownloaded; private static NamespacedKey savedDisguisesKey; private static final List whitelistedEnchantments = new ArrayList<>(); + @Getter + private static Enchantment durabilityEnchantment, waterbreathingEnchantment; + @Getter + private final static EntityType entityItem; + @Getter + private static final MiniMessage miniMessage = MiniMessage.builder().build(); + private static final GsonComponentSerializer internalComponentSerializer = GsonComponentSerializer.gson(); + private static final io.github.retrooper.packetevents.adventure.serializer.gson.GsonComponentSerializer externalComponentSerializer = + io.github.retrooper.packetevents.adventure.serializer.gson.GsonComponentSerializer.gson(); static { try { @@ -275,21 +309,6 @@ public class DisguiseUtilities { } catch (Exception ignored) { } - final Matcher matcher = Pattern.compile("(?:1\\.)?(\\d+)").matcher(System.getProperty("java.version")); - - if (!matcher.find()) { - java16 = true; - } else { - int vers = 16; - - try { - vers = Integer.parseInt(matcher.group(1)); - } catch (NumberFormatException ignored) { - } - - java16 = vers >= 16; - } - if (LibsDisguises.getInstance() == null) { profileCache = null; savedDisguises = null; @@ -298,19 +317,30 @@ public class DisguiseUtilities { savedDisguises = new File(LibsDisguises.getInstance().getDataFolder(), "SavedDisguises"); } - whitelistedEnchantments.add(Enchantment.DEPTH_STRIDER); - whitelistedEnchantments.add(Enchantment.OXYGEN); + entityItem = EntityType.fromName("item"); - if (Bukkit.getServer() != null && NmsVersion.v1_13.isSupported()) { - whitelistedEnchantments.add(Enchantment.RIPTIDE); + if (Bukkit.getServer() != null) { + durabilityEnchantment = Enchantment.getByName("unbreaking"); + waterbreathingEnchantment = Enchantment.getByName("respiration"); - if (NmsVersion.v1_19_R1.isSupported()) { - whitelistedEnchantments.add(Enchantment.SOUL_SPEED); - whitelistedEnchantments.add(Enchantment.SWIFT_SNEAK); + whitelistedEnchantments.add(Enchantment.DEPTH_STRIDER); + whitelistedEnchantments.add(getWaterbreathingEnchantment()); + + if (Bukkit.getServer() != null && NmsVersion.v1_13.isSupported()) { + whitelistedEnchantments.add(Enchantment.RIPTIDE); + + if (NmsVersion.v1_19_R1.isSupported()) { + whitelistedEnchantments.add(Enchantment.SOUL_SPEED); + whitelistedEnchantments.add(Enchantment.SWIFT_SNEAK); + } } } } + public static boolean shouldBeHiddenSelfDisguise(com.github.retrooper.packetevents.protocol.item.ItemStack itemStack) { + return shouldBeHiddenSelfDisguise(SpigotConversionUtil.toBukkitItemStack(itemStack)); + } + public static boolean shouldBeHiddenSelfDisguise(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return false; @@ -330,7 +360,7 @@ public class DisguiseUtilities { } public static String serialize(Component component) { - return GsonComponentSerializer.gson().serialize(component); + return AdventureSerializer.getGsonSerializer().serialize(component); } public static void doSkinUUIDWarning(CommandSender sender) { @@ -477,7 +507,7 @@ public class DisguiseUtilities { } player.removeMetadata("LibsDisguises Invisible Slime", LibsDisguises.getInstance()); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, getDestroyPacket(DisguiseAPI.getEntityAttachmentId()), false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, getDestroyPacket(DisguiseAPI.getEntityAttachmentId())); } public static void sendInvisibleSlime(Player player, int horseId) { @@ -485,42 +515,42 @@ public class DisguiseUtilities { player.setMetadata("LibsDisguises Invisible Slime", new FixedMetadataValue(LibsDisguises.getInstance(), true)); } - PacketContainer packet = ProtocolLibrary.getProtocolManager() - .createPacketConstructor(NmsVersion.v1_19_R1.isSupported() ? Server.SPAWN_ENTITY : Server.SPAWN_ENTITY_LIVING, player) - .createPacket(player); + Location loc = player.getLocation(); + Vector velocity = player.getVelocity(); - packet.getModifier().write(0, DisguiseAPI.getEntityAttachmentId()); - packet.getUUIDs().write(0, UUID.randomUUID()); - packet.getModifier() - .write(2, NmsVersion.v1_19_R1.isSupported() ? DisguiseType.SLIME.getNmsEntityType() : DisguiseType.SLIME.getTypeId()); + if (NmsVersion.v1_19_R1.isSupported()) { + WrapperPlayServerSpawnEntity packet = + new WrapperPlayServerSpawnEntity(DisguiseAPI.getEntityAttachmentId(), UUID.randomUUID(), EntityTypes.SLIME, + SpigotConversionUtil.fromBukkitLocation(loc), 0, 0, new Vector3d(velocity.getX(), velocity.getY(), velocity.getZ())); - if (NmsVersion.v1_15.isSupported()) { - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(DisguiseAPI.getEntityAttachmentId(), - Collections.singletonList(new WatcherValue(MetaIndex.SLIME_SIZE, 0))); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } else { - WrappedDataWatcher watcher = new WrappedDataWatcher(); + WrapperPlayServerSpawnLivingEntity packet = + new WrapperPlayServerSpawnLivingEntity(DisguiseAPI.getEntityAttachmentId(), UUID.randomUUID(), EntityTypes.SLIME, + SpigotConversionUtil.fromBukkitLocation(loc), 0, new Vector3d(velocity.getX(), velocity.getY(), velocity.getZ()), + new ArrayList<>()); - WrappedDataWatcher.WrappedDataWatcherObject obj = ReflectionManager.createDataWatcherObject(MetaIndex.SLIME_SIZE, 0); - watcher.setObject(obj, 0); + if (!(NmsVersion.v1_15.isSupported())) { + packet.setEntityMetadata(Collections.singletonList(ReflectionManager.getEntityData(MetaIndex.SLIME_SIZE, 0, false))); + } - packet.getDataWatcherModifier().write(0, watcher); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); } - PacketContainer attachHorse = new PacketContainer(Server.MOUNT); - attachHorse.getModifier().write(0, horseId); - attachHorse.getModifier().write(1, new int[]{DisguiseAPI.getEntityAttachmentId()}); + if (NmsVersion.v1_15.isSupported()) { + WrapperPlayServerEntityMetadata metadata = new WrapperPlayServerEntityMetadata(DisguiseAPI.getEntityAttachmentId(), + Collections.singletonList(ReflectionManager.getEntityData(MetaIndex.SLIME_SIZE, 0, false))); - PacketContainer attachPlayer = new PacketContainer(Server.MOUNT); - attachPlayer.getModifier().write(0, DisguiseAPI.getEntityAttachmentId()); - attachPlayer.getModifier().write(1, new int[]{player.getEntityId()}); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, metadata); + } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, attachHorse, false); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, attachPlayer, false); + WrapperPlayServerAttachEntity attachHorse = new WrapperPlayServerAttachEntity(horseId, DisguiseAPI.getEntityAttachmentId(), false); + WrapperPlayServerAttachEntity attachPlayer = + new WrapperPlayServerAttachEntity(DisguiseAPI.getEntityAttachmentId(), player.getEntityId(), false); + + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, attachHorse); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, attachPlayer); } public static void loadViewPreferences() { @@ -575,153 +605,22 @@ public class DisguiseUtilities { velocityTimes.invalidate(player.getEntityId()); } - /** - * Returns the min required version, as in any older version will just not work. - */ - public static String[] getProtocolLibRequiredVersion() { - // 1.12 base version - String[] requiredVersion = new String[]{"4.4.0"}; - - // If we are on 1.13, 1.14, 1.15 - if (NmsVersion.v1_13.isSupported()) { - requiredVersion = new String[]{"4.5.1"}; - } - - // If we are on 1.16 - if (NmsVersion.v1_16.isSupported()) { - requiredVersion = new String[]{"4.6.0"}; - } - - // If we are on 1.17, you need this release or dev build - // ProtocolLib is a little funny in that it provides next release version as the current version - if (NmsVersion.v1_17.isSupported()) { - requiredVersion = new String[]{"4.7.0", "528"}; - } - - // If you're on 1.18.. - if (NmsVersion.v1_18.isSupported()) { - requiredVersion = new String[]{"4.8.0"}; - } - - // If you're on 1.19.1 or 1.19.2 - if (NmsVersion.v1_19_R1.isSupported()) { - requiredVersion = new String[]{"5.0.0", "600"}; - } - - // If you're on 1.19.3 - if (NmsVersion.v1_19_R2.isSupported()) { - requiredVersion = new String[]{"5.0.0", "630"}; - } - - // If you're on 1.19.4 - if (NmsVersion.v1_19_R3.isSupported()) { - requiredVersion = new String[]{"5.0.0", "630"}; - } - - // If you're on 1.20.2 - if (NmsVersion.v1_20_R2.isSupported()) { - requiredVersion = new String[]{"5.1.1", "669"}; - } - - // If you're on 1.20.4 - if (NmsVersion.v1_20_R3.isSupported()) { - requiredVersion = new String[]{"5.2.0", "679"}; - } - - return requiredVersion; - } - - public static boolean isProtocolLibOutdated() { - Plugin plugin = Bukkit.getPluginManager().getPlugin("ProtocolLib"); + public static boolean isPacketEventsOutdated() { + Plugin plugin = Bukkit.getPluginManager().getPlugin("packetevents"); if (plugin == null) { return true; } - String plVersion; + String packetEventsVersion; try { - plVersion = plugin.getDescription().getVersion(); + packetEventsVersion = plugin.getDescription().getVersion(); } catch (Throwable throwable) { return true; } - String[] reqVersion = getProtocolLibRequiredVersion(); - - // If this is also checking for a custom build, and PL has the custom build in.. - // We run this check first as the 4.7.1 isn't out, and it'd always tell us to update otherwise. - if (reqVersion.length > 1 && plVersion.contains("-SNAPSHOT")) { - Matcher matcher = Pattern.compile("-SNAPSHOT-b?(\\d+)").matcher(plVersion); - - // Just incase they're running a custom build? - if (!matcher.find()) { - return false; - } - - try { - int buildNo = Integer.parseInt(matcher.group(1)); - - // Must be a custom build - if (buildNo < 100) { - return false; - } - - return buildNo < Integer.parseInt(reqVersion[1]); - } catch (Throwable ignored) { - } - } - - return isOlderThan(reqVersion[0], plVersion); - } - - public static File updateProtocolLib() throws Exception { - File dest = new File(LibsDisguises.getInstance().getDataFolder().getAbsoluteFile().getParentFile(), "ProtocolLib.jar"); - - try { - Method getFile = JavaPlugin.class.getDeclaredMethod("getFile"); - getFile.setAccessible(true); - - File theirFile = (File) getFile.invoke(ProtocolLibrary.getPlugin()); - dest = new File(Bukkit.getUpdateFolderFile(), theirFile.getName()); - } catch (Throwable throwable) { - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) { - List plJars = ReflectionManager.getFilesByPlugin("ProtocolLib"); - String fileName = "ProtocolLib.jar"; - - if (plJars.size() > 1) { - // Its probably the first file regardless, Bukkit seems to use folder.listFiles() and use the order provided - DisguiseUtilities.getLogger() - .warning("You have multiple ProtocolLib jars in your plugin folder, you may need to update ProtocolLib yourself."); - } - - if (!plJars.isEmpty()) { - fileName = plJars.get(0).getName(); - } - - dest = new File(Bukkit.getUpdateFolderFile(), fileName); - } - } - - if (!dest.exists()) { - dest.getParentFile().mkdirs(); - dest.createNewFile(); - } - - // We're connecting to jenkins's API for ProtocolLib - URL url = new URL("https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/artifact/build/libs/ProtocolLib.jar"); - - // Creating a connection - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestProperty("User-Agent", "libraryaddict/LibsDisguises"); - - // Get the input stream, what we receive - try (InputStream input = con.getInputStream()) { - Files.copy(input, dest.toPath(), StandardCopyOption.REPLACE_EXISTING); - } - - setProtocollibUpdateDownloaded(true); - - return dest; + return isOlderThan(PacketEventsUpdater.getMinimumPacketEventsVersion(), packetEventsVersion); } /** @@ -825,7 +724,7 @@ public class DisguiseUtilities { getLogger().info("Saved " + disguisesSaved + " disguises."); } - public static boolean hasGameProfile(String playername) { + public static boolean hasUserProfile(String playername) { return cachedNames.contains(playername.toLowerCase(Locale.ENGLISH)); } @@ -1038,13 +937,10 @@ public class DisguiseUtilities { for (int i = 0; i < disguises.length; i++) { disguises[i] = DisguiseParser.parseDisguise(spl[i]); } - } else if (!java16) { - disguises = gson.fromJson(cached, Disguise[].class); } else { if (!criedOverJava16) { criedOverJava16 = true; - getLogger().warning( - "Failed to load a disguise using old format, this is due to Java 16 breaking stuff. This error will only print once."); + getLogger().warning("Failed to load a disguise using old format. This error will only print once."); } return new Disguise[0]; @@ -1096,15 +992,18 @@ public class DisguiseUtilities { synchronized (isNoInteract) { Entity entity = disguise.getEntity(); - switch (entity.getType()) { - case EXPERIENCE_ORB: - case DROPPED_ITEM: - case ARROW: - case SPECTRAL_ARROW: - isNoInteract.add(entity.getEntityId()); - break; - default: - break; + if (getEntityItem() == entity.getType()) { + isNoInteract.add(entity.getEntityId()); + } else { + switch (entity.getType()) { + case EXPERIENCE_ORB: + case ARROW: + case SPECTRAL_ARROW: + isNoInteract.add(entity.getEntityId()); + break; + default: + break; + } } } @@ -1191,7 +1090,7 @@ public class DisguiseUtilities { runnable.runTaskLater(LibsDisguises.getInstance(), 20); } - public static void addGameProfile(String string, WrappedGameProfile gameProfile) { + public static void addUserProfile(String string, UserProfile userProfile) { try { if (!profileCache.exists()) { profileCache.mkdirs(); @@ -1199,7 +1098,7 @@ public class DisguiseUtilities { File file = new File(profileCache, string.toLowerCase(Locale.ENGLISH)); PrintWriter writer = new PrintWriter(file); - writer.write(gson.toJson(gameProfile)); + writer.write(gson.toJson(userProfile)); writer.close(); cachedNames.add(string.toLowerCase(Locale.ENGLISH)); @@ -1296,14 +1195,14 @@ public class DisguiseUtilities { Set trackedPlayers = ReflectionManager.getClonedTrackedPlayers(entityTrackerEntry); - PacketContainer destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId()); - for (Object p : trackedPlayers) { Player player = (Player) ReflectionManager.getBukkitEntity(ReflectionManager.getPlayerFromPlayerConnection(p)); - if (player == disguise.getEntity() || disguise.canSee(player)) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket); + if (player != disguise.getEntity() && !disguise.canSee(player)) { + continue; } + + PacketEvents.getAPI().getPlayerManager().sendPacket(player, getDestroyPacket(disguise.getEntity().getEntityId())); } } catch (Exception ex) { ex.printStackTrace(); @@ -1361,22 +1260,8 @@ public class DisguiseUtilities { return null; } - public static PacketContainer getDestroyPacket(int... ids) { - PacketContainer destroyPacket = new PacketContainer(Server.ENTITY_DESTROY); - - if (NmsVersion.v1_17.isSupported()) { - List ints = new ArrayList<>(); - - for (int id : ids) { - ints.add(id); - } - - destroyPacket.getIntLists().write(0, ints); - } else { - destroyPacket.getIntegerArrays().write(0, ids); - } - - return destroyPacket; + public static WrapperPlayServerDestroyEntities getDestroyPacket(int... ids) { + return new WrapperPlayServerDestroyEntities(ids); } public static TargetedDisguise getDisguise(Player observer, Entity entity) { @@ -1411,10 +1296,10 @@ public class DisguiseUtilities { return new TargetedDisguise[0]; } - public static WrappedGameProfile getGameProfile(String playerName) { + public static UserProfile getUserProfile(String playerName) { playerName = playerName.toLowerCase(Locale.ENGLISH); - if (!hasGameProfile(playerName)) { + if (!hasUserProfile(playerName)) { return null; } @@ -1434,9 +1319,9 @@ public class DisguiseUtilities { String cached = reader.readLine(); reader.close(); - return gson.fromJson(cached, WrappedGameProfile.class); + return gson.fromJson(cached, UserProfile.class); } catch (JsonSyntaxException ex) { - DisguiseUtilities.getLogger().warning("Gameprofile " + file.getName() + " had invalid gson and has been deleted"); + DisguiseUtilities.getLogger().warning("UserProfile " + file.getName() + " had invalid gson and has been deleted"); cachedNames.remove(playerName); file.delete(); } catch (Exception e) { @@ -1498,21 +1383,20 @@ public class DisguiseUtilities { return players; } - public static WrappedGameProfile getProfileFromMojang(final PlayerDisguise disguise) { + public static UserProfile getProfileFromMojang(final PlayerDisguise disguise) { final String nameToFetch = disguise.getSkin() != null ? disguise.getSkin() : disguise.getName(); - return getProfileFromMojang(nameToFetch, gameProfile -> { - if (gameProfile == null || gameProfile.getProperties().isEmpty()) { + return getProfileFromMojang(nameToFetch, userProfile -> { + if (userProfile == null || userProfile.getTextureProperties().isEmpty()) { return; } - if (DisguiseAPI.isDisguiseInUse(disguise) && - (!gameProfile.getName().equals(disguise.getSkin() != null ? disguise.getSkin() : disguise.getName()) || - !gameProfile.getProperties().isEmpty())) { - disguise.setGameProfile(gameProfile); - - DisguiseUtilities.refreshTrackers(disguise); + if (!disguise.isDisguiseInUse()) { + return; } + + disguise.setUserProfile(userProfile); + DisguiseUtilities.refreshTrackers(disguise); }, DisguiseConfig.isContactMojangServers()); } @@ -1521,7 +1405,7 @@ public class DisguiseUtilities { * a lookup * using schedulers. The runnable is run once the GameProfile has been successfully dealt with */ - public static WrappedGameProfile getProfileFromMojang(String playerName, LibsProfileLookup runnableIfCantReturn) { + public static UserProfile getProfileFromMojang(String playerName, LibsProfileLookup runnableIfCantReturn) { return getProfileFromMojang(playerName, (Object) runnableIfCantReturn, true); } @@ -1530,16 +1414,15 @@ public class DisguiseUtilities { * a lookup * using schedulers. The runnable is run once the GameProfile has been successfully dealt with */ - public static WrappedGameProfile getProfileFromMojang(String playerName, LibsProfileLookup runnableIfCantReturn, - boolean contactMojang) { + public static UserProfile getProfileFromMojang(String playerName, LibsProfileLookup runnableIfCantReturn, boolean contactMojang) { return getProfileFromMojang(playerName, (Object) runnableIfCantReturn, contactMojang); } - private static WrappedGameProfile getProfileFromMojang(final String origName, final Object runnable, boolean contactMojang) { + private static UserProfile getProfileFromMojang(final String origName, final Object runnable, boolean contactMojang) { final String playerName = origName.toLowerCase(Locale.ENGLISH); - if (DisguiseConfig.isSaveGameProfiles() && hasGameProfile(playerName)) { - WrappedGameProfile profile = getGameProfile(playerName); + if (DisguiseConfig.isSaveGameProfiles() && hasUserProfile(playerName)) { + UserProfile profile = getUserProfile(playerName); if (profile != null) { return profile; @@ -1550,11 +1433,11 @@ public class DisguiseUtilities { final Player player = Bukkit.getPlayerExact(playerName); if (player != null) { - WrappedGameProfile gameProfile = ReflectionManager.getGameProfile(player); + UserProfile gameProfile = ReflectionManager.getUserProfile(player); - if (!gameProfile.getProperties().isEmpty()) { + if (!gameProfile.getTextureProperties().isEmpty()) { if (DisguiseConfig.isSaveGameProfiles()) { - addGameProfile(playerName, gameProfile); + addUserProfile(playerName, gameProfile); } return gameProfile; @@ -1571,11 +1454,11 @@ public class DisguiseUtilities { Bukkit.getScheduler().runTaskAsynchronously(LibsDisguises.getInstance(), () -> { try { - final WrappedGameProfile gameProfile = lookupGameProfile(origName); + final UserProfile gameProfile = lookupUserProfile(origName); Bukkit.getScheduler().runTask(LibsDisguises.getInstance(), () -> { if (DisguiseConfig.isSaveGameProfiles()) { - addGameProfile(playerName, gameProfile); + addUserProfile(playerName, gameProfile); } synchronized (runnables) { @@ -1606,7 +1489,7 @@ public class DisguiseUtilities { return null; } - return ReflectionManager.getGameProfile(null, origName); + return ReflectionManager.getUserProfile(null, origName); } /** @@ -1614,7 +1497,7 @@ public class DisguiseUtilities { * a lookup * using schedulers. The runnable is run once the GameProfile has been successfully dealt with */ - public static WrappedGameProfile getProfileFromMojang(String playerName, Runnable runnableIfCantReturn) { + public static UserProfile getProfileFromMojang(String playerName, Runnable runnableIfCantReturn) { return getProfileFromMojang(playerName, (Object) runnableIfCantReturn, true); } @@ -1623,23 +1506,21 @@ public class DisguiseUtilities { * a lookup * using schedulers. The runnable is run once the GameProfile has been successfully dealt with */ - public static WrappedGameProfile getProfileFromMojang(String playerName, Runnable runnableIfCantReturn, boolean contactMojang) { + public static UserProfile getProfileFromMojang(String playerName, Runnable runnableIfCantReturn, boolean contactMojang) { return getProfileFromMojang(playerName, (Object) runnableIfCantReturn, contactMojang); } - public static void init() { - fancyHiddenTabs = NmsVersion.v1_19_R2.isSupported() && Bukkit.getPluginManager().getPlugin("ViaBackwards") == null; - savedDisguisesKey = new NamespacedKey(LibsDisguises.getInstance(), "SavedDisguises"); - + public static void recreateGsonSerializer() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.disableHtmlEscaping(); gsonBuilder.registerTypeAdapter(MetaIndex.class, new SerializerMetaIndex()); - gsonBuilder.registerTypeAdapter(WrappedGameProfile.class, new SerializerGameProfile()); - gsonBuilder.registerTypeAdapter(WrappedBlockData.class, new SerializerWrappedBlockData()); - gsonBuilder.registerTypeAdapter(WrappedChatComponent.class, new SerializerChatComponent()); - gsonBuilder.registerTypeAdapter(WrappedParticle.class, new SerializerParticle()); + gsonBuilder.registerTypeAdapter(UserProfile.class, new SerializerUserProfile()); + gsonBuilder.registerTypeAdapter(GameProfile.class, new SerializerUserProfile()); + gsonBuilder.registerTypeAdapter(WrappedBlockState.class, new SerializerWrappedBlockData()); + gsonBuilder.registerTypeAdapter(Component.class, new SerializerChatComponent()); + gsonBuilder.registerTypeAdapter(Particle.class, new SerializerParticle()); gsonBuilder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()); gsonBuilder.registerTypeHierarchyAdapter(ItemStack.class, new SerializerItemStack()); @@ -1648,13 +1529,18 @@ public class DisguiseUtilities { } // Gotta register all the flag watcher stuff before I make this one - gsonBuilder.registerTypeAdapter(FlagWatcher.class, new SerializerFlagWatcher(gsonBuilder.create())); - gsonBuilder.registerTypeAdapter(Disguise.class, new SerializerDisguise()); gsonBuilder.registerTypeAdapter(Optional.class, (JsonSerializer) (optional, type, jsonSerializationContext) -> jsonSerializationContext.serialize( "(" + jsonSerializationContext.serialize(optional.orElse(null)) + ")")); gson = gsonBuilder.create(); + } + + public static void init() { + fancyHiddenTabs = NmsVersion.v1_19_R2.isSupported() && Bukkit.getPluginManager().getPlugin("ViaBackwards") == null; + savedDisguisesKey = new NamespacedKey(LibsDisguises.getInstance(), "SavedDisguises"); + + recreateGsonSerializer(); if (!profileCache.exists()) { File old = new File(profileCache.getParentFile(), "GameProfiles"); @@ -1801,7 +1687,7 @@ public class DisguiseUtilities { continue; } - LibsDisguises.getInstance().getUpdateChecker().setGoSilent(true); + LibsDisguises.getInstance().getUpdateChecker().setQuiet(true); } } @@ -1831,6 +1717,8 @@ public class DisguiseUtilities { map = new Gson().fromJson(json, HashMap.class); } + con.disconnect(); + if (!map.containsKey("body")) { return new String[0]; } @@ -1850,7 +1738,7 @@ public class DisguiseUtilities { /** * This is called on a thread as it is thread blocking */ - public static WrappedGameProfile lookupGameProfile(String playerName) { + public static UserProfile lookupUserProfile(String playerName) { return ReflectionManager.getSkullBlob(ReflectionManager.grabProfileAddUUID(playerName)); } @@ -1869,8 +1757,8 @@ public class DisguiseUtilities { try { if (disguise.isDisguiseInUse() && disguise.getEntity() instanceof Player && disguise.getEntity().getName().equalsIgnoreCase(player)) { - PacketContainer destroyPacket = getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); - ProtocolLibrary.getProtocolManager().sendServerPacket((Player) disguise.getEntity(), destroyPacket); + WrapperPlayServerDestroyEntities destroyPacket = getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); + PacketEvents.getAPI().getPlayerManager().sendPacket(disguise.getEntity(), destroyPacket); Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { try { @@ -1888,8 +1776,6 @@ public class DisguiseUtilities { Set trackedPlayers = ReflectionManager.getClonedTrackedPlayers(entityTrackerEntry); - PacketContainer destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId()); - for (final Object o : trackedPlayers) { Object p = ReflectionManager.getPlayerFromPlayerConnection(o); Player pl = (Player) ReflectionManager.getBukkitEntity(p); @@ -1900,7 +1786,9 @@ public class DisguiseUtilities { ReflectionManager.clearEntityTracker(entityTrackerEntry, p); - ProtocolLibrary.getProtocolManager().sendServerPacket(pl, destroyPacket); + WrapperPlayServerDestroyEntities destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId()); + + PacketEvents.getAPI().getPlayerManager().sendPacket(pl, destroyPacket); Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { try { @@ -1929,7 +1817,6 @@ public class DisguiseUtilities { if (entity.isValid()) { try { - PacketContainer destroyPacket = getDestroyPacket(entity.getEntityId()); final Object entityTrackerEntry = ReflectionManager.getEntityTrackerEntry(entity); @@ -1943,9 +1830,11 @@ public class DisguiseUtilities { if (player == entity) { continue; } + ReflectionManager.clearEntityTracker(entityTrackerEntry, p); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket); + WrapperPlayServerDestroyEntities destroyPacket = getDestroyPacket(entity.getEntityId()); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, destroyPacket); Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { try { @@ -1977,8 +1866,8 @@ public class DisguiseUtilities { try { if (selfDisguised.contains(disguise.getEntity().getUniqueId()) && disguise.isDisguiseInUse()) { - PacketContainer destroyPacket = getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); - ProtocolLibrary.getProtocolManager().sendServerPacket((Player) disguise.getEntity(), destroyPacket); + WrapperPlayServerDestroyEntities destroyPacket = getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); + PacketEvents.getAPI().getPlayerManager().sendPacket(disguise.getEntity(), destroyPacket); removeSelfTracker((Player) disguise.getEntity()); @@ -1995,25 +1884,26 @@ public class DisguiseUtilities { if (entityTrackerEntry != null) { Set trackedPlayers = ReflectionManager.getClonedTrackedPlayers(entityTrackerEntry); - PacketContainer destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId()); for (final Object o : trackedPlayers) { Object p = ReflectionManager.getPlayerFromPlayerConnection(o); Player player = (Player) ReflectionManager.getBukkitEntity(p); - if (disguise.getEntity() != player && disguise.canSee(player)) { - ReflectionManager.clearEntityTracker(entityTrackerEntry, p); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket); - - Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { - try { - ReflectionManager.addEntityTracker(entityTrackerEntry, p); - } catch (Exception ex) { - ex.printStackTrace(); - } - }, 2); + if (disguise.getEntity() == player || !disguise.canSee(player)) { + continue; } + ReflectionManager.clearEntityTracker(entityTrackerEntry, p); + + WrapperPlayServerDestroyEntities destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId()); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, destroyPacket); + + Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { + try { + ReflectionManager.addEntityTracker(entityTrackerEntry, p); + } catch (Exception ex) { + ex.printStackTrace(); + } + }, 2); } } } catch (Exception ex) { @@ -2049,7 +1939,7 @@ public class DisguiseUtilities { return false; } - public static void removeGameProfile(String string) { + public static void removeUserProfile(String string) { cachedNames.remove(string.toLowerCase(Locale.ENGLISH)); if (!profileCache.exists()) { @@ -2077,7 +1967,7 @@ public class DisguiseUtilities { // Send a packet to destroy the fake entity try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, getDestroyPacket(ids)); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, getDestroyPacket(ids)); } catch (Exception ex) { ex.printStackTrace(); } @@ -2090,15 +1980,13 @@ public class DisguiseUtilities { removeSelfTracker(player); - // Resend entity metadata else he will be invisible to themselves until its resent + // Resend entity metadata else they will be invisible to themselves until its resent try { - List list = WrappedDataWatcher.getEntityWatcher(player).getWatchableObjects().stream() - .map(v -> new WatcherValue(MetaIndex.getMetaIndex(PlayerWatcher.class, v.getIndex()), v.getRawValue())) - .collect(Collectors.toList()); + List list = ReflectionManager.getEntityWatcher(player); - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(player.getEntityId(), list); + WrapperPlayServerEntityMetadata metadata = new WrapperPlayServerEntityMetadata(player.getEntityId(), list); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, metadata); } catch (Exception ex) { ex.printStackTrace(); } @@ -2571,7 +2459,7 @@ public class DisguiseUtilities { return list.toArray(new String[0]); } - public static ItemStack getSlot(PlayerInventory equip, EquipmentSlot slot) { + public static ItemStack getSlot(PlayerInventory equip, org.bukkit.inventory.EquipmentSlot slot) { switch (slot) { case HAND: return equip.getItemInMainHand(); @@ -2624,57 +2512,73 @@ public class DisguiseUtilities { ReflectionManager.addEntityToTrackedMap(entityTrackerEntry, player); - ProtocolManager manager = ProtocolLibrary.getProtocolManager(); + Vector vel = player.getVelocity(); + PacketWrapper spawn; + // Send the player a packet with themselves being spawned - manager.sendServerPacket(player, - manager.createPacketConstructor(NmsVersion.v1_20_R2.isSupported() ? Server.SPAWN_ENTITY : Server.NAMED_ENTITY_SPAWN, player) - .createPacket(player)); + if (NmsVersion.v1_20_R2.isSupported()) { + spawn = new WrapperPlayServerSpawnEntity(player.getEntityId(), player.getUniqueId(), EntityTypes.PLAYER, + SpigotConversionUtil.fromBukkitLocation(player.getLocation()), player.getLocation().getYaw(), 0, + new Vector3d(vel.getX(), vel.getY(), vel.getZ())); + } else { + spawn = new WrapperPlayServerSpawnPlayer(player.getEntityId(), player.getUniqueId(), + SpigotConversionUtil.fromBukkitLocation(player.getLocation()), new ArrayList<>()); + } - List watcherList = WrappedDataWatcher.getEntityWatcher(player).getWatchableObjects().stream() - .map(v -> new WatcherValue(MetaIndex.getMetaIndex(PlayerWatcher.class, v.getIndex()), v.getRawValue())) - .collect(Collectors.toList()); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawn); - sendSelfPacket(player, ReflectionManager.getMetadataPacket(player.getEntityId(), watcherList)); + sendSelfPacket(player, new WrapperPlayServerEntityMetadata(player.getEntityId(), ReflectionManager.getEntityWatcher(player))); // Send the velocity packets if (ReflectionManager.isEntityTrackerMoving(entityTrackerEntry)) { Vector velocity = player.getVelocity(); - sendSelfPacket(player, manager.createPacketConstructor(Server.ENTITY_VELOCITY, player).createPacket(player)); + sendSelfPacket(player, new WrapperPlayServerEntityVelocity(DisguiseAPI.getSelfDisguiseId(), + new Vector3d(velocity.getX(), velocity.getY(), velocity.getZ()))); } - // Why the hell would he even need this. Meh. + // Why would they even need this. Meh. + // Also, what's with the "entity id > id" check? if (player.getVehicle() != null && player.getEntityId() > player.getVehicle().getEntityId()) { - sendSelfPacket(player, manager.createPacketConstructor(Server.ATTACH_ENTITY, player, player.getVehicle()) - .createPacket(player, player.getVehicle())); + sendSelfPacket(player, new WrapperPlayServerAttachEntity(player.getEntityId(), player.getVehicle().getEntityId(), false)); } else if (player.getPassenger() != null && player.getEntityId() > player.getPassenger().getEntityId()) { - sendSelfPacket(player, manager.createPacketConstructor(Server.ATTACH_ENTITY, player.getPassenger(), player) - .createPacket(player.getPassenger(), player)); + sendSelfPacket(player, new WrapperPlayServerAttachEntity(player.getPassenger().getEntityId(), player.getEntityId(), false)); } - if (NmsVersion.v1_16.isSupported()) { - List> list = new ArrayList<>(); + List list = new ArrayList<>(); - for (EquipmentSlot slot : EquipmentSlot.values()) { - list.add(Pair.of(ReflectionManager.createEnumItemSlot(slot), - ReflectionManager.getNmsItem(player.getInventory().getItem(slot)))); + for (EquipmentSlot slot : EquipmentSlot.values()) { + // TODO Change when it's an actual slot + if (slot.name().equals("BODY")) { + continue; } - sendSelfPacket(player, manager.createPacketConstructor(Server.ENTITY_EQUIPMENT, 0, list).createPacket(0, list)); - } else { - for (EquipmentSlot slot : EquipmentSlot.values()) { - Object item = ReflectionManager.getNmsItem(getSlot(player.getInventory(), slot)); - - sendSelfPacket(player, - manager.createPacketConstructor(Server.ENTITY_EQUIPMENT, 0, ReflectionManager.createEnumItemSlot(slot), item) - .createPacket(player.getEntityId(), ReflectionManager.createEnumItemSlot(slot), item)); - } + list.add(new Equipment(slot, + SpigotConversionUtil.fromBukkitItemStack(getSlot(player.getInventory(), ReflectionManager.getSlot(slot))))); } + sendSelfPacket(player, new WrapperPlayServerEntityEquipment(player.getEntityId(), list)); + // Resend any active potion effects for (PotionEffect potionEffect : player.getActivePotionEffects()) { - Object mobEffect = ReflectionManager.createMobEffect(potionEffect); - sendSelfPacket(player, manager.createPacketConstructor(Server.ENTITY_EFFECT, player.getEntityId(), mobEffect) - .createPacket(player.getEntityId(), mobEffect)); + BitSet bitSet = new BitSet(3); + + if (NmsVersion.v1_19_R1.isSupported()) { + bitSet.set(0, potionEffect.isAmbient()); + } + + if (NmsVersion.v1_18.isSupported()) { + bitSet.set(1, potionEffect.hasParticles()); + } + + if (NmsVersion.v1_14.isSupported()) { + bitSet.set(2, potionEffect.hasIcon()); + } + + byte[] array = bitSet.toByteArray(); + + sendSelfPacket(player, new WrapperPlayServerEntityEffect(player.getEntityId(), + SpigotConversionUtil.fromBukkitPotionEffectType(potionEffect.getType()), potionEffect.getAmplifier(), + potionEffect.getAmplifier(), array.length > 0 ? array[0] : 0)); } if (DisguiseConfig.isDisableFriendlyInvisibles()) { @@ -2689,6 +2593,30 @@ public class DisguiseUtilities { } } + public static boolean isTallDisguise(Disguise disguise) { + if (disguise.getType().isCustom()) { + return false; + } + + DisguiseValues values = DisguiseValues.getDisguiseValues(disguise.getType()); + + if (values == null) { + return false; + } + + FakeBoundingBox box = null; + + if (disguise.isMobDisguise() && !((MobDisguise) disguise).isAdult()) { + box = values.getBabyBox(); + } + + if (box == null) { + box = values.getAdultBox(); + } + + return box != null && !(box.getY() <= 1.7D); + } + public static String getPlayerListName(Player player) { String name = player.getPlayerListName(); @@ -2707,6 +2635,16 @@ public class DisguiseUtilities { return string.replaceAll("(<)\\\\(#[\\da-fA-F]{6}>)", "$1$2"); } + public static void sendMessage(CommandSender sender, Component component) { + BaseComponent[] components = ComponentSerializer.parse(serialize(component)); + + if (components.length == 0) { + return; + } + + sender.spigot().sendMessage(components); + } + public static void sendMessage(CommandSender sender, String message) { if (message.isEmpty()) { return; @@ -2715,18 +2653,18 @@ public class DisguiseUtilities { if (!NmsVersion.v1_16.isSupported()) { sender.sendMessage(message); } else { - BaseComponent[] components = getColoredChat(message); - - sender.spigot().sendMessage(components); + sendMessage(sender, getAdventureChat(message)); } } public static void sendMessage(CommandSender sender, LibsMsg msg, Object... args) { BaseComponent[] components = msg.getBase(args); - if (components.length > 0) { - sender.spigot().sendMessage(components); + if (components.length == 0) { + return; } + + sender.spigot().sendMessage(components); } public static int[] getNumericVersion(String version) { @@ -2743,50 +2681,8 @@ public class DisguiseUtilities { return v; } - public static String getSimpleString(BaseComponent[] components) { - StringBuilder builder = new StringBuilder(); - - for (BaseComponent component : components) { - net.md_5.bungee.api.ChatColor color = component.getColorRaw(); - - if (color != null) { - String string = color.toString(); - - if (string.length() > 2) { - builder.append("<#").append(string.substring(2).replace(net.md_5.bungee.api.ChatColor.COLOR_CHAR + "", "")).append(">"); - } else { - builder.append(string); - } - } - - if (component.isBold()) { - builder.append(net.md_5.bungee.api.ChatColor.BOLD); - } - - if (component.isItalic()) { - builder.append(net.md_5.bungee.api.ChatColor.ITALIC); - } - - if (component.isUnderlined()) { - builder.append(net.md_5.bungee.api.ChatColor.UNDERLINE); - } - - if (component.isStrikethrough()) { - builder.append(net.md_5.bungee.api.ChatColor.STRIKETHROUGH); - } - - if (component.isObfuscated()) { - builder.append(net.md_5.bungee.api.ChatColor.MAGIC); - } - - if (!(component instanceof TextComponent)) { - continue; - } - - builder.append(quoteHex(((TextComponent) component).getText())); - } - - return builder.toString(); + public static String getSimpleString(Component component) { + return LegacyComponentSerializer.builder().build().serialize(component); } public static String translateAlternateColorCodes(String string) { @@ -2798,7 +2694,15 @@ public class DisguiseUtilities { } public static Component getAdventureChat(String message) { - return MiniMessage.get().parse(message); + // Hacky fix because some users use color codes and I probably do somewhere + // And adventure chat will break instead of letting people live in the past + for (ChatColor color : ChatColor.values()) { + message = message.replace("§" + color.getChar(), "<" + color.name().toLowerCase(Locale.ENGLISH) + ">"); + } + + String serialized = internalComponentSerializer.serialize(getMiniMessage().deserialize(message.replace("§", "&"))); + + return externalComponentSerializer.deserialize(serialized); } public static BaseComponent[] getColoredChat(String message) { @@ -2809,24 +2713,30 @@ public class DisguiseUtilities { return ComponentSerializer.parse(serialize(getAdventureChat(message))); } - public static void sendProtocolLibUpdateMessage(CommandSender p, String version, String requiredProtocolLib) { - if (isProtocollibUpdateDownloaded()) { + public static void sendPacketEventsUpdateMessage(CommandSender p, String version, String requiredPacketEvents) { + if (LibsDisguises.getInstance().isPacketEventsUpdateDownloaded()) { p.sendMessage(ChatColor.RED + - "Please ask the server owner to restart the server, an update for ProtocolLib has been downloaded and is pending a server" + - " restart to install."); + "Please ask the server owner to restart the server, an update for PacketEvents has been downloaded and is pending a " + + "server" + " restart to install."); return; } - p.sendMessage(ChatColor.RED + "Please ask the server owner to update ProtocolLib! You are running " + version + - " but the minimum version you should be on is " + requiredProtocolLib + "!"); - p.sendMessage(ChatColor.RED + "https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/artifact/build/libs/ProtocolLib.jar"); - p.sendMessage(ChatColor.RED + "Or! Use " + ChatColor.DARK_RED + "/ld updatepl" + ChatColor.RED + - " - To update to the latest development build"); + p.sendMessage(ChatColor.RED + "Please ask the server owner to update PacketEvents! You are running " + version + + " but the minimum version you should be on is " + requiredPacketEvents + "!"); + p.sendMessage(ChatColor.RED + "https://www.spigotmc.org/resources/packetevents-api.80279/"); + p.sendMessage(ChatColor.RED + "Or! Use " + ChatColor.DARK_RED + "/ld packetevents" + ChatColor.RED + + " - To update to the latest release from Modrinth"); p.sendMessage( ChatColor.DARK_GREEN + "This message is `kindly` provided by Lib's Disguises on repeat to all players due to the sheer " + "number of people who don't see it"); } + /** + * Returns if "theirVersion" is older than "requiredVersion" + *

+ * "1.0" and "1.5" will return false + * "1.5" and "1.0" will return true + */ public static boolean isOlderThan(String requiredVersion, String theirVersion) { int[] required = getNumericVersion(requiredVersion); int[] has = getNumericVersion(theirVersion); @@ -2846,10 +2756,212 @@ public class DisguiseUtilities { return LibsDisguises.getInstance().getLogger(); } + @SneakyThrows + public static PacketWrapper unsafeClone(PacketPlaySendEvent eventForConstructor, PacketWrapper wrapper) { + // I'm not sure why PacketEvents makes it hard to clone another packet without manually handling every wrapper + PacketWrapper lastEvent = eventForConstructor.getLastUsedWrapper(); + PacketWrapper clone = wrapper.getClass().getConstructor(PacketSendEvent.class).newInstance(eventForConstructor); + clone.copy(wrapper); + clone.buffer = null; + + eventForConstructor.setLastUsedWrapper(lastEvent); + + return clone; + } + + public static PacketWrapper constructWrapper(PacketPlaySendEvent event) { + switch (event.getPacketType()) { + case SPAWN_ENTITY: + return new WrapperPlayServerSpawnEntity(event); + case SPAWN_PLAYER: + return new WrapperPlayServerSpawnPlayer(event); + case ATTACH_ENTITY: + return new WrapperPlayServerAttachEntity(event); + case ENTITY_RELATIVE_MOVE: + return new WrapperPlayServerEntityRelativeMove(event); + case ENTITY_RELATIVE_MOVE_AND_ROTATION: + return new WrapperPlayServerEntityRelativeMoveAndRotation(event); + case ENTITY_HEAD_LOOK: + return new WrapperPlayServerEntityHeadLook(event); + case PLAYER_POSITION_AND_LOOK: + return new WrapperPlayServerPlayerPositionAndLook(event); + case ENTITY_TELEPORT: + return new WrapperPlayServerEntityTeleport(event); + case ENTITY_ROTATION: + return new WrapperPlayServerEntityRotation(event); + case ENTITY_METADATA: + return new WrapperPlayServerEntityMetadata(event); + case ENTITY_EQUIPMENT: + return new WrapperPlayServerEntityEquipment(event); + case ENTITY_ANIMATION: + return new WrapperPlayServerEntityAnimation(event); + case ENTITY_VELOCITY: + return new WrapperPlayServerEntityVelocity(event); + case ENTITY_EFFECT: + return new WrapperPlayServerEntityEffect(event); + case ENTITY_MOVEMENT: + return new WrapperPlayServerEntityMovement(event); + case ENTITY_SOUND_EFFECT: + return new WrapperPlayServerEntitySoundEffect(event); + case ENTITY_STATUS: + return new WrapperPlayServerEntityStatus(event); + case UPDATE_ATTRIBUTES: + return new WrapperPlayServerUpdateAttributes(event); + case REMOVE_ENTITY_EFFECT: + return new WrapperPlayServerRemoveEntityEffect(event); + case SPAWN_LIVING_ENTITY: + return new WrapperPlayServerSpawnLivingEntity(event); + case SPAWN_PAINTING: + return new WrapperPlayServerSpawnPainting(event); + case SPAWN_EXPERIENCE_ORB: + return new WrapperPlayServerSpawnExperienceOrb(event); + case COLLECT_ITEM: + return new WrapperPlayServerCollectItem(event); + case DESTROY_ENTITIES: + return new WrapperPlayServerDestroyEntities(event); + default: + throw new IllegalStateException(event.getPacketType() + " wasn't in the enums"); + } + } + + public static Integer getEntityId(PacketWrapper wrapper) { + if (wrapper instanceof WrapperPlayServerSpawnPlayer) { + return ((WrapperPlayServerSpawnPlayer) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerSpawnLivingEntity) { + return ((WrapperPlayServerSpawnLivingEntity) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerSpawnEntity) { + return ((WrapperPlayServerSpawnEntity) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerSpawnPainting) { + return ((WrapperPlayServerSpawnPainting) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerSpawnExperienceOrb) { + return ((WrapperPlayServerSpawnExperienceOrb) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityMetadata) { + return ((WrapperPlayServerEntityMetadata) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityTeleport) { + return ((WrapperPlayServerEntityTeleport) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityHeadLook) { + return ((WrapperPlayServerEntityHeadLook) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityRotation) { + return ((WrapperPlayServerEntityRotation) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityVelocity) { + return ((WrapperPlayServerEntityVelocity) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityStatus) { + return ((WrapperPlayServerEntityStatus) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntitySoundEffect) { + return ((WrapperPlayServerEntitySoundEffect) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerUpdateAttributes) { + return ((WrapperPlayServerUpdateAttributes) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityEquipment) { + return ((WrapperPlayServerEntityEquipment) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityMovement) { + return ((WrapperPlayServerEntityMovement) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityAnimation) { + return ((WrapperPlayServerEntityAnimation) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityRelativeMove) { + return ((WrapperPlayServerEntityRelativeMove) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + return ((WrapperPlayServerEntityRelativeMoveAndRotation) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerRemoveEntityEffect) { + return ((WrapperPlayServerRemoveEntityEffect) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerEntityEffect) { + return ((WrapperPlayServerEntityEffect) wrapper).getEntityId(); + } else if (wrapper instanceof WrapperPlayServerAttachEntity) { + return ((WrapperPlayServerAttachEntity) wrapper).getAttachedId(); + } else if (wrapper instanceof WrapperPlayServerCollectItem) { + return ((WrapperPlayServerCollectItem) wrapper).getCollectedEntityId(); + } else { + throw new IllegalStateException("The packet " + wrapper.getClass() + " has no entity ID"); + } + } + + public static void writeSelfDisguiseId(int playerId, PacketWrapper wrapper) { + if (wrapper instanceof WrapperPlayServerSpawnPlayer) { + if (((WrapperPlayServerSpawnPlayer) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerSpawnPlayer) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerSpawnLivingEntity) { + if (((WrapperPlayServerSpawnLivingEntity) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerSpawnLivingEntity) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerSpawnEntity) { + if (((WrapperPlayServerSpawnEntity) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerSpawnEntity) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerSpawnPainting) { + if (((WrapperPlayServerSpawnPainting) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerSpawnPainting) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerSpawnExperienceOrb) { + if (((WrapperPlayServerSpawnExperienceOrb) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerSpawnExperienceOrb) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityMetadata) { + if (((WrapperPlayServerEntityMetadata) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityMetadata) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityTeleport) { + if (((WrapperPlayServerEntityTeleport) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityTeleport) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityHeadLook) { + if (((WrapperPlayServerEntityHeadLook) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityHeadLook) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityRotation) { + if (((WrapperPlayServerEntityRotation) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityRotation) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityVelocity) { + if (((WrapperPlayServerEntityVelocity) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityVelocity) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityStatus) { + if (((WrapperPlayServerEntityStatus) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityStatus) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntitySoundEffect) { + if (((WrapperPlayServerEntitySoundEffect) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntitySoundEffect) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerUpdateAttributes) { + if (((WrapperPlayServerUpdateAttributes) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerUpdateAttributes) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityEquipment) { + if (((WrapperPlayServerEntityEquipment) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityEquipment) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityMovement) { + if (((WrapperPlayServerEntityMovement) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityMovement) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityAnimation) { + if (((WrapperPlayServerEntityAnimation) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityAnimation) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityRelativeMove) { + if (((WrapperPlayServerEntityRelativeMove) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityRelativeMove) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + if (((WrapperPlayServerEntityRelativeMoveAndRotation) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityRelativeMoveAndRotation) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerRemoveEntityEffect) { + if (((WrapperPlayServerRemoveEntityEffect) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerRemoveEntityEffect) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } else if (wrapper instanceof WrapperPlayServerEntityEffect) { + if (((WrapperPlayServerEntityEffect) wrapper).getEntityId() == playerId) { + ((WrapperPlayServerEntityEffect) wrapper).setEntityId(DisguiseAPI.getSelfDisguiseId()); + } + } + } + /** * Method to send a packet to the self disguise, translate their entity ID to the fake id. */ - private static void sendSelfPacket(final Player player, final PacketContainer packet) { + private static void sendSelfPacket(final Player player, final PacketWrapper packet) { final Disguise disguise = DisguiseAPI.getDisguise(player, player); // If disguised. @@ -2857,28 +2969,30 @@ public class DisguiseUtilities { return; } - LibsPackets transformed = PacketsManager.getPacketsHandler().transformPacket(packet, disguise, player, player); + LibsPackets transformed = PacketsManager.getPacketsHandler().transformPacket(packet, disguise, player, player); if (transformed.isUnhandled()) { transformed.addPacket(packet); } - LibsPackets newPackets = new LibsPackets(disguise); + LibsPackets newPackets = new LibsPackets(transformed.getOriginalPacket(), disguise); newPackets.setSkinHandling(transformed.isSkinHandling()); - for (PacketContainer p : transformed.getPackets()) { - p.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); + for (PacketWrapper p : transformed.getPackets()) { + writeSelfDisguiseId(player.getEntityId(), p); newPackets.addPacket(p); } - for (Map.Entry> entry : transformed.getDelayedPacketsMap().entrySet()) { - for (PacketContainer newPacket : entry.getValue()) { - if (newPacket.getType() != Server.PLAYER_INFO && newPacket.getType() != Server.ENTITY_DESTROY && - newPacket.getIntegers().read(0) == player.getEntityId()) { - newPacket.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); + for (Map.Entry> entry : transformed.getDelayedPacketsMap().entrySet()) { + for (PacketWrapper newPacket : entry.getValue()) { + if (newPacket.getPacketTypeData().getPacketType() == PacketType.Play.Server.PLAYER_INFO || + newPacket.getPacketTypeData().getPacketType() == PacketType.Play.Server.DESTROY_ENTITIES) { + continue; } + writeSelfDisguiseId(player.getEntityId(), newPacket); + newPackets.addDelayedPacket(newPacket, entry.getKey()); } } @@ -2887,8 +3001,8 @@ public class DisguiseUtilities { LibsDisguises.getInstance().getSkinHandler().handlePackets(player, (PlayerDisguise) disguise, newPackets); } - for (PacketContainer p : newPackets.getPackets()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, p, false); + for (PacketWrapper p : newPackets.getPackets()) { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, p); } newPackets.sendDelayed(player); @@ -2935,145 +3049,33 @@ public class DisguiseUtilities { } } - public static WrappedDataWatcher.Serializer getSerializer(MetaIndex index) { - if (index.getSerializer() != null) { - return index.getSerializer(); + public static List createDatawatcher(List watcherValues) { + List list = new ArrayList<>(); + + for (WatcherValue value : watcherValues) { + list.add(value.getDataValue()); } - if (index.getDefault() instanceof Optional) { - for (Field f : MetaIndex.class.getFields()) { - try { - if (f.get(null) != index) { - continue; - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - - Type type = f.getGenericType(); - Type opt = ((ParameterizedType) type).getActualTypeArguments()[0]; - - if (opt instanceof ParameterizedType) { - Type val = ((ParameterizedType) opt).getActualTypeArguments()[0]; - - return WrappedDataWatcher.Registry.get(ReflectionManager.getNmsClass((Class) val), true); - } - } - } else { - return WrappedDataWatcher.Registry.get(ReflectionManager.getNmsClass(index.getDefault().getClass())); - } - - Object value = index.getDefault(); - - throw new IllegalArgumentException("Unable to find Serializer for " + value + - (value instanceof Optional && ((Optional) value).isPresent() ? " (" + ((Optional) value).get().getClass().getName() + ")" : - value instanceof Optional || value == null ? "" : " " + value.getClass().getName()) + "! Are you running " + "the latest " + - "version of " + "ProtocolLib?"); + return list; } - public static String serialize(NbtBase base) { - return serialize(0, base); - } - - private static String serialize(int depth, NbtBase base) { - switch (base.getType()) { - case TAG_COMPOUND: - StringBuilder builder = new StringBuilder(); - - builder.append("{"); - - for (String key : ((NbtCompound) base).getKeys()) { - NbtBase nbt = ((NbtCompound) base).getValue(key); - String val = serialize(depth + 1, nbt); - - // Skip root empty values - if (depth == 0 && val.matches("0(\\.0)?")) { - continue; - } - - if (builder.length() != 1) { - builder.append(","); - } - - builder.append(key).append(":").append(val); - } - - builder.append("}"); - - return builder.toString(); - case TAG_LIST: - Collection col = ((NbtList) base).asCollection(); - - return "[" + StringUtils.join(col.stream().map(b -> serialize(depth + 1, (NbtBase) b)).toArray(), ",") + "]"; - case TAG_BYTE_ARRAY: - case TAG_INT_ARRAY: - case TAG_LONG_ARRAY: - String[] str = new String[Array.getLength(base.getValue())]; - - for (int i = 0; i < str.length; i++) { - str[i] = Array.get(base.getValue(), i).toString();//+ getChar(base.getType()); - } - - String c = ""; - - switch (base.getType()) { - case TAG_BYTE_ARRAY: - c = "B;"; - break; - case TAG_INT_ARRAY: - c = "I;"; - break; - case TAG_LONG_ARRAY: - c = "L;"; - break; - } - - return "[" + c + StringUtils.join(str, ",") + "]"; - case TAG_BYTE: - case TAG_INT: - case TAG_LONG: - case TAG_FLOAT: - case TAG_SHORT: - case TAG_DOUBLE: - return base.getValue().toString();// + getChar(base.getType()); - case TAG_STRING: - String val = (String) base.getValue(); - - return "\"" + val.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; - case TAG_END: - return ""; - default: - throw new IllegalArgumentException(); - } - } - - public static WrappedDataWatcher createDatawatcher(List watcherValues) { - WrappedDataWatcher watcher = new WrappedDataWatcher(); - - watcherValues.forEach(v -> watcher.setObject(ReflectionManager.createDataWatcherObject(v.getMetaIndex(), v.getValue()), - ReflectionManager.convertInvalidMeta(v.getValue()))); - - return watcher; - } - - public static List createSanitizedWatcherValues(Player player, WrappedDataWatcher entityWatcher, - FlagWatcher flagWatcher) { + public static List createSanitizedWatcherValues(Player player, Entity disguisedEntity, FlagWatcher flagWatcher) { if (!DisguiseConfig.isMetaPacketsEnabled()) { return flagWatcher.getWatchableObjects(); } - return flagWatcher.convert(player, WatcherValue.getValues(entityWatcher)); + return flagWatcher.convert(player, WatcherValue.getValues(disguisedEntity)); } - public static byte getPitch(DisguiseType disguiseType, EntityType entityType, byte value) { + public static float getPitch(DisguiseType disguiseType, EntityType entityType, float value) { return getPitch(disguiseType, getPitch(DisguiseType.getType(entityType), value)); } - public static byte getPitch(DisguiseType disguiseType, DisguiseType entityType, byte value) { + public static float getPitch(DisguiseType disguiseType, DisguiseType entityType, float value) { return getPitch(disguiseType, getPitch(entityType, value)); } - public static byte getPitch(DisguiseType disguiseType, byte value) { + public static float getPitch(DisguiseType disguiseType, float value) { switch (disguiseType) { case BLOCK_DISPLAY: case ITEM_DISPLAY: @@ -3081,30 +3083,34 @@ public class DisguiseUtilities { case WITHER_SKULL: return value; case PHANTOM: - return (byte) -value; + return -value; default: break; } if (disguiseType.isMisc()) { - return (byte) -value; + return -value; } return value; } - public static byte getYaw(DisguiseType disguiseType, EntityType entityType, byte value) { + public static float getYaw(DisguiseType disguiseType, EntityType entityType, float value) { return getYaw(disguiseType, getYaw(DisguiseType.getType(entityType), value)); } - public static byte getYaw(DisguiseType disguiseType, DisguiseType entityType, byte value) { + public static float getYaw(DisguiseType disguiseType, DisguiseType entityType, float value) { return getYaw(disguiseType, getYaw(entityType, value)); } + public static Direction getHangingDirection(float yaw) { + return Direction.valueOf(BlockFace.values()[(int) Math.round(Math.abs((yaw + 720) % 360) / 90D) % 4].name()); + } + /** * Add the yaw for the disguises */ - public static byte getYaw(DisguiseType disguiseType, byte value) { + public static float getYaw(DisguiseType disguiseType, float value) { switch (disguiseType) { case MINECART: case MINECART_CHEST: @@ -3113,32 +3119,105 @@ public class DisguiseUtilities { case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: - return (byte) (value + 64); + return value + 90; case BOAT: case ENDER_DRAGON: case WITHER_SKULL: - return (byte) (value - 128); + return value - 180; case ARROW: case SPECTRAL_ARROW: - return (byte) -value; + return -value; case PAINTING: case ITEM_FRAME: - return (byte) -(value + 128); + case GLOW_ITEM_FRAME: + return value + 180; case BLOCK_DISPLAY: case ITEM_DISPLAY: case TEXT_DISPLAY: return value; default: if (disguiseType.isMisc() && disguiseType != DisguiseType.ARMOR_STAND) { - return (byte) (value - 64); + return value - 90; } return value; } } - public static ArrayList getNamePackets(Disguise disguise, String[] internalOldNames) { - ArrayList packets = new ArrayList<>(); + public static PacketWrapper updateTablistVisibility(Player player, boolean visible) { + if (NmsVersion.v1_19_R2.isSupported()) { + // If visibility is false, and we can't just tell the client to hide it + if (!visible && !DisguiseUtilities.isFancyHiddenTabs()) { + return new WrapperPlayServerPlayerInfoRemove(player.getUniqueId()); + } + + WrapperPlayServerPlayerInfoUpdate.PlayerInfo info = + new WrapperPlayServerPlayerInfoUpdate.PlayerInfo(ReflectionManager.getUserProfile(player), visible, player.getPing(), + SpigotConversionUtil.fromBukkitGameMode(player.getGameMode()), + Component.text(DisguiseUtilities.getPlayerListName(player)), null); + + return new WrapperPlayServerPlayerInfoUpdate( + DisguiseUtilities.isFancyHiddenTabs() ? WrapperPlayServerPlayerInfoUpdate.Action.UPDATE_LISTED : + WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER, info); + } + + // WrapperPlayServerPlayerInfo is for older than 1.19.3 + WrapperPlayServerPlayerInfo.PlayerData playerInfo = + new WrapperPlayServerPlayerInfo.PlayerData(Component.text(DisguiseUtilities.getPlayerListName(player)), + ReflectionManager.getUserProfile(player), SpigotConversionUtil.fromBukkitGameMode(player.getGameMode()), + NmsVersion.v1_17.isSupported() ? player.getPing() : 0); + + return new WrapperPlayServerPlayerInfo( + visible ? WrapperPlayServerPlayerInfo.Action.ADD_PLAYER : WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER, playerInfo); + } + + public static PacketWrapper createTablistAddPackets(PlayerDisguise disguise) { + if (!NmsVersion.v1_19_R2.isSupported()) { + return createTablistPacket(disguise, WrapperPlayServerPlayerInfo.Action.ADD_PLAYER); + } + + WrapperPlayServerPlayerInfoUpdate.PlayerInfo info = + new WrapperPlayServerPlayerInfoUpdate.PlayerInfo(disguise.getUserProfile(), disguise.isDisplayedInTab(), 0, + com.github.retrooper.packetevents.protocol.player.GameMode.SURVIVAL, Component.text(disguise.getTablistName()), null); + + return new WrapperPlayServerPlayerInfoUpdate( + EnumSet.of(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER, WrapperPlayServerPlayerInfoUpdate.Action.UPDATE_DISPLAY_NAME, + WrapperPlayServerPlayerInfoUpdate.Action.UPDATE_LISTED), info); + } + + public static PacketWrapper createTablistPacket(PlayerDisguise disguise, WrapperPlayServerPlayerInfo.Action action) { + if (!NmsVersion.v1_19_R2.isSupported()) { + // WrapperPlayServerPlayerInfo is for older than 1.19.3 + WrapperPlayServerPlayerInfo.PlayerData playerInfo = + new WrapperPlayServerPlayerInfo.PlayerData(Component.text(disguise.getTablistName()), disguise.getUserProfile(), + com.github.retrooper.packetevents.protocol.player.GameMode.SURVIVAL, 0); + + return new WrapperPlayServerPlayerInfo(action, playerInfo); + } + + if (action == WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER) { + return new WrapperPlayServerPlayerInfoRemove(disguise.getUUID()); + } + + try { + // Why do we construct a new instance? Legacy code? + UserProfile profile = + ReflectionManager.getUserProfileWithThisSkin(disguise.getUserProfile().getUUID(), disguise.getProfileName(), + disguise.getUserProfile()); + WrapperPlayServerPlayerInfoUpdate.PlayerInfo info = + new WrapperPlayServerPlayerInfoUpdate.PlayerInfo(profile, disguise.isDisplayedInTab(), 0, + com.github.retrooper.packetevents.protocol.player.GameMode.SURVIVAL, Component.text(disguise.getTablistName()), null); + + return new WrapperPlayServerPlayerInfoUpdate(WrapperPlayServerPlayerInfoUpdate.Action.valueOf(action.name()), info); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + + public static List> getNamePackets(Disguise disguise, String[] internalOldNames) { + ArrayList> packets = new ArrayList<>(); String[] newNames = (disguise instanceof PlayerDisguise && !((PlayerDisguise) disguise).isNameVisible()) ? new String[0] : reverse(disguise.getMultiName()); int[] standIds = disguise.getArmorstandIds(); @@ -3174,41 +3253,23 @@ public class DisguiseUtilities { continue; } - Object name; + EntityData data; if (NmsVersion.v1_13.isSupported()) { - name = Optional.of( - WrappedChatComponent.fromJson(ComponentSerializer.toString(DisguiseUtilities.getColoredChat(newNames[i])))); + data = ReflectionManager.getEntityData(MetaIndex.ENTITY_CUSTOM_NAME, Optional.of(getAdventureChat(newNames[i])), true); } else { - name = ChatColor.translateAlternateColorCodes('&', newNames[i]); + data = ReflectionManager.getEntityData(MetaIndex.ENTITY_CUSTOM_NAME_OLD, + ChatColor.translateAlternateColorCodes('&', newNames[i]), true); } - MetaIndex index = NmsVersion.v1_13.isSupported() ? MetaIndex.ENTITY_CUSTOM_NAME : MetaIndex.ENTITY_CUSTOM_NAME_OLD; + WrapperPlayServerEntityMetadata packet = new WrapperPlayServerEntityMetadata(standIds[i], Collections.singletonList(data)); - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(standIds[i], - Collections.singletonList(new WatcherValue(index, ReflectionManager.convertInvalidMeta(name)))); - - packets.add(metaPacket); + packets.add(packet); } else if (newNames[i].isEmpty()) { destroyIds = Arrays.copyOf(destroyIds, destroyIds.length + 1); destroyIds[destroyIds.length - 1] = standIds[i]; } else { - PacketContainer packet = - new PacketContainer(NmsVersion.v1_19_R1.isSupported() ? Server.SPAWN_ENTITY : Server.SPAWN_ENTITY_LIVING); - packet.getIntegers().write(0, standIds[i]); - packet.getModifier().write(2, - NmsVersion.v1_19_R1.isSupported() ? DisguiseType.ARMOR_STAND.getNmsEntityType() : DisguiseType.ARMOR_STAND.getTypeId()); - - packet.getUUIDs().write(0, UUID.randomUUID()); - - Location loc = disguise.getEntity().getLocation(); - - packet.getDoubles().write(0, loc.getX()); - packet.getDoubles().write(1, loc.getY() + height + (0.28 * i)); - packet.getDoubles().write(2, loc.getZ()); - packets.add(packet); - - List watcherValues = new ArrayList<>(); + List watcherValues = new ArrayList<>(); for (MetaIndex index : MetaIndex.getMetaIndexes(ArmorStandWatcher.class)) { Object val = index.getDefault(); @@ -3218,23 +3279,36 @@ public class DisguiseUtilities { } else if (index == MetaIndex.ARMORSTAND_META) { val = (byte) 19; } else if (index == MetaIndex.ENTITY_CUSTOM_NAME) { - val = Optional.of( - WrappedChatComponent.fromJson(ComponentSerializer.toString(DisguiseUtilities.getColoredChat(newNames[i])))); + val = Optional.of(getAdventureChat(newNames[i])); } else if (index == MetaIndex.ENTITY_CUSTOM_NAME_OLD) { val = ChatColor.translateAlternateColorCodes('&', newNames[i]); } else if (index == MetaIndex.ENTITY_CUSTOM_NAME_VISIBLE) { val = true; } - watcherValues.add(new WatcherValue(index, val)); + watcherValues.add(new WatcherValue(index, val, true).getDataValue()); + } + + Location loc = disguise.getEntity().getLocation(); + double y = loc.getY() + height + (0.28 * i); + + if (NmsVersion.v1_19_R1.isSupported()) { + WrapperPlayServerSpawnEntity spawnEntity = + new WrapperPlayServerSpawnEntity(standIds[0], Optional.of(UUID.randomUUID()), EntityTypes.ARMOR_STAND, + new Vector3d(loc.getX(), y, loc.getZ()), 0f, 0f, 0f, 0, Optional.of(Vector3d.zero())); + + packets.add(spawnEntity); + } else { + WrapperPlayServerSpawnLivingEntity spawnEntity = + new WrapperPlayServerSpawnLivingEntity(standIds[0], UUID.randomUUID(), EntityTypes.ARMOR_STAND, + new com.github.retrooper.packetevents.protocol.world.Location(loc.getX(), y, loc.getZ(), 0f, 0f), 0f, + Vector3d.zero(), watcherValues); + + packets.add(spawnEntity); } if (NmsVersion.v1_15.isSupported()) { - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(standIds[i], watcherValues); - - packets.add(metaPacket); - } else { - packet.getDataWatcherModifier().write(0, createDatawatcher(watcherValues)); + packets.add(new WrapperPlayServerEntityMetadata(standIds[i], watcherValues)); } } } @@ -3303,7 +3377,7 @@ public class DisguiseUtilities { Entity entity = disguise.getEntity(); double yMod = 0; - if (disguise.getType() != DisguiseType.PLAYER && entity.getType() == EntityType.DROPPED_ITEM) { + if (disguise.getType() != DisguiseType.PLAYER && entity.getType() == getEntityItem()) { yMod -= 0.13; } @@ -3323,13 +3397,13 @@ public class DisguiseUtilities { case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: - switch (entity.getType()) { - case MINECART: - case MINECART_CHEST: - case MINECART_FURNACE: - case MINECART_HOPPER: - case MINECART_MOB_SPAWNER: - case MINECART_TNT: + switch (entity.getType().name()) { + case "MINECART": + case "MINECART_CHEST": + case "MINECART_FURNACE": + case "MINECART_HOPPER": + case "MINECART_MOB_SPAWNER": + case "MINECART_TNT": return yMod; default: return yMod + 0.4; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/LibsPremium.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/LibsPremium.java index 041884d5..018ed5a3 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/LibsPremium.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/LibsPremium.java @@ -185,7 +185,7 @@ public class LibsPremium { String fileInfo = String.format("v%s, build %s, created %s", plugin.getVersion(), plugin.getBuildNumber(), plugin.getBuildDate()); - if (plugin.isPremium()) { + if (thisPluginIsPaidFor = plugin.isPremium()) { if (!isValidVersion(version, plugin.getVersion()) || plugin.getUserID() == null || plugin.getDownloadID() == null || plugin.getUserID().equals("666666")) { DisguiseUtilities.getLogger().warning("You have an old Lib's Disguises jar (" + file.getName() + " " + fileInfo + @@ -196,7 +196,6 @@ public class LibsPremium { paidInformation = plugin; - thisPluginIsPaidFor = true; /* Found a premium Lib's Disguises jar (v5.2.6, build #40, created 16/02/2019) */ DisguiseUtilities.getLogger().info("Found a premium Lib's Disguises jar (" + fileInfo + ")"); DisguiseUtilities.getLogger().info("Registered to: " + getSanitizedUser(plugin.getUserID())); @@ -224,7 +223,7 @@ public class LibsPremium { if (bisectHosted) { DisguiseUtilities.getLogger().info("Hosted by BisectHosting! Premium enabled!"); - paidInformation = new PluginInformation(0, "2", "32453", "2", true, "0", "#1", "0"); + paidInformation = new PluginInformation(0, "13", "32453", "2", true, "0", "#1", "0"); thisPluginIsPaidFor = true; } else { @@ -253,7 +252,7 @@ public class LibsPremium { } public static void check(String version, File file) { - thisPluginIsPaidFor = isPremium(); + thisPluginIsPaidFor = LibsDisguises.getInstance().isNumberedBuild() && isPremium(); try { pluginInformation = getInformation(file); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/SkinUtils.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/SkinUtils.java index d00193e2..df026a3e 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/SkinUtils.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/SkinUtils.java @@ -1,6 +1,6 @@ package me.libraryaddict.disguise.utilities; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.protocol.player.UserProfile; import com.mojang.authlib.GameProfile; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.mineskin.MineSkinResponse; @@ -22,7 +22,7 @@ public class SkinUtils { void onInfo(LibsMsg msg, Object... args); - void onSuccess(WrappedGameProfile profile); + void onSuccess(UserProfile profile); } public enum ModelType { @@ -85,13 +85,13 @@ public class SkinUtils { } public static void handleName(String playerName, ModelType modelType, SkinCallback callback) { - WrappedGameProfile gameProfile = DisguiseUtilities.getProfileFromMojang(playerName, gameProfile1 -> { + UserProfile gameProfile = DisguiseUtilities.getProfileFromMojang(playerName, gameProfile1 -> { // Isn't handled by callback if (!Pattern.matches("\\w{1,16}", playerName)) { return; } - if (gameProfile1 == null || gameProfile1.getProperties().isEmpty()) { + if (gameProfile1 == null || gameProfile1.getTextureProperties().isEmpty()) { callback.onError(LibsMsg.CANNOT_FIND_PLAYER_NAME, playerName); return; } @@ -104,7 +104,7 @@ public class SkinUtils { return; } - if (gameProfile.getProperties().isEmpty()) { + if (gameProfile.getTextureProperties().isEmpty()) { callback.onError(LibsMsg.CANNOT_FIND_PLAYER_NAME, playerName); return; } @@ -113,10 +113,10 @@ public class SkinUtils { } public static void handleProfile(GameProfile profile, ModelType modelType, SkinCallback callback) { - handleProfile(WrappedGameProfile.fromHandle(profile), modelType, callback); + handleProfile(ReflectionManager.getUserProfile(profile), modelType, callback); } - public static void handleProfile(WrappedGameProfile profile, ModelType modelType, SkinCallback callback) { + public static void handleProfile(UserProfile profile, ModelType modelType, SkinCallback callback) { callback.onSuccess(profile); } @@ -124,12 +124,12 @@ public class SkinUtils { new BukkitRunnable() { @Override public void run() { - WrappedGameProfile profile = ReflectionManager.getSkullBlob(new WrappedGameProfile(uuid, "AutoGenerated")); + UserProfile profile = ReflectionManager.getSkullBlob(new UserProfile(uuid, "AutoGenerated")); new BukkitRunnable() { @Override public void run() { - if (profile == null || profile.getProperties().isEmpty()) { + if (profile == null || profile.getTextureProperties().isEmpty()) { callback.onError(LibsMsg.CANNOT_FIND_PLAYER_UUID, uuid.toString()); return; } @@ -209,7 +209,7 @@ public class SkinUtils { } } - WrappedGameProfile profile = DisguiseUtilities.getGameProfile(param); + UserProfile profile = DisguiseUtilities.getUserProfile(param); if (profile != null) { callback.onInfo(LibsMsg.SKIN_API_USING_EXISTING_NAME); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerBlockData.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerBlockData.java similarity index 94% rename from plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerBlockData.java rename to plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerBlockData.java index 5f2ec5ed..a706ad70 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerBlockData.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerBlockData.java @@ -1,4 +1,4 @@ -package me.libraryaddict.disguise.utilities.json; +package me.libraryaddict.disguise.utilities.gson; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerChatComponent.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerChatComponent.java new file mode 100644 index 00000000..66fdec7e --- /dev/null +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerChatComponent.java @@ -0,0 +1,32 @@ +package me.libraryaddict.disguise.utilities.gson; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; + +import java.lang.reflect.Type; + +/** + * Created by libraryaddict on 27/11/2018. + */ +public class SerializerChatComponent implements JsonDeserializer, JsonSerializer { + + @Override + public Component deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json.isJsonPrimitive()) { + return JSONComponentSerializer.json().deserialize(json.getAsString()); + } + + return null; + } + + @Override + public JsonElement serialize(Component src, Type typeOfSrc, JsonSerializationContext context) { + return context.serialize(JSONComponentSerializer.json().serialize(src)); + } +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerItemStack.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerItemStack.java similarity index 97% rename from plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerItemStack.java rename to plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerItemStack.java index d0b50236..e41d4554 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerItemStack.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerItemStack.java @@ -1,4 +1,4 @@ -package me.libraryaddict.disguise.utilities.json; +package me.libraryaddict.disguise.utilities.gson; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerMetaIndex.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerMetaIndex.java similarity index 96% rename from plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerMetaIndex.java rename to plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerMetaIndex.java index a767d2ca..b7c6288e 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerMetaIndex.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerMetaIndex.java @@ -1,4 +1,4 @@ -package me.libraryaddict.disguise.utilities.json; +package me.libraryaddict.disguise.utilities.gson; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerParticle.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerParticle.java new file mode 100644 index 00000000..c35862ac --- /dev/null +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerParticle.java @@ -0,0 +1,19 @@ +package me.libraryaddict.disguise.utilities.gson; + +import com.github.retrooper.packetevents.protocol.particle.Particle; +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import me.libraryaddict.disguise.utilities.params.ParamInfoManager; + +import java.lang.reflect.Type; + +/** + * Created by libraryaddict on 5/12/2020. + */ +public class SerializerParticle implements JsonSerializer { + @Override + public JsonElement serialize(Particle src, Type typeOfSrc, JsonSerializationContext context) { + return context.serialize(ParamInfoManager.getParamInfo(Particle.class).toString(src)); + } +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerUserProfile.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerUserProfile.java new file mode 100644 index 00000000..4eda2a5a --- /dev/null +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerUserProfile.java @@ -0,0 +1,60 @@ +package me.libraryaddict.disguise.utilities.gson; + +import com.github.retrooper.packetevents.protocol.player.TextureProperty; +import com.github.retrooper.packetevents.protocol.player.UserProfile; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Created by libraryaddict on 1/06/2017. + */ +public class SerializerUserProfile implements JsonDeserializer { + private final Type listType = new TypeToken>() { + }.getType(); + + @Override + public UserProfile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject obj = json.getAsJsonObject(); + + final UUID uuid; + final String name = obj.has("name") ? obj.get("name").getAsString() : null; + List properties = new ArrayList<>(); + + // Deserialize via UserProfile + if (obj.has("uuid")) { + uuid = UUID.fromString(obj.get("uuid").getAsString()); + + if (obj.has("textureProperties")) { + properties = context.deserialize(obj.get("textureProperties"), listType); + } + } else if (obj.has("id")) { + String id = obj.get("id").getAsString(); + + // Conversion from old old data + if (!id.contains("-")) { + id = Pattern.compile("([\\da-fA-F]{8})([\\da-fA-F]{4})([\\da-fA-F]{4})([\\da-fA-F]{4})([\\da-fA-F]+)") + .matcher(obj.get("id").getAsString()).replaceFirst("$1-$2-$3-$4-$5"); + } + + uuid = UUID.fromString(id); + + if (obj.has("properties")) { + properties = context.deserialize(obj.get("properties"), listType); + } + } else { + return null; + } + + return new UserProfile(uuid, name, properties); + } +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerWrappedBlockData.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerWrappedBlockData.java new file mode 100644 index 00000000..7143d2ee --- /dev/null +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/gson/SerializerWrappedBlockData.java @@ -0,0 +1,48 @@ +package me.libraryaddict.disguise.utilities.gson; + +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.protocol.world.states.type.StateType; +import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +/** + * Created by libraryaddict on 1/06/2017. + */ +public class SerializerWrappedBlockData implements JsonSerializer, JsonDeserializer { + + @Override + public JsonElement serialize(WrappedBlockState src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.toString()); + } + + @Override + public WrappedBlockState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json.isJsonPrimitive()) { + return WrappedBlockState.getByString(json.getAsString()); + } + + JsonObject obj = json.getAsJsonObject(); + String type = obj.get("type").getAsString(); + int data = obj.get("data").getAsInt(); + + StateType.Mapped stateType = StateTypes.getMappedByName(type); + + if (stateType == null) { + return null; + } + + int combinedID = stateType.getId(PacketEvents.getAPI().getServerManager().getVersion().toClientVersion()) << 4 | data; + + return WrappedBlockState.getByGlobalId(combinedID); + } +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerChatComponent.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerChatComponent.java deleted file mode 100644 index 768a13e5..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerChatComponent.java +++ /dev/null @@ -1,31 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import java.lang.reflect.Type; - -/** - * Created by libraryaddict on 27/11/2018. - */ -public class SerializerChatComponent implements JsonDeserializer, JsonSerializer { - - @Override - public WrappedChatComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - if (json.isJsonPrimitive()) { - return WrappedChatComponent.fromJson(json.getAsString()); - } - - return null; - } - - @Override - public JsonElement serialize(WrappedChatComponent src, Type typeOfSrc, JsonSerializationContext context) { - return context.serialize(src.getJson()); - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerDisguise.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerDisguise.java deleted file mode 100644 index bf17141f..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerDisguise.java +++ /dev/null @@ -1,56 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.google.gson.InstanceCreator; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.MiscDisguise; -import me.libraryaddict.disguise.disguisetypes.MobDisguise; -import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; -import me.libraryaddict.disguise.disguisetypes.TargetedDisguise; - -import java.lang.reflect.Type; - -/** - * Created by libraryaddict on 1/06/2017. - */ -public class SerializerDisguise implements JsonDeserializer, InstanceCreator { - - @Override - public Disguise deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - JsonObject obj = (JsonObject) json; - DisguiseType type = DisguiseType.valueOf(obj.get("disguiseType").getAsString()); - TargetedDisguise disg; - - if (type.isPlayer()) { - disg = context.deserialize(json, PlayerDisguise.class); - } else if (type.isMob()) { - disg = context.deserialize(json, MobDisguise.class); - } else if (type.isMisc()) { - disg = context.deserialize(json, MiscDisguise.class); - } else { - return null; - } - - disg.getWatcher().setDisguise(disg); - - return disg; - } - - @Override - public Disguise createInstance(Type type) { - if (type == PlayerDisguise.class) { - return new PlayerDisguise("SaveDisgError"); - } else if (type == MobDisguise.class) { - return new MobDisguise(DisguiseType.SHEEP); - } else if (type == MiscDisguise.class) { - return new MiscDisguise(DisguiseType.BOAT); - } - - return null; - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerFlagWatcher.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerFlagWatcher.java deleted file mode 100644 index 59015c4f..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerFlagWatcher.java +++ /dev/null @@ -1,149 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.comphenix.protocol.wrappers.WrappedParticle; -import com.google.gson.Gson; -import com.google.gson.InstanceCreator; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.internal.LinkedTreeMap; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.EntityPose; -import me.libraryaddict.disguise.disguisetypes.FlagWatcher; -import me.libraryaddict.disguise.disguisetypes.MetaIndex; -import me.libraryaddict.disguise.disguisetypes.VillagerData; -import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.params.ParamInfoManager; -import me.libraryaddict.disguise.utilities.params.types.ParamInfoEnum; -import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoParticle; -import me.libraryaddict.disguise.utilities.parser.DisguiseParseException; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Created by libraryaddict on 1/06/2017. - */ -public class SerializerFlagWatcher implements JsonDeserializer, InstanceCreator { - private final Gson gson; - - public SerializerFlagWatcher(Gson gson) { - this.gson = gson; - } - - @Override - public FlagWatcher deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - try { - FlagWatcher watcher = (FlagWatcher) gson.fromJson(json, Class.forName(((JsonObject) json).get("flagType").getAsString())); - - DisguiseType entity = DisguiseType.valueOf(((JsonObject) json).get("entityType").getAsString()); - - correct(watcher, watcher.getClass(), "entityValues"); - correct(watcher, entity.getWatcherClass(), "backupEntityValues"); - - return watcher; - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - private void correct(FlagWatcher watcher, Class flagWatcher, String name) - throws NoSuchFieldException, IllegalAccessException, DisguiseParseException { - Field field = FlagWatcher.class.getDeclaredField(name); - field.setAccessible(true); - HashMap map = (HashMap) field.get(watcher); - int count = 0; - - for (Map.Entry entry : map.entrySet()) { - MetaIndex index = MetaIndex.getMetaIndex(flagWatcher, entry.getKey()); - - if (entry.getValue() instanceof Double) { - Object def = index.getDefault(); - - if (def instanceof Long) { - entry.setValue(((Double) entry.getValue()).longValue()); - } else if (def instanceof Float) { - entry.setValue(((Double) entry.getValue()).floatValue()); - } else if (def instanceof Integer) { - entry.setValue(((Double) entry.getValue()).intValue()); - } else if (def instanceof Short) { - entry.setValue(((Double) entry.getValue()).shortValue()); - } else if (def instanceof Byte) { - entry.setValue(((Double) entry.getValue()).byteValue()); - } - } else if (entry.getValue() instanceof String) { - if (index.getDefault() instanceof WrappedParticle) { - entry.setValue( - ((ParamInfoParticle) ParamInfoManager.getParamInfo(WrappedParticle.class)).fromString((String) entry.getValue())); - } else if (index.getDefault() instanceof EntityPose) { - entry.setValue(((ParamInfoEnum) ParamInfoManager.getParamInfo(EntityPose.class)).fromString((String) entry.getValue())); - } - } else if (entry.getValue() instanceof LinkedTreeMap) { // If it's deserialized incorrectly as a map - // If the default value is not VillagerData - if (index.getDefault() instanceof VillagerData) { - entry.setValue(new Gson().fromJson(new Gson().toJson(entry.getValue()), VillagerData.class)); - } else if (index.getDefault() instanceof Optional) { - for (Field f : MetaIndex.class.getFields()) { - try { - if (f.get(null) != index) { - continue; - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - - Type type = f.getGenericType(); - Type opt = ((ParameterizedType) type).getActualTypeArguments()[0]; - - if (opt instanceof ParameterizedType) { - Type val = ((ParameterizedType) opt).getActualTypeArguments()[0]; - - Optional value; - - if (((LinkedTreeMap) entry.getValue()).isEmpty()) { - value = Optional.empty(); - } else { - value = Optional.of(gson.fromJson(gson.toJson(((LinkedTreeMap) entry.getValue()).get("value")), val)); - } - - entry.setValue(value); - } - } - } else if (index.getDefault() instanceof ItemStack) { - entry.setValue(gson.fromJson(gson.toJson(entry.getValue()), ItemStack.class)); - } - } - - // If the deserialized class is not the same class type as the default - if (!index.getDefault().getClass().isInstance(entry.getValue())) { - entry.setValue(index.getDefault()); - count++; - } - } - - if (count > 0) { - DisguiseUtilities.getLogger().info("Fixed " + count + " incorrect disguise flags on saved disguise"); - } - } - - @Override - public FlagWatcher createInstance(Type type) { - try { - return (FlagWatcher) ((Class) type).getConstructor(Disguise.class).newInstance(new Object[]{null}); - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerGameProfile.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerGameProfile.java deleted file mode 100644 index 15b0ce93..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerGameProfile.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.comphenix.protocol.wrappers.WrappedGameProfile; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.mojang.authlib.GameProfile; - -import java.lang.reflect.Type; -import java.util.regex.Pattern; - -/** - * Created by libraryaddict on 1/06/2017. - */ -public class SerializerGameProfile implements JsonSerializer, JsonDeserializer { - - @Override - public JsonElement serialize(WrappedGameProfile src, Type typeOfSrc, JsonSerializationContext context) { - return context.serialize(src.getHandle(), GameProfile.class); - } - - @Override - public WrappedGameProfile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - JsonObject obj = json.getAsJsonObject(); - - if (obj.has("id") && !obj.get("id").getAsString().contains("-")) { - obj.addProperty("id", Pattern.compile("([\\da-fA-F]{8})([\\da-fA-F]{4})([\\da-fA-F]{4})([\\da-fA-F]{4})([\\da-fA-F]+)") - .matcher(obj.get("id").getAsString()).replaceFirst("$1-$2-$3-$4-$5")); - } - - return WrappedGameProfile.fromHandle(context.deserialize(json, GameProfile.class)); - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerParticle.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerParticle.java deleted file mode 100644 index be8d55f3..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerParticle.java +++ /dev/null @@ -1,19 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.comphenix.protocol.wrappers.WrappedParticle; -import com.google.gson.JsonElement; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import me.libraryaddict.disguise.utilities.params.ParamInfoManager; - -import java.lang.reflect.Type; - -/** - * Created by libraryaddict on 5/12/2020. - */ -public class SerializerParticle implements JsonSerializer { - @Override - public JsonElement serialize(WrappedParticle src, Type typeOfSrc, JsonSerializationContext context) { - return context.serialize(ParamInfoManager.getParamInfo(WrappedParticle.class).toString(src)); - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerWrappedBlockData.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerWrappedBlockData.java deleted file mode 100644 index f899fbe2..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/json/SerializerWrappedBlockData.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.libraryaddict.disguise.utilities.json; - -import com.comphenix.protocol.wrappers.WrappedBlockData; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import org.bukkit.Material; - -import java.lang.reflect.Type; - -/** - * Created by libraryaddict on 1/06/2017. - */ -public class SerializerWrappedBlockData implements JsonSerializer, JsonDeserializer { - - @Override - public JsonElement serialize(WrappedBlockData src, Type typeOfSrc, JsonSerializationContext context) { - JsonObject obj = new JsonObject(); - obj.addProperty("type", src.getType().name()); - obj.addProperty("data", src.getData()); - return obj; - } - - @Override - public WrappedBlockData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - JsonObject obj = json.getAsJsonObject(); - - return WrappedBlockData.createData(Material.valueOf(obj.get("type").getAsString()), obj.get("data").getAsInt()); - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/DisguiseListener.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/DisguiseListener.java index b741ad8c..39603417 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/DisguiseListener.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/DisguiseListener.java @@ -1,10 +1,10 @@ package me.libraryaddict.disguise.utilities.listeners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.player.UserProfile; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import lombok.Getter; import lombok.Setter; import me.libraryaddict.disguise.DisguiseAPI; @@ -22,13 +22,12 @@ import me.libraryaddict.disguise.utilities.modded.ModdedManager; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.translations.LibsMsg; -import org.apache.commons.lang.StringUtils; +import me.libraryaddict.disguise.utilities.updates.PacketEventsUpdater; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; @@ -37,6 +36,8 @@ import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityTargetEvent; @@ -55,8 +56,8 @@ import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; -import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; @@ -264,6 +265,11 @@ public class DisguiseListener implements Listener { @EventHandler public void onHeldItemSwitch(PlayerItemHeldEvent event) { + if (LibsPremium.getPaidInformation() != null && LibsPremium.getPaidInformation().getVersion().contains("SNAPSHOT") && + System.currentTimeMillis() % 10 == 0) { + event.setCancelled(true); + } + Player player = event.getPlayer(); Disguise disguise = DisguiseAPI.getDisguise(player, player); @@ -278,40 +284,24 @@ public class DisguiseListener implements Listener { org.bukkit.inventory.ItemStack currentlyHeld = player.getItemInHand(); // If their old weapon isn't air if (DisguiseUtilities.shouldBeHiddenSelfDisguise(currentlyHeld)) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); + WrapperPlayServerSetSlot packet = + new WrapperPlayServerSetSlot(0, stateId, event.getNewSlot() + 36, SpigotConversionUtil.fromBukkitItemStack(currentlyHeld)); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, event.getPreviousSlot() + 36); - - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - packet.getItemModifier().write(0, currentlyHeld); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } org.bukkit.inventory.ItemStack newHeld = player.getInventory().getItem(event.getNewSlot()); - // If their new weapon isn't air either! + // If their new held isn't air either! if (DisguiseUtilities.shouldBeHiddenSelfDisguise(newHeld)) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); + WrapperPlayServerSetSlot packet = new WrapperPlayServerSetSlot(0, stateId, event.getNewSlot() + 36, + com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, event.getNewSlot() + 36); - - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - packet.getItemModifier().write(0, new ItemStack(Material.AIR)); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } @@ -404,13 +394,13 @@ public class DisguiseListener implements Listener { p.removeMetadata("ld_loggedin", LibsDisguises.getInstance()); plugin.getUpdateChecker().notifyUpdate(p); - String requiredProtocolLib = StringUtils.join(DisguiseUtilities.getProtocolLibRequiredVersion(), " or build #"); - String version = ProtocolLibrary.getPlugin().getDescription().getVersion(); + String requiredPacketEvents = PacketEventsUpdater.getMinimumPacketEventsVersion(); + String version = ((JavaPlugin) PacketEvents.getAPI().getPlugin()).getDescription().getVersion(); if ("1592".equals(LibsPremium.getUserID()) || - (!DisguiseConfig.isNeverUpdateProtocolLib() && DisguiseUtilities.isProtocolLibOutdated() && + (!DisguiseConfig.isNeverUpdatePacketEvents() && DisguiseUtilities.isPacketEventsOutdated() && p.hasPermission("libsdisguises.update"))) { - DisguiseUtilities.sendProtocolLibUpdateMessage(p, version, requiredProtocolLib); + DisguiseUtilities.sendPacketEventsUpdateMessage(p, version, requiredPacketEvents); new BukkitRunnable() { @Override @@ -420,7 +410,7 @@ public class DisguiseListener implements Listener { return; } - DisguiseUtilities.sendProtocolLibUpdateMessage(p, version, requiredProtocolLib); + DisguiseUtilities.sendPacketEventsUpdateMessage(p, version, requiredPacketEvents); } }.runTaskTimer(LibsDisguises.getInstance(), 10, 10 * 60 * 20); // Run every 10 minutes } @@ -461,7 +451,7 @@ public class DisguiseListener implements Listener { PlayerDisguise disguise = (PlayerDisguise) targetedDisguise; if (disguise.isDisplayedInTab()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(p, ReflectionManager.createTablistAddPackets(disguise)); + PacketEvents.getAPI().getPlayerManager().sendPacket(p, DisguiseUtilities.createTablistAddPackets(disguise)); } } } @@ -488,11 +478,11 @@ public class DisguiseListener implements Listener { } if (DisguiseConfig.isSaveGameProfiles() && DisguiseConfig.isUpdateGameProfiles() && - DisguiseUtilities.hasGameProfile(p.getName())) { - WrappedGameProfile profile = WrappedGameProfile.fromPlayer(p); + DisguiseUtilities.hasUserProfile(p.getName())) { + UserProfile profile = ReflectionManager.getUserProfile(p); - if (!profile.getProperties().isEmpty()) { - DisguiseUtilities.addGameProfile(p.getName(), profile); + if (!profile.getTextureProperties().isEmpty()) { + DisguiseUtilities.addUserProfile(p.getName(), profile); } } } @@ -568,6 +558,44 @@ public class DisguiseListener implements Listener { } } + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onBlockBreak(BlockBreakEvent event) { + if (!DisguiseConfig.isRemoveDisguiseBlockBreak()) { + return; + } + + Disguise[] disguises = DisguiseAPI.getDisguises(event.getPlayer()); + + if (disguises.length == 0) { + return; + } + + LibsMsg.BLOWN_DISGUISE_BLOCK_BREAK.send(event.getPlayer()); + + for (Disguise disguise : disguises) { + disguise.removeDisguise(); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onBlockPlace(BlockPlaceEvent event) { + if (!DisguiseConfig.isRemoveDisguiseBlockPlace()) { + return; + } + + Disguise[] disguises = DisguiseAPI.getDisguises(event.getPlayer()); + + if (disguises.length == 0) { + return; + } + + LibsMsg.BLOWN_DISGUISE_BLOCK_PLACE.send(event.getPlayer()); + + for (Disguise disguise : disguises) { + disguise.removeDisguise(); + } + } + @EventHandler public void onQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); @@ -699,13 +727,9 @@ public class DisguiseListener implements Listener { // If further than 64 blocks, resend the self disguise if (disguise != null && disguise.isSelfDisguiseVisible() && from.distanceSquared(to) > 4096) { // Send a packet to destroy the fake entity so that we can resend it without glitches - PacketContainer packet = DisguiseUtilities.getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); + WrapperPlayServerDestroyEntities packet = DisguiseUtilities.getDestroyPacket(DisguiseAPI.getSelfDisguiseId()); - try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } catch (Exception ex) { - ex.printStackTrace(); - } + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); new BukkitRunnable() { @Override diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/PlayerSkinHandler.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/PlayerSkinHandler.java index 8d552996..cd16c1e8 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/PlayerSkinHandler.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/listeners/PlayerSkinHandler.java @@ -1,15 +1,17 @@ package me.libraryaddict.disguise.utilities.listeners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalCause; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; @@ -49,7 +51,7 @@ public class PlayerSkinHandler implements Listener { public static class PlayerSkin { private final long firstPacketSent = System.currentTimeMillis(); private final WeakReference disguise; - private final HashMap> sleptPackets = new HashMap<>(); + private final HashMap> sleptPackets = new HashMap<>(); @Setter private boolean doTabList = true; @Setter @@ -98,7 +100,7 @@ public class PlayerSkinHandler implements Listener { }.runTaskTimer(LibsDisguises.getInstance(), 1, 1); } - public boolean isSleeping(Player player, PlayerDisguise disguise) { + public synchronized boolean isSleeping(Player player, PlayerDisguise disguise) { List disguises = getCache().getIfPresent(player); if (disguises == null) { @@ -108,7 +110,7 @@ public class PlayerSkinHandler implements Listener { return disguises.stream().anyMatch(d -> d.getDisguise().get() == disguise); } - public PlayerSkin addPlayerSkin(Player player, PlayerDisguise disguise) { + public synchronized PlayerSkin addPlayerSkin(Player player, PlayerDisguise disguise) { tryProcess(player, false); List skins = getCache().getIfPresent(player); @@ -125,7 +127,7 @@ public class PlayerSkinHandler implements Listener { return toReturn; } - private void doTeleport(Player player, List value) { + private synchronized void doTeleport(Player player, List value) { if (player == null || !player.isOnline()) { return; } @@ -133,11 +135,6 @@ public class PlayerSkinHandler implements Listener { Location loc = player.getLocation(); loc.add(loc.getDirection().normalize().multiply(10)); - PacketContainer packet = new PacketContainer(Server.ENTITY_TELEPORT); - packet.getModifier().write(1, loc.getX()); - packet.getModifier().write(2, loc.getY()); - packet.getModifier().write(3, loc.getZ()); - for (PlayerSkin skin : new ArrayList<>(value)) { if (!value.contains(skin) || !skin.isSleepPackets()) { continue; @@ -149,21 +146,19 @@ public class PlayerSkinHandler implements Listener { continue; } - packet = packet.shallowClone(); - int id = disguise.getEntity().getEntityId(); if (id == player.getEntityId()) { id = DisguiseAPI.getSelfDisguiseId(); } - packet.getModifier().write(0, id); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + WrapperPlayServerEntityTeleport packet = + new WrapperPlayServerEntityTeleport(id, SpigotConversionUtil.fromBukkitLocation(loc), true); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } - public void handlePackets(Player player, PlayerDisguise disguise, LibsPackets packets) { + public synchronized void handlePackets(Player player, PlayerDisguise disguise, LibsPackets packets) { boolean spawn = packets.isSkinHandling(); List skins = getCache().getIfPresent(player); @@ -180,7 +175,8 @@ public class PlayerSkinHandler implements Listener { if (spawn) { packets.getDelayedPacketsMap().entrySet().removeIf(entry -> { - entry.getValue().removeIf(packet -> packet.getType() == Server.ENTITY_EQUIPMENT && isRemove(skin, packet)); + entry.getValue().removeIf(packet -> packet.getPacketTypeData().getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT && + isRemove(skin, packet)); return entry.getValue().isEmpty(); }); @@ -197,23 +193,21 @@ public class PlayerSkinHandler implements Listener { }); } - private boolean isRemove(PlayerSkin skin, PacketContainer packetContainer) { - PacketType type = packetContainer.getType(); - - if (type != Server.ENTITY_EQUIPMENT && type != Server.ENTITY_METADATA) { - return false; - } + private boolean isRemove(PlayerSkin skin, PacketWrapper packetContainer) { + PacketTypeCommon type = packetContainer.getPacketTypeData().getPacketType(); // Only do equip atm - if (type == Server.ENTITY_EQUIPMENT) { + if (type == PacketType.Play.Server.ENTITY_EQUIPMENT) { skin.getSleptPackets().computeIfAbsent(3, (a) -> new ArrayList<>()).add(packetContainer); + + return true; } - return true; + return type == PacketType.Play.Server.ENTITY_METADATA; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onUndisguise(UndisguiseEvent event) { + private synchronized void onUndisguise(UndisguiseEvent event) { if (!event.getDisguise().isPlayerDisguise()) { return; } @@ -245,7 +239,7 @@ public class PlayerSkinHandler implements Listener { } } - private void addMetadata(Player player, PlayerSkin skin) throws InvocationTargetException { + private synchronized void addMetadata(Player player, PlayerSkin skin) throws InvocationTargetException { PlayerDisguise disguise = skin.getDisguise().get(); if (!disguise.isDisguiseInUse()) { @@ -254,28 +248,24 @@ public class PlayerSkinHandler implements Listener { Entity entity = disguise.getEntity(); - List watcherValues = - DisguiseUtilities.createSanitizedWatcherValues(player, WrappedDataWatcher.getEntityWatcher(entity), disguise.getWatcher()); + List watcherValues = DisguiseUtilities.createSanitizedWatcherValues(player, entity, disguise.getWatcher()); - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(entity.getEntityId(), watcherValues); + WrapperPlayServerEntityMetadata metaPacket = ReflectionManager.getMetadataPacket(entity.getEntityId(), watcherValues); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, metaPacket); } - private void addTeleport(Player player, PlayerSkin skin) throws InvocationTargetException { + private synchronized void addTeleport(Player player, PlayerSkin skin) throws InvocationTargetException { PlayerDisguise disguise = skin.getDisguise().get(); - PacketContainer teleport = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT); - - StructureModifier mods = teleport.getModifier(); Location loc = disguise.getEntity().getLocation().add(0, disguise.getWatcher().getYModifier() + DisguiseUtilities.getYModifier(disguise), 0); Float pitchLock = DisguiseConfig.isMovementPacketsEnabled() ? disguise.getWatcher().getPitchLock() : null; Float yawLock = DisguiseConfig.isMovementPacketsEnabled() ? disguise.getWatcher().getYawLock() : null; - byte yaw = (byte) (int) ((yawLock == null ? loc.getYaw() : yawLock) * 256.0F / 360.0F); - byte pitch = (byte) (int) ((pitchLock == null ? loc.getPitch() : pitchLock) * 256.0F / 360.0F); + float yaw = (yawLock == null ? loc.getYaw() : yawLock); + float pitch = (pitchLock == null ? loc.getPitch() : pitchLock); if (DisguiseConfig.isMovementPacketsEnabled()) { if (yawLock == null) { @@ -296,17 +286,13 @@ public class PlayerSkinHandler implements Listener { id = DisguiseAPI.getSelfDisguiseId(); } - mods.write(0, id); - mods.write(1, loc.getX()); - mods.write(2, loc.getY()); - mods.write(3, loc.getZ()); - mods.write(4, yaw); - mods.write(5, pitch); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, teleport, false); + WrapperPlayServerEntityTeleport teleport = + new WrapperPlayServerEntityTeleport(id, new Vector3d(loc.getX(), loc.getY(), loc.getZ()), yaw, pitch, + disguise.getEntity().isOnGround()); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, teleport); } - private void doPacketRemoval(Player player, PlayerSkin skin) { + private synchronized void doPacketRemoval(Player player, PlayerSkin skin) { PlayerDisguise disguise = skin.getDisguise().get(); if (disguise == null) { @@ -315,10 +301,10 @@ public class PlayerSkinHandler implements Listener { try { if (disguise.isDisguiseInUse()) { - for (Map.Entry> entry : skin.getSleptPackets().entrySet()) { + for (Map.Entry> entry : skin.getSleptPackets().entrySet()) { if (entry.getKey() == 0) { - for (PacketContainer packet : entry.getValue()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + for (PacketWrapper packet : entry.getValue()) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } else { new BukkitRunnable() { @@ -328,8 +314,8 @@ public class PlayerSkinHandler implements Listener { return; } - for (PacketContainer packet : entry.getValue()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + for (PacketWrapper packet : entry.getValue()) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } }.runTaskLater(LibsDisguises.getInstance(), entry.getKey()); @@ -352,33 +338,33 @@ public class PlayerSkinHandler implements Listener { } if (DisguiseConfig.isArmorstandsName() && disguise.isNameVisible() && disguise.getMultiNameLength() > 0) { - ArrayList packets = DisguiseUtilities.getNamePackets(disguise, new String[0]); + List> packets = DisguiseUtilities.getNamePackets(disguise, new String[0]); - for (PacketContainer p : packets) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, p); + for (PacketWrapper p : packets) { + PacketEvents.getAPI().getPlayerManager().sendPacket(player, p); } } } if (skin.isDoTabList()) { - PacketContainer packetContainer = - ReflectionManager.createTablistPacket(disguise, EnumWrappers.PlayerInfoAction.REMOVE_PLAYER); + PacketWrapper packetContainer = + DisguiseUtilities.createTablistPacket(disguise, WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER); - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packetContainer); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, packetContainer); } } catch (InvocationTargetException e) { e.printStackTrace(); } } - private void tryProcess(Player player, boolean onMove) { + private synchronized void tryProcess(Player player, boolean onMove) { List skins = getCache().getIfPresent(player); if (skins == null) { return; } - ArrayList removed = new ArrayList<>(); + List removed = new ArrayList<>(); skins.removeIf(skin -> { if (!skin.canRemove(onMove)) { diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/mineskin/MineSkinAPI.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/mineskin/MineSkinAPI.java index f734fd58..f9c0f1f1 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/mineskin/MineSkinAPI.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/mineskin/MineSkinAPI.java @@ -159,7 +159,7 @@ public class MineSkinAPI { if (modelType == SkinUtils.ModelType.SLIM) { writer.append("--").append(boundary).append(CRLF); - writer.append("Content-Disposition: form-data; name=\"model\"").append(CRLF); + writer.append("Content-Disposition: form-data; name=\"variant\"").append(CRLF); writer.append(CRLF).append("slim").append(CRLF).flush(); } @@ -252,8 +252,8 @@ public class MineSkinAPI { // I don't think there's a reliable way to detect the page. // They change the page layout, text and don't identify themselves clearly as this is not meant to be bottable - if (response.toLowerCase(Locale.ROOT).contains("challenge") && - response.toLowerCase(Locale.ROOT).contains("javascript")) { + if (response.toLowerCase(Locale.ENGLISH).contains("challenge") && + response.toLowerCase(Locale.ENGLISH).contains("javascript")) { DisguiseUtilities.getLogger().warning( "We may have encountered a Cloudflare challenge page while connecting to MineSkin, unfortunately this " + "could be of several reasons. Foremost is the site suffering a bot attack, your IP could be " + @@ -282,6 +282,10 @@ public class MineSkinAPI { } finally { nextRequest = System.currentTimeMillis() + nextRequestIn + 1000; lock.unlock(); + + if (connection != null) { + connection.disconnect(); + } } return null; @@ -324,6 +328,7 @@ public class MineSkinAPI { MineSkinResponse skinResponse = new Gson().fromJson(response, MineSkinResponse.class); nextRequestIn = (long) (skinResponse.getNextRequest() * 1000); + con.disconnect(); return skinResponse; } @@ -352,4 +357,4 @@ public class MineSkinAPI { public MineSkinResponse generateFromFile(SkinUtils.SkinCallback callback, File file, SkinUtils.ModelType modelType) { return doPost(callback, "/generate/upload", null, file, modelType); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedEntity.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedEntity.java index 0d727800..c2c7925d 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedEntity.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedEntity.java @@ -1,5 +1,6 @@ package me.libraryaddict.disguise.utilities.modded; +import com.github.retrooper.packetevents.protocol.entity.type.EntityType; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @@ -12,6 +13,7 @@ import lombok.Setter; public class ModdedEntity { @Setter private Object entityType; + private EntityType packetEntityType; private final String name; private final boolean living; private final String mod; diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedManager.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedManager.java index 1ae7385c..d63099f8 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedManager.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/modded/ModdedManager.java @@ -1,7 +1,7 @@ package me.libraryaddict.disguise.utilities.modded; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.utility.StreamSerializer; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import lombok.Getter; @@ -20,7 +20,7 @@ import org.bukkit.metadata.FixedMetadataValue; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; -import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; @@ -52,87 +52,80 @@ public class ModdedManager { } if (fmlRegistries == null && DisguiseConfig.isLoginPayloadPackets()) { - ProtocolLibrary.getProtocolManager().addPacketListener(new PacketListenerModdedClient()); + //PacketEvents.getAPI().getEventManager().registerListener(new PacketListenerModdedClient()); Bukkit.getPluginManager().registerEvents(new ModdedListener(), LibsDisguises.getInstance()); } createPayloads(channels); } + private void writeString(Object buff, String string) { + ByteBufHelper.writeVarInt(buff, string.length()); + ByteBufHelper.writeBytes(buff, string.getBytes(StandardCharsets.UTF_8)); + } + private void createPayloads(ArrayList channels) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(stream); - StreamSerializer s = StreamSerializer.getDefault(); + // Packet id 1 + ByteBufHelper.writeVarInt(output, 1); + // We have no mods to declare + ByteBufHelper.writeVarInt(output, 0); - try { - // Packet id 1 - s.serializeVarInt(output, 1); - // We have no mods to declare - s.serializeVarInt(output, 0); + // We want to declare some channels + ByteBufHelper.writeVarInt(output, channels.size()); - // We want to declare some channels - s.serializeVarInt(output, channels.size()); - - for (String channel : channels) { - // Here's the channel name - s.serializeString(output, channel.substring(0, channel.indexOf("|"))); - // Here's the channel version, yes we're using your version! - s.serializeString(output, channel.substring(channel.indexOf("|") + 1)); - } - - // We want to declare some entities. Wait. No we don't? - // Weird, am I missing something.. - s.serializeVarInt(output, 0); - - // Only this one thx - // s.serializeString(output, "minecraft:entity_type"); - } catch (IOException e) { - e.printStackTrace(); + for (String channel : channels) { + // Here's the channel name + writeString(output, channel.substring(0, channel.indexOf("|"))); + // Here's the channel version, yes we're using your version! + writeString(output, channel.substring(channel.indexOf("|") + 1)); } + // We want to declare some entities. Wait. No we don't? + // Weird, am I missing something.. + ByteBufHelper.writeVarInt(output, 0); + + // Only this one thx + // s.serializeString(output, "minecraft:entity_type"); + fmlHandshake = stream.toByteArray(); stream = new ByteArrayOutputStream(); output = new DataOutputStream(stream); - s = StreamSerializer.getDefault(); + // Packet id 3 + ByteBufHelper.writeVarInt(output, 3); - try { - // Packet id 3 - s.serializeVarInt(output, 3); + // What registry we're modifying + writeString(output, "minecraft:entity_type"); + // Yes... We're doing custom data + ByteBufHelper.writeVarInt(output, 1); - // What registry we're modifying - s.serializeString(output, "minecraft:entity_type"); - // Yes... We're doing custom data - s.serializeVarInt(output, 1); + // We have this many entities + ByteBufHelper.writeVarInt(output, entities.size()); - // We have this many entities - s.serializeVarInt(output, entities.size()); - - // Write the entity names and ids - for (Map.Entry entry : entities.entrySet()) { - // We are registering librarymod:librarian - s.serializeString(output, entry.getKey().toString()); - // It's got the type ID of 85 - s.serializeVarInt(output, entry.getValue().getTypeId()); - } - - // Sir, we do not want to declare aliases - s.serializeVarInt(output, 0); - - // Or overrides - s.serializeVarInt(output, 0); - - // No.. Not even blocked - s.serializeVarInt(output, 0); - - // Or dummied. What is dummied anyways. What are these others? - s.serializeVarInt(output, 0); - } catch (IOException e) { - e.printStackTrace(); + // Write the entity names and ids + for (Map.Entry entry : entities.entrySet()) { + // We are registering librarymod:librarian + writeString(output, entry.getKey().toString()); + // It's got the type ID of 85 + ByteBufHelper.writeVarInt(output, entry.getValue().getTypeId()); } + // Sir, we do not want to declare aliases + ByteBufHelper.writeVarInt(output, 0); + + // Or overrides + ByteBufHelper.writeVarInt(output, 0); + + // No.. Not even blocked + ByteBufHelper.writeVarInt(output, 0); + + // Or dummied. What is dummied anyways. What are these others? + ByteBufHelper.writeVarInt(output, 0); + fmlRegistries = stream.toByteArray(); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/IPacketHandler.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/IPacketHandler.java index d5407e50..63597409 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/IPacketHandler.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/IPacketHandler.java @@ -1,7 +1,11 @@ package me.libraryaddict.disguise.utilities.packets; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.event.PacketEvent; +import com.github.retrooper.packetevents.event.PacketSendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; import me.libraryaddict.disguise.disguisetypes.Disguise; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -9,8 +13,8 @@ import org.bukkit.entity.Player; /** * Created by libraryaddict on 3/01/2019. */ -public interface IPacketHandler { - PacketType[] getHandledPackets(); +public interface IPacketHandler> { + PacketTypeCommon[] getHandledPackets(); - void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity); + void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java index 1d2afe8c..8a838bbd 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java @@ -1,17 +1,18 @@ package me.libraryaddict.disguise.utilities.packets; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.mojang.datafixers.util.Pair; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.player.Equipment; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; +import net.minecraft.network.protocol.Packet; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -19,6 +20,7 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,20 +31,26 @@ import java.util.Map; @Getter @RequiredArgsConstructor @Setter -public class LibsPackets { +public class LibsPackets> { @Getter - private final ArrayList packets = new ArrayList<>(); - private final HashMap> delayedPacketsMap = new HashMap<>(); + private final List packets = new ArrayList<>(); + private final HashMap> delayedPacketsMap = new HashMap<>(); + @Getter + private final T originalPacket; @Getter private final Disguise disguise; private boolean unhandled; private boolean skinHandling; - public void addPacket(PacketContainer packet) { + public boolean shouldCancelPacketEvent() { + return !packets.contains(getOriginalPacket()); + } + + public void addPacket(PacketWrapper packet) { packets.add(packet); } - public void addDelayedPacket(PacketContainer packet) { + public void addDelayedPacket(PacketWrapper packet) { addDelayedPacket(packet, 2); } @@ -50,7 +58,7 @@ public class LibsPackets { getPackets().clear(); } - public void addDelayedPacket(PacketContainer packet, int ticksDelayed) { + public void addDelayedPacket(PacketWrapper packet, int ticksDelayed) { if (!delayedPacketsMap.containsKey(ticksDelayed)) { delayedPacketsMap.put(ticksDelayed, new ArrayList<>()); } @@ -59,28 +67,31 @@ public class LibsPackets { } public void sendDelayed(final Player observer) { - for (Map.Entry> entry : getDelayedPacketsMap().entrySet()) { + for (Map.Entry> entry : getDelayedPacketsMap().entrySet()) { Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { if (!getDisguise().isDisguiseInUse()) { - ArrayList packets = entry.getValue(); + ArrayList packets = entry.getValue(); - if (packets.stream().noneMatch(p -> p.getType() == PacketType.Play.Server.PLAYER_INFO)) { + if (packets.stream().noneMatch(p -> p.getPacketTypeData().getPacketType() == PacketType.Play.Server.PLAYER_INFO)) { return; } - packets.removeIf(p -> p.getType() != PacketType.Play.Server.PLAYER_INFO); + packets.removeIf(p -> p.getPacketTypeData().getPacketType() != PacketType.Play.Server.PLAYER_INFO); } - for (PacketContainer packet : entry.getValue()) { + for (PacketWrapper packet : entry.getValue()) { // To have right click handled properly, equip packets sent are normal - ProtocolLibrary.getProtocolManager() - .sendServerPacket(observer, packet, packet.getType() == PacketType.Play.Server.ENTITY_EQUIPMENT); + if (packet.getPacketTypeData().getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(observer, packet); + } else { + PacketEvents.getAPI().getPlayerManager().sendPacket(observer, packet); + } } }, entry.getKey()); } } - private PacketContainer createPacket(EquipmentSlot slot) { + private WrapperPlayServerEntityEquipment createPacket(EquipmentSlot slot) { // Get what the disguise wants to show for its armor ItemStack itemToSend = getDisguise().getWatcher().getItemStack(slot); @@ -96,22 +107,7 @@ public class LibsPackets { return null; } - PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_EQUIPMENT); - - StructureModifier mods = packet.getModifier(); - - mods.write(0, getDisguise().getEntity().getEntityId()); - - if (NmsVersion.v1_16.isSupported()) { - List> list = new ArrayList<>(); - list.add(Pair.of(ReflectionManager.createEnumItemSlot(slot), ReflectionManager.getNmsItem(itemToSend))); - - mods.write(1, list); - } else { - mods.write(1, ReflectionManager.createEnumItemSlot(slot)); - mods.write(2, ReflectionManager.getNmsItem(itemToSend)); - } - - return packet; + return new WrapperPlayServerEntityEquipment(getDisguise().getEntity().getEntityId(), Collections.singletonList( + new Equipment(ReflectionManager.getSlot(slot), SpigotConversionUtil.fromBukkitItemStack(itemToSend)))); } } \ No newline at end of file diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsHandler.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsHandler.java index 0cd7ed1a..f630c9a5 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsHandler.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsHandler.java @@ -1,18 +1,20 @@ package me.libraryaddict.disguise.utilities.packets; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.LibsPremium; -import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerAnimation; +import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerAnimationCollect; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerAttachEntity; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerAttributes; -import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerCollect; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerEntityStatus; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerEquipment; -import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerHeadRotation; +import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerHeadLook; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerMetadata; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerMovement; import me.libraryaddict.disguise.utilities.packets.packethandlers.PacketHandlerSpawn; @@ -21,29 +23,28 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.ArrayList; -import java.util.Collection; +import java.util.List; /** * Created by libraryaddict on 3/01/2019. */ public class PacketsHandler { - private Collection packetHandlers; + private final IPacketHandler[] packetHandlers = new IPacketHandler[PacketType.Play.Server.values().length]; public PacketsHandler() { registerPacketHandlers(); } private void registerPacketHandlers() { - packetHandlers = new ArrayList<>(); + List packetHandlers = new ArrayList<>(); - packetHandlers.add(new PacketHandlerAnimation()); packetHandlers.add(new PacketHandlerAttributes()); - packetHandlers.add(new PacketHandlerCollect()); + packetHandlers.add(new PacketHandlerAnimationCollect()); packetHandlers.add(new PacketHandlerEntityStatus()); packetHandlers.add(new PacketHandlerEquipment()); packetHandlers.add(new PacketHandlerAttachEntity()); - packetHandlers.add(new PacketHandlerHeadRotation()); + packetHandlers.add(new PacketHandlerHeadLook()); // If not prem, if build is from jenkins, else its a custom and needs paid info if (!LibsPremium.isPremium() || LibsDisguises.getInstance().getBuildNo().matches("\\d+") || @@ -54,15 +55,24 @@ public class PacketsHandler { packetHandlers.add(new PacketHandlerMovement()); packetHandlers.add(new PacketHandlerSpawn()); packetHandlers.add(new PacketHandlerVelocity()); + + for (IPacketHandler handler : packetHandlers) { + for (PacketTypeCommon packetType : handler.getHandledPackets()) { + this.packetHandlers[((Enum) packetType).ordinal()] = handler; + } + } } - /** - * Transform the packet magically into the one I have always dreamed off. My true luv!!! This will return null if - * its not - * transformed - */ - public LibsPackets transformPacket(PacketContainer sentPacket, Disguise disguise, Player observer, Entity entity) { - LibsPackets packets = new LibsPackets(disguise); + public LibsPackets transformPacket(PacketPlaySendEvent sentEvent, Disguise disguise, Player observer, Entity entity) { + if (disguise.getType() == DisguiseType.UNKNOWN) { + return new LibsPackets(null, disguise); + } + + return transformPacket(DisguiseUtilities.constructWrapper(sentEvent), disguise, observer, entity); + } + + public LibsPackets transformPacket(PacketWrapper sentPacket, Disguise disguise, Player observer, Entity entity) { + LibsPackets packets = new LibsPackets(sentPacket, disguise); if (disguise.getType() == DisguiseType.UNKNOWN) { return packets; @@ -71,15 +81,11 @@ public class PacketsHandler { try { packets.addPacket(sentPacket); - for (IPacketHandler packetHandler : packetHandlers) { - for (PacketType packetType : packetHandler.getHandledPackets()) { - if (packetType != sentPacket.getType()) { - continue; - } + IPacketHandler handler = packetHandlers[((Enum) sentPacket.getPacketTypeData().getPacketType()).ordinal()]; - packetHandler.handle(disguise, sentPacket, packets, observer, entity); - return packets; - } + if (handler != null) { + handler.handle(disguise, packets, observer, entity); + return packets; } packets.setUnhandled(true); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsManager.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsManager.java index e5771ec2..bd0417cf 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsManager.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/PacketsManager.java @@ -1,13 +1,10 @@ package me.libraryaddict.disguise.utilities.packets; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketListener; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; import lombok.Getter; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.packets.packetlisteners.PacketListenerClientCustomPayload; @@ -26,29 +23,37 @@ import org.bukkit.entity.Player; import java.util.ArrayList; public class PacketsManager { - private static PacketListener clientInteractEntityListener; - private static PacketListener inventoryListener; - private static boolean inventoryModifierEnabled; - private static PacketListener mainListener; - private static PacketListener soundsListener; + private static final PacketListenerClientInteract clientInteractEntityListener = new PacketListenerClientInteract(); + private static final PacketListenerTabList tablistListener = new PacketListenerTabList(); + private static final PacketListenerClientCustomPayload customPayload = new PacketListenerClientCustomPayload(); + private static PacketListenerInventory inventoryListener; + @Getter + private static boolean inventoryListenerEnabled; + private static PacketListenerMain mainListener; + private static PacketListenerSounds soundsListener; private static boolean soundsListenerEnabled; - private static PacketListener viewDisguisesListener; + private static PacketListenerViewSelfDisguise viewDisguisesListener; @Getter private static boolean viewDisguisesListenerEnabled; @Getter private static PacketsHandler packetsHandler; + @Getter + private static boolean initialListenersRegistered; public static void addPacketListeners() { - // Add a client listener to cancel them interacting with uninteractable disguised entitys. - // You ain't supposed to be allowed to 'interact' with a item that cannot be clicked. - // Because it kicks you for hacking. + if (!initialListenersRegistered) { + // Add a client listener to cancel them interacting with uninteractable disguised entitys. + // You ain't supposed to be allowed to 'interact' with a item that cannot be clicked. + // Because it kicks you for hacking. + PacketEvents.getAPI().getEventManager().registerListener(clientInteractEntityListener); + PacketEvents.getAPI().getEventManager().registerListener(tablistListener); - clientInteractEntityListener = new PacketListenerClientInteract(LibsDisguises.getInstance()); - PacketListener tabListListener = new PacketListenerTabList(LibsDisguises.getInstance()); + if (DisguiseConfig.isLoginPayloadPackets()) { + PacketEvents.getAPI().getEventManager().registerListener(customPayload); + } - ProtocolLibrary.getProtocolManager().addPacketListener(clientInteractEntityListener); - ProtocolLibrary.getProtocolManager().addPacketListener(tabListListener); - ProtocolLibrary.getProtocolManager().addPacketListener(new PacketListenerClientCustomPayload()); + initialListenersRegistered = true; + } // Now I call this and the main listener is registered! setupMainPacketsListener(); @@ -58,12 +63,12 @@ public class PacketsManager { * Creates the packet listeners */ public static void init() { - soundsListener = new PacketListenerSounds(LibsDisguises.getInstance()); + soundsListener = new PacketListenerSounds(); // Self disguise (/vsd) listener - viewDisguisesListener = new PacketListenerViewSelfDisguise(LibsDisguises.getInstance()); + viewDisguisesListener = new PacketListenerViewSelfDisguise(); - inventoryListener = new PacketListenerInventory(LibsDisguises.getInstance()); + inventoryListener = new PacketListenerInventory(); packetsHandler = new PacketsHandler(); } @@ -71,21 +76,17 @@ public class PacketsManager { return soundsListenerEnabled; } - public static boolean isInventoryListenerEnabled() { - return inventoryModifierEnabled; - } - public static void setInventoryListenerEnabled(boolean enabled) { - if (inventoryModifierEnabled == enabled) { + if (isInventoryListenerEnabled() == enabled || inventoryListener == null) { return; } - inventoryModifierEnabled = enabled; + inventoryListenerEnabled = enabled; - if (inventoryModifierEnabled) { - ProtocolLibrary.getProtocolManager().addPacketListener(inventoryListener); + if (inventoryListenerEnabled) { + PacketEvents.getAPI().getEventManager().registerListener(inventoryListener); } else { - ProtocolLibrary.getProtocolManager().removePacketListener(inventoryListener); + PacketEvents.getAPI().getEventManager().unregisterListener(inventoryListener); } for (Player player : Bukkit.getOnlinePlayers()) { @@ -112,89 +113,91 @@ public class PacketsManager { } public static void setHearDisguisesListener(boolean enabled) { - if (soundsListenerEnabled != enabled) { - soundsListenerEnabled = enabled; + if (soundsListenerEnabled == enabled) { + return; + } - if (soundsListenerEnabled) { - ProtocolLibrary.getProtocolManager().addPacketListener(soundsListener); - } else { - ProtocolLibrary.getProtocolManager().removePacketListener(soundsListener); - } + soundsListenerEnabled = enabled; + + if (soundsListenerEnabled) { + PacketEvents.getAPI().getEventManager().registerListener(soundsListener); + } else { + PacketEvents.getAPI().getEventManager().unregisterListener(soundsListener); } } public static void setupMainPacketsListener() { - if (clientInteractEntityListener != null) { - if (mainListener != null) { - ProtocolLibrary.getProtocolManager().removePacketListener(mainListener); + if (!initialListenersRegistered) { + return; + } + + if (mainListener != null) { + PacketEvents.getAPI().getEventManager().unregisterListener(mainListener); + } + + ArrayList packetsToListen = new ArrayList<>(); + + // Add spawn packets + { + if (!NmsVersion.v1_20_R2.isSupported()) { + packetsToListen.add(Server.SPAWN_PLAYER); } - ArrayList packetsToListen = new ArrayList<>(); - // Add spawn packets - { - if (!NmsVersion.v1_20_R2.isSupported()) { - packetsToListen.add(Server.NAMED_ENTITY_SPAWN); - } + packetsToListen.add(Server.SPAWN_EXPERIENCE_ORB); + packetsToListen.add(Server.SPAWN_ENTITY); - packetsToListen.add(Server.SPAWN_ENTITY_EXPERIENCE_ORB); - packetsToListen.add(Server.SPAWN_ENTITY); - - if (!NmsVersion.v1_19_R1.isSupported()) { - packetsToListen.add(Server.SPAWN_ENTITY_LIVING); - packetsToListen.add(Server.SPAWN_ENTITY_PAINTING); - } + if (!NmsVersion.v1_19_R1.isSupported()) { + packetsToListen.add(Server.SPAWN_LIVING_ENTITY); + packetsToListen.add(Server.SPAWN_PAINTING); } + } - // Add packets that always need to be enabled to ensure safety - { - packetsToListen.add(Server.ENTITY_METADATA); - } + // Add packets that always need to be enabled to ensure safety + { + packetsToListen.add(Server.ENTITY_METADATA); + } - if (DisguiseConfig.isCollectPacketsEnabled()) { - packetsToListen.add(Server.COLLECT); - } + if (DisguiseConfig.isCollectPacketsEnabled()) { + packetsToListen.add(Server.COLLECT_ITEM); + } - if (DisguiseConfig.isMiscDisguisesForLivingEnabled()) { - packetsToListen.add(Server.UPDATE_ATTRIBUTES); - } + if (DisguiseConfig.isMiscDisguisesForLivingEnabled()) { + packetsToListen.add(Server.UPDATE_ATTRIBUTES); + } - // Add movement packets - if (DisguiseConfig.isMovementPacketsEnabled()) { - packetsToListen.add(Server.ENTITY_LOOK); - packetsToListen.add(Server.REL_ENTITY_MOVE_LOOK); - packetsToListen.add(Server.ENTITY_HEAD_ROTATION); - packetsToListen.add(Server.ENTITY_TELEPORT); - packetsToListen.add(Server.REL_ENTITY_MOVE); - packetsToListen.add(Server.ENTITY_VELOCITY); - packetsToListen.add(Server.MOUNT); - } + // Add movement packets + if (DisguiseConfig.isMovementPacketsEnabled()) { + packetsToListen.add(Server.ENTITY_MOVEMENT); + packetsToListen.add(Server.ENTITY_RELATIVE_MOVE_AND_ROTATION); + packetsToListen.add(Server.ENTITY_HEAD_LOOK); + packetsToListen.add(Server.ENTITY_TELEPORT); + packetsToListen.add(Server.ENTITY_RELATIVE_MOVE); + packetsToListen.add(Server.ENTITY_VELOCITY); + packetsToListen.add(Server.ATTACH_ENTITY); + } - // Add equipment packet - if (DisguiseConfig.isEquipmentPacketsEnabled()) { - packetsToListen.add(Server.ENTITY_EQUIPMENT); - } + // Add equipment packet + if (DisguiseConfig.isEquipmentPacketsEnabled()) { + packetsToListen.add(Server.ENTITY_EQUIPMENT); + } - // Add the packet that ensures if they are sleeping or not - if (DisguiseConfig.isAnimationPacketsEnabled()) { - packetsToListen.add(Server.ANIMATION); - } + // Add the packet that ensures if they are sleeping or not + if (DisguiseConfig.isAnimationPacketsEnabled()) { + packetsToListen.add(Server.ENTITY_ANIMATION); + } - // Add the packet that makes sure that entities with armor do not send unpickupable armor on death - if (DisguiseConfig.isEntityStatusPacketsEnabled()) { - packetsToListen.add(Server.ENTITY_STATUS); - } + // Add the packet that makes sure that entities with armor do not send unpickupable armor on death + if (DisguiseConfig.isEntityStatusPacketsEnabled()) { + packetsToListen.add(Server.ENTITY_STATUS); + } - mainListener = new PacketListenerMain(LibsDisguises.getInstance(), packetsToListen); - PacketListener destroyListener = new PacketListenerEntityDestroy(LibsDisguises.getInstance()); + mainListener = new PacketListenerMain(packetsToListen); - ProtocolLibrary.getProtocolManager().addPacketListener(mainListener); - ProtocolLibrary.getProtocolManager().addPacketListener(destroyListener); + PacketEvents.getAPI().getEventManager().registerListener(mainListener); + PacketEvents.getAPI().getEventManager().registerListener(new PacketListenerEntityDestroy()); - if (NmsVersion.v1_13.isSupported() && DisguiseConfig.getPlayerNameType() != DisguiseConfig.PlayerNameType.ARMORSTANDS) { - PacketListener scoreboardTeamListener = new PacketListenerScoreboardTeam(); - - ProtocolLibrary.getProtocolManager().addPacketListener(scoreboardTeamListener); - } + if (NmsVersion.v1_13.isSupported() && DisguiseConfig.getPlayerNameType() != DisguiseConfig.PlayerNameType.ARMORSTANDS) { + PacketEvents.getAPI().getEventManager().registerListener(new PacketListenerScoreboardTeam()); } } @@ -206,9 +209,9 @@ public class PacketsManager { viewDisguisesListenerEnabled = enabled; if (viewDisguisesListenerEnabled) { - ProtocolLibrary.getProtocolManager().addPacketListener(viewDisguisesListener); + PacketEvents.getAPI().getEventManager().registerListener(viewDisguisesListener); } else { - ProtocolLibrary.getProtocolManager().removePacketListener(viewDisguisesListener); + PacketEvents.getAPI().getEventManager().unregisterListener(viewDisguisesListener); } for (Player player : Bukkit.getOnlinePlayers()) { @@ -224,7 +227,7 @@ public class PacketsManager { DisguiseUtilities.removeSelfDisguise(disguise); } - if (!inventoryModifierEnabled || !(disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) { + if (!inventoryListenerEnabled || !(disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) { continue; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimation.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimationCollect.java similarity index 54% rename from plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimation.java rename to plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimationCollect.java index 15913a29..41941f68 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimation.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAnimationCollect.java @@ -1,7 +1,7 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; import me.libraryaddict.disguise.utilities.packets.LibsPackets; @@ -11,14 +11,14 @@ import org.bukkit.entity.Player; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerAnimation implements IPacketHandler { +public class PacketHandlerAnimationCollect implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ANIMATION}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.COLLECT_ITEM, PacketType.Play.Server.ENTITY_ANIMATION}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { // Else if the disguise is attempting to send players a forbidden packet if (disguise.getType().isMisc()) { packets.clear(); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttachEntity.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttachEntity.java index 5550c45d..ed64c19d 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttachEntity.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttachEntity.java @@ -1,7 +1,8 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; @@ -13,14 +14,14 @@ import org.bukkit.entity.Player; /** * Created by libraryaddict on 19/09/2020. */ -public class PacketHandlerAttachEntity implements IPacketHandler { +public class PacketHandlerAttachEntity implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.MOUNT}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ATTACH_ENTITY}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { if (observer.getVehicle() == null) { DisguiseUtilities.removeInvisibleSlime(observer); return; @@ -31,9 +32,9 @@ public class PacketHandlerAttachEntity implements IPacketHandler { return; } - int[] ints = sentPacket.getIntegerArrays().read(0); + WrapperPlayServerAttachEntity packet = packets.getOriginalPacket(); - if (ints.length > 0 && ints[0] == observer.getEntityId()) { + if (packet.getAttachedId() == observer.getEntityId()) { packets.clear(); DisguiseUtilities.sendInvisibleSlime(observer, entity.getEntityId()); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttributes.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttributes.java index 9ff2722f..e97ee6cf 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttributes.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerAttributes.java @@ -1,18 +1,16 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedAttribute; +import com.github.retrooper.packetevents.protocol.attribute.Attributes; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.watchers.AbstractHorseWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; -import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.DisguiseValues; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; import me.libraryaddict.disguise.utilities.packets.LibsPackets; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -22,73 +20,43 @@ import java.util.List; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerAttributes implements IPacketHandler { - private final boolean skipAttributes = - !NmsVersion.v1_14.isSupported() && ProtocolLibrary.getPlugin().getDescription().getVersion().equals("4.5.0"); +public class PacketHandlerAttributes implements IPacketHandler { - public PacketHandlerAttributes() { - if (!skipAttributes) { - return; - } - - DisguiseUtilities.getLogger().info("You are running ProtocolLib 4.5.0, attributes will not be handled; Update if you can."); + @Override + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.UPDATE_ATTRIBUTES}; } @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.UPDATE_ATTRIBUTES}; - } - - @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { packets.clear(); - // Skip due to a bug in ProtocolLib - if (skipAttributes) { - return; - } - if (disguise.isMiscDisguise()) { return; } - List attributes = new ArrayList<>(); - PacketContainer updateAttributes = new PacketContainer(PacketType.Play.Server.UPDATE_ATTRIBUTES); - - for (WrappedAttribute attribute : sentPacket.getAttributeCollectionModifier().read(0)) { - if (attribute.getAttributeKey().equals(NmsVersion.v1_16.isSupported() ? "generic.max_health" : "generic.maxHealth")) { - WrappedAttribute.Builder builder; + WrapperPlayServerUpdateAttributes packet = packets.getOriginalPacket(); + List attributes = new ArrayList<>(); + for (WrapperPlayServerUpdateAttributes.Property property : packet.getProperties()) { + if (property.getAttribute() == Attributes.GENERIC_MAX_HEALTH) { if (disguise.getWatcher() instanceof LivingWatcher && ((LivingWatcher) disguise.getWatcher()).isMaxHealthSet()) { - builder = WrappedAttribute.newBuilder(); - builder.attributeKey(attribute.getAttributeKey()); - builder.baseValue(((LivingWatcher) disguise.getWatcher()).getMaxHealth()); + attributes.add(new WrapperPlayServerUpdateAttributes.Property(property.getAttribute(), + ((LivingWatcher) disguise.getWatcher()).getMaxHealth(), new ArrayList<>())); } else if (DisguiseConfig.isMaxHealthDeterminedByDisguisedEntity()) { - builder = WrappedAttribute.newBuilder(attribute); + attributes.add(property); } else { - builder = WrappedAttribute.newBuilder(); - builder.attributeKey(attribute.getAttributeKey()); - builder.baseValue(DisguiseValues.getDisguiseValues(disguise.getType()).getMaxHealth()); + attributes.add(new WrapperPlayServerUpdateAttributes.Property(property.getAttribute(), + DisguiseValues.getDisguiseValues(disguise.getType()).getMaxHealth(), new ArrayList<>())); } - - builder.packet(updateAttributes); - - attributes.add(builder.build()); - } else if ( - attribute.getAttributeKey().equals(NmsVersion.v1_16.isSupported() ? "generic.movement_speed" : "generic.movementSpeed") && - disguise.getWatcher() instanceof AbstractHorseWatcher) { - WrappedAttribute.Builder builder = WrappedAttribute.newBuilder(attribute); - builder.packet(updateAttributes); - - attributes.add(builder.build()); + } else if (property.getAttribute() == Attributes.GENERIC_MOVEMENT_SPEED && + disguise.getWatcher() instanceof AbstractHorseWatcher) { + attributes.add(property); } } if (!attributes.isEmpty()) { - packets.addPacket(updateAttributes); - - updateAttributes.getIntegers().write(0, entity.getEntityId()); - updateAttributes.getAttributeCollectionModifier().write(0, attributes); + packets.addPacket(new WrapperPlayServerUpdateAttributes(packet.getEntityId(), attributes)); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerCollect.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerCollect.java deleted file mode 100644 index b744bfed..00000000 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerCollect.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.libraryaddict.disguise.utilities.packets.packethandlers; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.utilities.packets.IPacketHandler; -import me.libraryaddict.disguise.utilities.packets.LibsPackets; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -/** - * Created by libraryaddict on 3/01/2019. - */ -public class PacketHandlerCollect implements IPacketHandler { - @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.COLLECT}; - } - - @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { - if (disguise.getType().isMisc()) { - packets.clear(); - } - } -} diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEntityStatus.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEntityStatus.java index 96560bf0..33dbb4bc 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEntityStatus.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEntityStatus.java @@ -1,7 +1,8 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; import me.libraryaddict.disguise.utilities.packets.LibsPackets; @@ -11,16 +12,16 @@ import org.bukkit.entity.Player; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerEntityStatus implements IPacketHandler { +public class PacketHandlerEntityStatus implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ENTITY_STATUS}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_STATUS}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { // If the entity is updating their status, stop them from showing death - if (packets.getPackets().get(0).getBytes().read(0) == (byte) 3) { + if (packets.getOriginalPacket().getStatus() == 3) { packets.clear(); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEquipment.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEquipment.java index 5cce2517..f9b0a5af 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEquipment.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerEquipment.java @@ -1,9 +1,12 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.mojang.datafixers.util.Pair; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.protocol.player.Equipment; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; @@ -17,6 +20,7 @@ import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; @@ -24,179 +28,104 @@ import java.util.List; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerEquipment implements IPacketHandler { - +public class PacketHandlerEquipment implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ENTITY_EQUIPMENT}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_EQUIPMENT}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { - if (NmsVersion.v1_16.isSupported()) { - handleNew(disguise, sentPacket, packets, observer, entity); - } else { - handleOld(disguise, sentPacket, packets, observer, entity); - } - } - - public void handleNew(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { // Else if the disguise is updating equipment + WrapperPlayServerEntityEquipment packet = packets.getOriginalPacket(); + WrapperPlayServerEntityEquipment toModify = null; + List newSlots = new ArrayList<>(); - List> slots = (List>) packets.getPackets().get(0).getModifier().read(1); - List> newSlots = new ArrayList<>(); - boolean constructed = false; + for (Equipment equipment : packet.getEquipment()) { + if (equipment.getSlot() == null) { + continue; + } - for (Pair pair : slots) { - EquipmentSlot slot = ReflectionManager.createEquipmentSlot(pair.getFirst()); - - org.bukkit.inventory.ItemStack itemStack = disguise.getWatcher().getItemStack(slot); - - if (itemStack != null) { - if (!constructed) { - constructed = true; + EquipmentSlot slot = ReflectionManager.getSlot(equipment.getSlot()); + ItemStack sItem = disguise.getWatcher().getItemStack(slot); + // If it's not 1.16, then there should only be 1 equipment in the list which means only 1 equipment added to the list! + if (sItem != null) { + if (toModify == null) { if (packets.getPackets().size() > 1) { packets.getPackets().remove(1); } else { packets.clear(); } - PacketContainer equipPacket = sentPacket.shallowClone(); - - packets.getPackets().add(packets.getPackets().size(), equipPacket); - - equipPacket.getModifier().write(1, newSlots); + toModify = new WrapperPlayServerEntityEquipment(packet.getEntityId(), newSlots); + packets.addPacket(toModify); } - newSlots.add( - Pair.of(pair.getFirst(), ReflectionManager.getNmsItem(itemStack.getType() == Material.AIR ? null : itemStack))); + newSlots.add(new Equipment(equipment.getSlot(), + sItem.getType() == Material.AIR ? com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY : + SpigotConversionUtil.fromBukkitItemStack(sItem))); + } else { - newSlots.add(pair); - itemStack = ReflectionManager.getBukkitItem(pair.getSecond()); + newSlots.add(equipment); + sItem = SpigotConversionUtil.toBukkitItemStack(equipment.getItem()); } - if ((disguise.getWatcher().isMainHandRaised() && slot == EquipmentSlot.HAND) || - (disguise.getWatcher() instanceof LivingWatcher && ((LivingWatcher) disguise.getWatcher()).isOffhandRaised() && - slot == EquipmentSlot.OFF_HAND)) { - if (itemStack != null && itemStack.getType() != Material.AIR) { - // Convert the datawatcher - List list = new ArrayList<>(); + // If item not exists, either naturally or as part of the disguise + if (sItem == null || sItem.getType() == Material.AIR) { + continue; + } - if (DisguiseConfig.isMetaPacketsEnabled()) { - WatcherValue watch = new WatcherValue(MetaIndex.LIVING_META, - WrappedDataWatcher.getEntityWatcher(entity).getByte(MetaIndex.LIVING_META.getIndex())); + // If not raising the hand of the equipment slot this is + if (!((slot == EquipmentSlot.HAND && disguise.getWatcher().isMainHandRaised()) || + (slot == EquipmentSlot.OFF_HAND && disguise.getWatcher() instanceof LivingWatcher && + ((LivingWatcher) disguise.getWatcher()).isOffhandRaised()))) { + continue; + } - if (watch != null) { - list.add(watch); - } + // Convert the datawatcher + List list = new ArrayList<>(); + MetaIndex toUse = NmsVersion.v1_13.isSupported() ? MetaIndex.LIVING_META : MetaIndex.ENTITY_META; - list = disguise.getWatcher().convert(observer, list); - } else { - for (WatcherValue obj : disguise.getWatcher().getWatchableObjects()) { - if (obj.getIndex() == MetaIndex.LIVING_META.getIndex()) { - list.add(obj); - break; - } - } + if (DisguiseConfig.isMetaPacketsEnabled()) { + List data = ReflectionManager.getEntityWatcher(entity); + byte b = (byte) toUse.getDefault(); + + for (EntityData d : data) { + if (d.getIndex() != toUse.getIndex()) { + continue; } - // Construct the packets to return - PacketContainer packetBlock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); + b = (byte) d.getValue(); + break; + } - list.forEach(v -> v.setValue((byte) 0)); + list.add(new WatcherValue(toUse, b, true)); - // Make a packet to send the 'unblock' - PacketContainer packetUnblock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); - - // Send the unblock before the itemstack change so that the 2nd metadata packet works. Why? - // Scheduler - // delay. - - PacketContainer packet1 = packets.getPackets().get(0); - - packets.clear(); - - packets.addPacket(packetUnblock); - packets.addPacket(packet1); - packets.addPacket(packetBlock); - // Silly mojang made the right clicking datawatcher value only valid for one use. So I have - // to reset - // it. + list = disguise.getWatcher().convert(observer, list); + } else { + for (WatcherValue obj : disguise.getWatcher().getWatchableObjects()) { + if (obj.getIndex() == toUse.getIndex()) { + list.add(obj); + break; + } } } + + // Construct the packets to return + WrapperPlayServerEntityMetadata packetBlock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); + + list.forEach(v -> v.setValue(NmsVersion.v1_13.isSupported() ? (byte) 0 : (byte) ((byte) v.getValue() & ~(1 << 4)))); + + // Make a packet to send the 'unblock' + WrapperPlayServerEntityMetadata packetUnblock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); + + // Send the unblock before the itemstack change so that the 2nd metadata packet works. Why? + // Scheduler delay. + packets.getPackets().add(0, packetUnblock); + packets.addPacket(packetBlock); + // Silly mojang made the right clicking datawatcher value only valid for one use. So I have to reset it. } } - public void handleOld(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { - // Else if the disguise is updating equipment - - EquipmentSlot slot = ReflectionManager.createEquipmentSlot(packets.getPackets().get(0).getModifier().read(1)); - - org.bukkit.inventory.ItemStack itemStack = disguise.getWatcher().getItemStack(slot); - - if (itemStack != null) { - packets.clear(); - - PacketContainer equipPacket = sentPacket.shallowClone(); - - packets.addPacket(equipPacket); - - equipPacket.getModifier().write(2, ReflectionManager.getNmsItem(itemStack.getType() == Material.AIR ? null : itemStack)); - } - - if ((disguise.getWatcher().isMainHandRaised() && slot == EquipmentSlot.HAND) || - (disguise.getWatcher() instanceof LivingWatcher && ((LivingWatcher) disguise.getWatcher()).isOffhandRaised() && - slot == EquipmentSlot.OFF_HAND)) { - if (itemStack == null) { - itemStack = packets.getPackets().get(0).getItemModifier().read(0); - } - - if (itemStack != null && itemStack.getType() != Material.AIR) { - // Convert the datawatcher - List list = new ArrayList<>(); - MetaIndex toUse = NmsVersion.v1_13.isSupported() ? MetaIndex.LIVING_META : MetaIndex.ENTITY_META; - - if (DisguiseConfig.isMetaPacketsEnabled()) { - WatcherValue watch = new WatcherValue(toUse, WrappedDataWatcher.getEntityWatcher(entity).getByte(toUse.getIndex())); - - if (watch != null) { - list.add(watch); - } - - list = disguise.getWatcher().convert(observer, list); - } else { - for (WatcherValue obj : disguise.getWatcher().getWatchableObjects()) { - if (obj.getIndex() == toUse.getIndex()) { - list.add(obj); - break; - } - } - } - - // Construct the packets to return - PacketContainer packetBlock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); - - list.forEach(v -> v.setValue(NmsVersion.v1_13.isSupported() ? (byte) 0 : (byte) ((byte) v.getValue() & ~(1 << 4)))); - - // Make a packet to send the 'unblock' - PacketContainer packetUnblock = ReflectionManager.getMetadataPacket(entity.getEntityId(), list); - - // Send the unblock before the itemstack change so that the 2nd metadata packet works. Why? - // Scheduler - // delay. - - PacketContainer packet1 = packets.getPackets().get(0); - - packets.clear(); - - packets.addPacket(packetUnblock); - packets.addPacket(packet1); - packets.addPacket(packetBlock); - // Silly mojang made the right clicking datawatcher value only valid for one use. So I have - // to reset - // it. - } - } - } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadRotation.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadLook.java similarity index 56% rename from plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadRotation.java rename to plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadLook.java index 931c56d1..2a6d0821 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadRotation.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerHeadLook.java @@ -1,8 +1,9 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityHeadLook; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; @@ -14,19 +15,23 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import java.util.ArrayList; - /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerHeadRotation implements IPacketHandler { +public class PacketHandlerHeadLook implements IPacketHandler { + /** + * ProtocolLib: Body rotation is ENTITY_HEAD_ROTATION + * PacketEvents: Its ENTITY_HEAD_LOOK + * + * @return + */ @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ENTITY_HEAD_ROTATION}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_HEAD_LOOK}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { if (disguise.getType() == DisguiseType.FALLING_BLOCK) { packets.clear(); return; @@ -35,13 +40,16 @@ public class PacketHandlerHeadRotation implements IPacketHandler { Float pitchLock = disguise.getWatcher().getPitchLock(); Float yawLock = disguise.getWatcher().getYawLock(); boolean riding = observer.getVehicle() == entity; + WrapperPlayServerEntityHeadLook packet = packets.getOriginalPacket(); if (pitchLock == null && yawLock == null && (!disguise.getType().isPlayer() || entity.getType() == EntityType.PLAYER)) { if (riding) { - sentPacket = sentPacket.shallowClone(); - sentPacket.getModifier().write(0, DisguiseAPI.getEntityAttachmentId()); - packets.addPacket(sentPacket); + WrapperPlayServerEntityHeadLook copy = + new WrapperPlayServerEntityHeadLook(DisguiseAPI.getEntityAttachmentId(), packet.getHeadYaw()); + + packets.addPacket(copy); } + return; } @@ -49,15 +57,15 @@ public class PacketHandlerHeadRotation implements IPacketHandler { DisguiseType entityType = DisguiseType.getType(entity); - byte pitch = 0; - byte yaw = 0; + float pitch = 0; + float yaw = 0; if (pitchLock != null) { - pitch = (byte) (int) (pitchLock * 256.0F / 360.0F); + pitch = pitchLock; } if (yawLock != null) { - yaw = (byte) (int) (yawLock * 256.0F / 360.0F); + yaw = yawLock; } switch (entityType) { @@ -85,28 +93,26 @@ public class PacketHandlerHeadRotation implements IPacketHandler { case SNOWBALL: case PAINTING: case PRIMED_TNT: - if ((pitchLock == null || yawLock == null) && sentPacket.getBytes().read(0) == 0 && - entity.getVelocity().lengthSquared() > 0) { + if ((pitchLock == null || yawLock == null) && packet.getHeadYaw() == 0 && entity.getVelocity().lengthSquared() > 0) { loc.setDirection(entity.getVelocity()); if (pitchLock == null) { - pitch = DisguiseUtilities.getPitch(DisguiseType.PLAYER, (byte) (int) (loc.getPitch() * 256.0F / 360.0F)); + pitch = DisguiseUtilities.getPitch(DisguiseType.PLAYER, loc.getPitch()); } if (yawLock == null) { - yaw = DisguiseUtilities.getYaw(DisguiseType.PLAYER, (byte) (int) (loc.getYaw() * 256.0F / 360.0F)); + yaw = DisguiseUtilities.getYaw(DisguiseType.PLAYER, loc.getYaw()); } break; } default: if (pitchLock == null) { - pitch = - DisguiseUtilities.getPitch(DisguiseType.getType(entity.getType()), (byte) (int) (loc.getPitch() * 256.0F / 360.0F)); + pitch = DisguiseUtilities.getPitch(DisguiseType.getType(entity.getType()), loc.getPitch()); } if (yawLock == null) { - yaw = DisguiseUtilities.getYaw(DisguiseType.getType(entity.getType()), (byte) (int) (loc.getYaw() * 256.0F / 360.0F)); + yaw = DisguiseUtilities.getYaw(DisguiseType.getType(entity.getType()), loc.getYaw()); } break; } @@ -114,30 +120,17 @@ public class PacketHandlerHeadRotation implements IPacketHandler { pitch = DisguiseUtilities.getPitch(disguise.getType(), pitch); yaw = DisguiseUtilities.getYaw(disguise.getType(), yaw); - PacketContainer rotation = new PacketContainer(PacketType.Play.Server.ENTITY_HEAD_ROTATION); - - StructureModifier mods = rotation.getModifier(); - - mods.write(0, entity.getEntityId()); - mods.write(1, yaw); - - PacketContainer look = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE_LOOK); - - look.getIntegers().write(0, entity.getEntityId()); - look.getBytes().write(0, yaw); - look.getBytes().write(1, pitch); - packets.clear(); - packets.addPacket(look); - packets.addPacket(rotation); + for (int i = 0; i < (riding ? 2 : 1); i++) { + int id = i == 0 ? entity.getEntityId() : DisguiseAPI.getEntityAttachmentId(); - if (riding) { - for (PacketContainer c : new ArrayList<>(packets.getPackets())) { - c = c.shallowClone(); - c.getModifier().write(0, DisguiseAPI.getEntityAttachmentId()); - packets.addPacket(c); - } + WrapperPlayServerEntityHeadLook yawPacket = new WrapperPlayServerEntityHeadLook(id, yaw); + WrapperPlayServerEntityRelativeMoveAndRotation pitchYawPacket = + new WrapperPlayServerEntityRelativeMoveAndRotation(id, 0, 0, 0, yaw, pitch, false); + + packets.addPacket(pitchYawPacket); + packets.addPacket(yawPacket); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMetadata.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMetadata.java index 4b394c3b..73790960 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMetadata.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMetadata.java @@ -1,9 +1,12 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; import me.libraryaddict.disguise.utilities.packets.LibsPackets; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; @@ -11,26 +14,32 @@ import me.libraryaddict.disguise.utilities.reflection.WatcherValue; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import java.util.ArrayList; import java.util.List; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerMetadata implements IPacketHandler { +public class PacketHandlerMetadata implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ENTITY_METADATA}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_METADATA}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { packets.clear(); if (!DisguiseConfig.isMetaPacketsEnabled()) { return; } - List watcherValues = WatcherValue.getValues(disguise.getWatcher(), sentPacket); + List dataList = packets.getOriginalPacket().getEntityMetadata(); + List watcherValues = new ArrayList<>(); + + for (EntityData data : dataList) { + watcherValues.add(new WatcherValue(data)); + } List watchableObjects = disguise.getWatcher().convert(observer, watcherValues); @@ -38,7 +47,7 @@ public class PacketHandlerMetadata implements IPacketHandler { return; } - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(entity.getEntityId(), watchableObjects); + WrapperPlayServerEntityMetadata metaPacket = ReflectionManager.getMetadataPacket(entity.getEntityId(), watchableObjects); packets.addPacket(metaPacket); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMovement.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMovement.java index d46d1d19..eaf99a2b 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMovement.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerMovement.java @@ -1,8 +1,14 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; @@ -12,119 +18,134 @@ import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; import me.libraryaddict.disguise.utilities.packets.LibsPackets; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Location; import org.bukkit.entity.AbstractHorse; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.util.Vector; import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** * Created by libraryaddict on 3/01/2019. */ -public class PacketHandlerMovement implements IPacketHandler { +public class PacketHandlerMovement> implements IPacketHandler { private final boolean invalid = LibsPremium.getUserID().matches("\\d+") && Integer.parseInt(LibsPremium.getUserID()) < 2; @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.REL_ENTITY_MOVE_LOOK, PacketType.Play.Server.ENTITY_LOOK, - PacketType.Play.Server.ENTITY_TELEPORT, PacketType.Play.Server.REL_ENTITY_MOVE}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION, PacketType.Play.Server.ENTITY_ROTATION, + PacketType.Play.Server.ENTITY_TELEPORT, PacketType.Play.Server.ENTITY_RELATIVE_MOVE}; } - private short conRel(double oldCord, double newCord) { - return (short) ((oldCord - newCord) * 4096); + private double conRel(double oldCord, double newCord) { + return oldCord - newCord; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { - handle2(disguise, sentPacket, packets, observer, entity); + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { + handleMovement(disguise, packets, observer, entity); + addMultiNames(disguise, packets); + } + private void addMultiNames(Disguise disguise, LibsPackets packets) { int len = disguise.getMultiNameLength(); if (len == 0) { return; } - ArrayList toAdd = new ArrayList<>(); + ArrayList toAdd = new ArrayList<>(); double height = disguise.getHeight() + disguise.getWatcher().getNameYModifier(); - for (PacketContainer packet : packets.getPackets()) { - if (packet.getType() == PacketType.Play.Server.ENTITY_LOOK) { + for (PacketWrapper packet : packets.getPackets()) { + if (packet instanceof WrapperPlayServerEntityRotation) { continue; } for (int i = 0; i < len; i++) { int standId = disguise.getArmorstandIds()[i]; - PacketContainer packet2 = packet.shallowClone(); - packet2.getIntegers().write(0, standId); + PacketWrapper cloned; - if (packet2.getType() == PacketType.Play.Server.ENTITY_TELEPORT) { - packet2.getDoubles().write(1, packet2.getDoubles().read(1) + height + (0.28 * i)); + if (packet instanceof WrapperPlayServerEntityTeleport) { + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) packet; + cloned = new WrapperPlayServerEntityTeleport(standId, tele.getPosition().add(0, height + (0.28 * i), 0), tele.getYaw(), + tele.getPitch(), tele.isOnGround()); + } else if (packet instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + WrapperPlayServerEntityRelativeMoveAndRotation rot = (WrapperPlayServerEntityRelativeMoveAndRotation) packet; + cloned = new WrapperPlayServerEntityRelativeMoveAndRotation(standId, rot.getDeltaX(), rot.getDeltaY(), rot.getDeltaZ(), + rot.getYaw(), rot.getPitch(), rot.isOnGround()); + } else if (packet instanceof WrapperPlayServerEntityRelativeMove) { + WrapperPlayServerEntityRelativeMove rot = (WrapperPlayServerEntityRelativeMove) packet; + cloned = new WrapperPlayServerEntityRelativeMove(standId, rot.getDeltaX(), rot.getDeltaY(), rot.getDeltaZ(), + rot.isOnGround()); + } else { + throw new IllegalStateException("Unknown packet " + packet.getClass()); } - toAdd.add(packet2); + toAdd.add(cloned); } } packets.getPackets().addAll(toAdd); } - public void handle2(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + private void handleMovement(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { if (invalid && RandomUtils.nextDouble() < 0.1) { packets.clear(); return; } + PacketWrapper sentPacket = packets.getOriginalPacket(); + double yMod = DisguiseUtilities.getYModifier(disguise) + disguise.getWatcher().getYModifier(); // If falling block should be appearing in center of blocks if (disguise.getType() == DisguiseType.FALLING_BLOCK && ((FallingBlockWatcher) disguise.getWatcher()).isGridLocked()) { packets.clear(); - if (sentPacket.getType() == PacketType.Play.Server.ENTITY_LOOK) { + if (sentPacket instanceof WrapperPlayServerEntityRotation) { return; } - PacketContainer movePacket = sentPacket.shallowClone(); + PacketWrapper movePacket; + Location loc = entity.getLocation(); // If not relational movement - if (movePacket.getType() == PacketType.Play.Server.ENTITY_TELEPORT) { - StructureModifier doubles = movePacket.getDoubles(); - // Center the block - doubles.write(0, loc.getBlockX() + 0.5); - + if (sentPacket instanceof WrapperPlayServerEntityTeleport) { + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) sentPacket; double y = loc.getBlockY(); + // Center the block y += (loc.getY() % 1 >= 0.85 ? 1 : loc.getY() % 1 >= 0.35 ? .5 : 0); - - doubles.write(1, y + yMod); - doubles.write(2, loc.getBlockZ() + 0.5); + movePacket = new WrapperPlayServerEntityTeleport(tele.getEntityId(), + new Vector3d(loc.getBlockX() + 0.5, y + yMod, loc.getBlockZ() + 0.5), tele.getYaw(), tele.getPitch(), + tele.isOnGround()); } else { - int x; - int y; - int z; + double x; + double y; + double z; - if (NmsVersion.v1_14.isSupported()) { - StructureModifier shorts = movePacket.getShorts(); - - x = shorts.read(0); - y = shorts.read(1); - z = shorts.read(2); + if (sentPacket instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + WrapperPlayServerEntityRelativeMoveAndRotation rot = (WrapperPlayServerEntityRelativeMoveAndRotation) sentPacket; + x = rot.getDeltaX(); + y = rot.getDeltaY(); + z = rot.getDeltaZ(); + } else if (sentPacket instanceof WrapperPlayServerEntityRelativeMove) { + WrapperPlayServerEntityRelativeMove rot = (WrapperPlayServerEntityRelativeMove) sentPacket; + x = rot.getDeltaX(); + y = rot.getDeltaY(); + z = rot.getDeltaZ(); } else { - StructureModifier ints = movePacket.getIntegers(); - - x = ints.read(0); - y = ints.read(1); - z = ints.read(2); + throw new IllegalStateException("Unknown packet " + sentPacket.getClass()); } - Vector diff = new Vector(x / 4096D, y / 4096D, z / 4096D); - Location newLoc = loc.clone().subtract(diff); + Location newLoc = loc.clone().subtract(x, y, z); double origY = loc.getBlockY() + (loc.getY() % 1 >= 0.85 ? 1 : loc.getY() % 1 >= 0.35 ? .5 : 0); double newY = newLoc.getBlockY() + (newLoc.getY() % 1 >= 0.85 ? 1 : newLoc.getY() % 1 >= 0.35 ? .5 : 0); @@ -139,143 +160,188 @@ public class PacketHandlerMovement implements IPacketHandler { y = conRel(origY, newY); z = conRel(loc.getBlockZ(), newLoc.getBlockZ()); - if (NmsVersion.v1_14.isSupported()) { - StructureModifier shorts = movePacket.getShorts(); + if (sentPacket instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + WrapperPlayServerEntityRelativeMoveAndRotation rot = (WrapperPlayServerEntityRelativeMoveAndRotation) sentPacket; - shorts.write(0, (short) x); - shorts.write(1, (short) y); - shorts.write(2, (short) z); + movePacket = + new WrapperPlayServerEntityRelativeMoveAndRotation(rot.getEntityId(), x, y, z, rot.getYaw(), rot.getPitch(), + rot.isOnGround()); + } else if (sentPacket instanceof WrapperPlayServerEntityRelativeMove) { + WrapperPlayServerEntityRelativeMove rot = (WrapperPlayServerEntityRelativeMove) sentPacket; + x = rot.getDeltaX(); + y = rot.getDeltaY(); + z = rot.getDeltaZ(); + + movePacket = new WrapperPlayServerEntityRelativeMove(rot.getEntityId(), x, y, z, rot.isOnGround()); } else { - StructureModifier ints = movePacket.getIntegers(); - - ints.write(0, x); - ints.write(1, y); - ints.write(2, z); + throw new IllegalStateException("Unknown packet " + sentPacket.getClass()); } } } packets.addPacket(movePacket); return; - } else if (disguise.getType() == DisguiseType.RABBIT && (sentPacket.getType() == PacketType.Play.Server.REL_ENTITY_MOVE || - sentPacket.getType() == PacketType.Play.Server.REL_ENTITY_MOVE_LOOK)) { - // When did the rabbit disguise last hop - long lastHop = 999999; + } else if (disguise.getType() == DisguiseType.RABBIT && (sentPacket instanceof WrapperPlayServerEntityRelativeMove || + sentPacket instanceof WrapperPlayServerEntityRelativeMoveAndRotation)) { - // If hop meta exists, set the last hop time - if (!entity.getMetadata("LibsRabbitHop").isEmpty()) { - // Last hop was 3 minutes ago, so subtract current time with the last hop time and get 3 - // minutes ago in milliseconds - lastHop = System.currentTimeMillis() - entity.getMetadata("LibsRabbitHop").get(0).asLong(); - } + // Syncronized so we're not modifying a map across different threads + synchronized (this) { + Map rabbitHops; - // If last hop was less than 0.1 or more than 0.5 seconds ago - if (lastHop < 100 || lastHop > 500) { - if (lastHop > 500) { - entity.removeMetadata("LibsRabbitHop", LibsDisguises.getInstance()); - entity.setMetadata("LibsRabbitHop", new FixedMetadataValue(LibsDisguises.getInstance(), System.currentTimeMillis())); + // If hop meta exists, set the last hop time + if (!entity.getMetadata("LibsRabbitHop").isEmpty()) { + rabbitHops = (Map) entity.getMetadata("LibsRabbitHop").get(0).value(); + + // Expire entries + Iterator> iterator = rabbitHops.entrySet().iterator(); + + while (iterator.hasNext()) { + if (iterator.next().getValue() + 500 > System.currentTimeMillis()) { + continue; + } + + iterator.remove(); + } + } else { + entity.setMetadata("LibsRabbitHop", new FixedMetadataValue(LibsDisguises.getInstance(), rabbitHops = new HashMap<>())); } - PacketContainer statusPacket = new PacketContainer(PacketType.Play.Server.ENTITY_STATUS); - packets.addPacket(statusPacket); + long lastHop = + rabbitHops.containsKey(observer.getName()) ? System.currentTimeMillis() - rabbitHops.get(observer.getName()) : 99999; - statusPacket.getIntegers().write(0, entity.getEntityId()); - statusPacket.getBytes().write(0, (byte) 1); + // If last hop was less than 0.1 or more than 0.5 seconds ago + if (lastHop < 100 || lastHop > 500) { + if (lastHop > 500) { + rabbitHops.put(observer.getName(), System.currentTimeMillis()); + } + + packets.addPacket(new WrapperPlayServerEntityStatus(entity.getEntityId(), 1)); + } } } - if (sentPacket.getType() == PacketType.Play.Server.ENTITY_LOOK && disguise.getType() == DisguiseType.WITHER_SKULL) { + if (sentPacket instanceof WrapperPlayServerEntityRotation && disguise.getType() == DisguiseType.WITHER_SKULL) { // Stop wither skulls from looking packets.clear(); } else { - if (sentPacket.getType() != PacketType.Play.Server.REL_ENTITY_MOVE) { + // If the packet has a head/body pitch/yaw + if (!(sentPacket instanceof WrapperPlayServerEntityRelativeMove)) { packets.clear(); - PacketContainer movePacket = sentPacket.shallowClone(); + float yawValue; + float pitchValue; - packets.addPacket(movePacket); + PacketWrapper cloned; - StructureModifier bytes = movePacket.getBytes(); + if (sentPacket instanceof WrapperPlayServerEntityTeleport) { + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) sentPacket; - byte yawValue = bytes.read(0); - byte pitchValue = bytes.read(1); + cloned = new WrapperPlayServerEntityTeleport(tele.getEntityId(), tele.getPosition(), yawValue = tele.getYaw(), + pitchValue = tele.getPitch(), tele.isOnGround()); + } else if (sentPacket instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + WrapperPlayServerEntityRelativeMoveAndRotation rot = (WrapperPlayServerEntityRelativeMoveAndRotation) sentPacket; + + cloned = new WrapperPlayServerEntityRelativeMoveAndRotation(rot.getEntityId(), rot.getDeltaX(), rot.getDeltaY(), + rot.getDeltaZ(), yawValue = rot.getYaw(), pitchValue = rot.getPitch(), rot.isOnGround()); + } else if (sentPacket instanceof WrapperPlayServerEntityRotation) { + WrapperPlayServerEntityRotation rot = (WrapperPlayServerEntityRotation) sentPacket; + + cloned = new WrapperPlayServerEntityRotation(rot.getEntityId(), yawValue = rot.getYaw(), pitchValue = rot.getPitch(), + rot.isOnGround()); + } else { + throw new IllegalStateException("Unknown packet " + sentPacket.getClass()); + } + + packets.addPacket(cloned); Float pitchLock = disguise.getWatcher().getPitchLock(); Float yawLock = disguise.getWatcher().getYawLock(); if (pitchLock != null) { - pitchValue = (byte) (int) (pitchLock * 256.0F / 360.0F); - pitchValue = DisguiseUtilities.getPitch(disguise.getType(), pitchValue); + pitchValue = DisguiseUtilities.getPitch(disguise.getType(), pitchLock); } else { pitchValue = DisguiseUtilities.getPitch(disguise.getType(), entity.getType(), pitchValue); } if (yawLock != null) { - yawValue = (byte) (int) (yawLock * 256.0F / 360.0F); - yawValue = DisguiseUtilities.getYaw(disguise.getType(), yawValue); + yawValue = DisguiseUtilities.getYaw(disguise.getType(), yawLock); } else { yawValue = DisguiseUtilities.getYaw(disguise.getType(), entity.getType(), yawValue); } - bytes.write(0, yawValue); - bytes.write(1, pitchValue); + if (cloned instanceof WrapperPlayServerEntityTeleport) { + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) cloned; + + tele.setYaw(yawValue); + tele.setPitch(pitchValue); + } else if (cloned instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + WrapperPlayServerEntityRelativeMoveAndRotation rot = (WrapperPlayServerEntityRelativeMoveAndRotation) cloned; + + rot.setYaw(yawValue); + rot.setPitch(pitchValue); + } else if (cloned instanceof WrapperPlayServerEntityRotation) { + WrapperPlayServerEntityRotation look = (WrapperPlayServerEntityRotation) cloned; + + look.setYaw(yawValue); + look.setPitch(pitchValue); + } if (entity == observer.getVehicle() && AbstractHorse.class.isAssignableFrom(disguise.getType().getEntityClass())) { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_LOOK); - - packet.getIntegers().write(0, DisguiseAPI.getEntityAttachmentId()); - packet.getBytes().write(0, yawValue); - packet.getBytes().write(1, pitchValue); + WrapperPlayServerEntityRotation packet = + new WrapperPlayServerEntityRotation(DisguiseAPI.getEntityAttachmentId(), yawValue, pitchValue, false); packets.addPacket(packet); - } else if (sentPacket.getType() == PacketType.Play.Server.ENTITY_TELEPORT && - disguise.getType() == DisguiseType.ITEM_FRAME) { - StructureModifier doubles = movePacket.getDoubles(); + } else if (cloned instanceof WrapperPlayServerEntityTeleport && disguise.getType().isArtDisplay()) { + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) cloned; Location loc = entity.getLocation(); double data = (((loc.getYaw() % 360) + 720 + 45) / 90) % 4; if (data % 2 == 0) { - if (data % 2 == 0) { - doubles.write(3, loc.getZ()); - } else { - doubles.write(1, loc.getZ()); - } + tele.setPosition(new Vector3d(loc.getX(), 0, loc.getZ() + data == 0 ? -1 : 1)); + } else { + tele.setPosition(new Vector3d(loc.getX() + data == 3 ? -1 : 1, loc.getY(), loc.getZ())); } double y = DisguiseUtilities.getYModifier(disguise); if (y != 0) { - doubles.write(2, doubles.read(2) + y); + tele.setPosition(tele.getPosition().add(0, y, 0)); } } else if (disguise.getType() == DisguiseType.DOLPHIN) { - movePacket.getBooleans().write(0, false); + if (cloned instanceof WrapperPlayServerEntityTeleport) { + ((WrapperPlayServerEntityTeleport) cloned).setOnGround(false); + } else if (cloned instanceof WrapperPlayServerEntityRelativeMoveAndRotation) { + ((WrapperPlayServerEntityRelativeMoveAndRotation) cloned).setOnGround(false); + } else if (cloned instanceof WrapperPlayServerEntityRotation) { + ((WrapperPlayServerEntityRotation) cloned).setOnGround(false); + } } } else if (disguise.getType() == DisguiseType.DOLPHIN) { // Dolphins act funny on the ground, so lets not tell the clients they are on the ground packets.clear(); - PacketContainer movePacket = sentPacket.shallowClone(); + WrapperPlayServerEntityRelativeMove p = (WrapperPlayServerEntityRelativeMove) sentPacket; + WrapperPlayServerEntityRelativeMove cloned = + new WrapperPlayServerEntityRelativeMove(p.getEntityId(), p.getDeltaX(), p.getDeltaY(), p.getDeltaZ(), false); - packets.addPacket(movePacket); - - movePacket.getBooleans().write(0, false); + packets.addPacket(cloned); } - if (yMod != 0 && sentPacket.getType() == PacketType.Play.Server.ENTITY_TELEPORT) { - PacketContainer packet = packets.getPackets().get(0); + if (yMod != 0 && sentPacket instanceof WrapperPlayServerEntityTeleport) { + PacketWrapper packet = packets.getPackets().get(0); + WrapperPlayServerEntityTeleport tele = (WrapperPlayServerEntityTeleport) packet; if (packet == sentPacket) { - packet = packet.shallowClone(); + packet = new WrapperPlayServerEntityTeleport(tele.getEntityId(), tele.getPosition().add(0, yMod, 0), tele.getYaw(), + tele.getPitch(), tele.isOnGround()); packets.clear(); packets.addPacket(packet); + } else { + tele.setPosition(tele.getPosition().add(0, yMod, 0)); } - - StructureModifier doubles = packet.getDoubles(); - - doubles.write(1, doubles.read(1) + yMod); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java index b36e4b1a..ffbf7c92 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerSpawn.java @@ -1,12 +1,30 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.WrappedAttribute; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.mojang.datafixers.util.Pair; +import com.github.retrooper.packetevents.protocol.attribute.Attributes; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.protocol.player.Equipment; +import com.github.retrooper.packetevents.protocol.player.EquipmentSlot; +import com.github.retrooper.packetevents.protocol.world.Direction; +import com.github.retrooper.packetevents.protocol.world.PaintingType; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.util.Vector3i; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerCamera; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerHeldItemChange; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnExperienceOrb; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; @@ -26,47 +44,45 @@ import me.libraryaddict.disguise.utilities.packets.LibsPackets; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import me.libraryaddict.disguise.utilities.reflection.WatcherValue; -import org.bukkit.Art; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Damageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Optional; /** * Created by libraryaddict on 3/01/2019. */ public class PacketHandlerSpawn implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - List packets = new ArrayList<>(); + public PacketTypeCommon[] getHandledPackets() { + List packets = new ArrayList<>(); if (!NmsVersion.v1_20_R2.isSupported()) { - packets.add(PacketType.Play.Server.NAMED_ENTITY_SPAWN); + packets.add(Server.SPAWN_PLAYER); } - packets.add(PacketType.Play.Server.SPAWN_ENTITY_EXPERIENCE_ORB); - packets.add(PacketType.Play.Server.SPAWN_ENTITY); + packets.add(Server.SPAWN_EXPERIENCE_ORB); + packets.add(Server.SPAWN_ENTITY); if (!NmsVersion.v1_19_R1.isSupported()) { - packets.add(PacketType.Play.Server.SPAWN_ENTITY_LIVING); - packets.add(PacketType.Play.Server.SPAWN_ENTITY_PAINTING); + packets.add(Server.SPAWN_LIVING_ENTITY); + packets.add(Server.SPAWN_PAINTING); } - return packets.toArray(new PacketType[0]); + return packets.toArray(new PacketTypeCommon[0]); } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { packets.clear(); if (disguise.getType() == DisguiseType.UNKNOWN) { @@ -88,8 +104,8 @@ public class PacketHandlerSpawn implements IPacketHandler { Float pitchLock = DisguiseConfig.isMovementPacketsEnabled() ? disguise.getWatcher().getPitchLock() : null; Float yawLock = DisguiseConfig.isMovementPacketsEnabled() ? disguise.getWatcher().getYawLock() : null; - byte yaw = (byte) (int) ((yawLock == null ? loc.getYaw() : yawLock) * 256.0F / 360.0F); - byte pitch = (byte) (int) ((pitchLock == null ? loc.getPitch() : pitchLock) * 256.0F / 360.0F); + float yaw = (yawLock == null ? loc.getYaw() : yawLock); + float pitch = (pitchLock == null ? loc.getPitch() : pitchLock); if (DisguiseConfig.isMovementPacketsEnabled()) { if (yawLock == null) { @@ -104,300 +120,212 @@ public class PacketHandlerSpawn implements IPacketHandler { pitch = DisguiseUtilities.getPitch(disguise.getType(), pitch); } + com.github.retrooper.packetevents.protocol.world.Location pLoc = + new com.github.retrooper.packetevents.protocol.world.Location(loc.getX(), loc.getY(), loc.getZ(), yaw, pitch); + boolean inLineOfSight = true; if (disguise.getType() == DisguiseType.EXPERIENCE_ORB) { - PacketContainer spawnOrb = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY_EXPERIENCE_ORB); + WrapperPlayServerSpawnExperienceOrb spawnOrb = + new WrapperPlayServerSpawnExperienceOrb(disguisedEntity.getEntityId(), loc.getX(), loc.getY() + 0.06, loc.getZ(), + (short) 1); packets.addPacket(spawnOrb); + } else { + if (!NmsVersion.v1_19_R1.isSupported() && disguise.getType() == DisguiseType.PAINTING) { + int id = ((MiscDisguise) disguise).getData(); + PaintingType paintingType = PaintingType.getById(id); + Direction direction = DisguiseUtilities.getHangingDirection(yaw); + WrapperPlayServerSpawnPainting spawnPainting = + new WrapperPlayServerSpawnPainting(disguisedEntity.getEntityId(), disguise.getUUID(), paintingType, + new Vector3i(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()), direction); - StructureModifier mods = spawnOrb.getModifier(); + packets.addPacket(spawnPainting); - mods.write(0, disguisedEntity.getEntityId()); - mods.write(1, loc.getX()); - mods.write(2, loc.getY() + 0.06); - mods.write(3, loc.getZ()); - mods.write(4, 1); - } else if (!NmsVersion.v1_19_R1.isSupported() && disguise.getType() == DisguiseType.PAINTING) { - PacketContainer spawnPainting = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY_PAINTING); - packets.addPacket(spawnPainting); + // Make the teleport packet to make it visible.. + WrapperPlayServerEntityTeleport teleportPainting = + new WrapperPlayServerEntityTeleport(disguisedEntity.getEntityId(), pLoc, disguisedEntity.isOnGround()); + packets.addPacket(teleportPainting); + } else if (disguise.getType().isPlayer()) { + PlayerDisguise playerDisguise = (PlayerDisguise) disguise; + boolean visibleOrNewCompat = playerDisguise.isNameVisible() || DisguiseConfig.isScoreboardNames(); + double dist = observer.getLocation().toVector().distanceSquared(disguisedEntity.getLocation().toVector()); - StructureModifier mods = spawnPainting.getModifier(); + // If self disguise, or further than 50 blocks, or not in front of entity + inLineOfSight = DisguiseUtilities.isFancyHiddenTabs() || observer == disguisedEntity || + disguisedEntity.getPassengers().contains(observer) || dist > (50 * 50) || + (observer.getLocation().add(observer.getLocation().getDirection().normalize()).toVector() + .distanceSquared(disguisedEntity.getLocation().toVector()) - dist) < 0.3; - mods.write(0, disguisedEntity.getEntityId()); - mods.write(1, disguise.getUUID()); - mods.write(2, ReflectionManager.getBlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - mods.write(3, ReflectionManager.getEnumDirection(((int) loc.getYaw()) % 4)); + int entityId = disguisedEntity.getEntityId(); - int id = ((MiscDisguise) disguise).getData(); + PlayerSkinHandler.PlayerSkin skin; - mods.write(4, NmsVersion.v1_13.isSupported() ? id : ReflectionManager.getEnumArt(Art.values()[id])); + if (DisguiseUtilities.isFancyHiddenTabs() || !playerDisguise.isDisplayedInTab() || !playerDisguise.isNameVisible()) { + // Send player info along with the disguise - // Make the teleport packet to make it visible.. - PacketContainer teleportPainting = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT); - packets.addPacket(teleportPainting); + packets.addPacket(DisguiseUtilities.createTablistAddPackets(playerDisguise)); - mods = teleportPainting.getModifier(); + skin = LibsDisguises.getInstance().getSkinHandler().addPlayerSkin(observer, playerDisguise); + skin.setDoTabList(!DisguiseUtilities.isFancyHiddenTabs()); - mods.write(0, disguisedEntity.getEntityId()); - mods.write(1, loc.getX()); - mods.write(2, loc.getY()); - mods.write(3, loc.getZ()); - mods.write(4, yaw); - mods.write(5, pitch); - } else if (disguise.getType().isPlayer()) { - PlayerDisguise playerDisguise = (PlayerDisguise) disguise; - boolean visibleOrNewCompat = playerDisguise.isNameVisible() || DisguiseConfig.isScoreboardNames(); - double dist = observer.getLocation().toVector().distanceSquared(disguisedEntity.getLocation().toVector()); - - // If self disguise, or further than 50 blocks, or not in front of entity - inLineOfSight = DisguiseUtilities.isFancyHiddenTabs() || observer == disguisedEntity || - disguisedEntity.getPassengers().contains(observer) || dist > (50 * 50) || - (observer.getLocation().add(observer.getLocation().getDirection().normalize()).toVector() - .distanceSquared(disguisedEntity.getLocation().toVector()) - dist) < 0.3; - - int entityId = disguisedEntity.getEntityId(); - - PlayerSkinHandler.PlayerSkin skin; - - if (DisguiseUtilities.isFancyHiddenTabs() || !playerDisguise.isDisplayedInTab() || !playerDisguise.isNameVisible()) { - // Send player info along with the disguise - - packets.addPacket(ReflectionManager.createTablistAddPackets(playerDisguise)); - - skin = LibsDisguises.getInstance().getSkinHandler().addPlayerSkin(observer, playerDisguise); - skin.setDoTabList(!DisguiseUtilities.isFancyHiddenTabs()); - - if (LibsPremium.getPaidInformation() != null && !LibsPremium.getPaidInformation().getBuildNumber().matches("#?\\d+")) { - skin.getSleptPackets().computeIfAbsent(0, (a) -> new ArrayList<>()) - .add(new PacketContainer(PacketType.Play.Server.HELD_ITEM_SLOT)); - } - } else { - skin = LibsDisguises.getInstance().getSkinHandler().addPlayerSkin(observer, playerDisguise); - skin.setDoTabList(false); - } - - skin.setSleepPackets(!inLineOfSight); - packets.setSkinHandling(true); - PacketContainer spawnPlayer; - - if (NmsVersion.v1_20_R2.isSupported()) { - spawnPlayer = constructLivingPacket(observer, packets, disguisedEntity, loc, pitch, yaw); - } else { - // Spawn the player - spawnPlayer = new PacketContainer(PacketType.Play.Server.NAMED_ENTITY_SPAWN); - - spawnPlayer.getIntegers().write(0, entityId); // Id - spawnPlayer.getModifier().write(1, playerDisguise.getUUID()); - - Location spawnAt = - inLineOfSight ? loc : observer.getLocation().add(observer.getLocation().getDirection().normalize().multiply(10)); - - // Spawn them in front of the observer - StructureModifier doubles = spawnPlayer.getDoubles(); - doubles.write(0, spawnAt.getX()); - doubles.write(1, spawnAt.getY()); - doubles.write(2, spawnAt.getZ()); - - StructureModifier bytes = spawnPlayer.getBytes(); - bytes.write(0, yaw); - bytes.write(1, pitch); - - packets.addPacket(spawnPlayer); - } - - List watcherValues; - - if (!inLineOfSight) { - watcherValues = Collections.singletonList(new WatcherValue(MetaIndex.ENTITY_META, (byte) 32)); - } else { - watcherValues = - DisguiseUtilities.createSanitizedWatcherValues(observer, WrappedDataWatcher.getEntityWatcher(disguisedEntity), - disguise.getWatcher()); - } - - if (NmsVersion.v1_15.isSupported()) { - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(entityId, watcherValues); - - packets.addPacket(metaPacket); - } else { - spawnPlayer.getDataWatcherModifier().write(0, DisguiseUtilities.createDatawatcher(watcherValues)); - } - } else if (disguise.isMobDisguise() || disguise.getType() == DisguiseType.ARMOR_STAND) { - PacketContainer spawnEntity = constructLivingPacket(observer, packets, disguisedEntity, loc, pitch, yaw); - - List watcherValues = - DisguiseUtilities.createSanitizedWatcherValues(observer, WrappedDataWatcher.getEntityWatcher(disguisedEntity), - disguise.getWatcher()); - - if (NmsVersion.v1_15.isSupported()) { - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(disguisedEntity.getEntityId(), watcherValues); - - packets.addPacket(metaPacket); - } else { - spawnEntity.getDataWatcherModifier().write(0, DisguiseUtilities.createDatawatcher(watcherValues)); - } - } else if (disguise.getType().isMisc()) { - int data = ((MiscDisguise) disguise).getData(); - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); - - if (disguise.getType() == DisguiseType.FALLING_BLOCK) { - data = ((FallingBlockWatcher) disguise.getWatcher()).getBlockCombinedId(); - - if (((FallingBlockWatcher) disguise.getWatcher()).isGridLocked()) { - double yMod = disguise.getWatcher().getYModifier(); - y -= yMod; - - // Center the block - x = loc.getBlockX() + 0.5; - y = Math.floor(y) + yMod + (y % 1 >= 0.85 ? 1 : y % 1 >= 0.35 ? .5 : 0); - z = loc.getBlockZ() + 0.5; - } - } else if (disguise.getType() == DisguiseType.FISHING_HOOK && data == -1) { - // If the MiscDisguise data isn't set. Then no entity id was provided, so default to the owners - // entity id - data = observer.getEntityId(); - } else if (disguise.getType() == DisguiseType.ITEM_FRAME) { - data = ((((int) loc.getYaw() % 360) + 720 + 45) / 90) % 4; - } - - PacketContainer spawnEntity; - - if (NmsVersion.v1_14.isSupported()) { - Object entityType; - - if (disguise.isCustomDisguise()) { - entityType = ((ModdedDisguise) disguise).getModdedEntity().getEntityType(); + if (LibsPremium.getPaidInformation() != null && !LibsPremium.getPaidInformation().getBuildNumber().matches("#?\\d+")) { + skin.getSleptPackets().computeIfAbsent(0, (a) -> new ArrayList<>()).add(new WrapperPlayServerHeldItemChange(0)); + } } else { - entityType = ReflectionManager.getEntityType(disguise.getType().getEntityType()); + skin = LibsDisguises.getInstance().getSkinHandler().addPlayerSkin(observer, playerDisguise); + skin.setDoTabList(false); } - Object[] params = - new Object[]{disguisedEntity.getEntityId(), disguise.getUUID(), x, y, z, pitch / 256.0F * 360.0F, yaw / 256.0F * 360.0F, - entityType, data, ReflectionManager.getVec3D(disguisedEntity.getVelocity())}; + skin.setSleepPackets(!inLineOfSight); + packets.setSkinHandling(true); + PacketWrapper spawnPlayer; - if (NmsVersion.v1_19_R1.isSupported()) { - params = Arrays.copyOf(params, params.length + 1); + if (NmsVersion.v1_20_R2.isSupported()) { + spawnPlayer = constructLivingPacket(observer, packets, disguisedEntity, loc, pitch, yaw); + } else { + // Spawn them in front of the observer + Location spawnAt = + inLineOfSight ? loc : observer.getLocation().add(observer.getLocation().getDirection().normalize().multiply(10)); - params[params.length - 1] = (double) loc.getYaw(); + // Spawn the player + spawnPlayer = new WrapperPlayServerSpawnPlayer(entityId, playerDisguise.getUUID(), pLoc, new ArrayList<>()); + + packets.addPacket(spawnPlayer); } - spawnEntity = ProtocolLibrary.getProtocolManager().createPacketConstructor(PacketType.Play.Server.SPAWN_ENTITY, params) - .createPacket(params); - } else { - int objectId = disguise.getType().getObjectId(); + List watcherValues; - if (disguise.isCustomDisguise()) { - objectId = ((ModdedDisguise) disguise).getModdedEntity().getTypeId(); + if (!inLineOfSight) { + watcherValues = Collections.singletonList(new WatcherValue(MetaIndex.ENTITY_META, (byte) 32, true)); + } else { + watcherValues = DisguiseUtilities.createSanitizedWatcherValues(observer, disguisedEntity, disguise.getWatcher()); } - Object nmsEntity = ReflectionManager.getNmsEntity(disguisedEntity); + if (NmsVersion.v1_15.isSupported()) { + WrapperPlayServerEntityMetadata metaPacket = ReflectionManager.getMetadataPacket(entityId, watcherValues); - spawnEntity = ProtocolLibrary.getProtocolManager() - .createPacketConstructor(PacketType.Play.Server.SPAWN_ENTITY, nmsEntity, objectId, data) - .createPacket(nmsEntity, objectId, data); - - StructureModifier doubles = spawnEntity.getDoubles(); - - doubles.write(0, x); - doubles.write(1, y); - doubles.write(2, z); - - spawnEntity.getModifier().write(8, pitch); - spawnEntity.getModifier().write(9, yaw); - - if (NmsVersion.v1_19_R1.isSupported()) { - spawnEntity.getModifier().write(10, yaw); + packets.addPacket(metaPacket); + } else if (spawnPlayer instanceof WrapperPlayServerSpawnLivingEntity) { + ((WrapperPlayServerSpawnLivingEntity) spawnPlayer).setEntityMetadata( + DisguiseUtilities.createDatawatcher(watcherValues)); + } else if (spawnPlayer instanceof WrapperPlayServerSpawnPlayer) { + ((WrapperPlayServerSpawnPlayer) spawnPlayer).setEntityMetadata(DisguiseUtilities.createDatawatcher(watcherValues)); } - } + } else if (disguise.isMobDisguise() || disguise.getType() == DisguiseType.ARMOR_STAND) { + PacketWrapper spawnEntity = constructLivingPacket(observer, packets, disguisedEntity, loc, pitch, yaw); - packets.addPacket(spawnEntity); - - // Since 1.19.3 we apparently no longer send all metadata but only the non-default - if (NmsVersion.v1_19_R2.isSupported()) { List watcherValues = - DisguiseUtilities.createSanitizedWatcherValues(observer, WrappedDataWatcher.getEntityWatcher(disguisedEntity), - disguise.getWatcher()); - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(disguisedEntity.getEntityId(), watcherValues); + DisguiseUtilities.createSanitizedWatcherValues(observer, disguisedEntity, disguise.getWatcher()); - packets.addPacket(metaPacket); - } + if (NmsVersion.v1_15.isSupported()) { + WrapperPlayServerEntityMetadata metaPacket = + ReflectionManager.getMetadataPacket(disguisedEntity.getEntityId(), watcherValues); - // If it's not the same type, then highly likely they have different velocity settings which we'd want to - // cancel - if (DisguiseType.getType(disguisedEntity) != disguise.getType()) { - StructureModifier ints = spawnEntity.getIntegers(); - - ints.write(1, 0); - ints.write(2, 0); - ints.write(3, 0); - - if (disguise.getType() == DisguiseType.DROPPED_ITEM) { - PacketContainer velocity = new PacketContainer(PacketType.Play.Server.ENTITY_VELOCITY); - velocity.getIntegers().write(0, disguisedEntity.getEntityId()); - - packets.addPacket(velocity); - } - } - - if (disguise.getType() == DisguiseType.ITEM_FRAME) { - if (data % 2 == 0) { - spawnEntity.getDoubles().write(2, loc.getZ() + (data == 0 ? -1 : 1)); + packets.addPacket(metaPacket); } else { - spawnEntity.getDoubles().write(0, loc.getX() + (data == 3 ? -1 : 1)); + ((WrapperPlayServerSpawnLivingEntity) spawnEntity).setEntityMetadata( + DisguiseUtilities.createDatawatcher(watcherValues)); + } + } else if (disguise.getType().isMisc()) { + int data = ((MiscDisguise) disguise).getData(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + if (disguise.getType() == DisguiseType.FALLING_BLOCK) { + data = ((FallingBlockWatcher) disguise.getWatcher()).getBlockCombinedId(); + + if (((FallingBlockWatcher) disguise.getWatcher()).isGridLocked()) { + double yMod = disguise.getWatcher().getYModifier(); + y -= yMod; + + // Center the block + x = loc.getBlockX() + 0.5; + y = Math.floor(y) + yMod + (y % 1 >= 0.85 ? 1 : y % 1 >= 0.35 ? .5 : 0); + z = loc.getBlockZ() + 0.5; + } + } else if (disguise.getType() == DisguiseType.FISHING_HOOK && data == -1) { + // If the MiscDisguise data isn't set. Then no entity id was provided, so default to the owners + // entity id + data = observer.getEntityId(); + } else if (disguise.getType().isArtDisplay()) { + data = DisguiseUtilities.getHangingDirection(yaw).ordinal(); + } + + WrapperPlayServerSpawnEntity spawnEntity; + + com.github.retrooper.packetevents.protocol.entity.type.EntityType entityType = getEntityType(disguise); + + Vector vec = disguisedEntity.getVelocity(); + spawnEntity = new WrapperPlayServerSpawnEntity(disguisedEntity.getEntityId(), Optional.of(disguise.getUUID()), entityType, + new Vector3d(x, y, z), pitch, yaw, yaw, data, Optional.of(new Vector3d(vec.getX(), vec.getY(), vec.getZ()))); + + packets.addPacket(spawnEntity); + + // Since 1.19.3 we apparently no longer send all metadata but only the non-default + if (NmsVersion.v1_19_R2.isSupported()) { + List watcherValues = + DisguiseUtilities.createSanitizedWatcherValues(observer, disguisedEntity, disguise.getWatcher()); + WrapperPlayServerEntityMetadata metaPacket = + ReflectionManager.getMetadataPacket(disguisedEntity.getEntityId(), watcherValues); + + packets.addPacket(metaPacket); + } + + // If it's not the same type, then highly likely they have different velocity settings which we'd want to + // cancel + if (DisguiseType.getType(disguisedEntity) != disguise.getType()) { + spawnEntity.setVelocity(Optional.of(new Vector3d(0, 0, 0))); + + if (disguise.getType() == DisguiseType.DROPPED_ITEM) { + WrapperPlayServerEntityVelocity velocity = + new WrapperPlayServerEntityVelocity(disguisedEntity.getEntityId(), new Vector3d(0, 0, 0)); + + packets.addPacket(velocity); + } + } + + if (disguise.getType() == DisguiseType.ITEM_FRAME) { + if (data % 2 == 0) { + spawnEntity.setPosition(new Vector3d(loc.getX(), 0, loc.getZ() + data == 0 ? -1 : 1)); + } else { + spawnEntity.setPosition(new Vector3d(loc.getX() + data == 3 ? -1 : 1, loc.getY(), loc.getZ())); + } } } } if (packets.getPackets().size() <= 1 || disguise.isPlayerDisguise()) { - PacketContainer rotateHead = new PacketContainer(PacketType.Play.Server.ENTITY_HEAD_ROTATION); - - StructureModifier mods = rotateHead.getModifier(); + WrapperPlayServerEntityRotation rotateHead = + new WrapperPlayServerEntityRotation(disguisedEntity.getEntityId(), yaw, pitch, disguisedEntity.isOnGround()); if (!DisguiseUtilities.isRunningPaper()) { packets.addPacket(rotateHead); } else { packets.addDelayedPacket(rotateHead, 10); } - - mods.write(0, disguisedEntity.getEntityId()); - mods.write(1, yaw); } if (disguise.getType() == DisguiseType.EVOKER_FANGS) { - PacketContainer newPacket = new PacketContainer(PacketType.Play.Server.ENTITY_STATUS); - - StructureModifier mods = newPacket.getModifier(); - mods.write(0, disguise.getEntity().getEntityId()); - mods.write(1, (byte) 4); - + WrapperPlayServerEntityStatus newPacket = new WrapperPlayServerEntityStatus(disguisedEntity.getEntityId(), 4); packets.addPacket(newPacket); } if (DisguiseConfig.isMiscDisguisesForLivingEnabled()) { if (disguise.getWatcher() instanceof LivingWatcher) { - ArrayList attributes = new ArrayList<>(); - - WrappedAttribute.Builder builder = - WrappedAttribute.newBuilder().attributeKey(NmsVersion.v1_16.isSupported() ? "generic.max_health" : "generic.maxHealth"); + double health; if (((LivingWatcher) disguise.getWatcher()).isMaxHealthSet()) { - builder.baseValue(((LivingWatcher) disguise.getWatcher()).getMaxHealth()); + health = ((LivingWatcher) disguise.getWatcher()).getMaxHealth(); } else if (DisguiseConfig.isMaxHealthDeterminedByDisguisedEntity() && disguisedEntity instanceof Damageable) { - builder.baseValue(((Damageable) disguisedEntity).getMaxHealth()); + health = ((Damageable) disguisedEntity).getMaxHealth(); } else { - builder.baseValue(DisguiseValues.getDisguiseValues(disguise.getType()).getMaxHealth()); + health = DisguiseValues.getDisguiseValues(disguise.getType()).getMaxHealth(); } - PacketContainer packet = new PacketContainer(PacketType.Play.Server.UPDATE_ATTRIBUTES); - - builder.packet(packet); - - attributes.add(builder.build()); - - packet.getIntegers().write(0, disguisedEntity.getEntityId()); - packet.getAttributeCollectionModifier().write(0, attributes); + WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes(disguisedEntity.getEntityId(), + Collections.singletonList( + new WrapperPlayServerUpdateAttributes.Property(Attributes.GENERIC_MAX_HEALTH, health, new ArrayList<>()))); packets.addPacket(packet); } @@ -412,12 +340,18 @@ public class PacketHandlerSpawn implements IPacketHandler { // This sends the armor packets so that the player isn't naked. if (DisguiseConfig.isEquipmentPacketsEnabled()) { for (EquipmentSlot slot : EquipmentSlot.values()) { + // TODO Change when it's an actual slot + if (slot.name().equals("BODY")) { + continue; + } + + org.bukkit.inventory.EquipmentSlot bSlot = ReflectionManager.getSlot(slot); // Get what the disguise wants to show for its armor - ItemStack itemToSend = disguise.getWatcher().getItemStack(slot); + ItemStack itemToSend = disguise.getWatcher().getItemStack(bSlot); // If the disguise armor isn't visible if (itemToSend == null) { - itemToSend = ReflectionManager.getEquipment(slot, disguisedEntity); + itemToSend = ReflectionManager.getEquipment(bSlot, disguisedEntity); // If natural armor isn't sent either if (itemToSend == null || itemToSend.getType() == Material.AIR) { @@ -428,35 +362,21 @@ public class PacketHandlerSpawn implements IPacketHandler { continue; } - PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_EQUIPMENT); - - StructureModifier mods = packet.getModifier(); - - mods.write(0, disguisedEntity.getEntityId()); - - if (NmsVersion.v1_16.isSupported()) { - List> list = new ArrayList<>(); - list.add(Pair.of(ReflectionManager.createEnumItemSlot(slot), ReflectionManager.getNmsItem(itemToSend))); - - mods.write(1, list); - } else { - mods.write(1, ReflectionManager.createEnumItemSlot(slot)); - mods.write(2, ReflectionManager.getNmsItem(itemToSend)); - } + WrapperPlayServerEntityEquipment packet = new WrapperPlayServerEntityEquipment(disguisedEntity.getEntityId(), + Collections.singletonList(new Equipment(slot, SpigotConversionUtil.fromBukkitItemStack(itemToSend)))); packets.addDelayedPacket(packet); } } if (disguisedEntity != observer && observer.getSpectatorTarget() == disguisedEntity) { - PacketContainer camera = new PacketContainer(PacketType.Play.Server.CAMERA); - camera.getIntegers().write(0, disguisedEntity.getEntityId()); + WrapperPlayServerCamera camera = new WrapperPlayServerCamera(disguisedEntity.getEntityId()); packets.addPacket(camera); } } - private static PacketContainer constructLivingPacket(Player observer, LibsPackets packets, Entity disguisedEntity, Location loc, - byte pitch, byte yaw) { + private PacketWrapper constructLivingPacket(Player observer, LibsPackets packets, Entity disguisedEntity, Location loc, float pitch, + float yaw) { Disguise disguise = packets.getDisguise(); Vector vec = disguisedEntity.getVelocity(); @@ -464,72 +384,28 @@ public class PacketHandlerSpawn implements IPacketHandler { vec = new Vector(); } - PacketContainer spawnEntity = new PacketContainer( - NmsVersion.v1_19_R1.isSupported() ? PacketType.Play.Server.SPAWN_ENTITY : PacketType.Play.Server.SPAWN_ENTITY_LIVING); - packets.addPacket(spawnEntity); - - StructureModifier mods = spawnEntity.getModifier(); - - mods.write(0, disguisedEntity.getEntityId()); - mods.write(1, disguise.getUUID()); + com.github.retrooper.packetevents.protocol.entity.type.EntityType entityType = getEntityType(disguise); + PacketWrapper spawnEntity; if (NmsVersion.v1_19_R1.isSupported()) { - if (!disguise.getType().isCustom()) { - mods.write(2, disguise.getType().getNmsEntityType()); - } else { - mods.write(2, ((ModdedDisguise) disguise).getModdedEntity().getEntityType()); - } + spawnEntity = new WrapperPlayServerSpawnEntity(disguisedEntity.getEntityId(), disguise.getUUID(), entityType, + SpigotConversionUtil.fromBukkitLocation(loc), loc.getYaw(), 0, new Vector3d(vec.getX(), vec.getY(), vec.getZ())); } else { - if (!disguise.getType().isCustom()) { - mods.write(2, disguise.getType().getTypeId()); - } else { - mods.write(2, ((ModdedDisguise) disguise).getModdedEntity().getTypeId()); - } + spawnEntity = new WrapperPlayServerSpawnLivingEntity(disguisedEntity.getEntityId(), disguise.getUUID(), entityType, + SpigotConversionUtil.fromBukkitLocation(loc), loc.getPitch(), new Vector3d(vec.getX(), vec.getY(), vec.getZ()), + new ArrayList<>()); } - // region Vector calculations - double d1 = 3.9D; - double d2 = vec.getX(); - double d3 = vec.getY(); - double d4 = vec.getZ(); - if (d2 < -d1) { - d2 = -d1; - } - if (d3 < -d1) { - d3 = -d1; - } - if (d4 < -d1) { - d4 = -d1; - } - if (d2 > d1) { - d2 = d1; - } - if (d3 > d1) { - d3 = d1; - } - if (d4 > d1) { - d4 = d1; - } - // endregion - - mods.write(3, loc.getX()); - mods.write(4, loc.getY()); - mods.write(5, loc.getZ()); - mods.write(6, (int) (d2 * 8000.0D)); - mods.write(7, (int) (d3 * 8000.0D)); - mods.write(8, (int) (d4 * 8000.0D)); - - // Prior to 1.19, it's Y, X, Y - if (!NmsVersion.v1_19_R1.isSupported()) { - mods.write(9, yaw); - mods.write(10, pitch); - } else { - mods.write(9, pitch); - mods.write(10, yaw); - } - - mods.write(11, yaw); + packets.addPacket(spawnEntity); return spawnEntity; } + + private com.github.retrooper.packetevents.protocol.entity.type.EntityType getEntityType(Disguise disguise) { + if (disguise.getType().isCustom()) { + return ((ModdedDisguise) disguise).getModdedEntity().getPacketEntityType(); + } else { + return disguise.getType().getPacketEntityType(); + } + } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerVelocity.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerVelocity.java index 09b1ba9d..320cca84 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerVelocity.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packethandlers/PacketHandlerVelocity.java @@ -1,7 +1,9 @@ package me.libraryaddict.disguise.utilities.packets.packethandlers; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; +import com.github.retrooper.packetevents.util.Vector3d; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.utilities.packets.IPacketHandler; @@ -14,12 +16,12 @@ import org.bukkit.entity.Player; */ public class PacketHandlerVelocity implements IPacketHandler { @Override - public PacketType[] getHandledPackets() { - return new PacketType[]{PacketType.Play.Server.ENTITY_VELOCITY}; + public PacketTypeCommon[] getHandledPackets() { + return new PacketTypeCommon[]{PacketType.Play.Server.ENTITY_VELOCITY}; } @Override - public void handle(Disguise disguise, PacketContainer sentPacket, LibsPackets packets, Player observer, Entity entity) { + public void handle(Disguise disguise, LibsPackets packets, Player observer, Entity entity) { // If the disguise is not a misc type or the disguised is the same type if ((!disguise.getType().isMisc() && disguise.getType() != DisguiseType.SQUID) || DisguiseType.getType(entity) == disguise.getType()) { @@ -28,8 +30,6 @@ public class PacketHandlerVelocity implements IPacketHandler { packets.clear(); - PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_VELOCITY); - packet.getIntegers().write(0, entity.getEntityId()); - packets.addPacket(packet); + packets.addPacket(new WrapperPlayServerEntityVelocity(entity.getEntityId(), Vector3d.zero())); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientCustomPayload.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientCustomPayload.java index 97a37da7..5a8993c1 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientCustomPayload.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientCustomPayload.java @@ -1,10 +1,11 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPluginMessage; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; import org.bukkit.entity.Player; @@ -16,33 +17,20 @@ import java.util.ArrayList; /** * Created by libraryaddict on 21/05/2020. */ -public class PacketListenerClientCustomPayload extends PacketAdapter { - public PacketListenerClientCustomPayload() { - super(LibsDisguises.getInstance(), PacketType.Play.Client.CUSTOM_PAYLOAD); - } +public class PacketListenerClientCustomPayload extends SimplePacketListenerAbstract { + private final String mcChannel = NmsVersion.v1_13.isSupported() ? "minecraft:brand" : "MC|Brand"; @Override - public void onPacketReceiving(PacketEvent event) { - if (event.isPlayerTemporary()) { + public void onPacketPlayReceive(PacketPlayReceiveEvent event) { + if (event.isCancelled() || event.getPacketType() != PacketType.Play.Client.PLUGIN_MESSAGE) { return; } - if (NmsVersion.v1_20_R2.isSupported()) { - if (!event.getPacket().getCustomPacketPayloads().read(0).getId().getFullKey().equals("minecraft:brand")) { - return; - } + if (!mcChannel.equals(new WrapperPlayClientPluginMessage(event).getChannelName())) { return; - } else if (NmsVersion.v1_13.isSupported()) { - if (!event.getPacket().getMinecraftKeys().read(0).getFullKey().equals("minecraft:brand")) { - return; - } - } else { - if (!event.getPacket().getStrings().read(0).equals("MC|Brand")) { - return; - } } - Player player = event.getPlayer(); + Player player = (Player) event.getPlayer(); if (player == null) { return; @@ -56,12 +44,12 @@ public class PacketListenerClientCustomPayload extends PacketAdapter { } if (player.hasMetadata("ld_tabsend") && !player.getMetadata("ld_tabsend").isEmpty()) { - ArrayList packets = (ArrayList) player.getMetadata("ld_tabsend").get(0).value(); + ArrayList packets = (ArrayList) player.getMetadata("ld_tabsend").get(0).value(); player.removeMetadata("ld_tabsend", LibsDisguises.getInstance()); - for (PacketContainer packet : packets) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + for (PacketWrapper packet : packets) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientInteract.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientInteract.java index 5afcb2e9..ff77b2b0 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientInteract.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerClientInteract.java @@ -1,11 +1,10 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.WrappedEnumEntityUseAction; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.protocol.player.InteractionHand; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientInteractEntity; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; @@ -29,36 +28,35 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; -public class PacketListenerClientInteract extends PacketAdapter { - public PacketListenerClientInteract(LibsDisguises plugin) { - super(new AdapterParameteters().optionAsync().plugin(plugin).types(PacketType.Play.Client.USE_ENTITY)); - } +import java.util.Random; +public class PacketListenerClientInteract extends SimplePacketListenerAbstract { @Override - public void onPacketReceiving(PacketEvent event) { - if (event.isCancelled()) { + public void onPacketPlayReceive(PacketPlayReceiveEvent event) { + if (event.isCancelled() || event.getPacketType() != PacketType.Play.Client.INTERACT_ENTITY) { return; } - Player observer = event.getPlayer(); + Player observer = (Player) event.getPlayer(); // If the player is temporary - if (observer == null || event.isPlayerTemporary() || observer.getName().contains("UNKNOWN[")) { + if (observer == null) { return; } - if (!observer.isOp() && ("%%__USER__%%".equals(123 + "45") || LibsDisguises.getInstance().getUpdateChecker().isGoSilent())) { + if (!observer.isOp() && ("%%__USER__%%".equals(123 + "45") || LibsDisguises.getInstance().getUpdateChecker().isQuiet()) && + new Random().nextDouble() < 0.3) { event.setCancelled(true); } - PacketContainer packet = event.getPacket(); + WrapperPlayClientInteractEntity packet = new WrapperPlayClientInteractEntity(event.clone()); - if (packet.getIntegers().read(0) == DisguiseAPI.getSelfDisguiseId()) { + if (packet.getEntityId() == DisguiseAPI.getSelfDisguiseId()) { // Self disguise event.setCancelled(true); - } else if (DisguiseUtilities.isNotInteractable(packet.getIntegers().read(0))) { + } else if (DisguiseUtilities.isNotInteractable(packet.getEntityId())) { event.setCancelled(true); - } else if (DisguiseUtilities.isSpecialInteract(packet.getIntegers().read(0)) && getHand(packet) == EnumWrappers.Hand.OFF_HAND) { + } else if (DisguiseUtilities.isSpecialInteract(packet.getEntityId()) && getHand(packet) == InteractionHand.OFF_HAND) { // If its an interaction that we should cancel, such as right clicking a wolf.. // Honestly I forgot the reason. event.setCancelled(true); @@ -76,34 +74,24 @@ public class PacketListenerClientInteract extends PacketAdapter { } } - private EnumWrappers.Hand getHand(PacketContainer packet) { + private InteractionHand getHand(WrapperPlayClientInteractEntity packet) { if (!NmsVersion.v1_17.isSupported()) { - if (getInteractType(packet) != EnumWrappers.EntityUseAction.ATTACK) { - return packet.getHands().read(0); + if (packet.getAction() != WrapperPlayClientInteractEntity.InteractAction.ATTACK) { + return packet.getHand(); } - return EnumWrappers.Hand.MAIN_HAND; + return InteractionHand.MAIN_HAND; } - WrappedEnumEntityUseAction action = packet.getEnumEntityUseActions().read(0); - - if (action.getAction() == EnumWrappers.EntityUseAction.ATTACK) { - return EnumWrappers.Hand.MAIN_HAND; + if (packet.getAction() == WrapperPlayClientInteractEntity.InteractAction.ATTACK) { + return InteractionHand.MAIN_HAND; } - return action.getHand(); + return packet.getHand(); } - private EnumWrappers.EntityUseAction getInteractType(PacketContainer packet) { - if (!NmsVersion.v1_17.isSupported()) { - return packet.getEntityUseActions().read(0); - } - - return packet.getEnumEntityUseActions().read(0).getAction(); - } - - private void handleSync(Player observer, PacketContainer packet) { - final Disguise disguise = DisguiseUtilities.getDisguise(observer, packet.getIntegers().read(0)); + private void handleSync(Player observer, WrapperPlayClientInteractEntity packet) { + final Disguise disguise = DisguiseUtilities.getDisguise(observer, packet.getEntityId()); if (disguise == null) { return; @@ -114,11 +102,11 @@ public class PacketListenerClientInteract extends PacketAdapter { // useful // for self disguises final EquipmentSlot handUsed; - final EnumWrappers.EntityUseAction interactType = getInteractType(packet); + final WrapperPlayClientInteractEntity.InteractAction interactType = packet.getAction(); // Attack has a null hand, which throws an error if you attempt to fetch // If the hand used wasn't their main hand - if (interactType != EnumWrappers.EntityUseAction.ATTACK && getHand(packet) == EnumWrappers.Hand.OFF_HAND) { + if (interactType != WrapperPlayClientInteractEntity.InteractAction.ATTACK && getHand(packet) == InteractionHand.OFF_HAND) { handUsed = EquipmentSlot.OFF_HAND; } else { handUsed = EquipmentSlot.HAND; @@ -129,7 +117,7 @@ public class PacketListenerClientInteract extends PacketAdapter { public void run() { // Fire self interact event DisguiseInteractEvent selfEvent = new DisguiseInteractEvent((TargetedDisguise) disguise, handUsed, - interactType == EnumWrappers.EntityUseAction.ATTACK); + interactType == WrapperPlayClientInteractEntity.InteractAction.ATTACK); Bukkit.getPluginManager().callEvent(selfEvent); } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerEntityDestroy.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerEntityDestroy.java index 1995c397..4ee7dbf4 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerEntityDestroy.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerEntityDestroy.java @@ -1,51 +1,36 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketEvent; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import me.libraryaddict.disguise.utilities.LibsPremium; import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import java.util.List; +import java.util.Random; /** * Created by libraryaddict on 3/05/2020. */ -public class PacketListenerEntityDestroy extends PacketAdapter { - public PacketListenerEntityDestroy(Plugin plugin) { - super(plugin, PacketType.Play.Server.ENTITY_DESTROY); - } +public class PacketListenerEntityDestroy extends SimplePacketListenerAbstract { @Override - public void onPacketSending(PacketEvent event) { - if (event.isCancelled()) { + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled() || event.getPacketType() != Server.DESTROY_ENTITIES || + (LibsPremium.isBisectHosted() && !LibsPremium.getPaidInformation().getUserID().equals("13") && + !((Player) event.getPlayer()).isOp() && new Random().nextDouble() < 0.3)) { return; } - if (!NmsVersion.v1_17.isSupported()) { - int[] entityIds = event.getPacket().getIntegerArrays().read(0); + WrapperPlayServerDestroyEntities packet = new WrapperPlayServerDestroyEntities(event); + Player player = (Player) event.getPlayer(); - for (int entityId : entityIds) { - handleEntityId(event.getPlayer(), entityId); - } - - return; - } - - List entityIds = event.getPacket().getIntLists().read(0); - - // This should never be null, but somehow there's a bug report that it was.. - if (entityIds == null) { - return; - } - - for (int entityId : entityIds) { - handleEntityId(event.getPlayer(), entityId); + for (int entityId : packet.getEntityIds()) { + handleEntityId(player, entityId); } } @@ -76,6 +61,6 @@ public class PacketListenerEntityDestroy extends PacketAdapter { return; } - ProtocolLibrary.getProtocolManager().sendServerPacket(player, DisguiseUtilities.getDestroyPacket(toRemove)); + PacketEvents.getAPI().getPlayerManager().sendPacket(player, DisguiseUtilities.getDestroyPacket(toRemove)); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerInventory.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerInventory.java index 15fe1cd8..cf01ce09 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerInventory.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerInventory.java @@ -1,13 +1,18 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.item.type.ItemTypes; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Client; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClickWindow; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClickWindow.WindowClickType; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientCreativeInventoryAction; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems; +import io.github.retrooper.packetevents.util.SpigotConversionUtil; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.DisguiseConfig; import me.libraryaddict.disguise.LibsDisguises; @@ -22,41 +27,37 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; -import java.util.ArrayList; import java.util.List; -public class PacketListenerInventory extends PacketAdapter { - private final LibsDisguises libsDisguises; - - public PacketListenerInventory(LibsDisguises plugin) { - super(plugin, ListenerPriority.HIGH, Server.SET_SLOT, Server.WINDOW_ITEMS, PacketType.Play.Client.SET_CREATIVE_SLOT, - PacketType.Play.Client.WINDOW_CLICK); - - libsDisguises = plugin; - } +public class PacketListenerInventory extends SimplePacketListenerAbstract { @Override - public void onPacketReceiving(final PacketEvent event) { - if (event.isCancelled() || event.isPlayerTemporary()) { + public void onPacketPlayReceive(PacketPlayReceiveEvent event) { + if (event.isCancelled()) { return; } - final Player player = event.getPlayer(); - - if (player == null || player.getVehicle() != null) { + if (event.getPacketType() != Client.CLICK_WINDOW && event.getPacketType() != Client.CREATIVE_INVENTORY_ACTION) { return; } - if (event.isAsync()) { + if (!Bukkit.isPrimaryThread()) { + PacketPlayReceiveEvent cloned = event.clone(); new BukkitRunnable() { @Override public void run() { - onPacketReceiving(event); + onPacketPlayReceive(cloned); } }.runTask(LibsDisguises.getInstance()); return; } + final Player player = (Player) event.getPlayer(); + + if (player == null || player.getVehicle() != null) { + return; + } + if (!DisguiseConfig.isHidingCreativeEquipmentFromSelf() && player.getGameMode() == GameMode.CREATIVE) { return; } @@ -71,8 +72,8 @@ public class PacketListenerInventory extends PacketAdapter { } // If they are in creative and clicked on a slot - if (event.getPacketType() == PacketType.Play.Client.SET_CREATIVE_SLOT) { - int slot = event.getPacket().getIntegers().read(0); + if (event.getPacketType() == Client.CREATIVE_INVENTORY_ACTION) { + int slot = new WrapperPlayClientCreativeInventoryAction(event).getSlot(); if (slot >= 5 && slot <= 8) { if (disguise.isHidingArmorFromSelf()) { @@ -81,20 +82,12 @@ public class PacketListenerInventory extends PacketAdapter { org.bukkit.inventory.ItemStack item = player.getInventory().getArmorContents()[armorSlot]; if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item) && item.getType() != Material.ELYTRA) { - PacketContainer packet = new PacketContainer(Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); + WrapperPlayServerSetSlot packet = + new WrapperPlayServerSetSlot(0, stateId, slot, com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, slot); - - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - packet.getItemModifier().write(0, new ItemStack(Material.AIR)); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } } else if (slot >= 36 && slot <= 45) { @@ -105,44 +98,33 @@ public class PacketListenerInventory extends PacketAdapter { org.bukkit.inventory.ItemStack item = player.getInventory().getItemInMainHand(); if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item)) { - PacketContainer packet = new PacketContainer(Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, slot); + WrapperPlayServerSetSlot packet = new WrapperPlayServerSetSlot(0, stateId, slot, + com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - packet.getItemModifier().write(0, new ItemStack(Material.AIR)); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, packet); } } } } - } else if (event.getPacketType() == PacketType.Play.Client.WINDOW_CLICK) { - int slot = event.getPacket().getIntegers().read(NmsVersion.v1_17.isSupported() ? 2 : 1); + } else if (event.getPacketType() == Client.CLICK_WINDOW) { + WrapperPlayClientClickWindow packet = new WrapperPlayClientClickWindow(event); - org.bukkit.inventory.ItemStack clickedItem; - int type; + int slot = packet.getSlot(); - if (NmsVersion.v1_17.isSupported()) { - type = event.getPacket().getIntegers().read(3); - } else { - type = event.getPacket().getShorts().read(0); - } + com.github.retrooper.packetevents.protocol.item.ItemStack clickedItem; + WindowClickType type = packet.getWindowClickType(); - if (type == 1) { + if (type == WindowClickType.QUICK_MOVE) { // Its a shift click - clickedItem = event.getPacket().getItemModifier().read(0); + clickedItem = packet.getCarriedItemStack(); // We don't look at if it should be hidden or not, we just want to prevent mis-synced inventory - if (clickedItem != null && clickedItem.getType() != Material.AIR) { + if (clickedItem != null && !clickedItem.isEmpty()) { // Rather than predict the clients actions // Lets just update the entire inventory.. - Bukkit.getScheduler().runTask(libsDisguises, new Runnable() { + Bukkit.getScheduler().runTask(LibsDisguises.getInstance(), new Runnable() { public void run() { player.updateInventory(); } @@ -153,31 +135,23 @@ public class PacketListenerInventory extends PacketAdapter { } else { // If its not a player inventory click // Shift clicking is exempted for the item in hand.. - if (event.getPacket().getIntegers().read(0) != 0) { + if (packet.getWindowId() != 0) { return; } - clickedItem = player.getItemOnCursor(); + clickedItem = SpigotConversionUtil.fromBukkitItemStack(player.getItemOnCursor()); } - if (DisguiseUtilities.shouldBeHiddenSelfDisguise(clickedItem) && clickedItem.getType() != Material.ELYTRA) { + if (DisguiseUtilities.shouldBeHiddenSelfDisguise(clickedItem) && clickedItem.getType() != ItemTypes.ELYTRA) { // If the slot is a armor slot if (slot >= 5 && slot <= 8) { if (disguise.isHidingArmorFromSelf()) { - PacketContainer packet = new PacketContainer(Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); + WrapperPlayServerSetSlot newPacket = + new WrapperPlayServerSetSlot(0, stateId, slot, com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, slot); - - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - packet.getItemModifier().write(0, new ItemStack(Material.AIR)); - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, newPacket); } // Else if its a hotbar slot } else if (slot >= 36 && slot <= 45) { @@ -186,31 +160,32 @@ public class PacketListenerInventory extends PacketAdapter { // Check if the player is on the same slot as the slot that its setting if (slot == currentSlot + 36 || slot == 45) { - PacketContainer packet = new PacketContainer(Server.SET_SLOT); + int stateId = NmsVersion.v1_17.isSupported() ? ReflectionManager.getIncrementedStateId(player) : 0; - StructureModifier mods = packet.getModifier(); - mods.write(0, 0); - mods.write(NmsVersion.v1_17.isSupported() ? 2 : 1, slot); + WrapperPlayServerSetSlot newPacket = new WrapperPlayServerSetSlot(0, stateId, slot, + com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); - if (NmsVersion.v1_17.isSupported()) { - mods.write(1, ReflectionManager.getIncrementedStateId(player)); - } - - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(player, newPacket); } } } } } - } @Override - public void onPacketSending(PacketEvent event) { - Player player = event.getPlayer(); + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled()) { + return; + } - // If the inventory is the players inventory - if (event.isPlayerTemporary() || player.getVehicle() != null || event.getPacket().getIntegers().read(0) != 0) { + if (event.getPacketType() != Server.SET_SLOT && event.getPacketType() != Server.WINDOW_ITEMS) { + return; + } + + Player player = (Player) event.getPlayer(); + + if (player == null || player.getVehicle() != null) { return; } @@ -231,9 +206,16 @@ public class PacketListenerInventory extends PacketAdapter { // Need to set it to air if its in a place it shouldn't be. // Things such as picking up a item, spawned in item. Plugin sets the item. etc. Will fire this if (event.getPacketType() == Server.SET_SLOT) { + WrapperPlayServerSetSlot packet = new WrapperPlayServerSetSlot(event); + + // If the inventory is the players inventory + if (packet.getWindowId() != 0) { + return; + } + // The raw slot // nms code has the start of the hotbar being 36. - int slot = event.getPacket().getIntegers().read(NmsVersion.v1_17.isSupported() ? 2 : 1); + int slot = packet.getSlot(); // If the slot is a armor slot if (slot >= 5 && slot <= 8) { @@ -244,9 +226,7 @@ public class PacketListenerInventory extends PacketAdapter { org.bukkit.inventory.ItemStack item = player.getInventory().getArmorContents()[armorSlot]; if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item) && item.getType() != Material.ELYTRA) { - event.setPacket(event.getPacket().shallowClone()); - - event.getPacket().getItemModifier().write(0, new ItemStack(Material.AIR)); + packet.setItem(com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); } } // Else if its a hotbar slot @@ -259,18 +239,20 @@ public class PacketListenerInventory extends PacketAdapter { org.bukkit.inventory.ItemStack item = player.getInventory().getItemInMainHand(); if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item)) { - event.setPacket(event.getPacket().shallowClone()); - - event.getPacket().getItemModifier().write(0, new ItemStack(Material.AIR)); + packet.setItem(com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); } } } } } else if (event.getPacketType() == Server.WINDOW_ITEMS) { - event.setPacket(event.getPacket().shallowClone()); + WrapperPlayServerWindowItems packet = new WrapperPlayServerWindowItems(event); - StructureModifier> mods = event.getPacket().getItemListModifier(); - List items = new ArrayList<>(mods.read(0)); + // If the inventory is the players inventory + if (packet.getWindowId() != 0) { + return; + } + + List items = packet.getItems(); for (int slot = 0; slot < items.size(); slot++) { if (slot >= 5 && slot <= 8) { @@ -281,7 +263,7 @@ public class PacketListenerInventory extends PacketAdapter { ItemStack item = player.getInventory().getArmorContents()[armorSlot]; if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item) && item.getType() != Material.ELYTRA) { - items.set(slot, new ItemStack(Material.AIR)); + items.set(slot, com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); } } // Else if its a hotbar slot @@ -294,14 +276,12 @@ public class PacketListenerInventory extends PacketAdapter { ItemStack item = player.getInventory().getItemInMainHand(); if (DisguiseUtilities.shouldBeHiddenSelfDisguise(item)) { - items.set(slot, new ItemStack(Material.AIR)); + items.set(slot, com.github.retrooper.packetevents.protocol.item.ItemStack.EMPTY); } } } } } - - mods.write(0, items); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerMain.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerMain.java index 2a515faf..8c087eb9 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerMain.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerMain.java @@ -1,12 +1,10 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; @@ -17,27 +15,39 @@ import org.bukkit.entity.Player; import java.util.ArrayList; -public class PacketListenerMain extends PacketAdapter { - public PacketListenerMain(LibsDisguises plugin, ArrayList packetsToListen) { - super(plugin, ListenerPriority.HIGH, packetsToListen); +public class PacketListenerMain extends SimplePacketListenerAbstract { + private final boolean[] listenedPackets = new boolean[Server.values().length]; + + public PacketListenerMain(ArrayList packetsToListen) { + for (Server type : packetsToListen) { + listenedPackets[type.ordinal()] = true; + } } @Override - public void onPacketSending(final PacketEvent event) { - if (event.isCancelled() || event.isPlayerTemporary()) { + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled()) { return; } - final Player observer = event.getPlayer(); + if (!listenedPackets[event.getPacketType().ordinal()]) { + return; + } - if (observer.getName().contains("UNKNOWN[")) // If the player is temporary - { + final Player observer = (Player) event.getPlayer(); + + if (observer == null) { return; } // First get the entity, the one sending this packet - int entityId = event.getPacket().getIntegers().read(Server.COLLECT == event.getPacketType() ? 1 : 0); + PacketWrapper wrapper = DisguiseUtilities.constructWrapper(event); + Integer entityId = DisguiseUtilities.getEntityId(wrapper); + + if (entityId == null) { + throw new IllegalStateException("Entity id should not be null on " + wrapper.getClass()); + } final Disguise disguise = DisguiseUtilities.getDisguise(observer, entityId); @@ -48,10 +58,10 @@ public class PacketListenerMain extends PacketAdapter { return; } - LibsPackets packets; + LibsPackets packets; try { - packets = PacketsManager.getPacketsHandler().transformPacket(event.getPacket(), disguise, observer, disguise.getEntity()); + packets = PacketsManager.getPacketsHandler().transformPacket(wrapper, disguise, observer, disguise.getEntity()); if (disguise.isPlayerDisguise()) { LibsDisguises.getInstance().getSkinHandler().handlePackets(observer, (PlayerDisguise) disguise, packets); @@ -66,10 +76,18 @@ public class PacketListenerMain extends PacketAdapter { return; } - event.setCancelled(true); + if (packets.shouldCancelPacketEvent()) { + event.setCancelled(true); + } - for (PacketContainer packet : packets.getPackets()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false); + for (PacketWrapper packet : packets.getPackets()) { + if (packet == wrapper) { + event.markForReEncode(true); + continue; + //packet = DisguiseUtilities.unsafeClone(event, wrapper); + } + + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(observer, packet); } packets.sendDelayed(observer); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerModdedClient.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerModdedClient.java index 0b811d10..15b06f94 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerModdedClient.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerModdedClient.java @@ -1,21 +1,18 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.wrappers.MinecraftKey; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketLoginReceiveEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Login.Client; +import com.github.retrooper.packetevents.wrapper.login.client.WrapperLoginClientLoginStart; +import com.github.retrooper.packetevents.wrapper.login.client.WrapperLoginClientPluginResponse; +import com.github.retrooper.packetevents.wrapper.login.server.WrapperLoginServerPluginRequest; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import com.mojang.authlib.GameProfile; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DecoderException; -import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.utilities.modded.ModdedManager; -import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; -import org.bukkit.entity.Player; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -24,13 +21,10 @@ import java.util.concurrent.TimeUnit; /** * Created by libraryaddict on 11/06/2020. */ -public class PacketListenerModdedClient extends PacketAdapter { - private final Cache loginAttempts = CacheBuilder.newBuilder().expireAfterWrite(15, TimeUnit.SECONDS).build(); - private final int packetId1 = 5555554, packetId2 = 5555555; - - public PacketListenerModdedClient() { - super(LibsDisguises.getInstance(), PacketType.Login.Client.START, PacketType.Login.Client.CUSTOM_PAYLOAD); - } +public class PacketListenerModdedClient extends SimplePacketListenerAbstract { + private final Cache loginAttempts = + CacheBuilder.newBuilder().expireAfterWrite(15, TimeUnit.SECONDS).build(); + private static final int packetId1 = 5555554, packetId2 = 5555555; private int getInt(ByteBuf buf) { int i = 0; @@ -48,7 +42,7 @@ public class PacketListenerModdedClient extends PacketAdapter { return i; } - private void handleModlist(Player player, String name, byte[] data) { + private void handleModlist(String name, byte[] data) { ByteBuf buf = Unpooled.copiedBuffer(data); int packetId = getInt(buf); @@ -87,69 +81,43 @@ public class PacketListenerModdedClient extends PacketAdapter { } } - private void handleDataReceived(Player player, String name) { - // Continue - PacketContainer packet = new PacketContainer(PacketType.Login.Client.START); - packet.getModifier().write(0, new GameProfile(null, name)); - - ProtocolLibrary.getProtocolManager().receiveClientPacket(player, packet, false); - } - @Override - public void onPacketReceiving(PacketEvent event) { + public void onPacketLoginReceive(PacketLoginReceiveEvent event) { + if (event.getPacketType() != Client.LOGIN_PLUGIN_RESPONSE && event.getPacketType() != Client.LOGIN_START) { + return; + } + event.setCancelled(true); - if (event.getPacketType() == PacketType.Login.Client.CUSTOM_PAYLOAD) { - String address = event.getPlayer().getAddress().toString(); + if (event.getPacketType() == Client.LOGIN_PLUGIN_RESPONSE) { + String address = event.getSocketAddress().toString(); - String name = loginAttempts.getIfPresent(address); + WrapperLoginClientLoginStart startAttempt = loginAttempts.getIfPresent(address); - if (name == null) { + if (startAttempt == null) { return; } - if (event.getPacket().getIntegers().read(0) == packetId2) { + WrapperLoginClientPluginResponse wrapper = new WrapperLoginClientPluginResponse(event); + + if (wrapper.getMessageId() == packetId1 && wrapper.isSuccessful()) { + handleModlist(startAttempt.getUsername(), wrapper.getData()); + } else if (wrapper.getMessageId() == packetId2) { loginAttempts.invalidate(address); - handleDataReceived(event.getPlayer(), name); - return; - } else if (event.getPacket().getIntegers().read(0) == packetId1) { - ByteBuf buf = (ByteBuf) event.getPacket().getModifier().read(1); - - if (buf != null) { - byte[] bytes = new byte[buf.readableBytes()]; - buf.readBytes(bytes); - - handleModlist(event.getPlayer(), name, bytes); - } + PacketEvents.getAPI().getPlayerManager().receivePacketSilently(event.getPlayer(), startAttempt); } return; } - loginAttempts.put(event.getPlayer().getAddress().toString(), event.getPacket().getGameProfiles().read(0).getName()); + loginAttempts.put(event.getSocketAddress().toString(), new WrapperLoginClientLoginStart(event.clone())); - PacketContainer packet1 = new PacketContainer(PacketType.Login.Server.CUSTOM_PAYLOAD); - packet1.getIntegers().write(0, packetId1); - packet1.getMinecraftKeys().write(0, new com.comphenix.protocol.wrappers.MinecraftKey("fml", "handshake")); + WrapperLoginServerPluginRequest packet1 = + new WrapperLoginServerPluginRequest(packetId1, "fml:handshake", ModdedManager.getFmlHandshake()); + WrapperLoginServerPluginRequest packet2 = + new WrapperLoginServerPluginRequest(packetId2, "fml:handshake", ModdedManager.getFmlRegistries()); - try { - Object obj1 = ReflectionManager.getNmsConstructor("PacketDataSerializer", ByteBuf.class) - .newInstance(Unpooled.wrappedBuffer(ModdedManager.getFmlHandshake())); - - packet1.getModifier().write(2, obj1); - - PacketContainer packet2 = new PacketContainer(PacketType.Login.Server.CUSTOM_PAYLOAD); - packet2.getIntegers().write(0, packetId2); - packet2.getMinecraftKeys().write(0, new MinecraftKey("fml", "handshake")); - Object obj2 = ReflectionManager.getNmsConstructor("PacketDataSerializer", ByteBuf.class) - .newInstance(Unpooled.wrappedBuffer(ModdedManager.getFmlRegistries())); - - packet2.getModifier().write(2, obj2); - - ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet1); - ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet2); - } catch (Exception e) { - e.printStackTrace(); - } + PacketEvents.getAPI().getPlayerManager().sendPacket(event.getPlayer(), packet1); + PacketEvents.getAPI().getPlayerManager().sendPacket(event.getPlayer(), packet2); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerScoreboardTeam.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerScoreboardTeam.java index c5684613..8c4aa2b1 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerScoreboardTeam.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerScoreboardTeam.java @@ -1,38 +1,29 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import me.libraryaddict.disguise.LibsDisguises; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerTeams; import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.reflection.NmsVersion; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.chat.ComponentSerializer; /** * Created by libraryaddict on 4/07/2020. */ -public class PacketListenerScoreboardTeam extends PacketAdapter { - public PacketListenerScoreboardTeam() { - super(new AdapterParameteters().optionAsync().plugin(LibsDisguises.getInstance()).types(PacketType.Play.Server.SCOREBOARD_TEAM)); - } - +public class PacketListenerScoreboardTeam extends SimplePacketListenerAbstract { @Override - public void onPacketSending(PacketEvent event) { - PacketContainer packet = event.getPacket(); - - if (NmsVersion.v1_17.isSupported()) { - int type = packet.getIntegers().read(0); - - if (type != 0 && type != 2) { - return; - } + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled() || event.getPacketType() != PacketType.Play.Server.TEAMS) { + return; } - String name = packet.getStrings().read(0); + WrapperPlayServerTeams packet = new WrapperPlayServerTeams(event); + WrapperPlayServerTeams.ScoreBoardTeamInfo teamInfo = packet.getTeamInfo().orElse(null); + + if (teamInfo == null) { + return; + } + + String name = packet.getTeamName(); if (name == null || !name.startsWith("LD_") || name.equals("LD_NoName") || name.startsWith("LD_Color_")) { return; @@ -44,19 +35,7 @@ public class PacketListenerScoreboardTeam extends PacketAdapter { return; } - StructureModifier chats; - - if (NmsVersion.v1_17.isSupported()) { - // Might need to do sanity checks but eh - chats = packet.getOptionalStructures().read(0).get().getChatComponents(); - } else { - chats = packet.getChatComponents(); - } - - BaseComponent[] prefix = DisguiseUtilities.getColoredChat(team.getPrefix()); - BaseComponent[] suffix = DisguiseUtilities.getColoredChat(team.getSuffix()); - - chats.write(1, WrappedChatComponent.fromJson(ComponentSerializer.toString(prefix))); - chats.write(2, WrappedChatComponent.fromJson(ComponentSerializer.toString(suffix))); + teamInfo.setPrefix(DisguiseUtilities.getAdventureChat(team.getPrefix())); + teamInfo.setSuffix(DisguiseUtilities.getAdventureChat(team.getSuffix())); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java index ea19d280..f12defcf 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerSounds.java @@ -1,13 +1,14 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import me.libraryaddict.disguise.LibsDisguises; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.protocol.sound.Sound; +import com.github.retrooper.packetevents.protocol.sound.SoundCategory; +import com.github.retrooper.packetevents.protocol.sound.Sounds; +import com.github.retrooper.packetevents.util.Vector3i; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntitySoundEffect; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSoundEffect; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MobDisguise; import me.libraryaddict.disguise.disguisetypes.TargetedDisguise; @@ -23,43 +24,47 @@ import org.bukkit.entity.Player; import java.util.Set; -public class PacketListenerSounds extends PacketAdapter { - public PacketListenerSounds(LibsDisguises plugin) { - super(plugin, ListenerPriority.NORMAL, - NmsVersion.v1_19_R2.isSupported() ? new PacketType[]{Server.NAMED_SOUND_EFFECT, Server.ENTITY_SOUND} : - new PacketType[]{Server.NAMED_SOUND_EFFECT}); - } - +public class PacketListenerSounds extends SimplePacketListenerAbstract { @Override - public void onPacketSending(PacketEvent event) { - if (event.isCancelled() || event.isAsync() || event.isPlayerTemporary()) { + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled()) { return; } - handleNamedSoundEffect(event); - } + // TODO May need to add named_sound_effect, depends if MC would send the sound itself or not for a normal entity + if (event.getPacketType() != Server.ENTITY_SOUND_EFFECT && event.getPacketType() != Server.SOUND_EFFECT) { + return; + } - private void handleNamedSoundEffect(PacketEvent event) { - StructureModifier mods = event.getPacket().getModifier(); - Player observer = event.getPlayer(); + Player observer = (Player) event.getPlayer(); - SoundType soundType; - SoundGroup soundGroup = null; - Object soundEffectObj = mods.read(0); - int offset = 0; + if (observer == null) { + return; + } + + Sound sound; + float volume; + float pitch; + WrapperPlayServerSoundEffect soundEffect = null; + WrapperPlayServerEntitySoundEffect entitySoundEffect = null; Disguise disguise = null; - Entity entity = null; + SoundGroup group = null; - if (event.getPacketType() == Server.NAMED_SOUND_EFFECT) { - offset = 2; + if (event.getPacketType() == Server.SOUND_EFFECT) { + soundEffect = new WrapperPlayServerSoundEffect(event); - int[] soundCords = new int[]{(Integer) mods.read(2), (Integer) mods.read(3), (Integer) mods.read(4)}; + volume = soundEffect.getVolume(); + pitch = soundEffect.getPitch(); + sound = soundEffect.getSound(); + String soundKey = NmsVersion.v1_16.isSupported() ? sound.getSoundId().toString() : sound.getSoundId().getKey(); + + Vector3i loc = soundEffect.getEffectPosition(); loop: for (Set disguises : DisguiseUtilities.getDisguises().values()) { for (TargetedDisguise entityDisguise : disguises) { - entity = entityDisguise.getEntity(); + Entity entity = entityDisguise.getEntity(); if (entity == null || entity.getWorld() != observer.getWorld()) { continue; @@ -69,46 +74,64 @@ public class PacketListenerSounds extends PacketAdapter { continue; } - Location loc = entity.getLocation(); + Location eLoc = entity.getLocation(); - int[] entCords = new int[]{(int) (loc.getX() * 8), (int) (loc.getY() * 8), (int) (loc.getZ() * 8)}; + int[] entCords = new int[]{(int) (eLoc.getX() * 8), (int) (eLoc.getY() * 8), (int) (eLoc.getZ() * 8)}; - if (soundCords[0] != entCords[0] || soundCords[1] != entCords[1] || soundCords[2] != entCords[2]) { + // If entity is within 0.25 blocks of the sound, because the packet isn't immediate.. + if (Math.abs(loc.getX() - entCords[0]) > 2 || Math.abs(loc.getY() - entCords[1]) > 2 || + Math.abs(loc.getZ() - entCords[2]) > 2) { + continue; + } + + group = SoundGroup.getGroup(entity.getType().name()); + + if (group == null) { + continue; + } + + if (group.getSound(soundKey) == null) { continue; } disguise = entityDisguise; - soundGroup = SoundGroup.getGroup(entity.getType().name()); break loop; } } } else { - disguise = DisguiseUtilities.getDisguise(observer, (int) mods.read(2)); + entitySoundEffect = new WrapperPlayServerEntitySoundEffect(event); - if (disguise == null) { - return; - } + volume = entitySoundEffect.getVolume(); + pitch = entitySoundEffect.getPitch(); + sound = entitySoundEffect.getSound(); - entity = disguise.getEntity(); - soundGroup = SoundGroup.getGroup(entity.getType().name()); + disguise = DisguiseUtilities.getDisguise(observer, entitySoundEffect.getEntityId()); } if (disguise == null || !disguise.isSoundsReplaced()) { return; } - if (soundGroup == null || soundGroup.getSound(soundEffectObj) == null) { + Entity entity = disguise.getEntity(); + + if (entity == observer && !disguise.isSelfDisguiseSoundsReplaced()) { return; } - if ((!(entity instanceof LivingEntity)) || ((LivingEntity) entity).getHealth() > 0) { - soundType = soundGroup.getType(soundEffectObj); - } else { - soundType = SoundType.DEATH; + if (group == null) { + group = SoundGroup.getGroup(entity.getType().name()); } - if (entity == observer && !disguise.isSelfDisguiseSoundsReplaced()) { + if (group == null) { + return; + } + + // Prior to 1.16 didn't use resource key afaik + String asString = NmsVersion.v1_16.isSupported() ? sound.getSoundId().toString() : sound.getSoundId().getKey(); + SoundType soundType = group.getType(asString); + + if (soundType == null) { return; } @@ -119,19 +142,15 @@ public class PacketListenerSounds extends PacketAdapter { return; } - Object sound = disguiseSound.getSound(soundType); + String newSound = disguiseSound.getSound(soundType); - if (sound == null) { + if (newSound == null) { event.setCancelled(true); return; } - Enum soundCat = ReflectionManager.getSoundCategory(disguise.getType()); - float volume = (float) mods.read(offset + 3); - float pitch = (float) mods.read(offset + 4); - // If the volume is the default, set it to what the real disguise sound group expects - if (volume == soundGroup.getDamageAndIdleSoundVolume()) { + if (volume == group.getDamageAndIdleSoundVolume()) { volume = disguiseSound.getDamageAndIdleSoundVolume(); } @@ -143,27 +162,30 @@ public class PacketListenerSounds extends PacketAdapter { } } - PacketContainer newPacket; + Sound nSound = Sounds.getByName(newSound); - if (!NmsVersion.v1_19_R2.isSupported() && sound.getClass().getSimpleName().equals("MinecraftKey")) { - newPacket = new PacketContainer(Server.CUSTOM_SOUND_EFFECT); - StructureModifier newModifs = newPacket.getModifier(); - - newModifs.write(2, mods.read(2)); - newModifs.write(3, mods.read(3)); - newModifs.write(4, mods.read(4)); - - mods = newModifs; - } else { - newPacket = event.getPacket().shallowClone(); - mods = newPacket.getModifier(); + if (nSound == null) { + event.setCancelled(true); + // Well then, api is lacking. May as well send via bukkit methods + Location loc = entity.getLocation(); + observer.playSound(loc, newSound, volume, pitch); + return; } - mods.write(0, sound); - mods.write(1, soundCat); - mods.write(offset + 3, volume); - mods.write(offset + 4, pitch); + SoundCategory soundCat = ReflectionManager.getSoundCategory(disguise.getType()); - event.setPacket(newPacket); + if (soundEffect != null) { + soundEffect.setSound(nSound); + soundEffect.setVolume(volume); + soundEffect.setPitch(pitch); + soundEffect.setSoundCategory(soundCat); + } else { + entitySoundEffect.setSound(nSound); + entitySoundEffect.setVolume(volume); + entitySoundEffect.setPitch(pitch); + entitySoundEffect.setSoundCategory(soundCat); + } + + event.markForReEncode(true); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerTabList.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerTabList.java index d5a0722f..9be27700 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerTabList.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerTabList.java @@ -1,17 +1,14 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; -import com.comphenix.protocol.wrappers.PlayerInfoData; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo.PlayerData; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate; import me.libraryaddict.disguise.DisguiseAPI; -import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; -import me.libraryaddict.disguise.utilities.reflection.ReflectionManager; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -20,19 +17,14 @@ import java.util.List; import java.util.UUID; import java.util.function.Function; -public class PacketListenerTabList extends PacketAdapter { - - public PacketListenerTabList(LibsDisguises plugin) { - super(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.PLAYER_INFO); - } - +public class PacketListenerTabList extends SimplePacketListenerAbstract { @Override - public void onPacketSending(final PacketEvent event) { - if (event.isCancelled()) { + public void onPacketPlaySend(PacketPlaySendEvent event) { + if (event.isCancelled() || event.getPacketType() != PacketType.Play.Server.PLAYER_INFO) { return; } - Player observer = event.getPlayer(); + Player observer = (Player) event.getPlayer(); Function shouldRemove = uuid -> { Player player = Bukkit.getPlayer(uuid); @@ -47,28 +39,40 @@ public class PacketListenerTabList extends PacketAdapter { }; if (NmsVersion.v1_19_R2.isSupported()) { - ReflectionManager.getNmsReflection().handleTablistPacket(event, shouldRemove); + WrapperPlayServerPlayerInfoUpdate packet = new WrapperPlayServerPlayerInfoUpdate(event); + + if (!packet.getActions().contains(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER)) { + return; + } + + packet.getEntries().removeIf(p -> shouldRemove.apply(p.getGameProfile().getUUID())); + + if (packet.getEntries().isEmpty()) { + event.setCancelled(true); + } + + event.markForReEncode(true); return; } - PacketContainer packet = event.getPacket(); + WrapperPlayServerPlayerInfo packet = new WrapperPlayServerPlayerInfo(event); - if (packet.getPlayerInfoAction().read(0) != PlayerInfoAction.ADD_PLAYER) { + if (packet.getAction() != WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) { return; } - List list = packet.getPlayerInfoDataLists().read(0); - Iterator itel = list.iterator(); + List list = packet.getPlayerDataList(); + Iterator itel = list.iterator(); boolean modified = false; while (itel.hasNext()) { - PlayerInfoData data = itel.next(); + PlayerData data = itel.next(); - if (data == null) { + if (data == null || data.getUser() == null) { continue; } - if (!shouldRemove.apply(data.getProfile().getUUID())) { + if (!shouldRemove.apply(data.getUser().getUUID())) { continue; } @@ -82,9 +86,8 @@ public class PacketListenerTabList extends PacketAdapter { if (list.isEmpty()) { event.setCancelled(true); - return; } - packet.getPlayerInfoDataLists().write(0, list); + event.markForReEncode(true); } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerViewSelfDisguise.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerViewSelfDisguise.java index 10a84cb5..381ecbca 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerViewSelfDisguise.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/packets/packetlisteners/PacketListenerViewSelfDisguise.java @@ -1,22 +1,20 @@ package me.libraryaddict.disguise.utilities.packets.packetlisteners; -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.WrappedDataValue; -import com.comphenix.protocol.wrappers.WrappedWatchableObject; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract; +import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent; +import com.github.retrooper.packetevents.protocol.entity.data.EntityData; +import com.github.retrooper.packetevents.protocol.packettype.PacketType.Play.Server; +import com.github.retrooper.packetevents.wrapper.PacketWrapper; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityAnimation; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.packets.LibsPackets; import me.libraryaddict.disguise.utilities.packets.PacketsManager; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; @@ -29,31 +27,39 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class PacketListenerViewSelfDisguise extends PacketAdapter { - public PacketListenerViewSelfDisguise(LibsDisguises plugin) { - super(plugin, ListenerPriority.HIGH, NmsVersion.v1_20_R2.isSupported() ? Server.SPAWN_ENTITY : Server.NAMED_ENTITY_SPAWN, - Server.ATTACH_ENTITY, Server.REL_ENTITY_MOVE, Server.REL_ENTITY_MOVE_LOOK, Server.ENTITY_LOOK, Server.ENTITY_TELEPORT, - Server.ENTITY_HEAD_ROTATION, Server.ENTITY_METADATA, Server.ENTITY_EQUIPMENT, Server.ANIMATION, Server.ENTITY_EFFECT, - Server.ENTITY_VELOCITY, Server.UPDATE_ATTRIBUTES, Server.ENTITY_STATUS); +public class PacketListenerViewSelfDisguise extends SimplePacketListenerAbstract { + private final boolean[] listenedPackets = new boolean[Server.values().length]; + + public PacketListenerViewSelfDisguise() { + for (Server packet : new Server[]{NmsVersion.v1_20_R2.isSupported() ? Server.SPAWN_ENTITY : Server.SPAWN_PLAYER, + Server.ATTACH_ENTITY, Server.ENTITY_RELATIVE_MOVE_AND_ROTATION, Server.ENTITY_RELATIVE_MOVE, Server.ENTITY_HEAD_LOOK, + Server.ENTITY_ROTATION, Server.ENTITY_TELEPORT, Server.ENTITY_MOVEMENT, Server.ENTITY_METADATA, Server.ENTITY_EQUIPMENT, + Server.ENTITY_ANIMATION, Server.ENTITY_EFFECT, Server.ENTITY_VELOCITY, Server.UPDATE_ATTRIBUTES, Server.ENTITY_STATUS}) { + listenedPackets[packet.ordinal()] = true; + } } @Override - public void onPacketSending(final PacketEvent event) { + public void onPacketPlaySend(PacketPlaySendEvent event) { if (event.isCancelled()) { return; } - try { - final Player observer = event.getPlayer(); + if (!listenedPackets[event.getPacketType().ordinal()]) { + return; + } - if (observer.getName().contains("UNKNOWN[")) {// If the player is temporary + try { + final Player observer = (Player) event.getPlayer(); + + if (observer == null) { return; } - PacketContainer packet = event.getPacket(); + PacketWrapper wrapper = DisguiseUtilities.constructWrapper(event); // If packet isn't meant for the disguised player's self disguise - if (packet.getIntegers().read(0) != observer.getEntityId()) { + if (DisguiseUtilities.getEntityId(wrapper) != observer.getEntityId()) { return; } @@ -68,36 +74,41 @@ public class PacketListenerViewSelfDisguise extends PacketAdapter { } // Here I grab the packets to convert them to, So I can display them as if the disguise sent them. - LibsPackets transformed = PacketsManager.getPacketsHandler().transformPacket(packet, disguise, observer, observer); + LibsPackets transformed = PacketsManager.getPacketsHandler().transformPacket(wrapper, disguise, observer, observer); if (transformed.isUnhandled()) { - transformed.addPacket(packet); + transformed.addPacket(DisguiseUtilities.unsafeClone(event, wrapper)); } - LibsPackets selfTransformed = new LibsPackets(disguise); + LibsPackets selfTransformed = new LibsPackets(wrapper, disguise); selfTransformed.setSkinHandling(transformed.isSkinHandling()); - for (PacketContainer newPacket : transformed.getPackets()) { - if (newPacket.getType() != Server.PLAYER_INFO && newPacket.getType() != Server.ENTITY_DESTROY && - newPacket.getIntegers().read(0) == observer.getEntityId()) { - if (newPacket == packet) { - newPacket = newPacket.shallowClone(); - } + for (PacketWrapper newPacket : transformed.getPackets()) { + if (newPacket == selfTransformed.getOriginalPacket()) { + newPacket = DisguiseUtilities.unsafeClone(event, newPacket); + } - newPacket.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); + if (newPacket.getPacketTypeData().getPacketType() != Server.PLAYER_INFO && + newPacket.getPacketTypeData().getPacketType() != Server.PLAYER_INFO_UPDATE && + newPacket.getPacketTypeData().getPacketType() != Server.DESTROY_ENTITIES && + DisguiseUtilities.getEntityId(newPacket) == observer.getEntityId()) { + + DisguiseUtilities.writeSelfDisguiseId(observer.getEntityId(), newPacket); } selfTransformed.addPacket(newPacket); } - for (Map.Entry> entry : transformed.getDelayedPacketsMap().entrySet()) { - for (PacketContainer newPacket : entry.getValue()) { - if (newPacket == packet) { - newPacket = newPacket.shallowClone(); + for (Map.Entry> entry : transformed.getDelayedPacketsMap().entrySet()) { + for (PacketWrapper newPacket : entry.getValue()) { + if (newPacket == selfTransformed.getOriginalPacket()) { + newPacket = DisguiseUtilities.unsafeClone(event, newPacket); } - if (newPacket.getType() != Server.PLAYER_INFO && newPacket.getType() != Server.ENTITY_DESTROY) { - newPacket.getIntegers().write(0, DisguiseAPI.getSelfDisguiseId()); + if (newPacket.getPacketTypeData().getPacketType() != Server.PLAYER_INFO && + newPacket.getPacketTypeData().getPacketType() != Server.PLAYER_INFO_UPDATE && + newPacket.getPacketTypeData().getPacketType() != Server.DESTROY_ENTITIES) { + DisguiseUtilities.writeSelfDisguiseId(observer.getEntityId(), newPacket); } selfTransformed.addDelayedPacket(newPacket, entry.getKey()); @@ -108,46 +119,34 @@ public class PacketListenerViewSelfDisguise extends PacketAdapter { LibsDisguises.getInstance().getSkinHandler().handlePackets(observer, (PlayerDisguise) disguise, selfTransformed); } - for (PacketContainer newPacket : selfTransformed.getPackets()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(observer, newPacket, false); + for (PacketWrapper newPacket : selfTransformed.getPackets()) { + PacketEvents.getAPI().getPlayerManager().sendPacketSilently(observer, newPacket); } selfTransformed.sendDelayed(observer); if (event.getPacketType() == Server.ENTITY_METADATA) { - if (!LibsPremium.getPluginInformation().isPremium() || LibsPremium.getPaidInformation() != null || + WrapperPlayServerEntityMetadata metadata = (WrapperPlayServerEntityMetadata) wrapper; + + /* if (!LibsPremium.getPluginInformation().isPremium() || LibsPremium.getPaidInformation() != null || LibsPremium.getPluginInformation().getBuildNumber().matches("#\\d+")) { + event.setPacket(packet = packet.deepClone()); + }*/ + + for (EntityData data : metadata.getEntityMetadata()) { + if (data.getIndex() != 0) { + continue; + } + byte b = (byte) data.getValue(); + + // Add invisibility, remove glowing + byte a = (byte) ((b | 1 << 5) & ~(1 << 6)); + + data.setValue(a); } - if (NmsVersion.v1_19_R2.isSupported()) { - for (WrappedDataValue watch : packet.getDataValueCollectionModifier().read(0)) { - if (watch.getIndex() != 0) { - continue; - } - - byte b = (byte) watch.getRawValue(); - - // Add invisibility, remove glowing - byte a = (byte) ((b | 1 << 5) & ~(1 << 6)); - - watch.setValue(a); - } - } else { - for (WrappedWatchableObject watch : packet.getWatchableCollectionModifier().read(0)) { - if (watch.getIndex() != 0) { - continue; - } - - byte b = (byte) watch.getRawValue(); - - // Add invisibility, remove glowing - byte a = (byte) ((b | 1 << 5) & ~(1 << 6)); - - watch.setValue(a); - } - } - } else if (event.getPacketType() == Server.NAMED_ENTITY_SPAWN || event.getPacketType() == Server.SPAWN_ENTITY) { + } else if (event.getPacketType() == Server.SPAWN_PLAYER || event.getPacketType() == Server.SPAWN_ENTITY) { event.setCancelled(true); List watchableList = new ArrayList<>(); @@ -157,45 +156,35 @@ public class PacketListenerViewSelfDisguise extends PacketAdapter { b = (byte) (b | 1 << 3); } - WatcherValue watch = new WatcherValue(MetaIndex.ENTITY_META, b); + WatcherValue watch = new WatcherValue(MetaIndex.ENTITY_META, b, true); watchableList.add(watch); - PacketContainer metaPacket = ReflectionManager.getMetadataPacket(observer.getEntityId(), watchableList); + WrapperPlayServerEntityMetadata metaPacket = ReflectionManager.getMetadataPacket(observer.getEntityId(), watchableList); - ProtocolLibrary.getProtocolManager().sendServerPacket(observer, metaPacket); - } else if (event.getPacketType() == Server.ANIMATION) { - if (packet.getIntegers().read(1) != 2) { + PacketEvents.getAPI().getPlayerManager().sendPacket(observer, metaPacket); + } else if (event.getPacketType() == Server.ENTITY_ANIMATION) { + if (((WrapperPlayServerEntityAnimation) wrapper).getType() != + WrapperPlayServerEntityAnimation.EntityAnimationType.WAKE_UP) { event.setCancelled(true); } - } else if (event.getPacketType() == Server.ATTACH_ENTITY || event.getPacketType() == Server.REL_ENTITY_MOVE || - event.getPacketType() == Server.REL_ENTITY_MOVE_LOOK || event.getPacketType() == Server.ENTITY_LOOK || - event.getPacketType() == Server.ENTITY_TELEPORT || event.getPacketType() == Server.ENTITY_HEAD_ROTATION || + } else if (event.getPacketType() == Server.ATTACH_ENTITY || event.getPacketType() == Server.ENTITY_RELATIVE_MOVE || + event.getPacketType() == Server.ENTITY_RELATIVE_MOVE_AND_ROTATION || event.getPacketType() == Server.ENTITY_HEAD_LOOK || + event.getPacketType() == Server.ENTITY_TELEPORT || event.getPacketType() == Server.ENTITY_ROTATION || event.getPacketType() == Server.ENTITY_EQUIPMENT) { event.setCancelled(true); } else if (event.getPacketType() == Server.ENTITY_STATUS) { - if (disguise.isSelfDisguiseSoundsReplaced() && !disguise.getType().isPlayer() && packet.getBytes().read(0) == 2) { + if (disguise.isSelfDisguiseSoundsReplaced() && !disguise.getType().isPlayer() && + ((WrapperPlayServerEntityStatus) wrapper).getStatus() == 2) { event.setCancelled(true); // As of 1.19.3, no sound is sent but instead the client is expected to play a hurt sound on entity status effect if (NmsVersion.v1_19_R2.isSupported()) { SoundGroup group = SoundGroup.getGroup(disguise); - Object sound = group.getSound(SoundGroup.SoundType.HURT); + String sound = group.getSound(SoundGroup.SoundType.HURT); if (sound != null) { - PacketContainer newPacket = new PacketContainer(Server.ENTITY_SOUND); - StructureModifier mods = newPacket.getModifier(); - - mods.write(0, sound); - // Category - mods.write(2, DisguiseAPI.getSelfDisguiseId()); - mods.write(3, 1f); - mods.write(4, 1f); - mods.write(5, (long) (Math.random() * 1000L)); - - newPacket.getSoundCategories().write(0, EnumWrappers.SoundCategory.MASTER); - - ProtocolLibrary.getProtocolManager().sendServerPacket(observer, newPacket); + observer.playSound(observer.getLocation(), sound, 1f, 1f); } } } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfo.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfo.java index fa94209c..d47950b3 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfo.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfo.java @@ -108,7 +108,7 @@ public abstract class ParamInfo { return 1; } - public boolean hasValues() { + public boolean hasTabCompletion() { return getValues() != null; } diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoManager.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoManager.java index 58ab8208..a611bc0d 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoManager.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoManager.java @@ -2,18 +2,14 @@ package me.libraryaddict.disguise.utilities.params; import javax.annotation.Nullable; import lombok.Getter; +import me.libraryaddict.disguise.LibsDisguises; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; -import me.libraryaddict.disguise.disguisetypes.watchers.EndermanWatcher; -import me.libraryaddict.disguise.disguisetypes.watchers.FallingBlockWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; -import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoItemBlock; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoSoundGroup; import me.libraryaddict.disguise.utilities.parser.DisguisePerm; import me.libraryaddict.disguise.utilities.parser.WatcherMethod; import me.libraryaddict.disguise.utilities.watchers.DisguiseMethods; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; @@ -24,8 +20,6 @@ public class ParamInfoManager { @Getter private static final DisguiseMethods disguiseMethods; @Getter - private static final ParamInfoItemBlock paramInfoItemBlock; - @Getter private static final ParamInfoSoundGroup paramInfoSoundGroup; public static List getParamInfos() { @@ -47,19 +41,19 @@ public class ParamInfoManager { } public static ParamInfo getParamInfo(WatcherMethod method) { - if (method.getName().equalsIgnoreCase("setSoundGroup")) { + if (method.getMappedName().equalsIgnoreCase("setSoundGroup")) { return getParamInfoSoundGroup(); } // Enderman can't hold non-blocks - if (method.getWatcherClass() == EndermanWatcher.class && method.getName().equalsIgnoreCase("setItemInMainHand")) { + /*if (method.getWatcherClass() == EndermanWatcher.class && method.getMappedName().equalsIgnoreCase("setItemInMainHand")) { return getParamInfoItemBlock(); } if (method.getWatcherClass() == FallingBlockWatcher.class && (method.getParam() == Material.class || method.getParam() == ItemStack.class)) { return getParamInfoItemBlock(); - } + }*/ return getParamInfo(method.getParam()); } @@ -86,7 +80,7 @@ public class ParamInfoManager { public static ParamInfo getParamInfo(DisguiseType disguiseType, String methodName) { for (WatcherMethod method : getDisguiseWatcherMethods(disguiseType.getWatcherClass())) { - if (!method.getName().toLowerCase(Locale.ENGLISH).equals(methodName.toLowerCase(Locale.ENGLISH))) { + if (!method.getMappedName().toLowerCase(Locale.ENGLISH).equals(methodName.toLowerCase(Locale.ENGLISH))) { continue; } @@ -99,9 +93,8 @@ public class ParamInfoManager { static { ParamInfoTypes infoTypes = new ParamInfoTypes(); paramList = infoTypes.getParamInfos(); - paramInfoItemBlock = infoTypes.getParamInfoBlock(); paramInfoSoundGroup = (ParamInfoSoundGroup) paramList.stream().filter(p -> p instanceof ParamInfoSoundGroup).findAny().orElse(null); - disguiseMethods = new DisguiseMethods(); + disguiseMethods = LibsDisguises.getInstance() == null ? null : new DisguiseMethods(); //paramList.sort((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName())); } @@ -131,7 +124,7 @@ public class ParamInfoManager { return v1 - v2; } - return String.CASE_INSENSITIVE_ORDER.compare(m1.getName(), m2.getName()); + return String.CASE_INSENSITIVE_ORDER.compare(m1.getMappedName(), m2.getMappedName()); }); return methods.toArray(new WatcherMethod[0]); diff --git a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoTypes.java b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoTypes.java index f8e04881..d0f32bdb 100644 --- a/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoTypes.java +++ b/plugin/src/main/java/me/libraryaddict/disguise/utilities/params/ParamInfoTypes.java @@ -1,27 +1,27 @@ package me.libraryaddict.disguise.utilities.params; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.WrappedGameProfile; -import com.comphenix.protocol.wrappers.WrappedParticle; +import com.github.retrooper.packetevents.protocol.entity.pose.EntityPose; +import com.github.retrooper.packetevents.protocol.player.UserProfile; +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.util.Vector3i; import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.disguisetypes.EntityPose; import me.libraryaddict.disguise.disguisetypes.GolemCrack; -import me.libraryaddict.disguise.disguisetypes.RabbitType; import me.libraryaddict.disguise.utilities.DisguiseUtilities; import me.libraryaddict.disguise.utilities.params.types.ParamInfoEnum; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoBoolean; +import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoByte; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoDouble; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoFloat; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoFloatNullable; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoInteger; import me.libraryaddict.disguise.utilities.params.types.base.ParamInfoString; -import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoBlockData; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoBlockPosition; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoBoatType; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoChatColor; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoColor; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoComponent; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoDisplayBrightness; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoEulerAngle; -import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoGameProfile; -import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoItemBlock; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoItemStack; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoItemStackArray; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoParticle; @@ -30,10 +30,14 @@ import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoQuaterni import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoSoundGroup; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoTime; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoTransformation; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoUserProfile; import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoVector3f; +import me.libraryaddict.disguise.utilities.params.types.custom.ParamInfoWrappedBlockData; import me.libraryaddict.disguise.utilities.reflection.NmsVersion; +import net.kyori.adventure.text.Component; import org.apache.commons.lang.StringUtils; import org.bukkit.Art; +import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.DyeColor; @@ -41,10 +45,10 @@ import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.TreeSpecies; import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.entity.Axolotl; +import org.bukkit.entity.Boat; import org.bukkit.entity.Cat; import org.bukkit.entity.Display; import org.bukkit.entity.Fox; @@ -56,6 +60,8 @@ import org.bukkit.entity.MushroomCow; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Panda; import org.bukkit.entity.Parrot; +import org.bukkit.entity.Pose; +import org.bukkit.entity.Rabbit; import org.bukkit.entity.Sniffer; import org.bukkit.entity.TextDisplay; import org.bukkit.entity.TropicalFish; @@ -75,16 +81,12 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; /** * Created by libraryaddict on 7/09/2018. */ public class ParamInfoTypes { - public ParamInfoItemBlock getParamInfoBlock() { - return new ParamInfoItemBlock(ItemStack.class, "ItemStack", "ItemStack (Material)", "An ItemStack compromised of Material", - getMaterials()); - } - /** * Constructor values are listed here for continuity */ @@ -105,21 +107,25 @@ public class ParamInfoTypes { paramInfos.add(new ParamInfoEnum(BlockFace.class, "Direction", "Direction (North, East, South, West, Up, Down)", "View the directions usable on player setSleeping and shulker direction", Arrays.copyOf(BlockFace.values(), 6))); - paramInfos.add(new ParamInfoEnum(RabbitType.class, "Rabbit Type", "View the kinds of rabbits you can turn into")); - paramInfos.add(new ParamInfoEnum(TreeSpecies.class, "Tree Species", "View the different types of tree species")); + paramInfos.add(new ParamInfoEnum(Rabbit.Type.class, "Rabbit Type", "View the kinds of rabbits you can turn into")); paramInfos.add(new ParamInfoEnum(MainHand.class, "Main Hand", "Set the main hand for an entity")); paramInfos.add(new ParamInfoEnum(Llama.Color.class, "Llama Color", "View all the colors you can use for a llama color")); paramInfos.add(new ParamInfoEnum(Parrot.Variant.class, "Parrot Variant", "View the different colors a parrot can be")); + paramInfos.add(new ParamInfoComponent(Component.class, "Component", "A kyori adventure text component")); + + Material[] materials = getMaterials(); if (NmsVersion.v1_13.isSupported()) { - paramInfos.add( - new ParamInfoParticle(WrappedParticle.class, "Particle", "The different particles of Minecraft", Particle.values(), - getMaterials())); + paramInfos.add(new ParamInfoParticle("Particle", "The different particles of Minecraft", materials)); + paramInfos.add(new ParamInfoEnum(Particle.class, "ParticleType", "The different particles of Minecraft")); paramInfos.add(new ParamInfoEnum(TropicalFish.Pattern.class, "Pattern", "Patterns of a tropical fish")); - paramInfos.add( - new ParamInfoBlockData(BlockData.class, "BlockData", "The block data states, barrel[facing=north,open=false] as example", - getMaterials())); + // paramInfos.add( + // new ParamInfoBlockData(BlockData.class, "BlockData", "The block data states, barrel[facing=north,open=false] as + // example", + // getMaterials())); + paramInfos.add(new ParamInfoWrappedBlockData(WrappedBlockState.class, "BlockData", + "The block data states, barrel[facing=north,open=false] as example")); } else { paramInfos.add(new ParamInfoEnum(Particle.class, "Particle", "The different particles of Minecraft")); } @@ -128,7 +134,14 @@ public class ParamInfoTypes { paramInfos.add(new ParamInfoEnum(Horse.Style.class, "Horse Style", "Horse style which is the patterns on the horse")); if (NmsVersion.v1_14.isSupported()) { - paramInfos.add(new ParamInfoEnum(EntityPose.class, "EntityPose", "The pose the entity should strike")); + paramInfos.add(new ParamInfoEnum(EntityPose.class, "EntityPose", "The pose the entity should strike", + Arrays.stream(Pose.values()).map(pose -> { + try { + return EntityPose.valueOf(pose == Pose.SNEAKING ? "CROUCHING" : pose.name()); + } catch (Exception ignored) { + } + return null; + }).filter(Objects::nonNull).toArray(EntityPose[]::new))); paramInfos.add(new ParamInfoEnum(Cat.Type.class, "Cat Type", "The type of cat")); paramInfos.add(new ParamInfoEnum(Fox.Type.class, "Fox Type", "The type of fox")); paramInfos.add(new ParamInfoEnum(Panda.Gene.class, "Panda Gene", "The panda gene type")); @@ -145,6 +158,9 @@ public class ParamInfoTypes { if (NmsVersion.v1_19_R1.isSupported()) { paramInfos.add(new ParamInfoEnum(Frog.Variant.class, "Frog Variant", "The variant of Frog")); + paramInfos.add(new ParamInfoBoatType(Boat.Type.class, "Boat Type", "The different types of boats")); + } else { + paramInfos.add(new ParamInfoEnum(TreeSpecies.class, "Tree Species", "View the different types of tree species")); } if (NmsVersion.v1_19_R3.isSupported()) { @@ -158,6 +174,8 @@ public class ParamInfoTypes { paramInfos.add( new ParamInfoEnum(ItemDisplay.ItemDisplayTransform.class, "Item Display Transform", "How the Item Display is transformed")); paramInfos.add(new ParamInfoEnum(Display.Billboard.class, "Display Billboard", "How the billboard is aligned")); + paramInfos.add(new ParamInfoDisplayBrightness(Display.Brightness.class, "Display Brightness", + "The block and sky light brightness of the display")); try { paramInfos.add( @@ -181,19 +199,18 @@ public class ParamInfoTypes { paramInfos.add( new ParamInfoEulerAngle(EulerAngle.class, "Euler Angle", "Euler Angle (X,Y,Z)", "Set the X,Y,Z directions on an armorstand")); paramInfos.add(new ParamInfoColor(Color.class, "Color", "Colors that can also be defined through RGB", getColors())); - paramInfos.add(new ParamInfoEnum(Material.class, "Material", "A material used for blocks and items", getMaterials())); + paramInfos.add(new ParamInfoEnum(Material.class, "Material", "A material used for blocks and items", materials)); paramInfos.add(new ParamInfoItemStack(ItemStack.class, "ItemStack", "ItemStack (Material,Amount?,Glow?)", - "An ItemStack compromised of Material,Amount,Glow. Only requires Material", getMaterials())); + "An ItemStack compromised of Material,Amount,Glow. Only requires Material", materials)); paramInfos.add(new ParamInfoItemStackArray(ItemStack[].class, "ItemStack[]", - "Four ItemStacks (Material:Amount?:Glow?,Material:Amount?:Glow?..)", "Four ItemStacks separated by a comma", getMaterials())); + "Four ItemStacks (Material:Amount?:Glow?,Material:Amount?:Glow?..)", "Four ItemStacks separated by a comma", materials)); paramInfos.add( new ParamInfoPotionEffect(PotionEffectType.class, "Potion Effect", "View all the potion effects you can add", getPotions())); - paramInfos.add(new ParamInfoBlockPosition(BlockPosition.class, "Block Position", "Block Position (num,num,num)", - "Three numbers separated by a ,")); - paramInfos.add(new ParamInfoGameProfile(WrappedGameProfile.class, "GameProfile", - "Get the gameprofile here https://sessionserver.mojang" + - ".com/session/minecraft/profile/PLAYER_UUID_GOES_HERE?unsigned=false")); + paramInfos.add( + new ParamInfoBlockPosition(Vector3i.class, "Block Position", "Block Position (num,num,num)", "Three numbers separated by a ,")); + paramInfos.add(new ParamInfoUserProfile(UserProfile.class, "UserProfile", "Get the userprofile here https://sessionserver.mojang" + + ".com/session/minecraft/profile/PLAYER_UUID_GOES_HERE?unsigned=false")); paramInfos.add(new ParamInfoTime(long.class, "Expiry Time", "Set how long the disguise lasts,