From 0aa08696563605760ad3d8bb12767b094ac316a1 Mon Sep 17 00:00:00 2001 From: darksaid98 Date: Tue, 1 Aug 2023 04:02:26 +0200 Subject: [PATCH] feat: native beam implementation --- build.gradle.kts | 7 +- .../conflict/battle/beam/CrystalLaser.java | 94 ++++ .../conflict/battle/beam/Laser.java | 226 ++++++++++ .../conflict/battle/beam/LaserType.java | 56 +++ .../conflict/battle/beam/Packets.java | 405 ++++++++++++++++++ .../conflict/battle/siege/SiegeRunnable.java | 5 +- 6 files changed, 786 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java create mode 100644 src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java create mode 100644 src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java create mode 100644 src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java diff --git a/build.gradle.kts b/build.gradle.kts index 1c9608d..88d3c77 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,7 @@ plugins { id("com.github.johnrengelman.shadow") version "8.1.1" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/ id("xyz.jpenilla.run-paper") version "2.1.0" // Adds runServer and runMojangMappedServer tasks for testing id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation + id("io.papermc.paperweight.userdev") version "1.5.5" // Used to develop internal plugins using Mojang mappings } group = "com.github.alathra.AlathranWars" @@ -49,16 +50,13 @@ repositories { dependencies { compileOnly("org.jetbrains:annotations:24.0.1") - compileOnly("io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT") + paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT") implementation("space.arim.morepaperlib:morepaperlib:0.4.3") implementation("com.github.milkdrinkers:simplixstorage:3.2.7") implementation("com.github.milkdrinkers:colorparser:2.0.0") { exclude(group = "net.kyori", module = "adventure-api") } - implementation("io.github.skytasul:guardianbeam:2.3.3") { - isTransitive = false - } compileOnly("com.github.MilkBowl:VaultAPI:1.7") @@ -118,7 +116,6 @@ tasks { reloc("dev.jorel.commandapi", "commandapi") reloc("com.zaxxer.hikari", "hikaricp") reloc("org.mariadb.jdbc", "mariadb") - reloc("fr.skytasul.guardianbeam", "guardianbeam") } runServer { diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java new file mode 100644 index 0000000..835d4fd --- /dev/null +++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java @@ -0,0 +1,94 @@ +/* +MIT License + +Copyright (c) 2021 SkytAsul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + +package com.github.alathra.AlathranWars.conflict.battle.beam; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.UUID; + +public class CrystalLaser extends Laser { + private final Object crystal; + private final int crystalID = Packets.generateEID(); + private Object createCrystalPacket; + private Object metadataPacketCrystal; + private final Object[] destroyPackets; + private final Object fakeCrystalDataWatcher; + + /** + * Creates a new Ender Crystal Laser instance + * + * @param start Location where laser will starts. The Crystal laser do not handle decimal number, it will be rounded to blocks. + * @param end Location where laser will ends. The Crystal laser do not handle decimal number, it will be rounded to blocks. + * @param duration Duration of laser in seconds (-1 if infinite) + * @param distance Distance where laser will be visible (-1 if infinite) + * @throws ReflectiveOperationException if a reflection exception occurred during Laser creation + * @see #start(Plugin) to start the laser + * @see #durationInTicks() to make the duration in ticks + * @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop + */ + public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException { + super(start, end, duration, distance); + + fakeCrystalDataWatcher = Packets.createFakeDataWatcher(); + Packets.setCrystalWatcher(fakeCrystalDataWatcher, end); + if (Packets.version < 17) { + crystal = null; + } else { + crystal = Packets.createCrystal(start, UUID.randomUUID(), crystalID); + } + metadataPacketCrystal = Packets.createPacketMetadata(crystalID, fakeCrystalDataWatcher); + + destroyPackets = Packets.createPacketsRemoveEntities(crystalID); + } + + private Object getCrystalSpawnPacket() throws ReflectiveOperationException { + if (createCrystalPacket == null) { + if (Packets.version < 17) { + createCrystalPacket = Packets.createPacketEntitySpawnNormal(start, Packets.crystalID, Packets.crystalType, crystalID); + } else { + createCrystalPacket = Packets.createPacketEntitySpawnNormal(crystal); + } + } + return createCrystalPacket; + } + + @Override + public LaserType getLaserType() { + return LaserType.ENDER_CRYSTAL; + } + + @Override + protected void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException { + Packets.sendPackets(p, getCrystalSpawnPacket()); + Packets.sendPackets(p, metadataPacketCrystal); + } + + @Override + protected void sendDestroyPackets(Player p) throws ReflectiveOperationException { + Packets.sendPackets(p, destroyPackets); + } +} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java new file mode 100644 index 0000000..933d913 --- /dev/null +++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java @@ -0,0 +1,226 @@ +/* +MIT License + +Copyright (c) 2021 SkytAsul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + +package com.github.alathra.AlathranWars.conflict.battle.beam; + +import com.github.alathra.AlathranWars.Main; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import space.arim.morepaperlib.scheduling.ScheduledTask; + +import java.time.Duration; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A whole class to create Guardian Lasers and Ender Crystal Beams using packets and reflection.
+ * Inspired by the API + * GuardianBeamAPI
+ * 1.9 -> 1.20 + * + * @author SkytAsul + * @version 2.3.3 + * @see GitHub repository + */ +public abstract class Laser { + protected final int distanceSquared; + protected final int duration; + protected boolean durationInTicks = false; + protected Location start; + protected Location end; + + protected Plugin plugin; + protected ScheduledTask task; + + protected Set show = ConcurrentHashMap.newKeySet(); + private final Set seen = new HashSet<>(); + + private final List executeEnd = new ArrayList<>(1); + + protected Laser(Location start, Location end, int duration, int distance) { + if (!Packets.enabled) + throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization."); + if (start.getWorld() != end.getWorld()) + throw new IllegalArgumentException("Locations do not belong to the same worlds."); + this.start = start; + this.end = end; + this.duration = duration; + distanceSquared = distance < 0 ? -1 : distance * distance; + } + + /** + * Adds a runnable to execute when the laser reaches its final duration + * + * @param runnable action to execute + * @return this {@link Laser} instance + */ + public Laser executeEnd(Runnable runnable) { + executeEnd.add(runnable); + return this; + } + + /** + * Makes the duration provided in the constructor passed as ticks and not seconds + * + * @return this {@link Laser} instance + */ + public Laser durationInTicks() { + durationInTicks = true; + return this; + } + + /** + * Starts this laser. + *

+ * It will make the laser visible for nearby players and start the countdown to the final duration. + *

+ * Once finished, it will destroy the laser and execute all runnables passed with {@link Laser#executeEnd}. + * + * @param plugin plugin used to start the task + */ + public void start(Plugin plugin) { + if (task != null) throw new IllegalStateException("Task already started"); +// if (runnable != null) throw new IllegalStateException("Task already started"); + this.plugin = plugin; + Runnable runnable = new BukkitRunnable() { + int time = 0; + + @Override + public void run() { + try { + if (time == duration) { + stop(); + return; + } + if (!durationInTicks || time % 20 == 0) { + for (Player p : start.getWorld().getPlayers()) { + if (isCloseEnough(p)) { + if (show.add(p)) { + sendStartPackets(p, !seen.add(p)); + } + } else if (show.remove(p)) { + sendDestroyPackets(p); + } + } + } + time++; + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + /*@Override + public synchronized void cancel() throws IllegalStateException { + super.cancel(); + runnable = null; + try { + for (Player p : show) { + sendDestroyPackets(p); + } + show.clear(); + executeEnd.forEach(Runnable::run); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + }*/ + }; +// main.runTaskTimerAsynchronously(plugin, 0L, durationInTicks ? 1L : 20L); +// Main.getPaperLib().scheduling().asyncScheduler().run(main); + task = Main.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L)); + } + + /** + * Stops this laser. + *

+ * This will destroy the laser for every player and start execute all runnables passed with {@link Laser#executeEnd} + */ + public synchronized void stop() { + if (task == null || task.isCancelled()) throw new IllegalStateException("Task not started"); + task.cancel(); + + try { + try { + for (Player p : show) { + sendDestroyPackets(p); + } + show.clear(); + executeEnd.forEach(Runnable::run); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } catch (IllegalStateException ignored) { + } + + + } + + /** + * Gets laser status. + * + * @return true if the laser is currently running + * (i.e. {@link #start} has been called and the duration is not over) + */ + public boolean isStarted() { + return task != null; + } + + /** + * Gets laser type. + * + * @return LaserType enum constant of this laser + */ + public abstract LaserType getLaserType(); + + /** + * Gets the start location of the laser. + * + * @return where exactly is the start position of the laser located + */ + public Location getStart() { + return start; + } + + /** + * Gets the end location of the laser. + * + * @return where exactly is the end position of the laser located + */ + public Location getEnd() { + return end; + } + + protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException; + + protected abstract void sendDestroyPackets(Player p) throws ReflectiveOperationException; + + protected boolean isCloseEnough(Player player) { + if (distanceSquared == -1) return true; + Location location = player.getLocation(); + return getStart().distanceSquared(location) <= distanceSquared || + getEnd().distanceSquared(location) <= distanceSquared; + } + +} \ No newline at end of file diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java new file mode 100644 index 0000000..1377f83 --- /dev/null +++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java @@ -0,0 +1,56 @@ +/* +MIT License + +Copyright (c) 2021 SkytAsul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + +package com.github.alathra.AlathranWars.conflict.battle.beam; + +import org.bukkit.Location; +import org.bukkit.plugin.Plugin; + +public enum LaserType { + /** + * Represents a laser from an Ender Crystal entity. + *

+ * Start and end locations are automatically rounded to integers (block locations). + */ + ENDER_CRYSTAL; + + /** + * Creates a new Laser instance, {@link CrystalLaser} depending on this enum value. + * + * @param start Location where laser will starts + * @param end Location where laser will ends + * @param duration Duration of laser in seconds (-1 if infinite) + * @param distance Distance where laser will be visible + * @throws ReflectiveOperationException if a reflection exception occurred during Laser creation + * @see Laser#start(Plugin) to start the laser + * @see Laser#durationInTicks() to make the duration in ticks + * @see Laser#executeEnd(Runnable) to add Runnable-s to execute when the laser will stop + */ + public Laser create(Location start, Location end, int duration, int distance) throws ReflectiveOperationException { + if (this == LaserType.ENDER_CRYSTAL) { + return new CrystalLaser(start, end, duration, distance); + } + throw new IllegalStateException(); + } +} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java new file mode 100644 index 0000000..b93711a --- /dev/null +++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java @@ -0,0 +1,405 @@ +/* +MIT License + +Copyright (c) 2021 SkytAsul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + +package com.github.alathra.AlathranWars.conflict.battle.beam; + +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.animal.Squid; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +class Packets { + public static boolean enabled = false; + private static Logger logger; + static int version; + private static int versionMinor; + private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + private static final String cpack = Bukkit.getServer().getClass().getPackage().getName() + "."; + + static final int crystalID = 51; // pre-1.13 + + static Object crystalType; + + private static Constructor crystalConstructor; + + private static Object watcherObject4; // crystal target + private static Object watcherObject5; // crystal base plate + + private static Constructor watcherConstructor; + private static Method watcherSet; + private static Method watcherRegister; + private static Method watcherDirty; + private static Method watcherPack; + + private static Constructor blockPositionConstructor; + + private static Constructor packetSpawnNormal; + private static Constructor packetRemove; + private static Constructor packetMetadata; + + private static Method getHandle; + private static Field playerConnection; + private static Method sendPacket; + private static Method setUUID; + private static Method setID; + + private static Object fakeSquid; + + private static Object nmsWorld; + + static { + try { + logger = new Logger("GuardianBeam", null) { + @Override + public void log(LogRecord logRecord) { + logRecord.setMessage("[GuardianBeam] " + logRecord.getMessage()); + super.log(logRecord); + } + }; + logger.setParent(Bukkit.getServer().getLogger()); + logger.setLevel(Level.ALL); + + // e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1 + String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_"); + version = Integer.parseInt(versions[1]); // 1.X + if (version >= 17) { + // e.g. Bukkit.getBukkitVersion() -> 1.17.1-R0.1-SNAPSHOT + versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\."); + versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]); + } else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y +// logger.info("Found server version 1." + version + "." + versionMinor); + + ProtocolMappings mappings = ProtocolMappings.getMappings(version); + if (mappings == null) { + mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1]; +// logger.warning("Loaded not matching version of the mappings for your server version (1." + version + "." + versionMinor + ")"); + } +// logger.info("Loaded mappings " + mappings.name()); + + Class entityTypesClass = EntityType.class; + Class entityClass = Entity.class; + Class crystalClass = EndCrystal.class; + Class squidClass = Squid.class; + // invisilibity + Object watcherObject1 = getField(entityClass, mappings.getWatcherFlags(), null); + watcherObject4 = getField(crystalClass, mappings.getWatcherTargetLocation(), null); + watcherObject5 = getField(crystalClass, mappings.getWatcherBasePlate(), null); + + if (version >= 13) { + crystalType = entityTypesClass.getDeclaredField(mappings.getCrystalTypeName()).get(null); + } + + Class dataWatcherClass = getNMSClass("network.syncher", "DataWatcher"); + watcherConstructor = dataWatcherClass.getDeclaredConstructor(entityClass); + if (version >= 18) { + watcherSet = dataWatcherClass.getDeclaredMethod("b", watcherObject1.getClass(), Object.class); + watcherRegister = dataWatcherClass.getDeclaredMethod("a", watcherObject1.getClass(), Object.class); + } else { + watcherSet = getMethod(dataWatcherClass, "set"); + watcherRegister = getMethod(dataWatcherClass, "register"); + } + if (version >= 15) watcherDirty = getMethod(dataWatcherClass, "markDirty"); + if (version > 19 || (version == 19 && versionMinor >= 3)) + watcherPack = dataWatcherClass.getDeclaredMethod("b"); + packetSpawnNormal = getNMSClass("network.protocol.game", "PacketPlayOutSpawnEntity").getDeclaredConstructor(version < 17 ? new Class[0] : new Class[]{getNMSClass("world.entity", "Entity")}); + packetRemove = getNMSClass("network.protocol.game", "PacketPlayOutEntityDestroy").getDeclaredConstructor(version == 17 && versionMinor == 0 ? int.class : int[].class); + packetMetadata = getNMSClass("network.protocol.game", "PacketPlayOutEntityMetadata") + .getDeclaredConstructor(version < 19 || (version == 19 && versionMinor < 3) + ? new Class[]{int.class, dataWatcherClass, boolean.class} + : new Class[]{int.class, List.class}); + + blockPositionConstructor = + getNMSClass("core", "BlockPosition").getConstructor(int.class, int.class, int.class); + + nmsWorld = Class.forName(cpack + "CraftWorld").getDeclaredMethod("getHandle").invoke(Bukkit.getWorlds().get(0)); + + Constructor squidConstructor = squidClass.getDeclaredConstructors()[0]; + if (version >= 17) { + crystalConstructor = crystalClass.getDeclaredConstructor(nmsWorld.getClass().getSuperclass(), double.class, double.class, double.class); + } + + Object[] entityConstructorParams = version < 14 ? new Object[]{nmsWorld} : new Object[]{entityTypesClass.getDeclaredField(mappings.getSquidTypeName()).get(null), nmsWorld}; + fakeSquid = squidConstructor.newInstance(entityConstructorParams); + Object fakeSquidWatcher = createFakeDataWatcher(); + tryWatcherSet(fakeSquidWatcher, watcherObject1, (byte) 32); + + getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle"); + playerConnection = getNMSClass("server.level", "EntityPlayer") + .getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c")); + sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(version < 18 ? "sendPacket" : "a", getNMSClass("network.protocol", "Packet")); + + if (version >= 17) { + setUUID = entityClass.getDeclaredMethod("a_", UUID.class); + setID = entityClass.getDeclaredMethod("e", int.class); + } + + enabled = true; + } catch (Exception e) { + e.printStackTrace(); + String errorMsg = "Laser Beam reflection failed to initialize. The util is disabled. Please ensure your version (" + Bukkit.getServer().getClass().getPackage().getName() + ") is supported."; + if (logger == null) + System.err.println(errorMsg); + else + logger.severe(errorMsg); + } + } + + static int generateEID() { + return Entity.nextEntityId(); + } + + public static void sendPackets(Player p, Object... packets) throws ReflectiveOperationException { + Object connection = playerConnection.get(getHandle.invoke(p)); + for (Object packet : packets) { + if (packet == null) continue; + sendPacket.invoke(connection, packet); + } + } + + public static Object createFakeDataWatcher() throws ReflectiveOperationException { + Object watcher = watcherConstructor.newInstance(fakeSquid); + if (version > 13) setField(watcher, "registrationLocked", false); + return watcher; + } + + public static Object createCrystal(Location location, UUID uuid, int id) throws ReflectiveOperationException { + Object entity = crystalConstructor.newInstance(nmsWorld, location.getX(), location.getY(), location.getZ()); + setEntityIDs(entity, uuid, id); + return entity; + } + + public static Object createPacketEntitySpawnNormal(Location location, int typeID, Object type, int id) throws ReflectiveOperationException { + Object packet = packetSpawnNormal.newInstance(); + setField(packet, "a", id); + setField(packet, "b", UUID.randomUUID()); + setField(packet, "c", location.getX()); + setField(packet, "d", location.getY()); + setField(packet, "e", location.getZ()); + setField(packet, "i", (int) (location.getYaw() * 256.0F / 360.0F)); + setField(packet, "j", (int) (location.getPitch() * 256.0F / 360.0F)); + setField(packet, "k", version < 13 ? typeID : type); + return packet; + } + + public static Object createPacketEntitySpawnNormal(Object entity) throws ReflectiveOperationException { + return packetSpawnNormal.newInstance(entity); + } + + public static void setCrystalWatcher(Object watcher, Location target) throws ReflectiveOperationException { + Object blockPosition = + blockPositionConstructor.newInstance(target.getBlockX(), target.getBlockY(), target.getBlockZ()); + tryWatcherSet(watcher, watcherObject4, Optional.of(blockPosition)); + tryWatcherSet(watcher, watcherObject5, Boolean.FALSE); + } + + public static Object[] createPacketsRemoveEntities(int... entitiesId) throws ReflectiveOperationException { + Object[] packets; + if (version == 17 && versionMinor == 0) { + packets = new Object[entitiesId.length]; + for (int i = 0; i < entitiesId.length; i++) { + packets[i] = packetRemove.newInstance(entitiesId[i]); + } + } else { + packets = new Object[]{packetRemove.newInstance(entitiesId)}; + } + return packets; + } + + public static void setEntityIDs(Object entity, UUID uuid, int id) throws ReflectiveOperationException { + setUUID.invoke(entity, uuid); + setID.invoke(entity, id); + } + + static Object createPacketMetadata(int entityId, Object watcher) throws ReflectiveOperationException { + if (version < 19 || (version == 19 && versionMinor < 3)) { + return packetMetadata.newInstance(entityId, watcher, false); + } else { + return packetMetadata.newInstance(entityId, watcherPack.invoke(watcher)); + } + } + + private static void tryWatcherSet(Object watcher, Object watcherObject, Object watcherData) throws ReflectiveOperationException { + try { + watcherSet.invoke(watcher, watcherObject, watcherData); + } catch (InvocationTargetException ex) { + watcherRegister.invoke(watcher, watcherObject, watcherData); + if (version >= 15) watcherDirty.invoke(watcher, watcherObject); + } + } + + /* Reflection utils */ + private static Method getMethod(Class clazz, String name) throws NoSuchMethodException { + for (Method m : clazz.getDeclaredMethods()) { + if (m.getName().equals(name)) return m; + } + throw new NoSuchMethodException(name + " in " + clazz.getName()); + } + + private static void setField(Object instance, String name, Object value) throws ReflectiveOperationException { + Field field = instance.getClass().getDeclaredField(name); + field.setAccessible(true); + field.set(instance, value); + } + + private static Object getField(Class clazz, String name, Object instance) throws ReflectiveOperationException { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field.get(instance); + } + + private static Class getNMSClass(String package17, String className) throws ClassNotFoundException { + return Class.forName((version < 17 ? npack : "net.minecraft." + package17) + "." + className); + } + + private enum ProtocolMappings { + V1_9(9, "Z", "bA", "bB", "b", "c", 94, 68), + V1_10(10, V1_9), + V1_11(11, V1_10), + V1_12(12, V1_11), + V1_13(13, "ac", "bF", "bG", "b", "c", 70, 28), + V1_14(14, "W", "b", "bD", "c", "d", 73, 30), + V1_15(15, "T", "b", "bA", "c", "d", 74, 31), + V1_16(16, null, "b", "d", "c", "d", -1, 31) { + @Override + public String getWatcherFlags() { + return Packets.versionMinor < 2 ? "T" : "S"; + } + }, + V1_17(17, "Z", "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "setCollisionRule", "getPlayerNameSet"), + V1_18(18, null, "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "a", "g") { + @Override + public String getWatcherFlags() { + return Packets.versionMinor < 2 ? "aa" : "Z"; + } + }, + V1_19(19, null, "b", "e", "c", "d", 89, 38, null, null, "w", "a", "g") { + @Override + public String getWatcherFlags() { + return versionMinor < 4 ? "Z" : "an"; + } + + @Override + public String getSquidTypeName() { + if (versionMinor < 3) + return "aM"; + else if (versionMinor == 3) + return "aN"; + else + return "aT"; + } + + }, + V1_20(20, "an", "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g"), + ; + + private final int major; + private final String watcherFlags; + private final String watcherSpikes; + private final String watcherTargetEntity; + private final String watcherTargetLocation; + private final String watcherBasePlate; + private final int squidID; + private final int guardianID; + private final String guardianTypeName; + private final String squidTypeName; + private final String crystalTypeName; + private final String teamSetCollision; + private final String teamGetPlayers; + + ProtocolMappings(int major, ProtocolMappings parent) { + this(major, parent.watcherFlags, parent.watcherSpikes, parent.watcherTargetEntity, parent.watcherTargetLocation, parent.watcherBasePlate, parent.squidID, parent.guardianID, parent.guardianTypeName, parent.squidTypeName, parent.crystalTypeName, parent.teamSetCollision, parent.teamGetPlayers); + } + + ProtocolMappings(int major, + String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate, + int squidID, int guardianID) { + this(major, watcherFlags, watcherSpikes, watcherTargetEntity, watcherTargetLocation, watcherBasePlate, squidID, guardianID, null, "SQUID", "END_CRYSTAL", null, null); + } + + ProtocolMappings(int major, + String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate, + int squidID, int guardianID, + String guardianTypeName, String squidTypeName, String crystalTypeName, String teamSetCollision, String teamGetPlayers) { + this.major = major; + this.watcherFlags = watcherFlags; + this.watcherSpikes = watcherSpikes; + this.watcherTargetEntity = watcherTargetEntity; + this.watcherTargetLocation = watcherTargetLocation; + this.watcherBasePlate = watcherBasePlate; + this.squidID = squidID; + this.guardianID = guardianID; + this.guardianTypeName = guardianTypeName; + this.squidTypeName = squidTypeName; + this.crystalTypeName = crystalTypeName; + this.teamSetCollision = teamSetCollision; + this.teamGetPlayers = teamGetPlayers; + } + + public static ProtocolMappings getMappings(int major) { + for (ProtocolMappings map : values()) { + if (major == map.getMajor()) return map; + } + return null; + } + + public int getMajor() { + return major; + } + + public String getWatcherFlags() { + return watcherFlags; + } + + public String getWatcherTargetLocation() { + return watcherTargetLocation; + } + + public String getWatcherBasePlate() { + return watcherBasePlate; + } + + public String getSquidTypeName() { + return squidTypeName; + } + + public String getCrystalTypeName() { + return crystalTypeName; + } + + } +} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java index 2f76c5f..44ca983 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java +++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java @@ -1,13 +1,14 @@ package com.github.alathra.AlathranWars.conflict.battle.siege; import com.github.alathra.AlathranWars.Main; +import com.github.alathra.AlathranWars.conflict.battle.beam.CrystalLaser; +import com.github.alathra.AlathranWars.conflict.battle.beam.Laser; import com.github.alathra.AlathranWars.enums.BattleSide; import com.github.alathra.AlathranWars.enums.CaptureProgressDirection; import com.github.alathra.AlathranWars.utility.UtilsChat; import com.github.milkdrinkers.colorparser.ColorParser; import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.TownBlock; -import fr.skytasul.guardianbeam.Laser; import org.bukkit.Location; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -243,7 +244,7 @@ public class SiegeRunnable implements Runnable { @Nullable Location loc1 = siege.getTownSpawn(); @NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ()); - beam = new Laser.CrystalLaser(loc1, loc2, -1, -1); + beam = new CrystalLaser(loc1, loc2, -1, 300); beam.start(Main.getInstance()); } catch (ReflectiveOperationException ignored) { }