diff --git a/.gitignore b/.gitignore index e1425cb..4938411 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ build/ .gradle/ -bin/ \ No newline at end of file +bin/ +.idea/ \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..90a6016 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..7d3b3e8 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..1fcfd5c --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..8a911c2 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..a25b6db --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..c4e1060 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/TuffXPlus.main.iml b/.idea/modules/TuffXPlus.main.iml new file mode 100644 index 0000000..ad42100 --- /dev/null +++ b/.idea/modules/TuffXPlus.main.iml @@ -0,0 +1,14 @@ + + + + + + + SPIGOT + ADVENTURE + + 1 + + + + \ No newline at end of file diff --git a/.idea/modules/TuffXPlus.test.iml b/.idea/modules/TuffXPlus.test.iml new file mode 100644 index 0000000..a376b96 --- /dev/null +++ b/.idea/modules/TuffXPlus.test.iml @@ -0,0 +1,13 @@ + + + + + + + ADVENTURE + + 1 + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle deleted file mode 100644 index fe10c6e..0000000 --- a/build.gradle +++ /dev/null @@ -1,82 +0,0 @@ -plugins { - id 'java' - id 'com.gradleup.shadow' version '8.3.0' -} - -group = 'tf.tuff' -version = '1.0.0' - -java { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 -} - -tasks.withType(JavaCompile).configureEach { - options.encoding = "UTF-8" -} - -repositories { - mavenCentral() - maven { url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } - maven { url = 'https://repo.papermc.io/repository/maven-public/' } - maven { url = 'https://repo.viaversion.com/everything/' } - maven { url = 'https://repo.codemc.io/repository/maven-releases/' } - maven { url = 'https://repo.codemc.io/repository/maven-snapshots/' } - maven { url = 'https://jitpack.io' } - maven { url = 'https://repo.dmulloy2.net/repository/public/' } -} - -dependencies { - compileOnly 'org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT' - - implementation 'com.github.retrooper:packetevents-spigot:2.11.1' - - compileOnly 'com.viaversion:viabackwards:5.3.2' - compileOnly 'com.viaversion:viaversion:5.4.1' - - compileOnly 'it.unimi.dsi:fastutil:8.5.16' - - implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' - - compileOnly 'io.netty:netty-all:4.1.97.Final' - - implementation 'org.java-websocket:Java-WebSocket:1.5.4' - - compileOnly 'org.projectlombok:lombok:1.18.30' - annotationProcessor 'org.projectlombok:lombok:1.18.30' -} - -processResources { - filesMatching('plugin.yml') { - expand( - 'version': project.version, - 'name': project.name - ) - } -} - -shadowJar { - archiveClassifier.set('') - archiveFileName.set("${project.name}-${project.version}.jar") - - relocate 'com.github.retrooper.packetevents', 'tf.tuff.packetevents' - relocate 'io.github.retrooper.packetevents', 'tf.tuff.packetevents' - relocate 'com.fasterxml.jackson', 'tf.tuff.jackson' - relocate 'org.java_websocket', 'tf.tuff.websocket' - - exclude 'META-INF/*.SF' - exclude 'META-INF/*.DSA' - exclude 'META-INF/*.RSA' - exclude 'META-INF/LICENSE' - exclude 'META-INF/NOTICE' - exclude 'META-INF/versions/**' - exclude 'module-info.class' -} - -tasks.named('jar') { - enabled = false -} - -tasks.named('build') { - dependsOn shadowJar -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..5f29b14 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,85 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + java + id("com.gradleup.shadow") version "8.3.0" + id("io.papermc.paperweight.userdev") version "2.0.0-beta.19" +} + +group = "tf.tuff" +version = "1.0.0" + + +repositories { + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://repo.viaversion.com/everything/") + maven("https://repo.codemc.io/repository/maven-releases/") + maven("https://repo.codemc.io/repository/maven-snapshots/") + maven("https://jitpack.io") + maven("https://repo.dmulloy2.net/repository/public/") + maven("https://repo.codemc.io/repository/maven-releases/") +} + +dependencies { + paperweight.paperDevBundle("1.21.8-R0.1-SNAPSHOT") + + implementation(libs.packetevents.spigot) + compileOnly(libs.viabackwards) + compileOnly(libs.viaversion) + compileOnly(libs.fastutil) + implementation(libs.jackson.databind) + compileOnly(libs.netty.all) + implementation(libs.java.websocket) + + compileOnly(libs.lombok) + annotationProcessor(libs.lombok) +} + + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +tasks { + withType().configureEach { + options.encoding = "UTF-8" + } + + processResources { + filesMatching("plugin.yml") { + expand( + "version" to project.version, + "name" to project.name + ) + } + } + + named("shadowJar") { + archiveClassifier.set("") + archiveFileName.set("${project.name}-${project.version}.jar") + + relocate("com.github.retrooper.packetevents", "tf.tuff.packetevents") + relocate("io.github.retrooper.packetevents", "tf.tuff.packetevents") + relocate("com.fasterxml.jackson", "tf.tuff.jackson") + relocate("org.java_websocket", "tf.tuff.websocket") + + exclude("META-INF/*.SF") + exclude("META-INF/*.DSA") + exclude("META-INF/*.RSA") + exclude("META-INF/LICENSE") + exclude("META-INF/NOTICE") + exclude("META-INF/versions/**") + exclude("module-info.class") + } + + withType { + enabled = false + } + + named("build") { + dependsOn(shadowJar) + } +} \ No newline at end of file diff --git a/gradle/gradle-wrapper-shared-8.5.jar b/gradle/gradle-wrapper-shared-8.5.jar deleted file mode 100644 index 54bc2d6..0000000 Binary files a/gradle/gradle-wrapper-shared-8.5.jar and /dev/null differ diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..e6503f4 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,21 @@ +[versions] + +packetevents = "2.11.1" +viabackwards = "5.3.2" +viaversion = "5.4.1" +fastutil = "8.5.16" +jackson = "2.15.2" +netty = "4.1.97.Final" +websocket = "1.5.4" +lombok = "1.18.30" + +[libraries] + +packetevents-spigot = { module = "com.github.retrooper:packetevents-spigot", version.ref = "packetevents" } +viabackwards = { module = "com.viaversion:viabackwards", version.ref = "viabackwards" } +viaversion = { module = "com.viaversion:viaversion", version.ref = "viaversion" } +fastutil = { module = "it.unimi.dsi:fastutil", version.ref = "fastutil" } +jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } +netty-all = { module = "io.netty:netty-all", version.ref = "netty" } +java-websocket = { module = "org.java-websocket:Java-WebSocket", version.ref = "websocket" } +lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1af9e09..37f78a6 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index e4ea97e..0000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'TuffXPlus' diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..873b2d7 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "TuffXPlus" diff --git a/src/main/java/tf/tuff/NetworkListener.java b/src/main/java/tf/tuff/NetworkListener.java index 9e99e48..57b7019 100644 --- a/src/main/java/tf/tuff/NetworkListener.java +++ b/src/main/java/tf/tuff/NetworkListener.java @@ -4,7 +4,6 @@ import com.github.retrooper.packetevents.event.PacketSendEvent; import com.github.retrooper.packetevents.protocol.packettype.PacketType; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerChunkData; -import org.bukkit.World; import org.bukkit.entity.Player; public class NetworkListener implements PacketListener { @@ -17,16 +16,18 @@ public NetworkListener(TuffX plugin) { @Override public void onPacketSend(PacketSendEvent event) { - if (event.getPacketType() == PacketType.Play.Server.CHUNK_DATA) { - Player player = (Player) event.getPlayer(); - if (player == null) return; + if (event.getPacketType() != PacketType.Play.Server.CHUNK_DATA) return; - WrapperPlayServerChunkData wrapper = new WrapperPlayServerChunkData(event); - int chunkX = wrapper.getColumn().getX(); - int chunkZ = wrapper.getColumn().getZ(); + Player player = event.getPlayer(); + WrapperPlayServerChunkData wrapper = new WrapperPlayServerChunkData(event); + + plugin.getY0Plugin().cpl + .handleChunk(plugin, + player, + player.getWorld(), + wrapper.getColumn().getX(), + wrapper.getColumn().getZ() + ); - World world = player.getWorld(); - plugin.y0Plugin.cpl.handleChunk(plugin, player, world, chunkX, chunkZ); - } } } diff --git a/src/main/java/tf/tuff/ServerRegistry.java b/src/main/java/tf/tuff/ServerRegistry.java index a561a59..ebf57ed 100644 --- a/src/main/java/tf/tuff/ServerRegistry.java +++ b/src/main/java/tf/tuff/ServerRegistry.java @@ -23,44 +23,35 @@ public void connect() { } private void doConnect() { - if (!running) - return; + if (!running) return; try { - client = new WebSocketClient(new URI(wsUrl)) { + client = new WebSocketClient( + new URI(wsUrl) + ) { @Override public void onOpen(ServerHandshake h) { send("{\"type\":\"register\",\"server\":\"" + server + "\"}"); } - @Override - public void onMessage(String msg) { - } + public void onMessage(String msg) {} @Override public void onClose(int code, String reason, boolean remote) { - if (running) { - p.getServer().getScheduler().runTaskLaterAsynchronously(p, () -> doConnect(), 100L); - } + if (running) p.getServer().getScheduler().runTaskLaterAsynchronously(p, () -> doConnect(), 100L); } - @Override - public void onError(Exception e) { - } + public void onError(Exception e) {} }; client.setConnectionLostTimeout(30); client.connect(); } catch (Exception e) { - if (running) { - p.getServer().getScheduler().runTaskLaterAsynchronously(p, () -> doConnect(), 100L); - } + if (running) p.getServer().getScheduler().runTaskLaterAsynchronously(p, this::doConnect, 100L); } } public void disconnect() { running = false; - if (client != null) { - client.close(); - } + if (client != null) client.close(); } } diff --git a/src/main/java/tf/tuff/TuffX.java b/src/main/java/tf/tuff/TuffX.java index 92e14ab..9ed99c0 100644 --- a/src/main/java/tf/tuff/TuffX.java +++ b/src/main/java/tf/tuff/TuffX.java @@ -1,45 +1,42 @@ package tf.tuff; +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.event.PacketListenerPriority; +import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder; +import lombok.Getter; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.*; -import org.bukkit.event.entity.EntityToggleGlideEvent; -import org.bukkit.event.entity.EntityToggleSwimEvent; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.PluginMessageListener; - -import com.github.retrooper.packetevents.PacketEvents; -import com.github.retrooper.packetevents.event.PacketListenerPriority; - -import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder; +import org.jetbrains.annotations.NotNull; +import tf.tuff.listeners.BlockListener; +import tf.tuff.listeners.PlayerListener; import tf.tuff.netty.ChunkInjector; import tf.tuff.tuffactions.TuffActions; import tf.tuff.viablocks.ViaBlocksPlugin; import tf.tuff.viaentities.ViaEntitiesPlugin; import tf.tuff.y0.Y0Plugin; -public class TuffX extends JavaPlugin implements Listener, PluginMessageListener { +import java.util.List; - public ServerRegistry serverRegistry; +public final class TuffX extends JavaPlugin implements PluginMessageListener { - public Y0Plugin y0Plugin; - public ViaBlocksPlugin viaBlocksPlugin; - public TuffActions tuffActions; - public ViaEntitiesPlugin viaEntitiesPlugin; - private ChunkInjector chunkInjector; + private ServerRegistry serverRegistry; + @Getter private static TuffX instance; + @Getter private Y0Plugin y0Plugin; + @Getter private ViaBlocksPlugin viaBlocksPlugin; + @Getter private TuffActions tuffActions; + @Getter private ViaEntitiesPlugin viaEntitiesPlugin; + + public TuffX() { + instance = this; + } @Override public void onLoad() { - this.y0Plugin = new Y0Plugin(this); + y0Plugin = new Y0Plugin(this); this.viaBlocksPlugin = new ViaBlocksPlugin(this); this.tuffActions = new TuffActions(this); this.viaEntitiesPlugin = new ViaEntitiesPlugin(this); @@ -55,24 +52,43 @@ public void onEnable() { PacketEvents.getAPI().init(); y0Plugin.onTuffXEnable(); - tuffActions.onTuffXEnable(); + tuffActions.load(); viaBlocksPlugin.onTuffXEnable(); viaEntitiesPlugin.onTuffXEnable(); - chunkInjector = new ChunkInjector(viaBlocksPlugin.blockListener, y0Plugin); + ChunkInjector chunkInjector = new ChunkInjector(viaBlocksPlugin.blockListener, y0Plugin); viaBlocksPlugin.blockListener.setChunkInjector(chunkInjector); y0Plugin.setChunkInjector(chunkInjector); saveDefaultConfig(); - PacketEvents.getAPI().getEventManager().registerListener( new NetworkListener(this), PacketListenerPriority.NORMAL ); - getServer().getPluginManager().registerEvents(this, this); - + Bukkit.getPluginManager().registerEvents(new BlockListener(), this); + Bukkit.getPluginManager().registerEvents(new PlayerListener(), this); setupRegistry(); - lfe(); + List.of( + "████████╗██╗ ██╗███████╗ ███████╗ ██╗ ██╗", + "╚══██╔══╝██║ ██║██╔════╝ ██╔════╝ ╚██╗██╔╝", + " ██║ ██║ ██║██████╗ ██████╗ ╚███╔╝ ", + " ██║ ██║ ██║██╔═══╝ ██╔═══╝ ██╔██╗ ", + " ██║ ╚██████╔╝██║ ██║ ██╔╝╚██╗", + " ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝", + "", + "CREDITS", + "Y0 support:", + "• Below y0 (client + plugin) programmed by Potato (@justatypicalpotato)", + "• llucasandersen - plugin optimizations", + "• ViaBlocks partial plugin and client rewrite by Potato", + "• llucasandersen (Complex client models and texture fixes,", + " optimizations, PacketEvents migration and async safety fixes)", + "• coleis1op, if ts is driving me crazy, im taking credit", + "• Swimming and creative items programmed by Potato (@justatypicalpotato)", + "• shaded build, 1.14+ support (before merge) - llucasandersen", + "• Restrictions - UplandJacob", + "• Overall plugin merges by Potato" + ).forEach(Bukkit.getConsoleSender()::sendMessage); } private void setupRegistry() { @@ -101,6 +117,20 @@ public void onDisable() { PacketEvents.getAPI().terminate(); } + @Override + public void onPluginMessageReceived(@NotNull String channel, Player player, byte[] message) { + if (!player.isOnline()) return; + + switch (channel) { + case "eagler:below_y0" -> y0Plugin.handlePacket(player, message); + case "viablocks:handshake" -> viaBlocksPlugin.handlePacket(player, message); + case "eagler:tuffactions" -> tuffActions.handlePacket(player, message); + case "entities:handshake" -> viaEntitiesPlugin.handlePacket(player, message); + default -> + getLogger().warning("Received plugin message on unknown channel '%s' from %s".formatted(channel, player.getName())); + } + } + public void reloadTuffX(){ reloadConfig(); saveDefaultConfig(); @@ -111,22 +141,19 @@ public void reloadTuffX(){ } setupRegistry(); - viaBlocksPlugin.onTuffXReload(); y0Plugin.onTuffXReload(); tuffActions.onTuffXReload(); viaEntitiesPlugin.onTuffXReload(); - getLogger().info("TuffX reloaded."); } public boolean TuffXCommand(CommandSender sender, Command command, String label, String[] args){ if (args.length > 0) { if (args[0].equalsIgnoreCase("reload")) { - if (!(sender instanceof Player)) { + if (!(sender instanceof Player player)) { reloadTuffX(); } else { - Player player = (Player) sender; if (!player.hasPermission("tuffx.reload")) { player.sendMessage("§cYou do not have permission to use this command."); return false; @@ -140,138 +167,10 @@ public boolean TuffXCommand(CommandSender sender, Command command, String label, } @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, Command command, @NotNull String label, String @NotNull [] args) { if (command.getName().equalsIgnoreCase("tuffx")) return TuffXCommand(sender, command, label, args); if (command.getName().equalsIgnoreCase("viablocks")) return viaBlocksPlugin.onTuffXCommand(sender, command, label, args); if (command.getName().equalsIgnoreCase("restrictions")) return tuffActions.onTuffXCommand(sender, command, label, args); return true; } - - @Override - public void onPluginMessageReceived(String channel, Player player, byte[] message) { - if (!player.isOnline()) return; - - if (channel.equals("eagler:below_y0")) y0Plugin.handlePacket(player,message); - else if (channel.equals("viablocks:handshake")) viaBlocksPlugin.handlePacket(player,message); - else if (channel.equals("eagler:tuffactions")) tuffActions.handlePacket(player,message); - else if (channel.equals("entities:handshake")) viaEntitiesPlugin.handlePacket(player,message); - else getLogger().warning("Received plugin message on unknown channel '%s' from %s".formatted(channel, player.getName())); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerChangeWorld(PlayerChangedWorldEvent e) { - y0Plugin.handlePlayerChangeWorld(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockForm(BlockFormEvent e) { - viaBlocksPlugin.blockListener.handleBlockForm(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockFade(BlockFadeEvent e) { - viaBlocksPlugin.blockListener.handleBlockFade(e); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(PlayerJoinEvent e) { - y0Plugin.handlePlayerJoin(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockGrow(BlockGrowEvent e) { - viaBlocksPlugin.blockListener.handleBlockGrow(e); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent e) { - y0Plugin.handlePlayerQuit(e); - tuffActions.handlePlayerQuit(e); - viaBlocksPlugin.blockListener.handlePlayerQuit(e); - viaEntitiesPlugin.handlePlayerQuit(e); - } - - @EventHandler - public void onToggleSwim(EntityToggleSwimEvent e) { - tuffActions.handleToggleSwim(e); - } - - @EventHandler - public void onToggleGlide(EntityToggleGlideEvent e) { - tuffActions.handleToggleGlide(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent e) { - viaBlocksPlugin.blockListener.handleBlockSpread(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent e) { - viaBlocksPlugin.blockListener.handleBlockBreak(e); - y0Plugin.handleBlockBreak(e); - } - - @EventHandler - public void onPlayerInventoryClick(InventoryClickEvent e) { - tuffActions.handlePlayerInventoryClick(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent e) { - viaBlocksPlugin.blockListener.handleBlockPlace(e); - y0Plugin.handleBlockPlace(e); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPhysics(BlockPhysicsEvent e) { - y0Plugin.handleBlockPhysics(e); - viaBlocksPlugin.blockListener.handleBlockPhysics(e); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onChunkLoad(ChunkLoadEvent e) { - y0Plugin.handleChunkLoad(e); - viaBlocksPlugin.blockListener.handleChunkLoad(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplode(BlockExplodeEvent e) { - viaBlocksPlugin.blockListener.handleBlockExplode(e); - y0Plugin.handleBlockExplode(e); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockFromTo(BlockFromToEvent e) { - viaBlocksPlugin.blockListener.handleBlockFromTo(e); - y0Plugin.handleBlockFromTo(e); - } - - private void lfe() { - getLogger().info(""); - getLogger().info("████████╗██╗ ██╗███████╗ ███████╗ ██╗ ██╗"); - getLogger().info("╚══██╔══╝██║ ██║██╔════╝ ██╔════╝ ╚██╗██╔╝"); - getLogger().info(" ██║ ██║ ██║██████╗ ██████╗ ╚███╔╝ "); - getLogger().info(" ██║ ██║ ██║██╔═══╝ ██╔═══╝ ██╔██╗ "); - getLogger().info(" ██║ ╚██████╔╝██║ ██║ ██╔╝╚██╗"); - getLogger().info(" ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝"); - getLogger().info(""); - getLogger().info("CREDITS"); - getLogger().info(""); - getLogger().info("Y0 support:"); - getLogger().info("• Below y0 (client + plugin) programmed by Potato (@justatypicalpotato)"); - getLogger().info("• llucasandersen - plugin optimizations"); - getLogger().info(""); - getLogger().info("ViaBlocks:"); - getLogger().info("• ViaBlocks partial plugin and client rewrite by Potato"); - getLogger().info("• llucasandersen (Complex client models and texture fixes,"); - getLogger().info(" optimizations, PacketEvents migration and async safety fixes)"); - getLogger().info("• coleis1op, if ts is driving me crazy, im taking credit"); - getLogger().info(""); - getLogger().info("Other:"); - getLogger().info("• Swimming and creative items programmed by Potato (@justatypicalpotato)"); - getLogger().info("• shaded build, 1.14+ support (before merge) - llucasandersen"); - getLogger().info("• Restrictions - UplandJacob"); - getLogger().info("• Overall plugin merges by Potato"); - } } diff --git a/src/main/java/tf/tuff/listeners/BlockListener.java b/src/main/java/tf/tuff/listeners/BlockListener.java new file mode 100644 index 0000000..f9c90a6 --- /dev/null +++ b/src/main/java/tf/tuff/listeners/BlockListener.java @@ -0,0 +1,64 @@ +package tf.tuff.listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.*; + +public class BlockListener extends ListenerBase implements Listener { + + public BlockListener() { + super(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockForm(BlockFormEvent e) { + viaBlocksPlugin.blockListener.handleBlockForm(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockFade(BlockFadeEvent e) { + viaBlocksPlugin.blockListener.handleBlockFade(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent e) { + viaBlocksPlugin.blockListener.handleBlockSpread(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent e) { + viaBlocksPlugin.blockListener.handleBlockBreak(e); + y0Plugin.handleBlockBreak(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockGrow(BlockGrowEvent e) { + viaBlocksPlugin.blockListener.handleBlockGrow(e); + } + + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent e) { + viaBlocksPlugin.blockListener.handleBlockPlace(e); + y0Plugin.handleBlockPlace(e); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPhysics(BlockPhysicsEvent e) { + y0Plugin.handleBlockPhysics(e); + viaBlocksPlugin.blockListener.handleBlockPhysics(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent e) { + viaBlocksPlugin.blockListener.handleBlockExplode(e); + y0Plugin.handleBlockExplode(e); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent e) { + viaBlocksPlugin.blockListener.handleBlockFromTo(e); + y0Plugin.handleBlockFromTo(e); + } +} diff --git a/src/main/java/tf/tuff/listeners/ListenerBase.java b/src/main/java/tf/tuff/listeners/ListenerBase.java new file mode 100644 index 0000000..678a752 --- /dev/null +++ b/src/main/java/tf/tuff/listeners/ListenerBase.java @@ -0,0 +1,21 @@ +package tf.tuff.listeners; + +import tf.tuff.TuffX; +import tf.tuff.tuffactions.TuffActions; +import tf.tuff.viablocks.ViaBlocksPlugin; +import tf.tuff.viaentities.ViaEntitiesPlugin; +import tf.tuff.y0.Y0Plugin; + +public abstract class ListenerBase { + protected final ViaBlocksPlugin viaBlocksPlugin; + protected final TuffActions tuffActions; + protected final ViaEntitiesPlugin viaEntitiesPlugin; + protected final Y0Plugin y0Plugin; + + public ListenerBase() { + viaBlocksPlugin = TuffX.getInstance().getViaBlocksPlugin(); + tuffActions = TuffX.getInstance().getTuffActions(); + viaEntitiesPlugin = TuffX.getInstance().getViaEntitiesPlugin(); + y0Plugin = TuffX.getInstance().getY0Plugin(); + } +} diff --git a/src/main/java/tf/tuff/listeners/PlayerListener.java b/src/main/java/tf/tuff/listeners/PlayerListener.java new file mode 100644 index 0000000..c6cba48 --- /dev/null +++ b/src/main/java/tf/tuff/listeners/PlayerListener.java @@ -0,0 +1,60 @@ +package tf.tuff.listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.EntityToggleGlideEvent; +import org.bukkit.event.entity.EntityToggleSwimEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.world.ChunkLoadEvent; + +public class PlayerListener extends ListenerBase implements Listener { + + public PlayerListener() { + super(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerChangeWorld(PlayerChangedWorldEvent e) { + y0Plugin.handlePlayerChangeWorld(e); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent e) { + y0Plugin.handlePlayerJoin(e); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent e) { + y0Plugin.handlePlayerQuit(e); + tuffActions.handlePlayerQuit(e); + viaBlocksPlugin.blockListener.handlePlayerQuit(e); + viaEntitiesPlugin.handlePlayerQuit(e); + } + + @EventHandler + public void onPlayerInventoryClick(InventoryClickEvent e) { + tuffActions.handlePlayerInventoryClick(e); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onChunkLoad(ChunkLoadEvent e) { + y0Plugin.handleChunkLoad(e); + viaBlocksPlugin.blockListener.handleChunkLoad(e); + } + + @EventHandler + public void onToggleSwim(EntityToggleSwimEvent e) { + tuffActions.handleToggleSwim(e); + } + + @EventHandler + public void onToggleGlide(EntityToggleGlideEvent e) { + tuffActions.handleToggleGlide(e); + } + +} diff --git a/src/main/java/tf/tuff/netty/BaseInjector.java b/src/main/java/tf/tuff/netty/BaseInjector.java index b2e521b..dc77096 100644 --- a/src/main/java/tf/tuff/netty/BaseInjector.java +++ b/src/main/java/tf/tuff/netty/BaseInjector.java @@ -1,6 +1,7 @@ package tf.tuff.netty; import com.viaversion.viaversion.api.Via; +import com.viaversion.viaversion.api.connection.UserConnection; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import org.bukkit.entity.Player; @@ -22,7 +23,7 @@ protected void onPostInject(Player player) { public void inject(Player player) { UUID uuid = player.getUniqueId(); - var viaConnection = Via.getAPI().getConnection(uuid); + UserConnection viaConnection = Via.getAPI().getConnection(uuid); if (viaConnection == null) return; Channel channel = viaConnection.getChannel(); @@ -36,12 +37,12 @@ public void inject(Player player) { String targetHandler = null; String[] anchors = {"packet_handler", "encoder", "via-encoder"}; - for (int i = 0; i < anchors.length; ++i) { - if (channel.pipeline().get(anchors[i]) != null) { - targetHandler = anchors[i]; - break; - } - } + for (String anchor : anchors) { + if (channel.pipeline().get(anchor) != null) { + targetHandler = anchor; + break; + } + } ChannelHandler handler = createHandler(player); if (targetHandler != null) { @@ -58,19 +59,15 @@ public void inject(Player player) { } public void eject(Player player) { - UUID uuid = player.getUniqueId(); - var viaConnection = Via.getAPI().getConnection(uuid); - if (viaConnection == null) return; - - Channel channel = viaConnection.getChannel(); + UserConnection viaConnection = Via.getAPI().getConnection(player.getUniqueId()); + Channel channel = viaConnection != null ? viaConnection.getChannel() : null; if (channel != null && channel.isOpen()) { channel.eventLoop().submit(() -> { try { if (channel.pipeline().get(handlerName) != null) { channel.pipeline().remove(handlerName); } - } catch (Exception e) { - } + } catch (Exception ignored) {} }); } } diff --git a/src/main/java/tf/tuff/tuffactions/TuffActions.java b/src/main/java/tf/tuff/tuffactions/TuffActions.java index bf90b04..23a5a40 100644 --- a/src/main/java/tf/tuff/tuffactions/TuffActions.java +++ b/src/main/java/tf/tuff/tuffactions/TuffActions.java @@ -1,14 +1,7 @@ package tf.tuff.tuffactions; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; - +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPluginMessage; import org.bukkit.GameMode; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -17,15 +10,20 @@ import org.bukkit.event.entity.EntityToggleSwimEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerQuitEvent; - -import com.github.retrooper.packetevents.PacketEvents; -import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPluginMessage; - import tf.tuff.TuffX; import tf.tuff.tuffactions.creative.CreativeMenu; import tf.tuff.tuffactions.restrictions.Restrictions; import tf.tuff.tuffactions.swimming.Swimming; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + public class TuffActions { public static final String CHANNEL = "eagler:tuffactions"; @@ -37,12 +35,12 @@ public class TuffActions { public static boolean swimmingEnabled = false; public static boolean creativeEnabled = false; public static boolean restrictionsEnabled = false; - + public final TuffX plugin; public static final Set tuffPlayers = ConcurrentHashMap.newKeySet(); - public TuffActions(TuffX plugin){ + public TuffActions(TuffX plugin) { this.plugin = plugin; } @@ -67,7 +65,7 @@ public void onTuffXReload() { info("Misc features reloaded."); } - public void onTuffXEnable() { + public void load() { loadConfig(); PacketEvents.getAPI().init(); @@ -75,13 +73,11 @@ public void onTuffXEnable() { this.creativeManager = new CreativeMenu(this); this.restrictions = new Restrictions(this); info("Finished enabling features."); - - plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "eagler:tuffactions"); - plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, "eagler:tuffactions", plugin); } public boolean onTuffXCommand(CommandSender sender, Command command, String label, String[] args) { - if (command.getName().equalsIgnoreCase("restrictions")) return this.restrictions.onTuffXCommand(sender, command, label, args); + if (command.getName().equalsIgnoreCase("restrictions")) + return this.restrictions.onTuffXCommand(sender, command, label, args); return true; } @@ -103,43 +99,59 @@ public void handlePacket(Player player, byte[] message) { tuffPlayers.add(player.getUniqueId()); - if ("swimming_state".equals(action) && swimmingEnabled) { - swimmingManager.handleSwimState(player, in.readBoolean()); - } else if ("elytra_state".equals(action) && swimmingEnabled) { - swimmingManager.handleElytraState(player, in.readBoolean()); - } else if ("creative_ready".equals(action) && creativeEnabled){ - creativeManager.handleCreativeReady(player); - } else if ("swim_ready".equals(action) && swimmingEnabled){ - swimmingManager.handleSwimReady(player); - } else if ("give_creative_item".equals(action) && creativeEnabled){ - if (player.getGameMode() != GameMode.CREATIVE) { - return; + switch (action.toLowerCase()) { + case "swimming_state" -> { + if (swimmingEnabled) { + swimmingManager.handleSwimState(player, in.readBoolean()); + break; + } + } + case "elytra_state" -> { + if (swimmingEnabled) { + swimmingManager.handleElytraState(player, in.readBoolean()); + break; + } } - int itemLength = in.readUnsignedByte(); - if (in.available() < itemLength + Integer.BYTES) { - return; + case "creative-ready" -> { + if (creativeEnabled) { + creativeManager.handleCreativeReady(player); + } } - byte[] itemBytes = new byte[itemLength]; - in.readFully(itemBytes); - String item = new String(itemBytes, StandardCharsets.UTF_8); - int amount = in.readInt(); - creativeManager.handlePlaceholderTaken(player, item, amount); - } else if ("pick_viablock".equals(action) && creativeEnabled){ - if (player.getGameMode() != GameMode.CREATIVE) { - return; + case "swim_ready" -> { + if (swimmingEnabled) { + swimmingManager.handleSwimReady(player); + } + } + case "give_creative_item" -> { + if (creativeEnabled) { + if (player.getGameMode() != GameMode.CREATIVE) return; + int itemLength = in.readUnsignedByte(); + if (in.available() < itemLength + Integer.BYTES) { + return; + } + byte[] itemBytes = new byte[itemLength]; + in.readFully(itemBytes); + String item = new String(itemBytes, StandardCharsets.UTF_8); + int amount = in.readInt(); + creativeManager.handlePlaceholderTaken(player, item, amount); + } } - int blockLength = in.readUnsignedByte(); - if (in.available() < blockLength + 1) { - return; + case "pick_viablock" -> { + if (creativeEnabled) { + if (player.getGameMode() != GameMode.CREATIVE) return; + int blockLength = in.readUnsignedByte(); + if (in.available() < blockLength + 1) return; + byte[] blockBytes = new byte[blockLength]; + in.readFully(blockBytes); + String blockName = new String(blockBytes, StandardCharsets.UTF_8); + int hotbarSlot = in.readUnsignedByte(); + creativeManager.handlePickViablock(player, blockName, hotbarSlot); + } } - byte[] blockBytes = new byte[blockLength]; - in.readFully(blockBytes); - String blockName = new String(blockBytes, StandardCharsets.UTF_8); - int hotbarSlot = in.readUnsignedByte(); - creativeManager.handlePickViablock(player, blockName, hotbarSlot); - } else if ("restrictions_ready".equals(action)) { - restrictions.handleRestrictionsReady(player); + case "restrictions_ready" -> + restrictions.handleRestrictionsReady(player); } + } catch (IOException e) { log(Level.WARNING, "Failed to read a plugin message from " + player.getName(), e); } @@ -150,44 +162,41 @@ public void sendPluginMessage(Player player, byte[] payload) { } public void sendPluginMessage(Player player, String channel, byte[] payload) { - if (player == null || payload == null || !player.isOnline() || !PacketEvents.getAPI().isInitialized()) { + if (player == null || payload == null || + !player.isOnline() || !PacketEvents.getAPI().isInitialized() + ) { return; } + WrapperPlayServerPluginMessage packet = new WrapperPlayServerPluginMessage(channel, payload); PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet); } public void handlePlayerQuit(PlayerQuitEvent event) { - if (swimmingEnabled) { - swimmingManager.handleSwimQuit(event); - } + if (swimmingEnabled) swimmingManager.handleSwimQuit(event); tuffPlayers.remove(event.getPlayer().getUniqueId()); } public void handleToggleSwim(EntityToggleSwimEvent event) { - if (swimmingEnabled) { - swimmingManager.handleToggleSwim(event); - } + if (swimmingEnabled) swimmingManager.handleToggleSwim(event); } public void handleToggleGlide(EntityToggleGlideEvent event) { - if (swimmingEnabled) { - swimmingManager.handleToggleGlide(event); - } + if (swimmingEnabled) swimmingManager.handleToggleGlide(event); } public void handlePlayerInventoryClick(InventoryClickEvent event) { - if (creativeEnabled) { - creativeManager.onPlayerInventoryClick(event); - } + if (creativeEnabled) creativeManager.onPlayerInventoryClick(event); } public void log(Level level, String msg, Throwable e) { - plugin.getLogger().log(level, "[TuffActions] "+msg, e); + plugin.getLogger().log(level, "[TuffActions] ".formatted(msg), e); } + public void log(Level level, String msg) { - plugin.getLogger().log(level, "[TuffActions] "+msg); + plugin.getLogger().log(level, "[TuffActions] %s".formatted(msg)); } + public void info(String msg) { log(Level.INFO, msg); } diff --git a/src/main/java/tf/tuff/tuffactions/creative/CreativeMenu.java b/src/main/java/tf/tuff/tuffactions/creative/CreativeMenu.java index 221f84b..af74561 100644 --- a/src/main/java/tf/tuff/tuffactions/creative/CreativeMenu.java +++ b/src/main/java/tf/tuff/tuffactions/creative/CreativeMenu.java @@ -1,17 +1,17 @@ package tf.tuff.tuffactions.creative; -import tf.tuff.tuffactions.TuffActions; - import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; +import tf.tuff.tuffactions.TuffActions; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -20,7 +20,7 @@ import java.util.logging.Level; public class CreativeMenu { - private final TuffActions plugin; + private final TuffActions plugin; private final Set itemMapping = ConcurrentHashMap.newKeySet(); private final Map playerHoldingPlaceholder = new ConcurrentHashMap<>(); @@ -29,18 +29,13 @@ public class CreativeMenu { public CreativeMenu(TuffActions plugin) { this.plugin = plugin; this.tabUtil = new TabUtil(plugin); - - if (TuffActions.creativeEnabled) { - initializeMappings(); - } + if (TuffActions.creativeEnabled) initializeMappings(); } public void initializeMappings() { - for (Material m : Material.values()){ - if (m.isItem()){ - itemMapping.add(m.name()); - } - } + Arrays.stream(Material.values()).toList().forEach(m -> { + if (m.isItem()) itemMapping.add(m.name()); + }); } public void handleCreativeReady(Player player) { @@ -73,10 +68,7 @@ public void handlePickViablock(Player player, String blockName, int hotbarSlot) if (material == null || !material.isItem()) { return; } - if (hotbarSlot < 0 || hotbarSlot > 8) { - hotbarSlot = 0; - } - player.getInventory().setItem(hotbarSlot, new ItemStack(material, 1)); + player.getInventory().setItem(hotbarSlot > 8 || hotbarSlot < 0 ? 0 : hotbarSlot, new ItemStack(material, 1)); } public void onPlayerInventoryClick(InventoryClickEvent event) { @@ -87,7 +79,7 @@ public void onPlayerInventoryClick(InventoryClickEvent event) { InventoryAction action = event.getAction(); if (action == InventoryAction.PLACE_ALL || action == InventoryAction.PLACE_ONE || action == InventoryAction.SWAP_WITH_CURSOR) { - Bukkit.getScheduler().runTaskLater(this.plugin.plugin, () -> { + Bukkit.getScheduler().runTaskLater(this.plugin.getPlugin(), () -> { ItemStack realItemStack = playerHoldingPlaceholder.get(playerUUID); if (realItemStack != null && event.getClickedInventory() != null) { diff --git a/src/main/java/tf/tuff/tuffactions/creative/TabUtil.java b/src/main/java/tf/tuff/tuffactions/creative/TabUtil.java index 428990c..c6ff551 100644 --- a/src/main/java/tf/tuff/tuffactions/creative/TabUtil.java +++ b/src/main/java/tf/tuff/tuffactions/creative/TabUtil.java @@ -1,16 +1,16 @@ package tf.tuff.tuffactions.creative; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.jetbrains.annotations.NotNull; +import tf.tuff.tuffactions.TuffActions; + +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.logging.Level; -import javax.annotation.Nullable; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import tf.tuff.tuffactions.TuffActions; public class TabUtil { private final TuffActions plugin; @@ -20,9 +20,7 @@ public class TabUtil { public TabUtil(TuffActions plugin) { this.plugin = plugin; this.mappingFile = new File(plugin.plugin.getDataFolder(), "tab-mapping.json"); - setupMappingFile(); - loadMapping(); } @@ -34,14 +32,13 @@ private void setupMappingFile() { } private void loadMapping() { + + ObjectMapper mapper = new ObjectMapper(); + TypeReference> typeRef = new TypeReference<>() {}; + try { - ObjectMapper mapper = new ObjectMapper(); - - TypeReference> typeRef = new TypeReference>() {}; - this.creativeTabMap = mapper.readValue(mappingFile, typeRef); plugin.info("Successfully loaded " + creativeTabMap.size() + " creative tab mappings."); - } catch (IOException e) { plugin.log(Level.SEVERE, "Failed to load creative tab mapping from file!", e); this.creativeTabMap = Collections.emptyMap(); @@ -49,10 +46,8 @@ private void loadMapping() { } @Nullable - public String getCreativeCategory(String material) { - if (material == null || creativeTabMap.isEmpty()) { - return null; - } + public String getCreativeCategory(@NotNull String material) { + if (creativeTabMap.isEmpty()) return null; return creativeTabMap.get(material); } } \ No newline at end of file diff --git a/src/main/java/tf/tuff/tuffactions/restrictions/Restrictions.java b/src/main/java/tf/tuff/tuffactions/restrictions/Restrictions.java index 4b2ead5..f482fdb 100644 --- a/src/main/java/tf/tuff/tuffactions/restrictions/Restrictions.java +++ b/src/main/java/tf/tuff/tuffactions/restrictions/Restrictions.java @@ -1,5 +1,11 @@ package tf.tuff.tuffactions.restrictions; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import tf.tuff.tuffactions.TuffActions; + import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -9,13 +15,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import tf.tuff.tuffactions.TuffActions; - public class Restrictions { private final TuffActions plugin; private RestrictionsCommand commandHandler; @@ -34,6 +33,7 @@ public Restrictions(TuffActions plugin) { private void validateConfig() { boolean configUpdated = false; + if (!plugin.plugin.getConfig().contains("restrictions.enabled", true)) { plugin.plugin.getConfig().set("restrictions.enabled", false); configUpdated = true; @@ -46,7 +46,7 @@ private void validateConfig() { plugin.plugin.saveConfig(); plugin.info("Restrictions config updated"); } - } + } public void loadConfig() { disallowed.clear(); if (!TuffActions.restrictionsEnabled) return; @@ -90,11 +90,12 @@ public void sendSingleUpdateToAll(String key) { private void handleSingleUpdate(Player player, String key) { if (!TuffActions.restrictionsEnabled) return; plugin.info("Sending restriction update for '%s' to %s".formatted(key, player.getName())); - try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bout)) { + try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bout) + ) { out.writeUTF("client_feature"); out.writeUTF(key); out.writeBoolean(!disallowed.contains(key)); - plugin.sendPluginMessage(player, bout.toByteArray()); } catch (IOException e) { plugin.log(Level.WARNING, "Failed to send Restriction "+key+" to " + player.getName(), e); diff --git a/src/main/java/tf/tuff/tuffactions/restrictions/RestrictionsCommand.java b/src/main/java/tf/tuff/tuffactions/restrictions/RestrictionsCommand.java index efe082d..9fb05c0 100644 --- a/src/main/java/tf/tuff/tuffactions/restrictions/RestrictionsCommand.java +++ b/src/main/java/tf/tuff/tuffactions/restrictions/RestrictionsCommand.java @@ -1,13 +1,12 @@ package tf.tuff.tuffactions.restrictions; -import java.util.List; -import java.util.logging.Level; - import org.bukkit.command.Command; import org.bukkit.command.CommandSender; - import tf.tuff.TuffX; +import java.util.List; +import java.util.logging.Level; + public class RestrictionsCommand { private final TuffX tuffx; private final Restrictions restrictions; @@ -54,16 +53,17 @@ public boolean onCommand(CommandSender sender, Command command, String label, St } else if (args[0].equalsIgnoreCase("allow")) { if (!sender.hasPermission("tuffx.restrictions.command.allow")) return noPermission(sender); if (args.length < 2) return invalidUsage(sender, "Module name required."); + List config = null; try { - @SuppressWarnings("unchecked") - List config = (List)tuffx.getConfig().getList("restrictions.disallow"); - if (!config.contains(args[1])) return error(sender, "Module '%s' not in disallow list. No change.".formatted(args[1])); - config.remove(args[1]); + + config = (List) tuffx.getConfig().getList("restrictions.disallow"); + if (config != null && !config.contains(args[1])) return error(sender, "Module '%s' not in disallow list. No change.".formatted(args[1])); + if (config != null) config.remove(args[1]); tuffx.getConfig().set("restrictions.disallow", config); tuffx.saveConfig(); restrictions.loadConfig(); restrictions.sendSingleUpdateToAll(args[1]); - } catch(Exception e) { + } catch (Exception e) { return unknownError(sender, e); } sender.sendMessage("\u00A7aModule '%s' removed from disallow list.".formatted(args[1])); diff --git a/src/main/java/tf/tuff/tuffactions/swimming/Swimming.java b/src/main/java/tf/tuff/tuffactions/swimming/Swimming.java index 64ae9b2..9bd6883 100644 --- a/src/main/java/tf/tuff/tuffactions/swimming/Swimming.java +++ b/src/main/java/tf/tuff/tuffactions/swimming/Swimming.java @@ -46,16 +46,14 @@ public void handleElytraState(Player player, boolean isGliding) { } public void handleToggleSwim(EntityToggleSwimEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player player)) return; if (!event.isSwimming() && swimmingPlayers.contains(player.getUniqueId())) { event.setCancelled(true); } } public void handleToggleGlide(EntityToggleGlideEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player player)) return; if (!event.isGliding() && glidingPlayers.contains(player.getUniqueId())) { event.setCancelled(true); } @@ -97,12 +95,11 @@ private void sendSwimState(Player recipient, Player subject, boolean isSwimming) } public void handleSwimReady(Player player) { - Player newPlayer = player; plugin.plugin.getServer().getScheduler().runTaskLater(plugin.plugin, () -> { for (UUID swimmingPlayerId : swimmingPlayers) { Player swimmingPlayer = Bukkit.getPlayer(swimmingPlayerId); if (swimmingPlayer != null && swimmingPlayer.isOnline()) { - sendSwimState(newPlayer, swimmingPlayer, true); + sendSwimState(player, swimmingPlayer, true); } } }, 20L); diff --git a/src/main/java/tf/tuff/viablocks/CustomBlockListener.java b/src/main/java/tf/tuff/viablocks/CustomBlockListener.java index 2ac645a..32ef7ca 100644 --- a/src/main/java/tf/tuff/viablocks/CustomBlockListener.java +++ b/src/main/java/tf/tuff/viablocks/CustomBlockListener.java @@ -1,46 +1,55 @@ package tf.tuff.viablocks; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; -import javax.annotation.Nonnull; - +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import lombok.Setter; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.block.data.type.Door; import org.bukkit.block.data.Bisected; import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Door; import org.bukkit.entity.Player; -import org.bukkit.event.block.*; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.world.ChunkLoadEvent; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - import tf.tuff.viablocks.version.VersionAdapter; +import javax.annotation.Nonnull; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + public class CustomBlockListener { public final ViaBlocksPlugin plugin; private final VersionAdapter versionAdapter; private final PaletteManager paletteManager; private final EnumSet modernMaterials; + @Setter private tf.tuff.netty.ChunkInjector chunkInjector; private static final Map worldMinHeights = new ConcurrentHashMap<>(); private static final long X_MASK = (1L << 26) - 1L; @@ -82,10 +91,6 @@ public byte[] getCachedChunkData(String worldName, int x, int z) { return chunkPacketCache.getIfPresent(chunkKey(worldName, x, z)); } - public void setChunkInjector(tf.tuff.netty.ChunkInjector injector) { - this.chunkInjector = injector; - } - private @Nonnull String chunkKey(String worldName, int x, int z) { return worldName + "_" + x + "_" + z; } @@ -142,7 +147,7 @@ private void sendInitialChunks(Player player) { } } - chunks.sort((a, b) -> Integer.compare(a[2], b[2])); + chunks.sort(Comparator.comparingInt(a -> a[2])); sendChunksBatched(player, world.getName(), chunks, 0); } @@ -201,7 +206,7 @@ public void prepareChunkCache(Chunk chunk) { } else { chunkPacketCache.put(key, buildChunkPacket(foundBlocks)); } - } catch (Exception e) {} + } catch (Exception ignored) {} }); } @@ -284,11 +289,7 @@ private Map> findModernBlocksInChunk(ChunkSnapshot chunkSnap if (materialId != -1) { long packedLocation = packLocation(chunkX + x, y, chunkZ + z); - List locs = foundBlocks.get(materialId); - if (locs == null) { - locs = new ArrayList<>(); - foundBlocks.put(materialId, locs); - } + List locs = foundBlocks.computeIfAbsent(materialId, k -> new ArrayList<>()); locs.add(packedLocation); } } @@ -303,11 +304,7 @@ public byte[] getExtraDataForMultiBlock(World world, List locations) { for (long packedLoc : locations) { Integer cachedId = recentModernChanges.getIfPresent(packedLoc); if (cachedId != null) { - List locs = foundBlocks.get(cachedId); - if (locs == null) { - locs = new ArrayList<>(); - foundBlocks.put(cachedId, locs); - } + List locs = foundBlocks.computeIfAbsent(cachedId, k -> new ArrayList<>()); locs.add(packedLoc); continue; } @@ -324,11 +321,7 @@ public byte[] getExtraDataForMultiBlock(World world, List locations) { if (isModernMaterial(data.getMaterial())) { int id = getMaterialId(data); if (id != -1) { - List locs2 = foundBlocks.get(id); - if (locs2 == null) { - locs2 = new ArrayList<>(); - foundBlocks.put(id, locs2); - } + List locs2 = foundBlocks.computeIfAbsent(id, k -> new ArrayList<>()); locs2.add(packedLoc); } } @@ -382,8 +375,7 @@ public void handleBlockBreak(BlockBreakEvent event) { handleModernBlockChange(data, Material.AIR.createBlockData(), loc); - if (data instanceof Door) { - Door door = (Door) data; + if (data instanceof Door door) { Location otherHalf = door.getHalf() == Bisected.Half.BOTTOM ? loc.clone().add(0, 1, 0) : loc.clone().add(0, -1, 0); @@ -526,16 +518,8 @@ private void invalidateChunkCache(Chunk chunk) { private void sendPacket(Player player, int stateId, Location location) { if (!player.isOnline()) return; UUID playerId = player.getUniqueId(); - Map> updateData = pendingUpdates.get(playerId); - if (updateData == null) { - updateData = new HashMap<>(); - pendingUpdates.put(playerId, updateData); - } - List stateList = updateData.get(stateId); - if (stateList == null) { - stateList = new ArrayList<>(); - updateData.put(stateId, stateList); - } + Map> updateData = pendingUpdates.computeIfAbsent(playerId, k -> new HashMap<>()); + List stateList = updateData.computeIfAbsent(stateId, k -> new ArrayList<>()); stateList.add(packLocation(location)); if (pendingFlush.add(playerId)) { runSyncLater(() -> flushPendingUpdates(playerId), plugin.getUpdateBatchDelayTicks()); @@ -555,7 +539,6 @@ private void flushPendingUpdates(UUID playerId) { } private int getMaterialId(BlockData data) { - @SuppressWarnings("null") Integer cachedId = blockDataIdCache.getIfPresent(data); if (cachedId != null) return cachedId; @@ -566,14 +549,12 @@ private int getMaterialId(BlockData data) { private byte[] buildChunkPacket(Map> blockData) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); - out.writeUTF("ADD_CHUNK"); + out.writeUTF("ADD_CHUNK"); out.writeInt(blockData.size()); for (Map.Entry> entry : blockData.entrySet()) { out.writeInt(entry.getKey()); out.writeInt(entry.getValue().size()); - for (Long loc : entry.getValue()) { - out.writeLong(loc); - } + entry.getValue().forEach(out::writeLong); } return out.toByteArray(); } @@ -583,9 +564,7 @@ public void sendPaletteToClient(Player player) { out.writeUTF("INIT_PALETTE"); List palette = this.paletteManager.getPalette(); out.writeInt(palette.size()); - for (String state : palette) { - out.writeUTF(state); - } + palette.forEach(out::writeUTF); player.sendPluginMessage(plugin.plugin, ViaBlocksPlugin.CLIENTBOUND_CHANNEL, out.toByteArray()); } @@ -594,7 +573,8 @@ public boolean isModernMaterial(Material material) { } public void processChunkForSinglePlayer(Chunk chunk, Player player) { - if (!chunk.isLoaded() || !plugin.isPlayerEnabled(player)) return; + if (!chunk.isLoaded() || + !plugin.isPlayerEnabled(player)) return; prepareChunkCache(chunk); byte[] data = getExtraDataForChunk(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); if (data != null && data.length > 0) { @@ -614,7 +594,7 @@ private void runSyncLater(Runnable task, long delay) { if (!plugin.plugin.isEnabled()) return; try { plugin.plugin.getServer().getScheduler().runTaskLater(plugin.plugin, task, delay); - } catch (Exception e) {} + } catch (Exception ignored) {} } private int getMinHeight(World world) { @@ -625,7 +605,7 @@ private int getMinHeight(World world) { if (value instanceof Integer) { return (Integer) value; } - } catch (Exception e) {} + } catch (Exception ignored) {} return 0; }); } diff --git a/src/main/java/tf/tuff/viablocks/PaletteManager.java b/src/main/java/tf/tuff/viablocks/PaletteManager.java index 2e56d0f..26e4c7b 100644 --- a/src/main/java/tf/tuff/viablocks/PaletteManager.java +++ b/src/main/java/tf/tuff/viablocks/PaletteManager.java @@ -1,20 +1,17 @@ package tf.tuff.viablocks; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import tf.tuff.viablocks.version.VersionAdapter; + import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - -import tf.tuff.viablocks.version.VersionAdapter; - public class PaletteManager { ViaBlocksPlugin plugin; @@ -32,7 +29,9 @@ private void generate(VersionAdapter versionAdapter) { plugin.info("Generating ViaBlocks Pre-Defined Palette..."); List initialPalette = new ArrayList<>(); - + versionAdapter.getModernMaterials().stream().filter(Material::isBlock).forEach( + mat -> addEntryInternal(initialPalette, versionAdapter.getMaterialKey(mat) + )); for (Material material : versionAdapter.getModernMaterials()) { if (material.isBlock()) { addEntryInternal(initialPalette, versionAdapter.getMaterialKey(material)); @@ -109,15 +108,12 @@ private void broadcastNewPaletteEntry(String state) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("NEW_PALETTE_ENTRY"); out.writeUTF(state); - byte[] data = out.toByteArray(); Bukkit.getScheduler().runTask(plugin.plugin, () -> { if (!plugin.plugin.isEnabled() || !plugin.isEnabled()) return; - for (Player player : Bukkit.getOnlinePlayers()) { - if (plugin.isPlayerEnabled(player)) { - player.sendPluginMessage(plugin.plugin, ViaBlocksPlugin.CLIENTBOUND_CHANNEL, data); - } - } + Bukkit.getOnlinePlayers().stream().filter(player -> plugin.isPlayerEnabled(player)).forEach( + player -> player.sendPluginMessage(plugin.plugin, ViaBlocksPlugin.CLIENTBOUND_CHANNEL, out.toByteArray()) + ); }); } @@ -128,8 +124,7 @@ public synchronized int getId(String state) { public synchronized List getPalette() { List snapshot = paletteSnapshot; if (snapshot == null) { - snapshot = new ArrayList<>(palette); - paletteSnapshot = snapshot; + paletteSnapshot = new ArrayList<>(palette); } return snapshot; } diff --git a/src/main/java/tf/tuff/viablocks/ViaBlocksPlugin.java b/src/main/java/tf/tuff/viablocks/ViaBlocksPlugin.java index 9537d87..38122ce 100644 --- a/src/main/java/tf/tuff/viablocks/ViaBlocksPlugin.java +++ b/src/main/java/tf/tuff/viablocks/ViaBlocksPlugin.java @@ -82,11 +82,8 @@ public void onTuffXReload() { public void onTuffXEnable() { instance = this; - this.chunkExecutor = Executors.newFixedThreadPool(Math.max(1, Runtime.getRuntime().availableProcessors())); - this.versionAdapter = new ModernAdapter(); - this.paletteManager = new PaletteManager(this.versionAdapter); try { diff --git a/src/main/java/tf/tuff/viablocks/version/VersionAdapter.java b/src/main/java/tf/tuff/viablocks/version/VersionAdapter.java index 79b0cd0..0c9cfd8 100644 --- a/src/main/java/tf/tuff/viablocks/version/VersionAdapter.java +++ b/src/main/java/tf/tuff/viablocks/version/VersionAdapter.java @@ -7,8 +7,12 @@ public interface VersionAdapter { String getBlockDataString(Block block); + String getMaterialKey(Material material); + int getClientViewDistance(Player player); + void giveCustomBlocks(Player player); + EnumSet getModernMaterials(); } \ No newline at end of file diff --git a/src/main/java/tf/tuff/viablocks/version/modern/ModernAdapter.java b/src/main/java/tf/tuff/viablocks/version/modern/ModernAdapter.java index be8e691..50d6ad6 100644 --- a/src/main/java/tf/tuff/viablocks/version/modern/ModernAdapter.java +++ b/src/main/java/tf/tuff/viablocks/version/modern/ModernAdapter.java @@ -644,8 +644,8 @@ public int getClientViewDistance(Player player) { if (clientViewDistanceMethod != null) { try { Object value = clientViewDistanceMethod.invoke(player); - if (value instanceof Integer) { - return (Integer) value; + if (value instanceof Integer integer) { + return integer; } } catch (Exception e) { return player.getServer().getViewDistance(); @@ -662,8 +662,6 @@ public void giveCustomBlocks(Player player) { private void addItemIfPresent(Player player, String materialName) { Material material = Material.matchMaterial(materialName); - if (material != null) { - player.getInventory().addItem(new ItemStack(material)); - } + if (material != null) player.getInventory().addItem(new ItemStack(material)); } } diff --git a/src/main/java/tf/tuff/viaentities/EntityDataHandler.java b/src/main/java/tf/tuff/viaentities/EntityDataHandler.java index b8f90d2..cd60797 100644 --- a/src/main/java/tf/tuff/viaentities/EntityDataHandler.java +++ b/src/main/java/tf/tuff/viaentities/EntityDataHandler.java @@ -1,12 +1,13 @@ package tf.tuff.viaentities; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import org.bukkit.entity.Player; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; +import java.util.List; public class EntityDataHandler extends ChannelOutboundHandlerAdapter { @@ -20,6 +21,7 @@ public EntityDataHandler(ViaEntitiesPlugin plugin, Player player) { this.entityMappingManager = plugin.entityMappingManager; } + @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { String className = msg.getClass().getName(); @@ -66,7 +68,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } } } - } catch (Exception e) { + } catch (Exception ignored) { } } @@ -80,21 +82,17 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) try { java.lang.reflect.Method getTypeMethod = msg.getClass().getMethod("getType"); java.lang.reflect.Method getIdMethod = msg.getClass().getMethod("getId"); - if (getTypeMethod != null && getIdMethod != null) { - Object typeResult = getTypeMethod.invoke(msg); - if (typeResult != null && typeResult.toString().contains("entity")) { - isSpawnPacket = true; - } + Object typeResult = getTypeMethod.invoke(msg); + if (typeResult != null && typeResult.toString().contains("entity")) { + isSpawnPacket = true; } - } catch (NoSuchMethodException e) { - } catch (Exception e) { - } + } catch (Exception ignored) {} } if (isSpawnPacket) { try { handleSpawnPacket(msg); - } catch (Exception e) { + } catch (Exception ignored) { } } else if (className.contains("EntityMetadata") || className.contains("SetEntityData") || simpleClassName.equals("PacketPlayOutEntityMetadata") || @@ -104,7 +102,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) if (entityId != -1) { sendEntityMetadata(entityId, null); } - } catch (Exception e) { + } catch (Exception ignored) { } } else if (className.contains("Animation") || simpleClassName.equals("PacketPlayOutAnimation") || @@ -115,14 +113,14 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) if (entityId != -1) { sendEntityAnimation(entityId, animationType); } - } catch (Exception e) { + } catch (Exception ignored) { } } else if (className.contains("EntityDestroy") || className.contains("RemoveEntities") || simpleClassName.equals("PacketPlayOutEntityDestroy") || simpleClassName.equals("ClientboundRemoveEntitiesPacket")) { try { handleDestroyPacket(msg); - } catch (Exception e) { + } catch (Exception ignored) { } } @@ -182,8 +180,7 @@ private void handleDestroyPacket(Object msg) throws Exception { for (java.lang.reflect.Field field : msg.getClass().getDeclaredFields()) { field.setAccessible(true); Object value = field.get(msg); - if (value instanceof it.unimi.dsi.fastutil.ints.IntList) { - it.unimi.dsi.fastutil.ints.IntList idList = (it.unimi.dsi.fastutil.ints.IntList) value; + if (value instanceof it.unimi.dsi.fastutil.ints.IntList idList) { for (int i = 0; i < idList.size(); i++) { sendEntityDestroy(idList.getInt(i)); } @@ -332,8 +329,7 @@ private void sendEntityMetadata(int entityId, Object packedItems) { out.writeUTF("ENTITY_METADATA"); out.writeInt(entityId); - if (packedItems instanceof java.util.List) { - java.util.List items = (java.util.List) packedItems; + if (packedItems instanceof List items) { out.writeInt(items.size()); for (Object item : items) { @@ -344,23 +340,28 @@ private void sendEntityMetadata(int entityId, Object packedItems) { java.lang.reflect.Method getValueMethod = item.getClass().getMethod("value"); Object value = getValueMethod.invoke(item); - if (value instanceof Boolean) { - out.writeByte(0); - out.writeBoolean((Boolean) value); - } else if (value instanceof Integer) { - out.writeByte(1); - out.writeInt((Integer) value); - } else if (value instanceof Float) { - out.writeByte(2); - out.writeFloat((Float) value); - } else if (value instanceof String) { - out.writeByte(3); - out.writeUTF((String) value); - } else if (value instanceof Byte) { - out.writeByte(4); - out.writeByte((Byte) value); - } else { - out.writeByte(-1); + switch (value) { + case Boolean b -> { + out.writeByte(0); + out.writeBoolean(b); + } + case Integer i -> { + out.writeByte(1); + out.writeInt(i); + } + case Float v -> { + out.writeByte(2); + out.writeFloat(v); + } + case String s -> { + out.writeByte(3); + out.writeUTF(s); + } + case Byte b -> { + out.writeByte(4); + out.writeByte(b); + } + case null, default -> out.writeByte(-1); } } } else { @@ -369,7 +370,7 @@ private void sendEntityMetadata(int entityId, Object packedItems) { byte[] data = out.toByteArray(); player.sendPluginMessage(plugin.plugin, ViaEntitiesPlugin.CLIENTBOUND_CHANNEL, data); - } catch (Exception e) { + } catch (Exception ignored) { } } diff --git a/src/main/java/tf/tuff/y0/ViaBlockIds.java b/src/main/java/tf/tuff/y0/ViaBlockIds.java index c3e2a9c..4312649 100644 --- a/src/main/java/tf/tuff/y0/ViaBlockIds.java +++ b/src/main/java/tf/tuff/y0/ViaBlockIds.java @@ -31,7 +31,7 @@ public class ViaBlockIds { public ViaBlockIds(TuffX pl) { p = pl; - plugin = pl.y0Plugin; + plugin = pl.getY0Plugin(); serverVersion = getServerMCVersion(); mappingsFile = new File(pl.getDataFolder(), serverVersion + "-mappings.json"); @@ -49,7 +49,7 @@ private void initializeMappings() { if (!mappingsFile.exists()) { plugin.info("Mapping file not found, generating..."); if (!p.getDataFolder().exists()) { - p.getDataFolder().mkdirs(); + if (p.getDataFolder().mkdirs()) plugin.info("Generated plugin data folder."); } generateMappings(mappingsFile); } else { @@ -160,22 +160,12 @@ private void generateMappings(File f) { String k = s.get(i).replace("minecraft:", ""); String blockName = k.contains("[") ? k.substring(0, k.indexOf("[")) : k; - int[] legacy; - - switch (blockName) { - case "chest": - legacy = new int[]{54, 0}; - break; - case "ender_chest": - legacy = new int[]{130, 0}; - break; - case "trapped_chest": - legacy = new int[]{146, 0}; - break; - default: - legacy = ctl(i); - break; - } + int[] legacy = switch (blockName) { + case "chest" -> new int[]{54, 0}; + case "ender_chest" -> new int[]{130, 0}; + case "trapped_chest" -> new int[]{146, 0}; + default -> ctl(i); + }; nlm.put(k, legacy); } @@ -259,17 +249,17 @@ public int[] ctl(int mbsi) { ProtocolPathEntry e = protoPath.get(i); Protocol pr = e.protocol(); - if (pr instanceof BackwardsProtocol) { - BackwardsMappingData md = ((BackwardsProtocol) pr).getMappingData(); + if (pr instanceof BackwardsProtocol backwardsProtocol) { + BackwardsMappingData md = backwardsProtocol.getMappingData(); if (md != null && md.getBlockStateMappings() != null) { int ni = md.getBlockStateMappings().getNewId(csi); - if (ni != -1) csi = ni; } } } - int bi = csi >> 4; - int mt = csi & 0xF; - return new int[]{bi, mt}; + return new int[] { + csi >> 4, + csi & 0xF + }; } } \ No newline at end of file diff --git a/src/main/java/tf/tuff/y0/Y0Plugin.java b/src/main/java/tf/tuff/y0/Y0Plugin.java index a875f8b..75a8742 100644 --- a/src/main/java/tf/tuff/y0/Y0Plugin.java +++ b/src/main/java/tf/tuff/y0/Y0Plugin.java @@ -39,7 +39,7 @@ public class Y0Plugin { public static final String CH = "eagler:below_y0"; public ViaBlockIds v; - + private final ObjectOpenHashSet aib = new ObjectOpenHashSet<>(); private ObjectOpenHashSet ew; private volatile Cache> cc; @@ -52,7 +52,7 @@ public class Y0Plugin { private final ThreadLocal tlbd = ThreadLocal.withInitial(() -> new byte[12288]); private TuffX plugin; - + private static final int[] EMPTY_LEGACY = {1, 0}; private static final Map emissionCache = new ConcurrentHashMap<>(); @@ -71,30 +71,30 @@ public class Y0Plugin { } private static final Map legacy_light_map = Map.ofEntries( - Map.entry(Material.TORCH, 14), - Map.entry(Material.SOUL_TORCH, 10), - Map.entry(Material.LANTERN, 15), - Map.entry(Material.SOUL_LANTERN, 10), - Map.entry(Material.GLOWSTONE, 15), - Map.entry(Material.SEA_LANTERN, 15), - Map.entry(Material.REDSTONE_LAMP, 15), - Map.entry(Material.SHROOMLIGHT, 15), - Map.entry(Material.CAMPFIRE, 15), - Map.entry(Material.SOUL_CAMPFIRE, 10), - Map.entry(Material.END_ROD, 14), - Map.entry(Material.MAGMA_BLOCK, 3), - Map.entry(Material.FIRE, 15), - Map.entry(Material.SOUL_FIRE, 10), - Map.entry(Material.CANDLE, 3), - Map.entry(Material.WHITE_CANDLE, 3), - Map.entry(Material.CAKE, 0), - Map.entry(Material.CANDLE_CAKE, 3) + Map.entry(Material.TORCH, 14), + Map.entry(Material.SOUL_TORCH, 10), + Map.entry(Material.LANTERN, 15), + Map.entry(Material.SOUL_LANTERN, 10), + Map.entry(Material.GLOWSTONE, 15), + Map.entry(Material.SEA_LANTERN, 15), + Map.entry(Material.REDSTONE_LAMP, 15), + Map.entry(Material.SHROOMLIGHT, 15), + Map.entry(Material.CAMPFIRE, 15), + Map.entry(Material.SOUL_CAMPFIRE, 10), + Map.entry(Material.END_ROD, 14), + Map.entry(Material.MAGMA_BLOCK, 3), + Map.entry(Material.FIRE, 15), + Map.entry(Material.SOUL_FIRE, 10), + Map.entry(Material.CANDLE, 3), + Map.entry(Material.WHITE_CANDLE, 3), + Map.entry(Material.CAKE, 0), + Map.entry(Material.CANDLE_CAKE, 3) ); public Y0Plugin(TuffX plugin){ this.plugin = plugin; } - + private void debug(String m) { if (d) plugin.getLogger().info("[Y0-Debug] " + m); } @@ -116,11 +116,11 @@ public record WCK(String w, int x, int z) {} public void onTuffXReload() { d = plugin.getConfig().getBoolean("y0.debug-mode", false); - + ObjectArrayList ewList = new ObjectArrayList<>(plugin.getConfig().getStringList("y0.enabled-worlds")); ew = new ObjectOpenHashSet<>(ewList.size()); if (plugin.getConfig().getBoolean("y0.y0-enabled", false)) ew.addAll(ewList); - + if (cc != null) { cc.invalidateAll(); } @@ -131,17 +131,17 @@ public void onTuffXReload() { int cacheExp = plugin.getConfig().getInt("y0.cache-expiration", 5); int concLevel = Runtime.getRuntime().availableProcessors(); cc = CacheBuilder.newBuilder() - .maximumSize(cacheSize) - .expireAfterAccess(cacheExp, TimeUnit.MINUTES) - .concurrencyLevel(concLevel) - .initialCapacity(256) - .build(); + .maximumSize(cacheSize) + .expireAfterAccess(cacheExp, TimeUnit.MINUTES) + .concurrencyLevel(concLevel) + .initialCapacity(256) + .build(); ccCombined = CacheBuilder.newBuilder() - .maximumSize(cacheSize) - .expireAfterAccess(cacheExp, TimeUnit.MINUTES) - .concurrencyLevel(concLevel) - .initialCapacity(256) - .build(); + .maximumSize(cacheSize) + .expireAfterAccess(cacheExp, TimeUnit.MINUTES) + .concurrencyLevel(concLevel) + .initialCapacity(256) + .build(); if (cp != null) { cp.shutdown(); @@ -154,7 +154,7 @@ public void onTuffXReload() { Thread.currentThread().interrupt(); } } - + int ct = plugin.getConfig().getInt("y0.chunk-processor-threads", -1); int tc; if (ct <= 0) { @@ -162,13 +162,13 @@ public void onTuffXReload() { } else { tc = ct; } - + cp = Executors.newFixedThreadPool(tc, r -> { Thread t = new Thread(r, "TuffX-Chunk-" + System.nanoTime()); t.setDaemon(true); t.setPriority(Thread.NORM_PRIORITY - 1); return t; - }); + }); emissionCache.clear(); @@ -190,17 +190,17 @@ public void onTuffXEnable() { int cacheExp2 = plugin.getConfig().getInt("y0.cache-expiration", 5); int concLevel2 = Runtime.getRuntime().availableProcessors(); cc = CacheBuilder.newBuilder() - .maximumSize(cacheSize2) - .expireAfterAccess(cacheExp2, TimeUnit.MINUTES) - .concurrencyLevel(concLevel2) - .initialCapacity(256) - .build(); + .maximumSize(cacheSize2) + .expireAfterAccess(cacheExp2, TimeUnit.MINUTES) + .concurrencyLevel(concLevel2) + .initialCapacity(256) + .build(); ccCombined = CacheBuilder.newBuilder() - .maximumSize(cacheSize2) - .expireAfterAccess(cacheExp2, TimeUnit.MINUTES) - .concurrencyLevel(concLevel2) - .initialCapacity(256) - .build(); + .maximumSize(cacheSize2) + .expireAfterAccess(cacheExp2, TimeUnit.MINUTES) + .concurrencyLevel(concLevel2) + .initialCapacity(256) + .build(); plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, CH); plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, CH, plugin); @@ -214,7 +214,7 @@ public void onTuffXEnable() { } else { tc = ct; } - + cp = Executors.newFixedThreadPool(tc, r -> { Thread t = new Thread(r, "TuffX-Chunk-" + System.nanoTime()); t.setDaemon(true); @@ -253,7 +253,7 @@ public void onTuffXDisable() { } aib.clear(); - + if (v != null) { v = null; } @@ -395,7 +395,7 @@ private void sendY0ChunksBatched(Player p, String worldName, List chunks, if (endIndex < chunks.size()) { final int nextStart = endIndex; plugin.getServer().getScheduler().runTaskLater(plugin, () -> - sendY0ChunksBatched(p, worldName, chunks, nextStart), 1); + sendY0ChunksBatched(p, worldName, chunks, nextStart), 1); } } @@ -641,7 +641,7 @@ public void cacheChunkWithCallback(Player p, int chunkX, int chunkZ, Consumer= 0) continue; stu.add(new CSC( - (bx + dx) >> 4, - ny >> 4, - (bz + dz) >> 4 + (bx + dx) >> 4, + ny >> 4, + (bz + dz) >> 4 )); } } @@ -856,7 +856,7 @@ private void slu(Location l) { for (CSC sc : stu) { if (!w.isChunkLoaded(sc.x, sc.z)) continue; ChunkSnapshot s = w.getChunkAt(sc.x, sc.z).getChunkSnapshot(true, false, false); - + if (cp != null && !cp.isShutdown()) { cp.submit(() -> { try { @@ -877,8 +877,8 @@ private void slu(Location l) { } private byte[] clp(ChunkSnapshot s, CSC sc) throws IOException { - try (ByteArrayOutputStream b = new ByteArrayOutputStream(4120); - DataOutputStream o = new DataOutputStream(b)) { + try (ByteArrayOutputStream b = new ByteArrayOutputStream(4120); + DataOutputStream o = new DataOutputStream(b)) { o.writeUTF("lighting_update"); o.writeInt(sc.x); o.writeInt(sc.z);