diff --git a/build.gradle b/build.gradle index b0b745008..5c9fec3e8 100644 --- a/build.gradle +++ b/build.gradle @@ -1,13 +1,13 @@ plugins { id("dev.magicspells.msjava") - id("io.papermc.paperweight.userdev") version "2.0.0-beta.21" apply false + id("io.papermc.paperweight.userdev") version "2.0.0-beta.24" apply false } subprojects { apply plugin: "dev.magicspells.msjava" dependencies { - compileOnly("io.papermc.paper:paper-api:26.1.2.build.+") + compileOnly("io.papermc.paper:paper-api:26.3.build.+") } processResources { diff --git a/core/build.gradle b/core/build.gradle index 6be45d5c6..f73109897 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -1,5 +1,5 @@ plugins { - id("com.gradleup.shadow") version "9.4.1" + id("com.gradleup.shadow") version "9.6.1" id("antlr") } @@ -11,26 +11,24 @@ dependencies { implementation("org.incendo:cloud-minecraft-extras:2.0.1") implementation("org.incendo:cloud-processors-requirements:1.0.0-rc.1") implementation("org.bstats:bstats-bukkit:3.2.1") - implementation("com.github.ezylang:EvalEx:3.6.2") + implementation("com.ezylang:EvalEx:3.8.0") implementation("org.antlr:antlr4-runtime:4.13.2") antlr("org.antlr:antlr4:4.13.2") implementation(project(path: ":nms:shared")) implementation(project(path: ":nms:latest")) - implementation(project(path: ":nms:v26_1_2")) - implementation(project(path: ":nms:v26_2")) - compileOnly("com.github.retrooper:packetevents-spigot:2.11.2") + compileOnly("com.github.retrooper:packetevents-spigot:2.14.0") compileOnly("net.dmulloy2:ProtocolLib:5.4.0") - compileOnly("me.libraryaddict.disguises:libsdisguises:11.0.16-SNAPSHOT") + compileOnly("me.libraryaddict.disguises:libsdisguises:26.11.10-SNAPSHOT") compileOnly("net.milkbowl.vault:VaultAPI:1.7") compileOnly("me.clip:placeholderapi:2.12.2") compileOnly("com.github.GriefPrevention:GriefPrevention:18.0.0") compileOnly("com.sk89q.worldguard:worldguard-core:7.1.0-SNAPSHOT") compileOnly("com.sk89q.worldguard:worldguard-bukkit:7.1.0-SNAPSHOT") - compileOnly("com.sk89q.worldedit:worldedit-core:7.4.0-SNAPSHOT") - compileOnly("com.sk89q.worldedit:worldedit-bukkit:7.4.0-SNAPSHOT") + compileOnly("com.sk89q.worldedit:worldedit-core:7.4.6-SNAPSHOT") + compileOnly("com.sk89q.worldedit:worldedit-bukkit:7.4.6-SNAPSHOT") } /* diff --git a/core/src/main/java/com/nisovin/magicspells/MagicSpells.java b/core/src/main/java/com/nisovin/magicspells/MagicSpells.java index 502140822..5ee6a4081 100644 --- a/core/src/main/java/com/nisovin/magicspells/MagicSpells.java +++ b/core/src/main/java/com/nisovin/magicspells/MagicSpells.java @@ -18,7 +18,6 @@ import java.lang.reflect.Constructor; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; -import java.lang.annotation.Annotation; import java.net.URL; import java.net.URLClassLoader; @@ -93,6 +92,7 @@ import com.nisovin.magicspells.events.SpellLearnEvent.LearnSource; import com.nisovin.magicspells.spelleffects.trackers.EffectTracker; import com.nisovin.magicspells.spells.passive.util.PassiveListener; +import com.nisovin.magicspells.util.recipes.RecipeDiscoverListener; import com.nisovin.magicspells.variables.variabletypes.GlobalVariable; import com.nisovin.magicspells.spelleffects.trackers.AsyncEffectTracker; import com.nisovin.magicspells.spelleffects.effecttypes.EffectLibEffect; @@ -447,6 +447,8 @@ public void load() { } log("..." + MagicItems.getMagicItems().size() + " magic items loaded"); + // Load custom recipes + registerEvents(new RecipeDiscoverListener()); if (config.isSection(path + "recipes")) { log("Loading recipes..."); CustomRecipes.load(config.getSection(path + "recipes")); @@ -2093,9 +2095,7 @@ public static void profilingReport() { if (plugin.profilingTotalTime == null) return; if (plugin.profilingRuns == null) return; - PrintWriter writer = null; - try { - writer = new PrintWriter(new File(plugin.getDataFolder(), "profiling_report_" + System.currentTimeMillis() + ".txt")); + try (PrintWriter writer = new PrintWriter(new File(plugin.getDataFolder(), "profiling_report_" + System.currentTimeMillis() + ".txt"))) { long totalTime = 0; writer.println("Key\tRuns\tAvg\tTotal"); for (String key : plugin.profilingTotalTime.keySet()) { @@ -2109,8 +2109,6 @@ public static void profilingReport() { } catch (Exception ex) { error("Failed to save profiling report"); handleException(ex); - } finally { - if (writer != null) writer.close(); } plugin.profilingTotalTime.clear(); plugin.profilingRuns.clear(); @@ -2249,11 +2247,11 @@ public void unload() { cooldown = cooldowns.get(id); if (cooldown <= System.currentTimeMillis()) continue; writer.append(spell.getInternalName()) - .append(String.valueOf(':')) + .append(':') .append(id.toString()) - .append(String.valueOf(':')) + .append(':') .append(String.valueOf(cooldown)) - .append(String.valueOf('\n')); + .append('\n'); } } writer.close(); diff --git a/core/src/main/java/com/nisovin/magicspells/Spellbook.java b/core/src/main/java/com/nisovin/magicspells/Spellbook.java index 0ed28abf4..9535b64d1 100644 --- a/core/src/main/java/com/nisovin/magicspells/Spellbook.java +++ b/core/src/main/java/com/nisovin/magicspells/Spellbook.java @@ -2,7 +2,6 @@ import java.util.*; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.inventory.ItemStack; @@ -273,7 +272,7 @@ public boolean hasSpell(Spell spell, boolean checkGranted) { protected CastItem getCastItemForCycling(ItemStack item) { CastItem castItem; if (item != null) castItem = new CastItem(item); - else castItem = new CastItem(new ItemStack(Material.AIR)); + else castItem = new CastItem(ItemStack.empty()); List spells = itemSpells.get(castItem); if (spells != null && (spells.size() > 1 || (spells.size() == 1 && MagicSpells.canCycleToNoSpell()))) return castItem; diff --git a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HasItemCondition.java b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HasItemCondition.java index 247c9923b..e1a2771fc 100644 --- a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HasItemCondition.java +++ b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HasItemCondition.java @@ -90,7 +90,7 @@ private boolean checkInventory(Inventory inventory) { if (item == null) continue; Component itemName = null; try { - if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) itemName = item.getItemMeta().displayName(); + if (item.hasItemMeta() && item.getItemMeta().hasCustomName()) itemName = item.getItemMeta().customName(); } catch (Exception e) { DebugHandler.debugGeneral(e); } @@ -112,7 +112,7 @@ private boolean checkEquipment(EntityEquipment entityEquipment) { if (item == null) continue; Component itemName = null; try { - if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) itemName = item.getItemMeta().displayName(); + if (item.hasItemMeta() && item.getItemMeta().hasCustomName()) itemName = item.getItemMeta().customName(); } catch (Exception e) { DebugHandler.debugGeneral(e); } diff --git a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HoldingCondition.java b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HoldingCondition.java index 6afa0bbbb..347a314ca 100644 --- a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HoldingCondition.java +++ b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/HoldingCondition.java @@ -97,7 +97,7 @@ private boolean checkHolding(LivingEntity target) { Component name = null; try { - if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) name = item.getItemMeta().displayName(); + if (item.hasItemMeta() && item.getItemMeta().hasCustomName()) name = item.getItemMeta().customName(); } catch (Exception e) { DebugHandler.debugGeneral(e); } diff --git a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/OffhandCondition.java b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/OffhandCondition.java index 2eab82b14..a031d2d1c 100644 --- a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/OffhandCondition.java +++ b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/OffhandCondition.java @@ -93,7 +93,7 @@ private boolean offHand(LivingEntity target) { int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage() : 0; Component name = null; try { - if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) name = item.getItemMeta().displayName(); + if (item.hasItemMeta() && item.getItemMeta().hasCustomName()) name = item.getItemMeta().customName(); } catch (Exception e) { // no op } diff --git a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/WearingCondition.java b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/WearingCondition.java index cf7268e97..d32752b64 100644 --- a/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/WearingCondition.java +++ b/core/src/main/java/com/nisovin/magicspells/castmodifiers/conditions/WearingCondition.java @@ -102,7 +102,7 @@ private boolean checkItem(ItemStack item) { int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage() : 0; Component name = null; try { - if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) name = item.getItemMeta().displayName(); + if (item.hasItemMeta() && item.getItemMeta().hasCustomName()) name = item.getItemMeta().customName(); } catch (Exception e) { DebugHandler.debugGeneral(e); } diff --git a/core/src/main/java/com/nisovin/magicspells/commands/parsers/SpellCastArgumentsParser.java b/core/src/main/java/com/nisovin/magicspells/commands/parsers/SpellCastArgumentsParser.java index 4baaec8ee..55cf6bd4b 100644 --- a/core/src/main/java/com/nisovin/magicspells/commands/parsers/SpellCastArgumentsParser.java +++ b/core/src/main/java/com/nisovin/magicspells/commands/parsers/SpellCastArgumentsParser.java @@ -3,7 +3,6 @@ import org.jetbrains.annotations.NotNull; import java.util.*; -import java.util.stream.Stream; import java.util.stream.StreamSupport; import java.util.concurrent.CompletableFuture; @@ -115,7 +114,7 @@ public static ParserDescriptor spellCastArgumentsP } @Override - public @NotNull CompletableFuture<@NotNull ? extends Iterable<@NotNull ? extends Suggestion>> suggestionsFuture(@NotNull CommandContext context, @NotNull CommandInput input) { + public @NotNull CompletableFuture> suggestionsFuture(@NotNull CommandContext context, @NotNull CommandInput input) { if (context.contains(PARSE_SUGGESTIONS)) return CompletableFuture.completedFuture(context.get(PARSE_SUGGESTIONS)); diff --git a/core/src/main/java/com/nisovin/magicspells/handlers/PotionEffectHandler.java b/core/src/main/java/com/nisovin/magicspells/handlers/PotionEffectHandler.java index 6c1887577..1309e8f63 100644 --- a/core/src/main/java/com/nisovin/magicspells/handlers/PotionEffectHandler.java +++ b/core/src/main/java/com/nisovin/magicspells/handlers/PotionEffectHandler.java @@ -12,9 +12,19 @@ public class PotionEffectHandler { static { // Add bukkit and minecraft potion effect names - for (PotionEffectType potionEffect : Registry.EFFECT) { - //noinspection deprecation - potionEffects.put(potionEffect.getName().toLowerCase(), potionEffect); + + // Add legacy values + potionEffects.put("slow", PotionEffectType.SLOWNESS); + potionEffects.put("fast_digging", PotionEffectType.HASTE); + potionEffects.put("slow_digging", PotionEffectType.MINING_FATIGUE); + potionEffects.put("increase_damage", PotionEffectType.STRENGTH); + potionEffects.put("heal", PotionEffectType.INSTANT_HEALTH); + potionEffects.put("harm", PotionEffectType.INSTANT_DAMAGE); + potionEffects.put("jump", PotionEffectType.JUMP_BOOST); + potionEffects.put("confusion", PotionEffectType.NAUSEA); + potionEffects.put("damage_resistance", PotionEffectType.RESISTANCE); + + for (PotionEffectType potionEffect : Registry.MOB_EFFECT) { potionEffects.put(potionEffect.key().value(), potionEffect); } } diff --git a/core/src/main/java/com/nisovin/magicspells/listeners/CastListener.java b/core/src/main/java/com/nisovin/magicspells/listeners/CastListener.java index 96abc3ab8..5e33a1fd9 100644 --- a/core/src/main/java/com/nisovin/magicspells/listeners/CastListener.java +++ b/core/src/main/java/com/nisovin/magicspells/listeners/CastListener.java @@ -21,8 +21,8 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; -import org.bukkit.event.player.PlayerAnimationEvent; +import io.papermc.paper.event.player.PlayerArmSwingEvent; import io.papermc.paper.event.player.PrePlayerAttackEntityEvent; import com.nisovin.magicspells.Spell; @@ -96,7 +96,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { } @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerAnimation(PlayerAnimationEvent event) { + public void onPlayerArmSwing(PlayerArmSwingEvent event) { if (!MagicSpells.isCastingOnAnimate()) return; Player player = event.getPlayer(); diff --git a/core/src/main/java/com/nisovin/magicspells/listeners/DanceCastListener.java b/core/src/main/java/com/nisovin/magicspells/listeners/DanceCastListener.java index 2c14db79a..448253000 100644 --- a/core/src/main/java/com/nisovin/magicspells/listeners/DanceCastListener.java +++ b/core/src/main/java/com/nisovin/magicspells/listeners/DanceCastListener.java @@ -38,11 +38,11 @@ public class DanceCastListener implements Listener { private Map playerTasks = new HashMap<>(); private Map playerLocations = new HashMap<>(); - private boolean dynamicCasting = false; + private boolean dynamicCasting; private boolean enableMovement = false; private boolean enableDoubleJump = false; - private String startSound = null; + private String startSound; private float startSoundVolume = 1; private float startSoundPitch = 1; diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/BossBarEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/BossBarEffect.java index 5f478056b..20b9dc1a6 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/BossBarEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/BossBarEffect.java @@ -141,7 +141,7 @@ private void updateBar(Player player, SpellData data) { else progress = this.progress.get(data); } else progress = this.progress.get(data); - progress = Math.min(Math.max(progress, 0), 1); + progress = Math.clamp(progress, 0, 1); String title = Util.getLegacyFromComponent(Util.getMiniMessage(this.title, player, data)); bar.set(title, progress, barStyle.get(data), barColor.get(data), visible.get(data)); diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CloudEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CloudEffect.java index 15a43b64c..87eba1b6d 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CloudEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CloudEffect.java @@ -54,12 +54,12 @@ public Runnable playEffectLocation(Location location, SpellData data) { private void smoke(World w, Block b, int r) { Location loc = b.getLocation(); if (r <= 5) { - for (int i = 0; i <= 8; i += 2) w.playEffect(loc, Effect.SMOKE, i); + for (int i = 0; i <= 8; i += 2) w.playEffect(loc, Effect.SMOKE_SHOOT, i); } else if (r <= 8) { - w.playEffect(loc, Effect.SMOKE, random.nextInt(9)); - w.playEffect(loc, Effect.SMOKE, random.nextInt(9)); + w.playEffect(loc, Effect.SMOKE_SHOOT, random.nextInt(9)); + w.playEffect(loc, Effect.SMOKE_SHOOT, random.nextInt(9)); } else { - w.playEffect(loc, Effect.SMOKE, random.nextInt(9)); + w.playEffect(loc, Effect.SMOKE_SHOOT, random.nextInt(9)); } } diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CompleteUsingItemEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CompleteUsingItemEffect.java index 9d5202589..1f2981427 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CompleteUsingItemEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/CompleteUsingItemEffect.java @@ -17,7 +17,6 @@ protected void loadFromConfig(ConfigurationSection config) { } - @SuppressWarnings("UnstableApiUsage") @Override protected Runnable playEffectEntity(Entity entity, SpellData data) { if (entity instanceof LivingEntity livingEntity) diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/FireworksEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/FireworksEffect.java index 4fdfbdacb..71037f36c 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/FireworksEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/FireworksEffect.java @@ -1,11 +1,16 @@ package com.nisovin.magicspells.spelleffects.effecttypes; +import java.util.List; + import org.bukkit.*; import org.bukkit.entity.Firework; -import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import org.bukkit.configuration.ConfigurationSection; +import io.papermc.paper.datacomponent.item.Fireworks; +import io.papermc.paper.datacomponent.DataComponentTypes; + import com.nisovin.magicspells.util.Name; import com.nisovin.magicspells.MagicSpells; import com.nisovin.magicspells.util.SpellData; @@ -87,10 +92,9 @@ public Runnable playEffectLocation(Location location, SpellData data) { .build(); location.getWorld().spawn(location, Firework.class, firework -> { - FireworkMeta meta = firework.getFireworkMeta(); - meta.addEffect(effect); - meta.setPower(0); - firework.setFireworkMeta(meta); + ItemStack rocket = firework.getItem(); + rocket.setData(DataComponentTypes.FIREWORKS, Fireworks.fireworks(List.of(effect), 0)); + firework.setItem(rocket); firework.setSilent(true); firework.setTicksToDetonate(flightDuration.get(data)); diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ItemSprayEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ItemSprayEffect.java index e67bf79cb..4c592f44e 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ItemSprayEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ItemSprayEffect.java @@ -64,7 +64,7 @@ public void loadFromConfig(ConfigurationSection config) { public Runnable playEffectLocation(Location location, SpellData data) { Material material = this.material.get(data); if (material == null) return null; - ItemStack itemStack = new ItemStack(material); + ItemStack itemStack = ItemStack.of(material); Location loc = location.clone().add(0, 1, 0); diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/NovaEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/NovaEffect.java index c96efdc3a..6deec2b40 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/NovaEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/NovaEffect.java @@ -86,7 +86,7 @@ public Runnable playEffectLocation(Location location, SpellData data) { if (blockData == null) return null; double range = this.range.get(data); - range = Math.max(Math.min(range, MagicSpells.getGlobalRadius()), 1); + range = Math.clamp(range, 1, MagicSpells.getGlobalRadius()); Collection nearbyPlayers = location.getWorld().getNearbyPlayers(location, range, range, range); diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesEffect.java index f1b866a2e..e8d07d44a 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesEffect.java @@ -20,7 +20,6 @@ import org.bukkit.configuration.ConfigurationSection; import com.nisovin.magicspells.util.Name; -import com.nisovin.magicspells.MagicSpells; import com.nisovin.magicspells.util.SpellData; import com.nisovin.magicspells.util.config.ConfigData; import com.nisovin.magicspells.spelleffects.SpellEffect; @@ -135,7 +134,7 @@ protected Runnable playEffectEntity(Entity entity, SpellData data) { .location(spawnLocation) .count(count.get(data)) .offset(xSpread.get(data), ySpread.get(data), zSpread.get(data)) - .extra(speed.get(data)) + .speed(speed.get(data)) .data(getParticleData(particle, entity, location, data)) .force(force.get(data)) .receivers(radius.get(data), true) @@ -155,7 +154,7 @@ public Runnable playEffectLocation(Location location, SpellData data) { .location(spawnLocation) .count(count.get(data)) .offset(xSpread.get(data), ySpread.get(data), zSpread.get(data)) - .extra(speed.get(data)) + .speed(speed.get(data)) .data(getParticleData(particle, null, location, data)) .force(force.get(data)) .receivers(radius.get(data), true) @@ -165,12 +164,10 @@ public Runnable playEffectLocation(Location location, SpellData data) { } protected Object getParticleData(@NotNull Particle particle, @Nullable Entity entity, @NotNull Location location, @NotNull SpellData data) { - Object nmsData = MagicSpells.getVolatileCodeHandler().getVolatileParticleData( - particle, - () -> geyserWaterBlocks.get(data), - () -> geyserBurstImpulse.get(data) - ); - if (nmsData != null) return nmsData; +// Object nmsData = MagicSpells.getVolatileCodeHandler().getVolatileParticleData( +// particle, +// ); +// if (nmsData != null) return nmsData; Class type = particle.getDataType(); @@ -182,7 +179,22 @@ protected Object getParticleData(@NotNull Particle particle, @Nullable Entity en if (type == ItemStack.class) { Material material = this.material.get(data); - return material == null ? null : new ItemStack(material); + return material == null ? null : ItemStack.of(material); + } + + if (type == Particle.Geyser.class) { + Integer waterBlocks = geyserWaterBlocks.get(data); + if (waterBlocks == null) return null; + + return new Particle.Geyser(waterBlocks); + } + + if (type == Particle.GeyserBase.class) { + Integer waterBlocks = geyserWaterBlocks.get(data); + Float burstImpulse = geyserBurstImpulse.get(data); + if (waterBlocks == null || burstImpulse == null) return null; + + return new Particle.GeyserBase(waterBlocks, burstImpulse); } if (type == Vibration.class) { diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesPersonalEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesPersonalEffect.java index adad24182..dbefc286d 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesPersonalEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/ParticlesPersonalEffect.java @@ -39,7 +39,7 @@ protected Runnable playEffectEntity(Entity entity, SpellData data) { .location(location) .count(count.get(data)) .offset(xSpread.get(data), ySpread.get(data), zSpread.get(data)) - .extra(speed.get(data)) + .speed(speed.get(data)) .data(getParticleData(particle, entity, location, data)) .force(force.get(data)) .receivers(player) @@ -62,7 +62,7 @@ public Runnable playEffectLocation(Location location, SpellData data) { .location(location) .count(count.get(data)) .offset(xSpread.get(data), ySpread.get(data), zSpread.get(data)) - .extra(speed.get(data)) + .speed(speed.get(data)) .data(getParticleData(particle, null, location, data)) .force(force.get(data)) .receivers(player) diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeSwirlEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeSwirlEffect.java index a4d428c04..8a61285c3 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeSwirlEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeSwirlEffect.java @@ -79,7 +79,7 @@ public void run() { if (location != null) loc = location; else loc = entity.getLocation(); - loc.getWorld().playEffect(loc.clone().add(X[i], 0, Z[i]), Effect.SMOKE, V[i]); + loc.getWorld().playEffect(loc.clone().add(X[i], 0, Z[i]), Effect.SMOKE_SHOOT, V[i]); iteration++; } diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeTrailEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeTrailEffect.java index 948ce3e3e..1b80da80a 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeTrailEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/SmokeTrailEffect.java @@ -73,7 +73,7 @@ public void run() { } Location loc = locationsForProjection.get(i); for (int j = 0; j <= 8; j += 2) { - world.playEffect(loc, Effect.SMOKE, j); + world.playEffect(loc, Effect.SMOKE_SHOOT, j); } i++; } diff --git a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/StartUsingItemEffect.java b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/StartUsingItemEffect.java index 0195c0cf2..ae0a5466c 100644 --- a/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/StartUsingItemEffect.java +++ b/core/src/main/java/com/nisovin/magicspells/spelleffects/effecttypes/StartUsingItemEffect.java @@ -21,7 +21,6 @@ protected void loadFromConfig(ConfigurationSection config) { hand = ConfigDataUtil.getEnum(config, "hand", HandType.class, HandType.MAINHAND); } - @SuppressWarnings("UnstableApiUsage") @Override protected Runnable playEffectEntity(Entity entity, SpellData data) { if (entity instanceof LivingEntity livingEntity) diff --git a/core/src/main/java/com/nisovin/magicspells/spells/BowSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/BowSpell.java index 9f90d4b86..ae2e8e7de 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/BowSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/BowSpell.java @@ -225,7 +225,7 @@ public void handleBowCast(EntityShootBowEvent event) { float maximumForce = this.maximumForce.get(data); if (maximumForce > 0 && force > maximumForce) return; - Component name = bow.getItemMeta().displayName(); + Component name = bow.getItemMeta().customName(); if (bowNames != null && !bowNames.contains(name)) return; if (disallowedBowNames != null && disallowedBowNames.contains(name)) return; if (bowName != null && !bowName.equals(name)) return; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/MenuSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/MenuSpell.java index 0a7ccaaec..822e7106f 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/MenuSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/MenuSpell.java @@ -344,7 +344,7 @@ private ItemStack translateItem(Player opener, ItemStack item, SpellData data) { ItemStack newItem = item.clone(); newItem.editMeta(meta -> { - meta.displayName(translateRawComponent(meta.displayName(), opener, data)); + meta.customName(translateRawComponent(meta.customName(), opener, data)); List lore = meta.lore(); if (lore != null) { diff --git a/core/src/main/java/com/nisovin/magicspells/spells/PlayerMenuSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/PlayerMenuSpell.java index 39c5bab3d..2e3233a83 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/PlayerMenuSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/PlayerMenuSpell.java @@ -194,9 +194,9 @@ private ItemStack createItem(String path, String defaultName) { MagicItem magicItem = MagicItems.getMagicItemFromString(getConfigString(path, null)); if (magicItem != null) return magicItem.getItemStack().clone(); - ItemStack item = new ItemStack(Material.GREEN_WOOL); + ItemStack item = ItemStack.of(Material.GREEN_WOOL); Component name = Component.text(defaultName).color(NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false); - item.editMeta(meta -> meta.displayName(name)); + item.editMeta(meta -> meta.customName(name)); return item; } @@ -227,10 +227,10 @@ private void open(Player opener, PlayerMenuInventory menu) { Player player = players.get(i); SpellData subData = menu.openerData.target(player); - ItemStack head = new ItemStack(Material.PLAYER_HEAD); + ItemStack head = ItemStack.of(Material.PLAYER_HEAD); head.editMeta(SkullMeta.class, meta -> { meta.setOwningPlayer(player); - meta.displayName(Util.getItemMiniMessage(skullName, opener, subData)); + meta.customName(Util.getItemMiniMessage(skullName, opener, subData)); if (skullLore != null) { List lore = new ArrayList<>(); @@ -283,7 +283,7 @@ public void onItemClick(InventoryClickEvent event) { OfflinePlayer target = skullMeta.getOwningPlayer(); if (target == null || !target.isOnline()) { - meta.displayName(Util.getItemMiniMessage(skullNameOffline, opener, menu.openerData)); + meta.customName(Util.getItemMiniMessage(skullNameOffline, opener, menu.openerData)); if (spellOffline != null) spellOffline.subcast(menu.openerData); if (menu.stayOpen) item.setItemMeta(meta); @@ -300,11 +300,11 @@ public void onItemClick(InventoryClickEvent event) { SpellData targetData = menu.openerData.target(targetPlayer); - meta.displayName(Util.getItemMiniMessage(skullName, opener, targetData)); + meta.customName(Util.getItemMiniMessage(skullName, opener, targetData)); item.setItemMeta(meta); if (menu.radius > 0 && targetPlayer.getLocation().distance(opener.getLocation()) > menu.radius) { - meta.displayName(Util.getItemMiniMessage(skullNameRadius, opener, targetData)); + meta.customName(Util.getItemMiniMessage(skullNameRadius, opener, targetData)); if (spellRange != null) spellRange.subcast(menu.openerData); if (menu.stayOpen) item.setItemMeta(meta); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/buff/GillsSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/buff/GillsSpell.java index 765626bb8..34ae9ec2e 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/buff/GillsSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/buff/GillsSpell.java @@ -101,7 +101,7 @@ private ItemStack getHelmet(SpellData data) { Material headMaterial = this.headMaterial.get(data); if (headMaterial.getEquipmentSlot() != EquipmentSlot.HEAD && !headMaterial.isBlock()) return null; - ItemStack helmet = new ItemStack(headMaterial); + ItemStack helmet = ItemStack.of(headMaterial); helmet.editMeta(meta -> meta.getPersistentDataContainer().set(MARKER, PersistentDataType.BOOLEAN, true)); return helmet; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/buff/ReachSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/buff/ReachSpell.java index 7af660855..521faa518 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/buff/ReachSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/buff/ReachSpell.java @@ -124,7 +124,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { if (!evt.callEvent()) return; // Remove block - targetBlock.getWorld().playEffect(targetBlock.getLocation(), Effect.STEP_SOUND, targetBlock.getBlockData()); + targetBlock.getWorld().playEffect(targetBlock.getLocation(), Effect.DESTROY_BLOCK, targetBlock.getBlockData()); if (!data.dropBlocks) targetBlock.setType(Material.AIR); else { diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/ImbueSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/ImbueSpell.java index 0327f19fd..05ae9444a 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/ImbueSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/ImbueSpell.java @@ -129,7 +129,7 @@ public CastResult cast(SpellData data) { if (data.args().length > 1 && CAST_ARG_USES_PATTERN.asMatchPredicate().test(data.args()[1]) && (allowSpecifyUses.get(data) || Perm.ADVANCED_IMBUE.has(caster))) { uses = Integer.parseInt(data.args()[1]); } - uses = Math.max(Math.min(uses, maxUses), 1); + uses = Math.clamp(uses, 1, maxUses); if (chargeReagentsForSpellPerUse.get(data) && !Perm.NO_REAGENTS.has(caster)) { SpellReagents reagents = spell.getReagents().multiply(uses); @@ -225,7 +225,7 @@ private void setItemNameAndLore(ItemStack item, Spell spell, int uses) { ItemMeta meta = item.getItemMeta(); if (!strItemName.isEmpty()) { String displayName = strItemName.replace("%s", spell.getName()).replace("%u", uses + ""); - meta.displayName(Util.getItemMiniMessage(displayName)); + meta.customName(Util.getItemMiniMessage(displayName)); } if (!strItemLore.isEmpty()) { String lore = strItemLore.replace("%s", spell.getName()).replace("%u", uses + ""); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/ItemSerializeSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/ItemSerializeSpell.java index 6a3823e6a..54f020cdc 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/ItemSerializeSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/ItemSerializeSpell.java @@ -41,6 +41,8 @@ public ItemSerializeSpell(MagicConfig config, String spellName) { @Override protected void initialize() { + super.initialize(); + // Setup data folder dataFolder = new File(MagicSpells.getInstance().getDataFolder(), "items"); if (!dataFolder.exists()) dataFolder.mkdirs(); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/KeybindSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/KeybindSpell.java index 21e6a8a96..758b3c2bf 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/KeybindSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/KeybindSpell.java @@ -24,9 +24,9 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; -import org.bukkit.event.player.PlayerAnimationEvent; import org.bukkit.configuration.file.YamlConfiguration; +import io.papermc.paper.event.player.PlayerArmSwingEvent; import io.papermc.paper.command.brigadier.CommandSourceStack; import com.nisovin.magicspells.Spell; @@ -127,13 +127,13 @@ public CastResult cast(SpellData data) { } if (!item.getType().isAir()) { - caster.sendMessage("Not empty."); + caster.sendPlainMessage("Not empty."); return new CastResult(PostCastAction.ALREADY_HANDLED, data); } Spell spell = MagicSpells.getSpellByName(data.args()[0]); if (spell == null || !MagicSpells.getSpellbook(caster).hasSpell(spell)) { - caster.sendMessage("No spell."); + caster.sendPlainMessage("No spell."); return new CastResult(PostCastAction.ALREADY_HANDLED, data); } @@ -169,7 +169,7 @@ public void onItemHeldChange(PlayerItemHeldEvent event) { } @EventHandler - public void onAnimate(PlayerAnimationEvent event) { + public void onArmSwing(PlayerArmSwingEvent event) { Keybinds keybinds = playerKeybinds.get(event.getPlayer().getName()); if (keybinds == null) return; boolean casted = keybinds.castKeybind(event.getPlayer().getInventory().getHeldItemSlot()); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/ScrollSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/ScrollSpell.java index f079990b2..aca6c5f31 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/ScrollSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/ScrollSpell.java @@ -212,20 +212,20 @@ public boolean castFromConsole(CommandSender sender, String[] args) { } } - if (slot != -1) players.get(0).getInventory().setItem(slot, createScroll(spell, uses, new ItemStack(itemType, 1))); + if (slot != -1) players.get(0).getInventory().setItem(slot, createScroll(spell, uses, ItemStack.of(itemType))); return true; } public ItemStack createScroll(Spell spell, int uses, ItemStack item) { - if (item == null) item = new ItemStack(itemType); + if (item == null) item = ItemStack.of(itemType); ItemMeta meta = item.getItemMeta(); if (meta instanceof Damageable damageable) damageable.setDamage(0); String usageCount = uses >= 0 ? String.valueOf(uses) : "many"; String displayName = strScrollName.replace("%s", spell.getName()).replace("%u", usageCount); - meta.displayName(Util.getItemMiniMessage(displayName)); + meta.customName(Util.getItemMiniMessage(displayName)); if (strScrollSubtext != null && !strScrollSubtext.isEmpty()) { Component lore = Util.getItemMiniMessage(strScrollSubtext.replace("%s", spell.getName()).replace("%u", usageCount)); @@ -318,7 +318,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { if (removeScrollWhenDepleted) { player.getInventory().setItemInMainHand(null); event.setCancelled(true); - } else player.getInventory().setItemInMainHand(new ItemStack(itemType)); + } else player.getInventory().setItemInMainHand(ItemStack.of(itemType)); } } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/SpellbookSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/SpellbookSpell.java index 6f8f75ae7..fcfa692df 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/SpellbookSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/SpellbookSpell.java @@ -117,7 +117,7 @@ public CastResult cast(SpellData data) { bookSpells = new ArrayList<>(); bookUses = new ArrayList<>(); loadSpellbooks(); - player.sendMessage("Spellbook file reloaded."); + player.sendPlainMessage("Spellbook file reloaded."); return new CastResult(PostCastAction.ALREADY_HANDLED, data); } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/command/TomeSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/command/TomeSpell.java index 3d16f5498..2157e7348 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/command/TomeSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/command/TomeSpell.java @@ -143,7 +143,7 @@ public ItemStack createTome(Spell spell, int uses, ItemStack item, SpellData dat else if (uses < 0) uses = defaultUses.get(data); if (item == null) { - item = new ItemStack(Material.WRITTEN_BOOK); + item = ItemStack.of(Material.WRITTEN_BOOK); item.editMeta(BookMeta.class, meta -> meta.setTitle(getName() + ": " + spell.getName())); } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureBookSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureBookSpell.java index c11513a40..91d051c42 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureBookSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureBookSpell.java @@ -149,8 +149,8 @@ private ItemStack createBook(Player player, SpellData data) { loreRaw.add(createComponent(line, player, playerDisplayName, data)); } - ItemStack item = new ItemStack(Material.WRITTEN_BOOK); - BookMeta meta = (BookMeta) ((BookMeta) item.getItemMeta()) + ItemStack item = ItemStack.of(Material.WRITTEN_BOOK); + BookMeta meta = ((BookMeta) item.getItemMeta()) .title(createComponent(title, player, playerDisplayName, data)) .author(createComponent(author, player, playerDisplayName, data)) .pages(pagesRaw); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureFireworkSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureFireworkSpell.java index f0a9331e9..c7f6a4df8 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureFireworkSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureFireworkSpell.java @@ -45,10 +45,10 @@ public ConjureFireworkSpell(MagicConfig config, String spellName) { String fireworkName = getConfigString("firework-name", ""); - firework = new ItemStack(Material.FIREWORK_ROCKET); + firework = ItemStack.of(Material.FIREWORK_ROCKET); FireworkMeta meta = (FireworkMeta) firework.getItemMeta(); - if (!fireworkName.isEmpty()) meta.displayName(Util.getItemMiniMessage(fireworkName)); + if (!fireworkName.isEmpty()) meta.customName(Util.getItemMiniMessage(fireworkName)); List fireworkEffects = getConfigStringList("firework-effects", null); if (fireworkEffects != null && !fireworkEffects.isEmpty()) { diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureSpell.java index e000418a7..6640f5a3e 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/ConjureSpell.java @@ -291,7 +291,6 @@ private void conjureItems(Location loc, SpellData data) { playSpellEffects(data); } - @SuppressWarnings("UnstableApiUsage") private void conjureItems(Player player, SpellData data) { List items = new ArrayList<>(); if (calculateDropsIndividually.get(data)) individual(items, data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/DowseSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/DowseSpell.java index d15300256..101603795 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/DowseSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/DowseSpell.java @@ -212,15 +212,7 @@ public void setStrNotFound(String strNotFound) { this.strNotFound = strNotFound; } - private static class NearbyEntity implements Comparable { - - private final Entity entity; - private final double distanceSquared; - - private NearbyEntity(Entity entity, double distanceSquared) { - this.entity = entity; - this.distanceSquared = distanceSquared; - } + private record NearbyEntity(Entity entity, double distanceSquared) implements Comparable { @Override public int compareTo(NearbyEntity e) { diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/FoodSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/FoodSpell.java index 226315814..900a82567 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/FoodSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/FoodSpell.java @@ -27,11 +27,11 @@ public FoodSpell(MagicConfig config, String spellName) { public CastResult cast(SpellData data) { if (!(data.caster() instanceof HumanEntity caster)) return new CastResult(PostCastAction.ALREADY_HANDLED, data); - int food = Math.max(Math.min(caster.getFoodLevel() + this.food.get(data), 20), 0); + int food = Math.clamp(caster.getFoodLevel() + this.food.get(data), 0, 20); caster.setFoodLevel(food); float maxSaturation = this.maxSaturation.get(data); - float saturation = Math.max(Math.min(this.saturation.get(data), maxSaturation), 0); + float saturation = Math.clamp(this.saturation.get(data), 0, maxSaturation); caster.setSaturation(saturation); playSpellEffects(data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/RitualSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/RitualSpell.java index a92a14b72..5f1875a8e 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/RitualSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/RitualSpell.java @@ -12,7 +12,7 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; import com.nisovin.magicspells.Spell; import com.nisovin.magicspells.util.*; @@ -109,7 +109,7 @@ public CastResult cast(SpellData data) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerInteract(PlayerInteractEntityEvent event) { + public void onPlayerInteract(PlayerInteractAtEntityEvent event) { if (!(event.getRightClicked() instanceof Player player)) return; if (event.getHand().equals(EquipmentSlot.OFF_HAND)) return; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/instant/SteedSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/instant/SteedSpell.java index 33959f2ec..d9b9e5013 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/instant/SteedSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/instant/SteedSpell.java @@ -125,7 +125,7 @@ public CastResult cast(SpellData data) { abstractHorse.setTamed(true); if (data.caster() instanceof AnimalTamer tamer) abstractHorse.setOwner(tamer); abstractHorse.setJumpStrength(jumpStrength.get(data)); - abstractHorse.getInventory().setSaddle(new ItemStack(Material.SADDLE)); + abstractHorse.getInventory().setSaddle(ItemStack.of(Material.SADDLE)); if (abstractHorse instanceof Horse horse) { Horse.Color color = this.color.get(data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/AnvilListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/AnvilListener.java index ca17b04fd..6537b6366 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/AnvilListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/AnvilListener.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; -import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.inventory.ItemStack; import org.bukkit.entity.LivingEntity; @@ -102,7 +101,7 @@ public void onAnvil(PrepareAnvilEvent event) { } private boolean contains(Set items, ItemStack item) { - if (item == null) item = new ItemStack(Material.AIR); + if (item == null) item = ItemStack.empty(); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null) return false; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/EnchantListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/EnchantListener.java index 1cd17c6b7..e67aa6dbc 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/EnchantListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/EnchantListener.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; -import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; @@ -55,7 +54,7 @@ public void onEnchant(EnchantItemEvent event) { } private boolean contains(ItemStack item) { - if (item == null) item = new ItemStack(Material.AIR); + if (item == null) item = ItemStack.empty(); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null) return false; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/GrindstoneListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/GrindstoneListener.java index e9e08ea58..829c12f36 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/GrindstoneListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/GrindstoneListener.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; -import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.inventory.Inventory; @@ -108,7 +107,7 @@ public void onGrindstone(PrepareResultEvent event) { } private boolean contains(Set items, ItemStack item) { - if (item == null) item = new ItemStack(Material.AIR); + if (item == null) item = ItemStack.empty(); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null) return false; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/PlayerAnimationListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/PlayerAnimationListener.java index d6ab9e997..3cde2dc94 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/PlayerAnimationListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/PlayerAnimationListener.java @@ -8,8 +8,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.event.player.PlayerAnimationEvent; + +import io.papermc.paper.event.player.PlayerArmSwingEvent; import com.nisovin.magicspells.util.Name; import com.nisovin.magicspells.MagicSpells; @@ -43,18 +43,14 @@ public void initialize(@NotNull String var) { @OverridePriority @EventHandler - public void onAnimate(PlayerAnimationEvent event) { + public void onArmSwing(PlayerArmSwingEvent event) { if (!isCancelStateOk(event.isCancelled())) return; Player caster = event.getPlayer(); if (!canTrigger(caster)) return; if (!items.isEmpty()) { - ItemStack item = caster.getInventory().getItem(switch (event.getAnimationType()) { - case ARM_SWING -> EquipmentSlot.HAND; - case OFF_ARM_SWING -> EquipmentSlot.OFF_HAND; - }); - + ItemStack item = caster.getInventory().getItem(event.getHand()); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null || !contains(itemData)) return; } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/PotionEffectListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/PotionEffectListener.java index 4192913b7..cb4e4c6ff 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/PotionEffectListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/PotionEffectListener.java @@ -68,10 +68,10 @@ public void initialize(@NotNull String var) { @EventHandler public void onPotionEffect(EntityPotionEffectEvent event) { - if (!(event.getEntity() instanceof LivingEntity entity)) return; if (!isCancelStateOk(event.isCancelled())) return; - if (!actions.contains(event.getAction()) || !causes.contains(event.getCause())) return; + + LivingEntity entity = event.getEntity(); if (!canTrigger(entity)) return; if (!isAnyType) { diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/PrepareEnchantListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/PrepareEnchantListener.java index 3ecf56ed8..ab2ba0b25 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/PrepareEnchantListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/PrepareEnchantListener.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; -import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; @@ -57,7 +56,7 @@ public void onEnchant(PrepareItemEnchantEvent event) { } private boolean contains(ItemStack item) { - if (item == null) item = new ItemStack(Material.AIR); + if (item == null) item = ItemStack.empty(); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null) return false; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/passive/SmithListener.java b/core/src/main/java/com/nisovin/magicspells/spells/passive/SmithListener.java index 85b5392a0..d3faff7d6 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/passive/SmithListener.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/passive/SmithListener.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; -import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; @@ -105,7 +104,7 @@ public void onSmith(PrepareSmithingEvent event) { } private boolean contains(Set items, ItemStack item) { - if (item == null) item = new ItemStack(Material.AIR); + if (item == null) item = ItemStack.empty(); MagicItemData itemData = MagicItems.getMagicItemDataFromItemStack(item); if (itemData == null) return false; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/BuildSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/BuildSpell.java index 17a5a0196..3b45030c6 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/BuildSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/BuildSpell.java @@ -128,7 +128,7 @@ private boolean build(Player player, Block block, Block against, ItemStack item, } } - if (playBreakEffect.get(data)) block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getBlockData()); + if (playBreakEffect.get(data)) block.getWorld().playEffect(block.getLocation(), Effect.DESTROY_BLOCK, block.getBlockData()); if (consumeBlock.get(data)) { int amt = item.getAmount() - 1; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/CaptureSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/CaptureSpell.java index ac6bf9b03..32c1ed023 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/CaptureSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/CaptureSpell.java @@ -54,7 +54,7 @@ public CastResult castAtEntity(SpellData data) { Material material = Bukkit.getItemFactory().getSpawnEgg(target.getType()); if (material == null) return noTarget(data); - ItemStack item = new ItemStack(material); + ItemStack item = ItemStack.of(material); if (powerAffectsQuantity.get(data)) { int q = Math.round(data.power()); @@ -65,7 +65,7 @@ public CastResult castAtEntity(SpellData data) { String[] replacements = {"%name%", getTargetName(target)}; item.editMeta(meta -> { - if (itemName != null) meta.displayName(Util.getItemMiniMessage(itemName, data, replacements)); + if (itemName != null) meta.customName(Util.getItemMiniMessage(itemName, data, replacements)); if (itemLore != null) { List lore = new ArrayList<>(); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/DiscoverRecipeSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/DiscoverRecipeSpell.java index 1d677bb1a..681e902a7 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/DiscoverRecipeSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/DiscoverRecipeSpell.java @@ -7,10 +7,12 @@ import com.nisovin.magicspells.spells.TargetedSpell; import com.nisovin.magicspells.util.config.ConfigData; import com.nisovin.magicspells.spells.TargetedEntitySpell; +import com.nisovin.magicspells.util.recipes.RecipeDiscoverListener; public class DiscoverRecipeSpell extends TargetedSpell implements TargetedEntitySpell { private final ConfigData discover; + private final ConfigData suppressToast; private final ConfigData recipe; @@ -18,6 +20,7 @@ public DiscoverRecipeSpell(MagicConfig config, String spellName) { super(config, spellName); discover = getConfigDataBoolean("discover", true); + suppressToast = getConfigDataBoolean("suppress-toast", false); recipe = getConfigDataNamespacedKey("recipe", null); } @@ -39,7 +42,11 @@ private CastResult discover(Player target, SpellData data) { NamespacedKey recipe = this.recipe.get(data); if (recipe == null) return new CastResult(PostCastAction.ALREADY_HANDLED, data); - if (discover.get(data)) target.discoverRecipe(recipe); + if (discover.get(data)) { + Runnable op = () -> target.discoverRecipe(recipe); + if (suppressToast.get(data)) RecipeDiscoverListener.suppressToastWhile(op); + else op.run(); + } else target.undiscoverRecipe(recipe); playSpellEffects(data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/FarmSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/FarmSpell.java index 25cdf6b06..217d7596b 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/FarmSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/FarmSpell.java @@ -102,7 +102,7 @@ public CastResult castAtLocation(SpellData data) { if (cropType instanceof Ageable ageable) { if (resolveGrowthPerCrop) growth = this.growth.get(data); - if (growth > 1) ageable.setAge(Math.max(Math.min(growth - 1, ageable.getMaximumAge()), 0)); + if (growth > 1) ageable.setAge(Math.clamp(growth - 1, 0, ageable.getMaximumAge())); b.setBlockData(ageable); count++; @@ -137,7 +137,7 @@ public CastResult castAtLocation(SpellData data) { if (ageable.getAge() == ageable.getMaximumAge()) continue; if (resolveGrowthPerCrop) growth = this.growth.get(data); - ageable.setAge(Math.max(Math.min(ageable.getAge() + growth, ageable.getMaximumAge()), 0)); + ageable.setAge(Math.clamp(ageable.getAge() + growth, 0, ageable.getMaximumAge())); b.setBlockData(ageable); count++; } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/HealSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/HealSpell.java index 4fb8b2614..5a4a47bab 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/HealSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/HealSpell.java @@ -66,7 +66,7 @@ public CastResult castAtEntity(SpellData data) { healAmount = event.getAmount(); } - data.target().setHealth(Math.max(Math.min(health + healAmount, maxHealth), 0)); + data.target().setHealth(Math.clamp(health + healAmount, 0, maxHealth)); playSpellEffects(data); return new CastResult(PostCastAction.HANDLE_NORMALLY, data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/MaterializeSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/MaterializeSpell.java index cec57419f..99dcce506 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/MaterializeSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/MaterializeSpell.java @@ -342,7 +342,7 @@ private boolean materialize(Player player, Block block, Block against, SpellData playSpellEffectsTrail(player.getLocation(), block.getLocation(), data); } - if (playBreakEffect) block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getBlockData()); + if (playBreakEffect) block.getWorld().playEffect(block.getLocation(), Effect.DESTROY_BLOCK, block.getBlockData()); if (removeBlocks) blocks.add(block); if (resetDelay > 0 && !falling) { @@ -357,7 +357,7 @@ private boolean materialize(Player player, Block block, Block against, SpellData } block.setType(Material.AIR); playSpellEffects(EffectPosition.BLOCK_DESTRUCTION, block.getLocation(), data); - if (playBreakEffect) block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getBlockData()); + if (playBreakEffect) block.getWorld().playEffect(block.getLocation(), Effect.DESTROY_BLOCK, block.getBlockData()); } }, resetDelay); } diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/PainSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/PainSpell.java index d4a04bc0b..dcc8b22f3 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/PainSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/PainSpell.java @@ -102,7 +102,7 @@ public CastResult castAtEntity(SpellData data) { double maxHealth = Util.getMaxHealth(data.target()); double health = Math.min(data.target().getHealth(), maxHealth); - health = Math.max(Math.min(health - damage, maxHealth), 0); + health = Math.clamp(health - damage, 0, maxHealth); if (health == 0 && data.caster() instanceof Player player) data.target().setKiller(player); data.target().setHealth(health); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ParticleCloudSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ParticleCloudSpell.java index 99fa0c0e4..5db6aefc8 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ParticleCloudSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ParticleCloudSpell.java @@ -23,7 +23,6 @@ import net.kyori.adventure.text.Component; import com.nisovin.magicspells.util.*; -import com.nisovin.magicspells.MagicSpells; import com.nisovin.magicspells.spells.TargetedSpell; import com.nisovin.magicspells.util.config.ConfigData; import com.nisovin.magicspells.events.SpellTargetEvent; @@ -112,12 +111,12 @@ public ParticleCloudSpell(MagicConfig config, String spellName) { if (material.isConstant()) { Material mat = material.get(); - ItemStack stack = mat != null && mat.isItem() ? new ItemStack(mat) : null; + ItemStack stack = mat != null && mat.isItem() ? ItemStack.of(mat) : null; item = data -> stack; } else { item = data -> { Material mat = material.get(data); - return mat != null && mat.isItem() ? new ItemStack(mat) : null; + return mat != null && mat.isItem() ? ItemStack.of(mat) : null; }; } @@ -251,12 +250,10 @@ public void onRemove(EntityRemoveFromWorldEvent event) { } private Object getParticleData(@NotNull Particle particle, @NotNull SpellData data) { - Object nmsData = MagicSpells.getVolatileCodeHandler().getVolatileParticleData( - particle, - () -> geyserWaterBlocks.get(data), - () -> geyserBurstImpulse.get(data) - ); - if (nmsData != null) return nmsData; +// Object nmsData = MagicSpells.getVolatileCodeHandler().getVolatileParticleData( +// particle, +// ); +// if (nmsData != null) return nmsData; Class type = particle.getDataType(); @@ -272,6 +269,21 @@ private Object getParticleData(@NotNull Particle particle, @NotNull SpellData da rgbColor.get(data); } + if (type == Particle.Geyser.class) { + Integer waterBlocks = geyserWaterBlocks.get(data); + if (waterBlocks == null) return null; + + return new Particle.Geyser(waterBlocks); + } + + if (type == Particle.GeyserBase.class) { + Integer waterBlocks = geyserWaterBlocks.get(data); + Float burstImpulse = geyserBurstImpulse.get(data); + if (waterBlocks == null || burstImpulse == null) return null; + + return new Particle.GeyserBase(waterBlocks, burstImpulse); + } + if (type == Particle.Trail.class) { Color color = trailColor.get(data); if (color == null) return null; diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ShearSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ShearSpell.java index 8beb8d498..10f0ce638 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ShearSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ShearSpell.java @@ -87,7 +87,7 @@ private CastResult shear(Shearable shearable, SpellData data) { } sheep.setSheared(true); - sheep.getWorld().dropItemNaturally(sheep.getLocation().add(0, dropOffset.get(data), 0), new ItemStack(wool, count)); + sheep.getWorld().dropItemNaturally(sheep.getLocation().add(0, dropOffset.get(data), 0), ItemStack.of(wool, count)); } else shearable.shear(); playSpellEffects(data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/SlimeSizeSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/SlimeSizeSpell.java index 2f74cc622..8da9afc87 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/SlimeSizeSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/SlimeSizeSpell.java @@ -55,7 +55,7 @@ private CastResult setSize(Slime target, SpellData data) { if (maxSize < minSize) maxSize = minSize; double rawOutputValue = variableMod.getValue(data, target.getSize()); - int finalSize = Math.min(Math.max((int) rawOutputValue, minSize), maxSize); + int finalSize = Math.clamp((int) rawOutputValue, minSize, maxSize); target.setSize(finalSize); playSpellEffects(data); diff --git a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ZapSpell.java b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ZapSpell.java index 7c6675344..729d3e172 100644 --- a/core/src/main/java/com/nisovin/magicspells/spells/targeted/ZapSpell.java +++ b/core/src/main/java/com/nisovin/magicspells/spells/targeted/ZapSpell.java @@ -84,11 +84,11 @@ public CastResult castAtLocation(SpellData data) { if (!event.callEvent()) return noTarget(strCantZap, data); } - if (playBreakEffect.get(data)) target.getWorld().playEffect(target.getLocation(), Effect.STEP_SOUND, target.getBlockData()); + if (playBreakEffect.get(data)) target.getWorld().playEffect(target.getLocation(), Effect.DESTROY_BLOCK, target.getBlockData()); if (dropBlock.get(data)) { if (dropNormal.get(data)) target.breakNaturally(); - else location.getWorld().dropItemNaturally(location, new ItemStack(target.getBlockData().getPlacementMaterial())); + else location.getWorld().dropItemNaturally(location, ItemStack.of(target.getBlockData().getPlacementMaterial())); } target.setType(Material.AIR); diff --git a/core/src/main/java/com/nisovin/magicspells/storage/databases/MySQLDatabase.java b/core/src/main/java/com/nisovin/magicspells/storage/databases/MySQLDatabase.java index 398129906..2e57bf2ab 100644 --- a/core/src/main/java/com/nisovin/magicspells/storage/databases/MySQLDatabase.java +++ b/core/src/main/java/com/nisovin/magicspells/storage/databases/MySQLDatabase.java @@ -19,7 +19,7 @@ public MySQLDatabase(MagicSpells plugin, String dbLocation) { @Override public Connection openConnection() { - File folder = plugin.getInstance().getDataFolder(); + File folder = MagicSpells.getInstance().getDataFolder(); if (!folder.exists()) folder.mkdirs(); File file = new File(folder, dbLocation); diff --git a/core/src/main/java/com/nisovin/magicspells/util/CastItem.java b/core/src/main/java/com/nisovin/magicspells/util/CastItem.java index 14d591425..27b829e9d 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/CastItem.java +++ b/core/src/main/java/com/nisovin/magicspells/util/CastItem.java @@ -62,9 +62,9 @@ public CastItem(ItemStack item) { if (isTypeValid()) { if (!MagicSpells.ignoreCastItemNames()) { if (MagicSpells.ignoreCastItemNameColors()) - name = PlainTextComponentSerializer.plainText().serializeOrNull(meta.displayName()); + name = PlainTextComponentSerializer.plainText().serializeOrNull(meta.customName()); else - name = LegacyComponentSerializer.legacySection().serializeOrNull(meta.displayName()); + name = LegacyComponentSerializer.legacySection().serializeOrNull(meta.customName()); } if (!MagicSpells.ignoreCastItemAmount()) amount = item.getAmount(); if (!MagicSpells.ignoreCastItemDurability(type) && type.getMaxDurability() > 0) durability = DurabilityHandler.getDurability(meta); diff --git a/core/src/main/java/com/nisovin/magicspells/util/EntityData.java b/core/src/main/java/com/nisovin/magicspells/util/EntityData.java index 132e30393..9de04193e 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/EntityData.java +++ b/core/src/main/java/com/nisovin/magicspells/util/EntityData.java @@ -129,7 +129,6 @@ public EntityData(ConfigurationSection config) { this(config, false); } - @SuppressWarnings("UnstableApiUsage") public EntityData(ConfigurationSection config, boolean forceOptional) { entityType = ConfigDataUtil.getEntityType(config, "entity", null); @@ -253,9 +252,16 @@ public EntityData(ConfigurationSection config, boolean forceOptional) { tameable.setOwner(tamer); }); + // Abstract Cube Mob + fallback( + transformers, key -> ConfigDataUtil.getInteger(config, key), 0, forceOptional, + AbstractCubeMob.class, AbstractCubeMob::setSize, + "cube.size", "slime.size", "size" + ); + // Abstract Horse saddled = addBoolean(transformers, config, "saddled", false, AbstractHorse.class, (horse, saddled) -> { - if (saddled) horse.getInventory().setSaddle(new ItemStack(Material.SADDLE)); + if (saddled) horse.getInventory().setSaddle(ItemStack.of(Material.SADDLE)); }, forceOptional); // Abstract Skeleton @@ -493,7 +499,7 @@ public EntityData(ConfigurationSection config, boolean forceOptional) { "llama.variant", "llama-variant", "color" ); fallback( - key -> addOptMaterial(transformers, config, key, Llama.class, (llama, material) -> llama.getInventory().setDecor(new ItemStack(material))), + key -> addOptMaterial(transformers, config, key, Llama.class, (llama, material) -> llama.getInventory().setDecor(ItemStack.of(material))), "llama.decor", "llama-decor", "material" ); @@ -641,16 +647,18 @@ public EntityData(ConfigurationSection config, boolean forceOptional) { // Sittable addOptBoolean(transformers, config, "sitting", Sittable.class, Sittable::setSitting); - // Slime - fallback( - transformers, key -> ConfigDataUtil.getInteger(config, key), 0, forceOptional, - Slime.class, Slime::setSize, - "slime.size", "size" - ); - // Steerable addBoolean(transformers, config, "saddled", false, Steerable.class, Steerable::setSaddle, forceOptional); + // Sulfur Cube + addOptItemStack(transformers, config, "sulfur-cube.swallow", SulfurCube.class, SulfurCube::swallow); + + addOptInteger(transformers, config, "sulfur-cube.fuse-ticks", SulfurCube.class, (cube, ticks) -> { + try { + cube.setFuseTicks(ticks); + } catch (IllegalArgumentException _) {} // debug + }); + // Tropical Fish fallback( key -> addOptEnum(transformers, config, key, TropicalFish.class, DyeColor.class, TropicalFish::setBodyColor), diff --git a/core/src/main/java/com/nisovin/magicspells/util/Util.java b/core/src/main/java/com/nisovin/magicspells/util/Util.java index ba3bdfbb4..d7dcea3e3 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/Util.java +++ b/core/src/main/java/com/nisovin/magicspells/util/Util.java @@ -7,6 +7,7 @@ import java.util.function.Supplier; import java.util.function.Predicate; +import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.format.NamedTextColor; @@ -33,6 +34,7 @@ import com.destroystokyo.paper.profile.ProfileProperty; import io.papermc.paper.block.fluid.FluidData; +import io.papermc.paper.potion.SuspiciousEffectEntry; import com.nisovin.magicspells.MagicSpells; import com.nisovin.magicspells.handlers.DebugHandler; @@ -100,11 +102,11 @@ public static PotionEffect buildPotionEffect(String effectString) { } // - (duration) - public static PotionEffect buildSuspiciousStewPotionEffect(String effectString) { + public static SuspiciousEffectEntry buildSuspiciousStewPotionEffect(String effectString) { String[] data = effectString.split(" "); - PotionEffectType t = PotionEffectHandler.getPotionEffectType(data[0]); + PotionEffectType type = PotionEffectHandler.getPotionEffectType(data[0]); - if (t == null) { + if (type == null) { MagicSpells.error('\'' + data[0] + "' could not be connected to a potion effect type"); return null; } @@ -117,7 +119,8 @@ public static PotionEffect buildSuspiciousStewPotionEffect(String effectString) DebugHandler.debugNumberFormat(ex); } } - return new PotionEffect(t, duration, 0, true); + + return SuspiciousEffectEntry.create(type, duration); } public static Color[] getColorsFromString(String str) { @@ -257,7 +260,11 @@ public static void playHurtEffect(@NotNull LivingEntity receiver, @Nullable Livi } receiver.playHurtAnimation(angle); - MagicSpells.getVolatileCodeHandler().playHurtSound(receiver); + + var sound = receiver.getHurtSound(); + if (sound == null) return; + + receiver.getWorld().playSound(Sound.sound(sound, receiver.soundSource(), receiver.getSoundVolume(), receiver.getSoundPitch()), receiver); } public static String arrayJoin(String[] array, char with) { diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/DialogBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/DialogBuilder.java index 34937cb41..e31f124b7 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/DialogBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/DialogBuilder.java @@ -21,7 +21,6 @@ import com.nisovin.magicspells.util.config.dialog.base.BaseBuilder; import com.nisovin.magicspells.util.config.dialog.types.TypeBuilder; -@SuppressWarnings("UnstableApiUsage") public class DialogBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/ActionButtonBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/ActionButtonBuilder.java index cce45a90a..6303ed903 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/ActionButtonBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/ActionButtonBuilder.java @@ -15,7 +15,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class ActionButtonBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CommandTemplateAction.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CommandTemplateAction.java index 57f9de2f2..5ad0f4dc0 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CommandTemplateAction.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CommandTemplateAction.java @@ -12,7 +12,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class CommandTemplateAction extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CustomClickAction.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CustomClickAction.java index 11fcdc736..932277c16 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CustomClickAction.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/CustomClickAction.java @@ -29,7 +29,6 @@ import com.nisovin.magicspells.variables.variabletypes.GlobalStringVariable; import com.nisovin.magicspells.variables.variabletypes.PlayerStringVariable; -@SuppressWarnings("UnstableApiUsage") public class CustomClickAction extends BuildContext { private static final ClickCallback.Options CLICK_OPTIONS = ClickCallback.Options.builder() diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/StaticAction.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/StaticAction.java index fe95098bd..c6e34144b 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/StaticAction.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/action/StaticAction.java @@ -20,7 +20,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class StaticAction extends BuildContext { private final ConfigurationSection config; @@ -45,7 +44,7 @@ private StaticAction(Debugger debugger, ConfigurationSection config, String path @Override protected @NotNull NullConfigData build() { - ConfigData eventData = switch (config.getString("type")) { + ConfigData> eventData = switch (config.getString("type")) { case "open_url" -> clickEventString(ClickEvent::openUrl, config, path, "url"); case "run_command" -> clickEventString(ClickEvent::runCommand, config, path, "command"); case "suggest_command" -> clickEventString(ClickEvent::suggestCommand, config, path, "command"); @@ -60,7 +59,7 @@ private StaticAction(Debugger debugger, ConfigurationSection config, String path }; return data -> { - ClickEvent event = eventData.get(data); + ClickEvent event = eventData.get(data); if (event == null) return null; return DialogAction.staticAction(event); @@ -71,8 +70,8 @@ private ConfigData configDataDialog(ConfigurationSection config, String return ConfigDataUtil.getRegistryEntry(config, path, RegistryKey.DIALOG, def); } - private NullConfigData clickEventString( - Function clickEventFun, + private NullConfigData> clickEventString( + Function> clickEventFun, ConfigurationSection config, String basePath, String subPath @@ -80,9 +79,9 @@ private NullConfigData clickEventString( return clickEvent(ConfigDataUtil::getString, clickEventFun, config, basePath, subPath); } - private NullConfigData clickEvent( + private NullConfigData> clickEvent( TriFunction> configDataFun, - Function clickEventFun, + Function> clickEventFun, ConfigurationSection config, String basePath, String subPath diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BaseBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BaseBuilder.java index b1a66567d..e7329633d 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BaseBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BaseBuilder.java @@ -23,7 +23,6 @@ import io.papermc.paper.registry.data.dialog.body.PlainMessageDialogBody; import io.papermc.paper.registry.data.dialog.DialogBase.DialogAfterAction; -@SuppressWarnings("UnstableApiUsage") public class BaseBuilder extends BuildContext { private static final String PATH = "base"; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BooleanInput.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BooleanInput.java index e52279aa2..a51e18055 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BooleanInput.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/BooleanInput.java @@ -14,7 +14,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class BooleanInput extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/NumberRangeInput.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/NumberRangeInput.java index 21e5a4335..021240f49 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/NumberRangeInput.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/NumberRangeInput.java @@ -14,7 +14,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class NumberRangeInput extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/SingleOptionInput.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/SingleOptionInput.java index 44ee60259..9a9899040 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/SingleOptionInput.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/SingleOptionInput.java @@ -17,7 +17,6 @@ import io.papermc.paper.registry.data.dialog.input.DialogInput; import io.papermc.paper.registry.data.dialog.input.SingleOptionDialogInput; -@SuppressWarnings("UnstableApiUsage") public class SingleOptionInput extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/TextInput.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/TextInput.java index 7d5eb8322..47af5cd73 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/TextInput.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/base/TextInput.java @@ -15,7 +15,6 @@ import io.papermc.paper.registry.data.dialog.input.DialogInput; import io.papermc.paper.registry.data.dialog.input.TextDialogInput.MultilineOptions; -@SuppressWarnings("UnstableApiUsage") public class TextInput extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ConfirmationBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ConfirmationBuilder.java index 0c7cc7a2e..24e576040 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ConfirmationBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ConfirmationBuilder.java @@ -13,7 +13,6 @@ import com.nisovin.magicspells.util.config.dialog.NullConfigData; import com.nisovin.magicspells.util.config.dialog.action.ActionButtonBuilder; -@SuppressWarnings("UnstableApiUsage") public class ConfirmationBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/MultiActionBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/MultiActionBuilder.java index c1afa7c7c..bc4d280d9 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/MultiActionBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/MultiActionBuilder.java @@ -17,7 +17,6 @@ import com.nisovin.magicspells.util.config.dialog.NullConfigData; import com.nisovin.magicspells.util.config.dialog.action.ActionButtonBuilder; -@SuppressWarnings("UnstableApiUsage") public class MultiActionBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/NoticeBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/NoticeBuilder.java index 16fcec8b0..74708e75f 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/NoticeBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/NoticeBuilder.java @@ -12,7 +12,6 @@ import com.nisovin.magicspells.util.config.dialog.NullConfigData; import com.nisovin.magicspells.util.config.dialog.action.ActionButtonBuilder; -@SuppressWarnings("UnstableApiUsage") public class NoticeBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ServerListTypeBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ServerListTypeBuilder.java index d55a3b74c..f98ff23c6 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ServerListTypeBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/ServerListTypeBuilder.java @@ -14,7 +14,6 @@ import com.nisovin.magicspells.util.config.dialog.NullConfigData; import com.nisovin.magicspells.util.config.dialog.action.ActionButtonBuilder; -@SuppressWarnings("UnstableApiUsage") public class ServerListTypeBuilder extends BuildContext { private final ConfigurationSection config; diff --git a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/TypeBuilder.java b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/TypeBuilder.java index 7c0fe7a07..e6db5fb7a 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/TypeBuilder.java +++ b/core/src/main/java/com/nisovin/magicspells/util/config/dialog/types/TypeBuilder.java @@ -10,7 +10,6 @@ import com.nisovin.magicspells.util.config.dialog.BuildContext; import com.nisovin.magicspells.util.config.dialog.NullConfigData; -@SuppressWarnings("UnstableApiUsage") public class TypeBuilder extends BuildContext { private static final String PATH = "dialog-type"; diff --git a/core/src/main/java/com/nisovin/magicspells/util/glow/impl/PacketEventsGlowManager.java b/core/src/main/java/com/nisovin/magicspells/util/glow/impl/PacketEventsGlowManager.java index d3d3b4236..c1766a5b0 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/glow/impl/PacketEventsGlowManager.java +++ b/core/src/main/java/com/nisovin/magicspells/util/glow/impl/PacketEventsGlowManager.java @@ -170,7 +170,7 @@ public GlowPacketListener() { } @Override - public void onPacketSend(PacketSendEvent event) { + public void onPacketSend(@NotNull PacketSendEvent event) { synchronized (PacketEventsGlowManager.this) { if (glows.isEmpty() && perPlayerGlows.isEmpty()) return; diff --git a/core/src/main/java/com/nisovin/magicspells/util/grammars/RegistryEntryPredicateVisitorImpl.java b/core/src/main/java/com/nisovin/magicspells/util/grammars/RegistryEntryPredicateVisitorImpl.java index b36a91153..3c0b417e3 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/grammars/RegistryEntryPredicateVisitorImpl.java +++ b/core/src/main/java/com/nisovin/magicspells/util/grammars/RegistryEntryPredicateVisitorImpl.java @@ -8,8 +8,8 @@ import net.kyori.adventure.key.InvalidKeyException; import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; import org.bukkit.Registry; +import org.bukkit.NamespacedKey; import io.papermc.paper.registry.tag.Tag; import io.papermc.paper.registry.TypedKey; diff --git a/core/src/main/java/com/nisovin/magicspells/util/grammars/SpellFilterVisitorImpl.java b/core/src/main/java/com/nisovin/magicspells/util/grammars/SpellFilterVisitorImpl.java index c84ca7ca0..cc0d6f1d0 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/grammars/SpellFilterVisitorImpl.java +++ b/core/src/main/java/com/nisovin/magicspells/util/grammars/SpellFilterVisitorImpl.java @@ -1,8 +1,6 @@ package com.nisovin.magicspells.util.grammars; import java.util.Set; -import java.util.List; -import java.util.ArrayList; import java.util.function.Predicate; import com.nisovin.magicspells.Spell; diff --git a/core/src/main/java/com/nisovin/magicspells/util/itemreader/NameHandler.java b/core/src/main/java/com/nisovin/magicspells/util/itemreader/NameHandler.java index 06387b472..fdc781cdc 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/itemreader/NameHandler.java +++ b/core/src/main/java/com/nisovin/magicspells/util/itemreader/NameHandler.java @@ -15,18 +15,18 @@ public class NameHandler { public static void process(ConfigurationSection config, ItemMeta meta, MagicItemData data) { if (!config.isString(CONFIG_NAME)) return; - meta.displayName(Util.getItemMiniMessage(config.getString(CONFIG_NAME))); - data.setAttribute(NAME, meta.displayName()); + meta.customName(Util.getItemMiniMessage(config.getString(CONFIG_NAME))); + data.setAttribute(NAME, meta.customName()); } public static void processItemMeta(ItemMeta meta, MagicItemData data) { if (!data.hasAttribute(NAME)) return; - meta.displayName((Component) data.getAttribute(NAME)); + meta.customName((Component) data.getAttribute(NAME)); } public static void processMagicItemData(ItemMeta meta, MagicItemData data) { - if (!meta.hasDisplayName()) return; - data.setAttribute(NAME, meta.displayName()); + if (!meta.hasCustomName()) return; + data.setAttribute(NAME, meta.customName()); } } diff --git a/core/src/main/java/com/nisovin/magicspells/util/itemreader/SuspiciousStewHandler.java b/core/src/main/java/com/nisovin/magicspells/util/itemreader/SuspiciousStewHandler.java index 5c2ea2575..46b121fce 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/itemreader/SuspiciousStewHandler.java +++ b/core/src/main/java/com/nisovin/magicspells/util/itemreader/SuspiciousStewHandler.java @@ -8,6 +8,8 @@ import org.bukkit.inventory.meta.SuspiciousStewMeta; import org.bukkit.configuration.ConfigurationSection; +import io.papermc.paper.potion.SuspiciousEffectEntry; + import com.nisovin.magicspells.util.Util; import com.nisovin.magicspells.util.magicitems.MagicItemData; import static com.nisovin.magicspells.util.magicitems.MagicItemData.MagicItemAttribute.POTION_EFFECTS; @@ -25,11 +27,11 @@ public static void process(ConfigurationSection config, ItemMeta meta, MagicItem List effects = config.getStringList(CONFIG_NAME); List potionEffects = new ArrayList<>(); for (String str : effects) { - PotionEffect potionEffect = Util.buildSuspiciousStewPotionEffect(str); - if (potionEffect == null) continue; + SuspiciousEffectEntry stewEffect = Util.buildSuspiciousStewPotionEffect(str); + if (stewEffect == null) continue; - stewMeta.addCustomEffect(potionEffect, true); - potionEffects.add(potionEffect); + stewMeta.addCustomEffect(stewEffect, true); + potionEffects.add(new PotionEffect(stewEffect.effect(), stewEffect.duration(), 0)); } if (!potionEffects.isEmpty()) data.setAttribute(POTION_EFFECTS, potionEffects); } @@ -38,7 +40,9 @@ public static void processItemMeta(ItemMeta meta, MagicItemData data) { if (!(meta instanceof SuspiciousStewMeta stewMeta)) return; if (!data.hasAttribute(POTION_EFFECTS)) return; stewMeta.clearCustomEffects(); - ((List) data.getAttribute(POTION_EFFECTS)).forEach(potionEffect -> stewMeta.addCustomEffect(potionEffect, true)); + ((List) data.getAttribute(POTION_EFFECTS)).forEach(effect -> + stewMeta.addCustomEffect(SuspiciousEffectEntry.create(effect.getType(), effect.getDuration()), true) + ); } public static void processMagicItemData(ItemMeta meta, MagicItemData data) { diff --git a/core/src/main/java/com/nisovin/magicspells/util/magicitems/MagicItems.java b/core/src/main/java/com/nisovin/magicspells/util/magicitems/MagicItems.java index 48dcef366..71746107a 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/magicitems/MagicItems.java +++ b/core/src/main/java/com/nisovin/magicspells/util/magicitems/MagicItems.java @@ -182,7 +182,7 @@ public static MagicItem getMagicItemFromData(MagicItemData data) { Material type = (Material) data.getAttribute(TYPE); if (type == null) return null; - ItemStack item = new ItemStack(type); + ItemStack item = ItemStack.of(type); if (type.isAir()) return new MagicItem(item, data); @@ -342,7 +342,7 @@ public static MagicItem getMagicItemFromSection(ConfigurationSection section) { return null; } - item = new ItemStack(type); + item = ItemStack.of(type); itemData.setAttribute(TYPE, type); if (type.isAir()) return new MagicItem(item, itemData); diff --git a/core/src/main/java/com/nisovin/magicspells/util/managers/VariableManager.java b/core/src/main/java/com/nisovin/magicspells/util/managers/VariableManager.java index 18f42f14f..ba5665c49 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/managers/VariableManager.java +++ b/core/src/main/java/com/nisovin/magicspells/util/managers/VariableManager.java @@ -172,6 +172,7 @@ private void initialize() { addMetaVariableType("unsaturated_regen_rate", new UnsaturatedRegenRateVariable()); addMetaVariableType("attack_cooldown", new AttackCooldownVariable()); addMetaVariableType("current_tick", new CurrentTickVariable()); + addMetaVariableType("invulnerable_time", new InvulnerableTimeVariable()); // meta variable attribute types for (Attribute attribute : Registry.ATTRIBUTE) { @@ -500,9 +501,7 @@ public void saveGlobalVariables() { return; } - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, false)); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, false))) { for (String line : lines) { writer.write(line); writer.newLine(); @@ -511,14 +510,6 @@ public void saveGlobalVariables() { } catch (Exception e) { MagicSpells.error("ERROR SAVING GLOBAL VARIABLES"); MagicSpells.handleException(e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception e) { - // No op - } - } } dirtyGlobalVars = false; @@ -576,9 +567,7 @@ public void savePlayerVariables(String player, String uniqueId) { return; } - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, false)); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, false))) { for (String line : lines) { writer.write(line); writer.newLine(); @@ -587,14 +576,6 @@ public void savePlayerVariables(String player, String uniqueId) { } catch (Exception e) { MagicSpells.error("ERROR SAVING PLAYER VARIABLES FOR " + player); MagicSpells.handleException(e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception e) { - DebugHandler.debugGeneral(e); - } - } } dirtyPlayerVars.remove(player); diff --git a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerLingeringPotion.java b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerLingeringPotion.java index c21ea392a..6cef3c739 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerLingeringPotion.java +++ b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerLingeringPotion.java @@ -10,7 +10,7 @@ public class ProjectileManagerLingeringPotion extends ProjectileManagerThrownPot @NotNull @Override protected ItemStack getItem() { - return new ItemStack(Material.LINGERING_POTION); + return ItemStack.of(Material.LINGERING_POTION); } } diff --git a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerSplashPotion.java b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerSplashPotion.java index 3823cfddd..0871fcfbc 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerSplashPotion.java +++ b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerSplashPotion.java @@ -10,7 +10,7 @@ public class ProjectileManagerSplashPotion extends ProjectileManagerThrownPotion @NotNull @Override protected ItemStack getItem() { - return new ItemStack(Material.SPLASH_POTION); + return ItemStack.of(Material.SPLASH_POTION); } } diff --git a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerThrownPotion.java b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerThrownPotion.java index e07740dec..cb01f776e 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerThrownPotion.java +++ b/core/src/main/java/com/nisovin/magicspells/util/projectile/ProjectileManagerThrownPotion.java @@ -19,7 +19,7 @@ public Class getProjectileClass() { @NotNull protected ItemStack getItem() { - return new ItemStack(Material.POTION); + return ItemStack.of(Material.POTION); } @NotNull diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/CustomRecipes.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/CustomRecipes.java index 43358d08c..dad50a091 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/CustomRecipes.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/CustomRecipes.java @@ -1,11 +1,14 @@ package com.nisovin.magicspells.util.recipes; +import java.util.Map; import java.util.List; +import java.util.HashMap; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.NamespacedKey; +import org.bukkit.inventory.Recipe; import org.bukkit.configuration.ConfigurationSection; import com.nisovin.magicspells.util.Util; @@ -14,7 +17,7 @@ public class CustomRecipes { - private static final List RECIPES = new ArrayList<>(); + private static final Map RECIPES = new HashMap<>(); private static final List AUTO_DISCOVER = new ArrayList<>(); public static void load(ConfigurationSection recipesSection) { @@ -41,34 +44,34 @@ public static void load(ConfigurationSection recipesSection) { } if (recipe == null) continue; - RECIPES.add(recipe); - recipe.add(); + RECIPES.put(recipe.key(), recipe.recipe()); - if (!(recipe instanceof CraftingRecipe crafting) || !crafting.isAutoDiscover()) continue; - AUTO_DISCOVER.add(crafting.getKey()); + if (!recipe.autoDiscover()) continue; + AUTO_DISCOVER.add(recipe.key()); } if (RECIPES.isEmpty()) return; - Bukkit.updateRecipes(); + Bukkit.addRecipes(RECIPES.values()); - if (!AUTO_DISCOVER.isEmpty()) + if (AUTO_DISCOVER.isEmpty()) return; + RecipeDiscoverListener.suppressToastWhile(() -> { for (Player player : Bukkit.getOnlinePlayers()) player.discoverRecipes(AUTO_DISCOVER); + }); } public static void clearRecipes() { - RECIPES.forEach(CustomRecipe::remove); - if (!AUTO_DISCOVER.isEmpty()) for (Player player : Bukkit.getOnlinePlayers()) player.undiscoverRecipes(AUTO_DISCOVER); + Bukkit.removeRecipes(RECIPES.keySet()); + RECIPES.clear(); AUTO_DISCOVER.clear(); - Bukkit.updateRecipes(); } - public static List getRecipes() { + public static Map getRecipes() { return RECIPES; } diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeDiscoverListener.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeDiscoverListener.java new file mode 100644 index 000000000..7d9f95143 --- /dev/null +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeDiscoverListener.java @@ -0,0 +1,21 @@ +package com.nisovin.magicspells.util.recipes; + +import org.bukkit.event.Listener; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerRecipeDiscoverEvent; + +public class RecipeDiscoverListener implements Listener { + + private static final ScopedValue SUPPRESS_TOAST = ScopedValue.newInstance(); + + @EventHandler + private void onDiscover(PlayerRecipeDiscoverEvent event) { + if (!SUPPRESS_TOAST.isBound()) return; + event.shouldShowNotification(false); + } + + public static void suppressToastWhile(Runnable op) { + ScopedValue.where(SUPPRESS_TOAST, null).run(op); + } + +} diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeType.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeType.java index b05ffca45..27b5bdb0e 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeType.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/RecipeType.java @@ -19,9 +19,9 @@ public enum RecipeType { ; - private final RecipeFactory factory; + private final RecipeFactory factory; - RecipeType(RecipeFactory factory) { + RecipeType(RecipeFactory factory) { this.factory = factory; } diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CookingRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CookingRecipeFactory.java index b72517d7b..e7fb0723e 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CookingRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CookingRecipeFactory.java @@ -1,16 +1,20 @@ package com.nisovin.magicspells.util.recipes.types; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import org.jspecify.annotations.NullMarked; import org.bukkit.inventory.*; import org.bukkit.NamespacedKey; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.recipe.CookingBookCategory; -public abstract class CookingRecipeFactory> extends CraftingRecipeFactory { +@NullMarked +public abstract class CookingRecipeFactory> extends RecipeFactory { @Override - protected final Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result) { + @Nullable + protected final Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { int cookingTime = config.getInt("cooking-time", 0); RecipeChoice ingredient = resolveRecipeChoice(config, "ingredient"); if (ingredient == null) return null; @@ -27,13 +31,12 @@ protected final Recipe createCrafting(ConfigurationSection config, NamespacedKey return recipe; } - @NotNull protected abstract R createCooking(CookingData data); protected record CookingData( - @NotNull NamespacedKey key, - @NotNull ItemStack result, - @NotNull RecipeChoice ingredient, + NamespacedKey key, + ItemStack result, + RecipeChoice ingredient, float experience, int cookingTime ) {} @@ -41,7 +44,6 @@ protected record CookingData( public static class Blasting extends CookingRecipeFactory { @Override - @NotNull protected BlastingRecipe createCooking(CookingData data) { return new BlastingRecipe(data.key(), data.result(), data.ingredient(), data.experience(), data.cookingTime()); } @@ -51,7 +53,6 @@ protected BlastingRecipe createCooking(CookingData data) { public static class Campfire extends CookingRecipeFactory { @Override - @NotNull protected CampfireRecipe createCooking(CookingData data) { return new CampfireRecipe(data.key(), data.result(), data.ingredient(), data.experience(), data.cookingTime()); } @@ -61,7 +62,6 @@ protected CampfireRecipe createCooking(CookingData data) { public static class Furnace extends CookingRecipeFactory { @Override - @NotNull protected FurnaceRecipe createCooking(CookingData data) { return new FurnaceRecipe(data.key(), data.result(), data.ingredient(), data.experience(), data.cookingTime()); } @@ -71,7 +71,6 @@ protected FurnaceRecipe createCooking(CookingData data) { public static class Smoking extends CookingRecipeFactory { @Override - @NotNull protected SmokingRecipe createCooking(CookingData data) { return new SmokingRecipe(data.key(), data.result(), data.ingredient(), data.experience(), data.cookingTime()); } diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CraftingRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CraftingRecipeFactory.java deleted file mode 100644 index cc577d254..000000000 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/CraftingRecipeFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nisovin.magicspells.util.recipes.types; - -import org.jetbrains.annotations.Nullable; - -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.ItemStack; -import org.bukkit.configuration.ConfigurationSection; - -import com.nisovin.magicspells.util.recipes.wrapper.CraftingRecipe; - -public abstract class CraftingRecipeFactory extends RecipeFactory { - - @Override - @Nullable - protected final CraftingRecipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { - boolean autoDiscover = config.getBoolean("auto-discover", true); - - Recipe recipe = createCrafting(config, key, result); - if (recipe == null) return null; - - return new CraftingRecipe(recipe, key, autoDiscover); - } - - @Nullable - protected abstract Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result); - -} diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/PotionRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/PotionRecipeFactory.java index 645db3949..7ce9d47c3 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/PotionRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/PotionRecipeFactory.java @@ -2,25 +2,26 @@ import org.jetbrains.annotations.Nullable; -import io.papermc.paper.potion.PotionMix; +import org.jspecify.annotations.NullMarked; import org.bukkit.NamespacedKey; +import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.BrewingRecipe; import org.bukkit.configuration.ConfigurationSection; -import com.nisovin.magicspells.util.recipes.wrapper.PotionRecipe; - -public class PotionRecipeFactory extends RecipeFactory { +@NullMarked +public class PotionRecipeFactory extends RecipeFactory { @Override @Nullable - protected PotionRecipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { + protected Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { RecipeChoice input = resolveRecipeChoice(config, "input"); RecipeChoice ingredient = resolveRecipeChoice(config, "ingredient"); if (input == null || ingredient == null) return null; - return new PotionRecipe(new PotionMix(key, result, input, ingredient)); + return new BrewingRecipe(key, result, input, ingredient); } } diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/RecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/RecipeFactory.java index 06e0af95a..00e860354 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/RecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/RecipeFactory.java @@ -1,9 +1,6 @@ package com.nisovin.magicspells.util.recipes.types; -import java.util.Map; -import java.util.List; -import java.util.HashMap; -import java.util.ArrayList; +import java.util.*; import java.lang.reflect.Field; import org.jetbrains.annotations.Nullable; @@ -12,13 +9,20 @@ import com.destroystokyo.paper.MaterialSetTag; import org.bukkit.Tag; -import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.Registry; import org.bukkit.NamespacedKey; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ItemType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.configuration.ConfigurationSection; +import io.papermc.paper.registry.tag.TagKey; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.set.RegistrySet; +import io.papermc.paper.registry.set.RegistryKeySet; + import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextDecoration; @@ -29,7 +33,8 @@ import com.nisovin.magicspells.util.magicitems.MagicItems; import com.nisovin.magicspells.util.recipes.wrapper.CustomRecipe; -public abstract class RecipeFactory { +@SuppressWarnings("UnstableApiUsage") +public abstract class RecipeFactory { private static final Map> MATERIAL_TAGS = new HashMap<>(); static { @@ -59,18 +64,23 @@ public final CustomRecipe create(ConfigurationSection config) { ItemStack result = magicItem.getItemStack().clone(); result.setAmount(Math.max(1, config.getInt("quantity", 1))); - return createRecipe(config, key, result); + boolean autoDiscover = config.getBoolean("auto-discover", true); + + Recipe recipe = createRecipe(config, key, result); + if (recipe == null) return null; + + return new CustomRecipe(recipe, key, autoDiscover); } @Nullable - protected abstract R createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result); + protected abstract Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result); protected final RecipeChoice resolveRecipeChoice(ConfigurationSection config, String path) { if (!config.isList(path)) { Object object = config.get(path); if (object instanceof String tagName && (tagName.startsWith("tag:") || tagName.startsWith("#"))) { - Tag tag = resolveMaterialTag(config, path, tagName); - return tag == null ? null : new RecipeChoice.MaterialChoice(tag); + RegistryKeySet set = resolveMaterialTag(config, path, tagName); + return set == null ? null : RecipeChoice.itemType(set); } MagicItem magicItem = getMagicItem(object); @@ -78,23 +88,23 @@ protected final RecipeChoice resolveRecipeChoice(ConfigurationSection config, St MagicSpells.error("Invalid magic item defined for '%s' on custom recipe '%s'.".formatted(path, config.getName())); return null; } - return new RecipeChoice.ExactChoice(getItalicVariants(magicItem.getItemStack())); + return RecipeChoice.exactChoice(getItalicVariants(magicItem.getItemStack())); } List items = new ArrayList<>(); - List materials = new ArrayList<>(); + List itemTypes = new ArrayList<>(); List list = config.getList(path, new ArrayList<>()); for (int i = 0; i < list.size(); i++) { Object object = list.get(i); if (object instanceof String tagName && (tagName.startsWith("tag:") || tagName.startsWith("#"))) { - Tag tag = resolveMaterialTag(config, path, tagName); - if (tag == null) return null; - materials.addAll(tag.getValues()); + RegistryKeySet set = resolveMaterialTag(config, path, tagName); + if (set == null) return null; + itemTypes.addAll(set.resolve(Registry.ITEM)); continue; } - if (!materials.isEmpty()) { + if (!itemTypes.isEmpty()) { MagicSpells.error("Invalid entry on custom recipe '%s' at index %d of '%s' - you cannot mix material tags and item-based recipe choices together.".formatted(config.getName(), i, path)); return null; } @@ -107,9 +117,9 @@ protected final RecipeChoice resolveRecipeChoice(ConfigurationSection config, St items.addAll(getItalicVariants(magicItem.getItemStack())); } - return materials.isEmpty() ? - new RecipeChoice.ExactChoice(items) : - new RecipeChoice.MaterialChoice(materials); + return itemTypes.isEmpty() ? + RecipeChoice.exactChoice(items) : + RecipeChoice.itemType(RegistrySet.keySetFromValues(RegistryKey.ITEM, itemTypes)); } /* @@ -119,12 +129,12 @@ private List getItalicVariants(ItemStack original) { ItemStack clone = original.clone(); if (!original.hasItemMeta()) return List.of(clone); - Component displayName = original.getItemMeta().displayName(); - if (displayName == null || !displayName.hasDecoration(TextDecoration.ITALIC)) + Component customName = original.getItemMeta().customName(); + if (customName == null || !customName.hasDecoration(TextDecoration.ITALIC)) return List.of(clone); ItemStack item = original.clone(); - item.editMeta(meta -> meta.displayName(displayName.decoration(TextDecoration.ITALIC, TextDecoration.State.NOT_SET))); + item.editMeta(meta -> meta.customName(customName.decoration(TextDecoration.ITALIC, TextDecoration.State.NOT_SET))); return List.of(clone, item); } @@ -136,18 +146,31 @@ private MagicItem getMagicItem(Object object) { }; } - private Tag resolveMaterialTag(ConfigurationSection config, String path, String tagName) { + private RegistryKeySet resolveMaterialTag(ConfigurationSection config, String path, String tagName) { String tagString = tagName.replaceFirst("tag:|#", ""); - Tag tag = MATERIAL_TAGS.get(tagString.toUpperCase()); - if (tag != null) return tag; + Tag matTag = MATERIAL_TAGS.get(tagString.toUpperCase()); + if (matTag != null) { + Set items = new HashSet<>(); + + for (Material material : matTag.getValues()) { + ItemType itemType = material.asItemType(); + + if (itemType == null) { + MagicSpells.error("Invalid material tag '%s' on option '%s' of custom recipe '%s' - cannot use non-item entry '%s'.".formatted(tagName, path, config.getName(), material)); + return null; + } + + items.add(itemType); + } + + return RegistrySet.keySetFromValues(RegistryKey.ITEM, items); + } NamespacedKey key = NamespacedKey.fromString(tagString); if (key != null) { - tag = Bukkit.getTag(Tag.REGISTRY_ITEMS, key, Material.class); - if (tag != null) return tag; - - tag = Bukkit.getTag(Tag.REGISTRY_BLOCKS, key, Material.class); - if (tag != null) return tag; + try { + return Registry.ITEM.getTag(TagKey.create(RegistryKey.ITEM, key)); + } catch (NoSuchElementException _) {} } MagicSpells.error("Invalid material tag '%s' on option '%s' of custom recipe '%s'.".formatted(tagName, path, config.getName())); diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapedRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapedRecipeFactory.java index 29158b020..b4b60576c 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapedRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapedRecipeFactory.java @@ -4,6 +4,8 @@ import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; + import com.nisovin.magicspells.MagicSpells; import org.bukkit.NamespacedKey; @@ -14,11 +16,12 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.recipe.CraftingBookCategory; -public class ShapedRecipeFactory extends CraftingRecipeFactory { +@NullMarked +public class ShapedRecipeFactory extends RecipeFactory { @Override @Nullable - protected Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result) { + protected Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { ShapedRecipe recipe = new ShapedRecipe(key, result); List shape = config.getStringList("shape"); diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapelessRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapelessRecipeFactory.java index da0778959..ec84570e6 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapelessRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/ShapelessRecipeFactory.java @@ -5,6 +5,8 @@ import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; + import com.nisovin.magicspells.MagicSpells; import org.bukkit.NamespacedKey; @@ -15,11 +17,12 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.recipe.CraftingBookCategory; -public class ShapelessRecipeFactory extends CraftingRecipeFactory { +@NullMarked +public class ShapelessRecipeFactory extends RecipeFactory { @Override @Nullable - protected Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result) { + protected Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { ShapelessRecipe recipe = new ShapelessRecipe(key, result); String path = "ingredients"; diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/SmithingRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/SmithingRecipeFactory.java index 686236513..f1f6da289 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/SmithingRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/SmithingRecipeFactory.java @@ -2,6 +2,8 @@ import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; + import org.bukkit.NamespacedKey; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ItemStack; @@ -9,11 +11,12 @@ import org.bukkit.inventory.SmithingTransformRecipe; import org.bukkit.configuration.ConfigurationSection; -public class SmithingRecipeFactory extends CraftingRecipeFactory { +@NullMarked +public class SmithingRecipeFactory extends RecipeFactory { @Override @Nullable - protected Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result) { + protected Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { RecipeChoice template = resolveRecipeChoice(config, "template"); RecipeChoice base = resolveRecipeChoice(config, "base"); RecipeChoice addition = resolveRecipeChoice(config, "addition"); diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/StonecuttingRecipeFactory.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/StonecuttingRecipeFactory.java index fb81b828c..389d178ba 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/types/StonecuttingRecipeFactory.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/types/StonecuttingRecipeFactory.java @@ -2,6 +2,8 @@ import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NullMarked; + import org.bukkit.NamespacedKey; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ItemStack; @@ -9,11 +11,12 @@ import org.bukkit.inventory.StonecuttingRecipe; import org.bukkit.configuration.ConfigurationSection; -public class StonecuttingRecipeFactory extends CraftingRecipeFactory { +@NullMarked +public class StonecuttingRecipeFactory extends RecipeFactory { @Override @Nullable - protected Recipe createCrafting(ConfigurationSection config, NamespacedKey key, ItemStack result) { + protected Recipe createRecipe(ConfigurationSection config, NamespacedKey key, ItemStack result) { RecipeChoice ingredient = resolveRecipeChoice(config,"ingredient"); if (ingredient == null) return null; diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CraftingRecipe.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CraftingRecipe.java deleted file mode 100644 index 6ead7388a..000000000 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CraftingRecipe.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.nisovin.magicspells.util.recipes.wrapper; - -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.Recipe; - -import org.jetbrains.annotations.NotNull; - -public class CraftingRecipe extends CustomRecipe { - - @NotNull - private final Recipe recipe; - private final boolean autoDiscover; - - public CraftingRecipe(@NotNull Recipe recipe, NamespacedKey key, boolean autoDiscover) { - super(key); - this.recipe = recipe; - this.autoDiscover = autoDiscover; - } - - public boolean isAutoDiscover() { - return autoDiscover; - } - - @Override - public void add() { - Bukkit.addRecipe(recipe); - } - - @Override - public void remove() { - Bukkit.removeRecipe(getKey()); - } - -} diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CustomRecipe.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CustomRecipe.java index 438ea2055..c18bae6e9 100644 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CustomRecipe.java +++ b/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/CustomRecipe.java @@ -1,25 +1,10 @@ package com.nisovin.magicspells.util.recipes.wrapper; import org.bukkit.NamespacedKey; +import org.bukkit.inventory.Recipe; -import org.jetbrains.annotations.NotNull; - -public abstract class CustomRecipe { - - @NotNull - private final NamespacedKey key; - - public CustomRecipe(@NotNull NamespacedKey key) { - this.key = key; - } - - @NotNull - public NamespacedKey getKey() { - return key; - } - - public abstract void add(); - - public abstract void remove(); +import org.jspecify.annotations.NullMarked; +@NullMarked +public record CustomRecipe(Recipe recipe, NamespacedKey key, boolean autoDiscover) { } diff --git a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/PotionRecipe.java b/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/PotionRecipe.java deleted file mode 100644 index eaea0b945..000000000 --- a/core/src/main/java/com/nisovin/magicspells/util/recipes/wrapper/PotionRecipe.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.nisovin.magicspells.util.recipes.wrapper; - -import org.bukkit.Bukkit; - -import io.papermc.paper.potion.PotionMix; - -import org.jetbrains.annotations.NotNull; - -public class PotionRecipe extends CustomRecipe { - - @NotNull - private final PotionMix mix; - - public PotionRecipe(@NotNull PotionMix mix) { - super(mix.getKey()); - this.mix = mix; - } - - @Override - public void add() { - Bukkit.getPotionBrewer().addPotionMix(mix); - } - - @Override - public void remove() { - Bukkit.getPotionBrewer().removePotionMix(getKey()); - } - -} diff --git a/core/src/main/java/com/nisovin/magicspells/variables/meta/InvulnerableTimeVariable.java b/core/src/main/java/com/nisovin/magicspells/variables/meta/InvulnerableTimeVariable.java new file mode 100644 index 000000000..597b770f6 --- /dev/null +++ b/core/src/main/java/com/nisovin/magicspells/variables/meta/InvulnerableTimeVariable.java @@ -0,0 +1,23 @@ +package com.nisovin.magicspells.variables.meta; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.nisovin.magicspells.variables.variabletypes.MetaVariable; + +public class InvulnerableTimeVariable extends MetaVariable { + + @Override + public double getValue(String player) { + Player p = Bukkit.getPlayerExact(player); + if (p != null) return p.getInvulnerableTime(); + return 0; + } + + @Override + public void set(String player, double amount) { + Player p = Bukkit.getPlayerExact(player); + if (p != null) p.setInvulnerableTime((int) amount); + } + +} diff --git a/core/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeDisabled.java b/core/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeDisabled.java index 5818c4cda..460f68dd4 100644 --- a/core/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeDisabled.java +++ b/core/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeDisabled.java @@ -1,6 +1,5 @@ package com.nisovin.magicspells.volatilecode; -import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.entity.*; import org.bukkit.Location; @@ -47,13 +46,6 @@ public void setClientVelocity(Player player, Vector velocity) { } - @Override - public void playHurtSound(LivingEntity entity) { - Sound sound = entity.getHurtSound(); - if (sound == null) return; - entity.getWorld().playSound(entity.getLocation(), sound, 1, 1); - } - @Override public void sendToastEffect(Player receiver, ItemStack icon, Frame frameType, Component text) { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 8bdaf60c7..51cbd2a6f 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index c61a118f7..04d795952 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,9 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip networkTimeout=10000 +retries=0 +retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index adff685a0..249efbb03 100755 --- a/gradlew +++ b/gradlew @@ -20,7 +20,7 @@ ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -29,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -57,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. diff --git a/gradlew.bat b/gradlew.bat index c4bdd3ab8..3185a43f7 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -19,12 +19,39 @@ @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @@ -45,13 +72,14 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -59,35 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/nms/latest/src/main/java/com/nisovin/magicspells/volatilecode/latest/VolatileCodeLatest.java b/nms/latest/src/main/java/com/nisovin/magicspells/volatilecode/latest/VolatileCodeLatest.java index 88bd098ef..a31689641 100644 --- a/nms/latest/src/main/java/com/nisovin/magicspells/volatilecode/latest/VolatileCodeLatest.java +++ b/nms/latest/src/main/java/com/nisovin/magicspells/volatilecode/latest/VolatileCodeLatest.java @@ -4,7 +4,6 @@ import java.lang.invoke.VarHandle; import java.util.function.Consumer; import java.lang.invoke.MethodType; -import java.util.function.Supplier; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -12,7 +11,6 @@ import org.bukkit.World; import org.bukkit.Bukkit; -import org.bukkit.Particle; import org.bukkit.Location; import org.bukkit.util.Vector; import org.bukkit.entity.Entity; @@ -149,6 +147,7 @@ public void sendFakeSlotUpdate(Player player, int slot, ItemStack item) { } @Override + @SuppressWarnings("UnstableApiUsage") public boolean simulateTnt(Location target, LivingEntity source, float explosionSize, boolean fire) { ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); var igniter = ((CraftLivingEntity) source).getHandle(); @@ -192,22 +191,6 @@ public void setClientVelocity(Player player, Vector velocity) { ((CraftPlayer) player).getHandle().connection.send(packet); } - @Override - public void playHurtSound(LivingEntity entity) { - var nmsEntity = ((CraftLivingEntity) entity).getHandle(); - var sound = nmsEntity.getHurtSound(nmsEntity.damageSources().generic()); - - if (sound == null || nmsEntity.isSilent()) return; - nmsEntity.level().playSound( - null, - nmsEntity.blockPosition(), - sound, - nmsEntity.getSoundSource(), - nmsEntity.getSoundVolume(), - nmsEntity.getVoicePitch() - ); - } - @Override public void sendToastEffect(Player receiver, ItemStack icon, AdvancementDisplay.Frame frameType, Component text) { var iconNms = CraftItemStack.asTemplate(icon); @@ -300,32 +283,6 @@ public long countEntitySchedulerTasks() { return count; } - @Override - public @Nullable Object getVolatileParticleData( - Particle particle, - Supplier geyserWaterBlocks, - Supplier geyserBurstImpulse - ) { - Class type = particle.getDataType(); - - if (type == Particle.Geyser.class) { - Integer waterBlocks = geyserWaterBlocks.get(); - if (waterBlocks == null) return null; - - return new Particle.Geyser(waterBlocks); - } - - if (type == Particle.GeyserBase.class) { - Integer waterBlocks = geyserWaterBlocks.get(); - Float burstImpulse = geyserBurstImpulse.get(); - if (waterBlocks == null || burstImpulse == null) return null; - - return new Particle.GeyserBase(waterBlocks, burstImpulse); - } - - return null; - } - @Override public @Nullable String getCommandStorageString(Key containerId, String tagKey) { Tag tag = getCommandStorage(containerId).get(tagKey); diff --git a/nms/shared/build.gradle b/nms/shared/build.gradle index 2cace6375..7d44d386a 100644 --- a/nms/shared/build.gradle +++ b/nms/shared/build.gradle @@ -1,3 +1,3 @@ dependencies { - compileOnly("me.libraryaddict.disguises:libsdisguises:11.0.16-SNAPSHOT") + compileOnly("me.libraryaddict.disguises:libsdisguises:26.11.10-SNAPSHOT") } diff --git a/nms/shared/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeHandle.java b/nms/shared/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeHandle.java index 16fcd293d..5449dac68 100644 --- a/nms/shared/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeHandle.java +++ b/nms/shared/src/main/java/com/nisovin/magicspells/volatilecode/VolatileCodeHandle.java @@ -1,7 +1,5 @@ package com.nisovin.magicspells.volatilecode; -import java.util.function.Supplier; - import org.bukkit.World; import org.bukkit.Particle; import org.bukkit.entity.*; @@ -37,8 +35,6 @@ public VolatileCodeHandle(VolatileCodeHelper helper) { public abstract void setClientVelocity(Player player, Vector velocity); - public abstract void playHurtSound(LivingEntity entity); - public abstract void sendToastEffect(Player receiver, ItemStack icon, Frame frameType, Component text); public abstract byte getEntityMetadata(Entity entity); @@ -53,9 +49,8 @@ public VolatileCodeHandle(VolatileCodeHelper helper) { @Nullable public Object getVolatileParticleData( - Particle particle, - Supplier geyserWaterBlocks, - Supplier geyserBurstImpulse + Particle particle + // Supplier supplier ) { return null; } diff --git a/nms/v26_1_2/build.gradle b/nms/v26_1_2/build.gradle deleted file mode 100644 index 0f8288b90..000000000 --- a/nms/v26_1_2/build.gradle +++ /dev/null @@ -1,8 +0,0 @@ -plugins { - id "io.papermc.paperweight.userdev" -} - -dependencies { - paperweight.paperDevBundle("26.1.2.build.+") - compileOnly project(":nms:shared") -} diff --git a/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileCode_v26_1_2.java b/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileCode_v26_1_2.java deleted file mode 100644 index b2b54d408..000000000 --- a/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileCode_v26_1_2.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.nisovin.magicspells.volatilecode.v26_1_2; - -import java.util.*; -import java.lang.invoke.VarHandle; -import java.util.function.Consumer; -import java.lang.invoke.MethodType; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; - -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; - -import org.bukkit.World; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.util.Vector; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.entity.LivingEntity; -import org.bukkit.inventory.ItemStack; -import org.bukkit.event.entity.ExplosionPrimeEvent; - -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.entity.CraftTNTPrimed; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import net.kyori.adventure.key.Key; -import net.kyori.adventure.text.Component; - -import io.papermc.paper.adventure.PaperAdventure; -import io.papermc.paper.advancement.AdvancementDisplay; -import io.papermc.paper.threadedregions.EntityScheduler; -import io.papermc.paper.threadedregions.scheduler.ScheduledTask; -import io.papermc.paper.threadedregions.scheduler.FoliaGlobalRegionScheduler; - -import com.nisovin.magicspells.util.glow.GlowManager; -import com.nisovin.magicspells.volatilecode.VolatileCodeHandle; -import com.nisovin.magicspells.volatilecode.VolatileCodeHelper; - -import net.minecraft.nbt.Tag; -import net.minecraft.util.ARGB; -import net.minecraft.core.BlockPos; -import net.minecraft.advancements.*; -import net.minecraft.world.phys.Vec3; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.Identifier; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.entity.EntityType; -import net.minecraft.network.protocol.game.*; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.item.PrimedTnt; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.core.particles.ColorParticleOption; -import net.minecraft.advancements.criterion.ImpossibleTrigger; -import net.minecraft.world.entity.boss.enderdragon.EnderDragon; - -public class VolatileCode_v26_1_2 extends VolatileCodeHandle { - - private final Identifier TOAST_KEY = Identifier.fromNamespaceAndPath("magicspells", "toast_effect"); - - private final EntityDataAccessor> DATA_EFFECT_PARTICLES; - private final EntityDataAccessor DATA_EFFECT_AMBIENCE_ID; - private final EntityDataAccessor DATA_SHARED_FLAGS_ID; - private final MethodHandle UPDATE_EFFECT_PARTICLES; - - private final Long2ObjectOpenHashMap> GLOBAL_REGION_TASKS; - private final VarHandle CURRENTLY_EXECUTING_HANDLE; - private final VarHandle ONE_TIME_DELAYED_HANDLE; - private final VarHandle RUN_HANDLE; - - @SuppressWarnings("unchecked") - public VolatileCode_v26_1_2(VolatileCodeHelper helper) throws Exception { - super(helper); - - MethodHandles.Lookup lookup = MethodHandles.lookup(); - - Class leClass = net.minecraft.world.entity.LivingEntity.class; - Class eClass = net.minecraft.world.entity.Entity.class; - - DATA_SHARED_FLAGS_ID = (EntityDataAccessor<@NotNull Byte>) MethodHandles.privateLookupIn(eClass, lookup) - .findStaticVarHandle(eClass, "DATA_SHARED_FLAGS_ID", EntityDataAccessor.class).get(); - - MethodHandles.Lookup leLookup = MethodHandles.privateLookupIn(leClass, lookup); - - DATA_EFFECT_PARTICLES = (EntityDataAccessor<@NotNull List>) leLookup - .findStaticVarHandle(leClass, "DATA_EFFECT_PARTICLES", EntityDataAccessor.class).get(); - - DATA_EFFECT_AMBIENCE_ID = (EntityDataAccessor<@NotNull Boolean>) leLookup - .findStaticVarHandle(leClass, "DATA_EFFECT_AMBIENCE_ID", EntityDataAccessor.class).get(); - - UPDATE_EFFECT_PARTICLES = leLookup.findVirtual(leClass, "updateSynchronizedMobEffectParticles", MethodType.methodType(void.class)); - - GLOBAL_REGION_TASKS = (Long2ObjectOpenHashMap>) MethodHandles.privateLookupIn(FoliaGlobalRegionScheduler.class, lookup) - .findVarHandle(FoliaGlobalRegionScheduler.class, "tasksByDeadline", Long2ObjectOpenHashMap.class) - .get(Bukkit.getGlobalRegionScheduler()); - - MethodHandles.Lookup esLookup = MethodHandles.privateLookupIn(EntityScheduler.class, lookup); - - CURRENTLY_EXECUTING_HANDLE = esLookup.findVarHandle(EntityScheduler.class, "currentlyExecuting", ArrayDeque.class); - ONE_TIME_DELAYED_HANDLE = esLookup.findVarHandle(EntityScheduler.class, "oneTimeDelayed", Long2ObjectOpenHashMap.class); - - Class scheduledTaskClass = esLookup.findClass("io.papermc.paper.threadedregions.EntityScheduler$ScheduledTask"); - RUN_HANDLE = esLookup.findVarHandle(scheduledTaskClass, "run", Consumer.class); - } - - @Override - public void addPotionGraphicalEffect(LivingEntity entity, int color, long duration) { - var nmsEntity = (((CraftLivingEntity) entity)).getHandle(); - SynchedEntityData entityData = nmsEntity.getEntityData(); - - entityData.set( - DATA_EFFECT_PARTICLES, - List.of(ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.opaque(color))) - ); - - entityData.set(DATA_EFFECT_AMBIENCE_ID, false); - - if (duration <= 0) return; - helper.scheduleDelayedTask(() -> { - try { - UPDATE_EFFECT_PARTICLES.invoke(nmsEntity); - } catch (Throwable e) { - e.printStackTrace(); - } - }, duration); - } - - @Override - public void sendFakeSlotUpdate(Player player, int slot, ItemStack item) { - var nmsItem = CraftItemStack.asNMSCopy(item); - ClientboundContainerSetSlotPacket packet = new ClientboundContainerSetSlotPacket(0, 0, slot + 36, nmsItem); - - ((CraftPlayer) player).getHandle().connection.send(packet); - } - - @Override - public boolean simulateTnt(Location target, LivingEntity source, float explosionSize, boolean fire) { - ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); - var igniter = ((CraftLivingEntity) source).getHandle(); - - PrimedTnt tnt = new PrimedTnt(world, target.x(), target.y(), target.z(), igniter); - CraftTNTPrimed craftTNT = new CraftTNTPrimed((CraftServer) Bukkit.getServer(), tnt); - - return !new ExplosionPrimeEvent(craftTNT, explosionSize, fire).callEvent(); - } - - @Override - public void playDragonDeathEffect(Location location) { - EnderDragon dragon = new EnderDragon(EntityType.ENDER_DRAGON, ((CraftWorld) location.getWorld()).getHandle()); - dragon.setPos(location.x(), location.y(), location.z()); - - BlockPos pos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - ClientboundAddEntityPacket addMobPacket = new ClientboundAddEntityPacket(dragon, 0, pos); - ClientboundEntityEventPacket entityEventPacket = new ClientboundEntityEventPacket(dragon, (byte) 3); - ClientboundRemoveEntitiesPacket removeEntityPacket = new ClientboundRemoveEntitiesPacket(dragon.getId()); - - List players = new ArrayList<>(); - for (Player player : location.getNearbyPlayers(64.0)) { - players.add(player); - ServerPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); - nmsPlayer.connection.send(addMobPacket); - nmsPlayer.connection.send(entityEventPacket); - } - - helper.scheduleDelayedTask(() -> { - for (Player player : players) { - if (!player.isValid()) continue; - ((CraftPlayer) player).getHandle().connection.send(removeEntityPacket); - } - }, 200); - } - - @Override - public void setClientVelocity(Player player, Vector velocity) { - Vec3 pos = new Vec3(velocity.getX(), velocity.getY(), velocity.getZ()); - ClientboundSetEntityMotionPacket packet = new ClientboundSetEntityMotionPacket(player.getEntityId(), pos); - ((CraftPlayer) player).getHandle().connection.send(packet); - } - - @Override - public void playHurtSound(LivingEntity entity) { - var nmsEntity = ((CraftLivingEntity) entity).getHandle(); - var sound = nmsEntity.getHurtSound(nmsEntity.damageSources().generic()); - - if (sound == null || nmsEntity.isSilent()) return; - nmsEntity.level().playSound( - null, - nmsEntity.blockPosition(), - sound, - nmsEntity.getSoundSource(), - nmsEntity.getSoundVolume(), - nmsEntity.getVoicePitch() - ); - } - - @Override - public void sendToastEffect(Player receiver, ItemStack icon, AdvancementDisplay.Frame frameType, Component text) { - var iconNms = CraftItemStack.asTemplate(icon); - var textNms = PaperAdventure.asVanilla(text); - var description = PaperAdventure.asVanilla(Component.empty()); - AdvancementType frame; - try { - frame = AdvancementType.valueOf(frameType.name()); - } catch (IllegalArgumentException ignored) { - frame = AdvancementType.TASK; - } - - AdvancementHolder advancement = Advancement.Builder.advancement() - .display(iconNms, textNms, description, null, frame, true, false, true) - .addCriterion("impossible", new Criterion<>(new ImpossibleTrigger(), new ImpossibleTrigger.TriggerInstance())) - .build(TOAST_KEY); - AdvancementProgress progress = new AdvancementProgress(); - progress.update(new AdvancementRequirements(List.of(List.of("impossible")))); - progress.grantProgress("impossible"); - - ServerPlayer player = ((CraftPlayer) receiver).getHandle(); - player.connection.send(new ClientboundUpdateAdvancementsPacket( - false, - Collections.singleton(advancement), - Collections.emptySet(), - Collections.singletonMap(TOAST_KEY, progress), - true - )); - player.connection.send(new ClientboundUpdateAdvancementsPacket( - false, - Collections.emptySet(), - Collections.singleton(TOAST_KEY), - Collections.emptyMap(), - true - )); - } - - @Override - public byte getEntityMetadata(Entity entity) { - return ((CraftEntity) entity).getHandle().getEntityData().get(DATA_SHARED_FLAGS_ID); - } - - @Override - public Entity getEntityFromId(World world, int id) { - var entity = ((CraftWorld) world).getHandle().moonrise$getEntityLookup().get(id); - return entity == null ? null : entity.getBukkitEntity(); - } - - @Override - public GlowManager getGlowManager() { - return new VolatileGlowManager_v26_1_2(helper); - } - - @Override - public long countGlobalRegionSchedulerTasks() { - Plugin plugin = helper.getPlugin(); - - return GLOBAL_REGION_TASKS.values().stream() - .flatMap(List::stream) - .filter(task -> task.getOwningPlugin() == plugin) - .count(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public long countEntitySchedulerTasks() { - EntityScheduler.EntitySchedulerTickList entitySchedulerTickList = MinecraftServer.getServer().entitySchedulerTickList; - EntityScheduler[] schedulers = entitySchedulerTickList.getAllSchedulers(); - Plugin plugin = helper.getPlugin(); - - int count = 0; - for (EntityScheduler scheduler : schedulers) { - Long2ObjectOpenHashMap oneTimeDelayed = (Long2ObjectOpenHashMap) ONE_TIME_DELAYED_HANDLE.get(scheduler); - ArrayDeque currentlyExecuting = (ArrayDeque) CURRENTLY_EXECUTING_HANDLE.get(scheduler); - - for (List taskList : oneTimeDelayed.values()) { - for (Object taskObject : taskList) { - ScheduledTask task = (ScheduledTask) (Consumer) RUN_HANDLE.get(taskObject); - if (task.getOwningPlugin() == plugin) count++; - } - } - - for (Object taskObject : currentlyExecuting) { - ScheduledTask task = (ScheduledTask) (Consumer) RUN_HANDLE.get(taskObject); - if (task.getOwningPlugin() == plugin) count++; - } - } - - return count; - } - - @Override - public @Nullable String getCommandStorageString(Key containerId, String tagKey) { - Tag tag = getCommandStorage(containerId).get(tagKey); - return tag == null ? null : tag.asString().orElse(tag.toString()); - } - - @Override - public @Nullable Double getCommandStorageDouble(Key containerId, String tagKey) { - return getCommandStorage(containerId).getDouble(tagKey).orElse(null); - } - - private CompoundTag getCommandStorage(Key id) { - MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer(); - return server.getCommandStorage().get(PaperAdventure.asVanilla(id)); - } - -} diff --git a/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileGlowManager_v26_1_2.java b/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileGlowManager_v26_1_2.java deleted file mode 100644 index adbf17545..000000000 --- a/nms/v26_1_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_1_2/VolatileGlowManager_v26_1_2.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.nisovin.magicspells.volatilecode.v26_1_2; - -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.lang.invoke.MethodType; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; - -import io.netty.channel.ChannelPromise; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandlerAdapter; - -import net.minecraft.ChatFormatting; -import net.minecraft.network.protocol.Packet; -import net.minecraft.world.scores.PlayerTeam; -import net.minecraft.world.scores.Scoreboard; -import net.minecraft.util.StringRepresentable; -import net.minecraft.world.scores.Team.Visibility; -import net.minecraft.world.scores.Team.CollisionRule; -import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.network.syncher.EntityDataSerializers; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; -import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.scoreboard.Team; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.configuration.ConfigurationSection; - -import com.nisovin.magicspells.util.glow.LibsDisguiseHelper; -import com.nisovin.magicspells.volatilecode.VolatileCodeHelper; -import com.nisovin.magicspells.util.glow.PacketBasedGlowManager; - -public class VolatileGlowManager_v26_1_2 extends PacketBasedGlowManager, ClientboundSetEntityDataPacket, ClientboundSetPlayerTeamPacket> { - - private static final EntityDataAccessor DATA_SHARED_FLAGS_ID = new EntityDataAccessor<>(0, EntityDataSerializers.BYTE); - - private final Set> handled = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>())); - private final MethodHandle teamPacketHandle; - private final VolatileCodeHelper helper; - - public VolatileGlowManager_v26_1_2(VolatileCodeHelper helper) { - this.helper = helper; - - try { - teamPacketHandle = MethodHandles - .privateLookupIn(ClientboundSetPlayerTeamPacket.class, MethodHandles.lookup()) - .findConstructor( - ClientboundSetPlayerTeamPacket.class, - MethodType.methodType(void.class, String.class, int.class, Optional.class, Collection.class) - ); - } catch (Exception e) { - throw new RuntimeException("Encountered an error while initializing " + getClass().getSimpleName(), e); - } - - helper.registerEvents(this); - } - - @Override - public void load() { - super.load(); - - Bukkit.getOnlinePlayers().forEach(this::addGlowChannelHandler); - } - - @Override - public synchronized void unload() { - Bukkit.getOnlinePlayers().forEach(this::removeGlowChannelHandler); - - super.unload(); - handled.clear(); - } - - @Override - protected Collection createAddTeamPackets() { - List teamPackets = new ArrayList<>(); - - ConfigurationSection config = helper.getMainConfig(); - boolean seeFriendlyInvisibles = config.getBoolean("general.glow-spell-scoreboard-teams.see-friendly-invisibles", false); - CollisionRule collision = getStringOption("collision-rule", CollisionRule.ALWAYS, StringRepresentable.createNameLookup(CollisionRule.values()), config, helper::error); - Visibility visibility = getStringOption("name-tag-visibility", Visibility.ALWAYS, StringRepresentable.createNameLookup(Visibility.values()), config, helper::error); - - Scoreboard scoreboard = new Scoreboard(); - for (ChatFormatting formatting : ChatFormatting.values()) { - if (!formatting.isColor()) continue; - - PlayerTeam team = new PlayerTeam(scoreboard, "magicspells:" + formatting.getName()); - team.setSeeFriendlyInvisibles(seeFriendlyInvisibles); - team.setNameTagVisibility(visibility); - team.setCollisionRule(collision); - team.setColor(formatting); - - teamPackets.add(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(team, true)); - } - - return teamPackets; - } - - @Override - protected Collection createRemoveTeamPackets() { - List packets = new ArrayList<>(); - - Scoreboard scoreboard = new Scoreboard(); - for (ChatFormatting formatting : ChatFormatting.values()) { - if (!formatting.isColor()) continue; - - PlayerTeam team = new PlayerTeam(scoreboard, "magicspells:" + formatting.getName()); - packets.add(ClientboundSetPlayerTeamPacket.createRemovePacket(team)); - } - - return packets; - } - - @Override - protected ClientboundSetEntityDataPacket createEntityDataPacket(@NotNull Entity entity, boolean forceGlow) { - byte metadata = ((CraftEntity) entity).getHandle().getEntityData().get(DATA_SHARED_FLAGS_ID); - if (forceGlow) metadata |= 0x40; - - return new ClientboundSetEntityDataPacket( - entity.getEntityId(), - list(new SynchedEntityData.DataValue<>( - 0, - EntityDataSerializers.BYTE, - metadata - )) - ); - } - - @Override - protected Collection createJoinTeamPacket(@NotNull GlowData data) { - return data.lastScoreboardEntry().map(entry -> { - try { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - "magicspells:" + data.color(), - 3, - Optional.empty(), - list(entry) - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }); - } - - @Override - protected Collection createResetTeamPacket(org.bukkit.scoreboard.@NotNull Scoreboard scoreboard, @NotNull GlowData data) { - return data.lastScoreboardEntry().map(entry -> { - try { - Team team = scoreboard.getEntryTeam(entry); - if (team != null) { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - team.getName(), - 3, - Optional.empty(), - list(entry) - ); - } - - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - "magicspells:" + data.color(), - 4, - Optional.empty(), - list(entry) - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }); - } - - @Override - protected void sendPacket(@NotNull Player player, @NotNull Packet packet) { - if (!(packet instanceof ClientboundSetPlayerTeamPacket teamPacket) || teamPacket.getTeamAction() == null) - handled.add(packet); - - ServerGamePacketListenerImpl connection = ((CraftPlayer) player).getHandle().connection; - connection.send(packet); - } - - @Override - protected void registerEvents(Listener listener) { - helper.registerEvents(listener); - } - - @Override - protected void cancelTask(int taskId) { - helper.cancelTask(taskId); - } - - @Override - public int scheduleDelayedTask(Runnable runnable, long delay) { - return helper.scheduleDelayedTask(runnable, delay); - } - - private void addGlowChannelHandler(Player player) { - ChannelPipeline pipeline = ((CraftPlayer) player).getHandle().connection.connection.channel.pipeline(); - pipeline.addBefore("unbundler", "magicspells:glow_channel_handler", new GlowChannelHandler(player)); - } - - private void removeGlowChannelHandler(Player player) { - ChannelPipeline pipeline = ((CraftPlayer) player).getHandle().connection.connection.channel.pipeline(); - - if (pipeline.get("magicspells:glow_channel_handler") != null) - pipeline.remove("magicspells:glow_channel_handler"); - } - - private List list(T element) { - List list = new ArrayList<>(1); - list.add(element); - - return list; - } - - @Override - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - super.onPlayerJoin(event); - addGlowChannelHandler(event.getPlayer()); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - removeGlowChannelHandler(event.getPlayer()); - } - - private class GlowChannelHandler extends ChannelOutboundHandlerAdapter { - - private final Player player; - - private GlowChannelHandler(Player player) { - this.player = player; - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - if (msg instanceof Packet p && handled.contains(p)) { - super.write(ctx, msg, promise); - return; - } - - synchronized (VolatileGlowManager_v26_1_2.this) { - if (glows.isEmpty() && perPlayerGlows.isEmpty()) { - super.write(ctx, msg, promise); - return; - } - } - - switch (msg) { - case ClientboundSetEntityDataPacket packet -> handleEntityData(packet); - case ClientboundSetPlayerTeamPacket packet -> { - msg = handleTeamPacket(packet); - if (msg == null) return; - } - default -> {} - } - - super.write(ctx, msg, promise); - } - - private void handleEntityData(ClientboundSetEntityDataPacket packet) { - List> packedItems = packet.packedItems(); - if (packedItems.isEmpty()) return; - - SynchedEntityData.DataValue item = packedItems.getFirst(); - if (item.id() != 0) return; - - byte flags = (byte) item.value(); - if ((flags & 0x40) > 0) return; - - UUID uuid; - if (!libsDisguisesLoaded || packet.id() != LibsDisguiseHelper.getSelfDisguiseId()) { - var entity = ((CraftPlayer) player).getHandle().level().moonrise$getEntityLookup().get(packet.id()); - if (entity == null) return; - - uuid = entity.getUUID(); - } else uuid = player.getUniqueId(); - - GlowData data = getGlowData(player.getUniqueId(), uuid); - if (data == null) return; - - flags |= 0x40; - packedItems.set(0, new SynchedEntityData.DataValue<>(0, EntityDataSerializers.BYTE, flags)); - } - - private ClientboundSetPlayerTeamPacket handleTeamPacket(ClientboundSetPlayerTeamPacket packet) { - ClientboundSetPlayerTeamPacket.Action playerAction = packet.getPlayerAction(); - if (playerAction == null || packet.getTeamAction() != null) return packet; - - Collection entries = packet.getPlayers(); - if (entries.isEmpty()) return packet; - - Collection filtered = filterTeamEntries(player, entries); - if (filtered == null) return packet; - if (filtered.isEmpty()) return null; - - try { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - packet.getName(), - playerAction == ClientboundSetPlayerTeamPacket.Action.ADD ? 3 : 4, - packet.getParameters(), - filtered - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - } - - } - -} diff --git a/nms/v26_2/build.gradle b/nms/v26_2/build.gradle deleted file mode 100644 index 229ded7f4..000000000 --- a/nms/v26_2/build.gradle +++ /dev/null @@ -1,8 +0,0 @@ -plugins { - id "io.papermc.paperweight.userdev" -} - -dependencies { - paperweight.paperDevBundle("26.2.build.+") - compileOnly project(":nms:shared") -} diff --git a/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileCode_v26_2.java b/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileCode_v26_2.java deleted file mode 100644 index 8e07136fd..000000000 --- a/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileCode_v26_2.java +++ /dev/null @@ -1,343 +0,0 @@ -package com.nisovin.magicspells.volatilecode.v26_2; - -import java.util.*; -import java.lang.invoke.VarHandle; -import java.util.function.Consumer; -import java.lang.invoke.MethodType; -import java.util.function.Supplier; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; - -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; - -import org.bukkit.World; -import org.bukkit.Bukkit; -import org.bukkit.Particle; -import org.bukkit.Location; -import org.bukkit.util.Vector; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.entity.LivingEntity; -import org.bukkit.inventory.ItemStack; -import org.bukkit.event.entity.ExplosionPrimeEvent; - -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.entity.CraftTNTPrimed; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import net.kyori.adventure.key.Key; -import net.kyori.adventure.text.Component; - -import io.papermc.paper.adventure.PaperAdventure; -import io.papermc.paper.advancement.AdvancementDisplay; -import io.papermc.paper.threadedregions.EntityScheduler; -import io.papermc.paper.threadedregions.scheduler.ScheduledTask; -import io.papermc.paper.threadedregions.scheduler.FoliaGlobalRegionScheduler; - -import com.nisovin.magicspells.util.glow.GlowManager; -import com.nisovin.magicspells.volatilecode.VolatileCodeHandle; -import com.nisovin.magicspells.volatilecode.VolatileCodeHelper; - -import net.minecraft.nbt.Tag; -import net.minecraft.util.ARGB; -import net.minecraft.core.BlockPos; -import net.minecraft.advancements.*; -import net.minecraft.world.phys.Vec3; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.Identifier; -import net.minecraft.server.MinecraftServer; -import net.minecraft.network.protocol.game.*; -import net.minecraft.world.entity.EntityTypes; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.item.PrimedTnt; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.advancements.triggers.Criterion; -import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.core.particles.ColorParticleOption; -import net.minecraft.advancements.triggers.ImpossibleTrigger; -import net.minecraft.world.entity.boss.enderdragon.EnderDragon; - -public class VolatileCode_v26_2 extends VolatileCodeHandle { - - private final Identifier TOAST_KEY = Identifier.fromNamespaceAndPath("magicspells", "toast_effect"); - - private final EntityDataAccessor> DATA_EFFECT_PARTICLES; - private final EntityDataAccessor DATA_EFFECT_AMBIENCE_ID; - private final EntityDataAccessor DATA_SHARED_FLAGS_ID; - private final MethodHandle UPDATE_EFFECT_PARTICLES; - - private final Long2ObjectOpenHashMap> GLOBAL_REGION_TASKS; - private final VarHandle CURRENTLY_EXECUTING_HANDLE; - private final VarHandle ONE_TIME_DELAYED_HANDLE; - private final VarHandle RUN_HANDLE; - - @SuppressWarnings("unchecked") - public VolatileCode_v26_2(VolatileCodeHelper helper) throws Exception { - super(helper); - - MethodHandles.Lookup lookup = MethodHandles.lookup(); - - Class leClass = net.minecraft.world.entity.LivingEntity.class; - Class eClass = net.minecraft.world.entity.Entity.class; - - DATA_SHARED_FLAGS_ID = (EntityDataAccessor<@NotNull Byte>) MethodHandles.privateLookupIn(eClass, lookup) - .findStaticVarHandle(eClass, "DATA_SHARED_FLAGS_ID", EntityDataAccessor.class).get(); - - MethodHandles.Lookup leLookup = MethodHandles.privateLookupIn(leClass, lookup); - - DATA_EFFECT_PARTICLES = (EntityDataAccessor<@NotNull List>) leLookup - .findStaticVarHandle(leClass, "DATA_EFFECT_PARTICLES", EntityDataAccessor.class).get(); - - DATA_EFFECT_AMBIENCE_ID = (EntityDataAccessor<@NotNull Boolean>) leLookup - .findStaticVarHandle(leClass, "DATA_EFFECT_AMBIENCE_ID", EntityDataAccessor.class).get(); - - UPDATE_EFFECT_PARTICLES = leLookup.findVirtual(leClass, "updateSynchronizedMobEffectParticles", MethodType.methodType(void.class)); - - GLOBAL_REGION_TASKS = (Long2ObjectOpenHashMap>) MethodHandles.privateLookupIn(FoliaGlobalRegionScheduler.class, lookup) - .findVarHandle(FoliaGlobalRegionScheduler.class, "tasksByDeadline", Long2ObjectOpenHashMap.class) - .get(Bukkit.getGlobalRegionScheduler()); - - MethodHandles.Lookup esLookup = MethodHandles.privateLookupIn(EntityScheduler.class, lookup); - - CURRENTLY_EXECUTING_HANDLE = esLookup.findVarHandle(EntityScheduler.class, "currentlyExecuting", ArrayDeque.class); - ONE_TIME_DELAYED_HANDLE = esLookup.findVarHandle(EntityScheduler.class, "oneTimeDelayed", Long2ObjectOpenHashMap.class); - - Class scheduledTaskClass = esLookup.findClass("io.papermc.paper.threadedregions.EntityScheduler$ScheduledTask"); - RUN_HANDLE = esLookup.findVarHandle(scheduledTaskClass, "run", Consumer.class); - } - - @Override - public void addPotionGraphicalEffect(LivingEntity entity, int color, long duration) { - var nmsEntity = (((CraftLivingEntity) entity)).getHandle(); - SynchedEntityData entityData = nmsEntity.getEntityData(); - - entityData.set( - DATA_EFFECT_PARTICLES, - List.of(ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.opaque(color))) - ); - - entityData.set(DATA_EFFECT_AMBIENCE_ID, false); - - if (duration <= 0) return; - helper.scheduleDelayedTask(() -> { - try { - UPDATE_EFFECT_PARTICLES.invoke(nmsEntity); - } catch (Throwable e) { - e.printStackTrace(); - } - }, duration); - } - - @Override - public void sendFakeSlotUpdate(Player player, int slot, ItemStack item) { - var nmsItem = CraftItemStack.asNMSCopy(item); - ClientboundContainerSetSlotPacket packet = new ClientboundContainerSetSlotPacket(0, 0, slot + 36, nmsItem); - - ((CraftPlayer) player).getHandle().connection.send(packet); - } - - @Override - public boolean simulateTnt(Location target, LivingEntity source, float explosionSize, boolean fire) { - ServerLevel world = ((CraftWorld) target.getWorld()).getHandle(); - var igniter = ((CraftLivingEntity) source).getHandle(); - - PrimedTnt tnt = new PrimedTnt(world, target.x(), target.y(), target.z(), igniter); - CraftTNTPrimed craftTNT = new CraftTNTPrimed((CraftServer) Bukkit.getServer(), tnt); - - return !new ExplosionPrimeEvent(craftTNT, explosionSize, fire).callEvent(); - } - - @Override - public void playDragonDeathEffect(Location location) { - EnderDragon dragon = new EnderDragon(EntityTypes.ENDER_DRAGON, ((CraftWorld) location.getWorld()).getHandle()); - dragon.setPos(location.x(), location.y(), location.z()); - - BlockPos pos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - ClientboundAddEntityPacket addMobPacket = new ClientboundAddEntityPacket(dragon, 0, pos); - ClientboundEntityEventPacket entityEventPacket = new ClientboundEntityEventPacket(dragon, (byte) 3); - ClientboundRemoveEntitiesPacket removeEntityPacket = new ClientboundRemoveEntitiesPacket(dragon.getId()); - - List players = new ArrayList<>(); - for (Player player : location.getNearbyPlayers(64.0)) { - players.add(player); - ServerPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); - nmsPlayer.connection.send(addMobPacket); - nmsPlayer.connection.send(entityEventPacket); - } - - helper.scheduleDelayedTask(() -> { - for (Player player : players) { - if (!player.isValid()) continue; - ((CraftPlayer) player).getHandle().connection.send(removeEntityPacket); - } - }, 200); - } - - @Override - public void setClientVelocity(Player player, Vector velocity) { - Vec3 pos = new Vec3(velocity.getX(), velocity.getY(), velocity.getZ()); - ClientboundSetEntityMotionPacket packet = new ClientboundSetEntityMotionPacket(player.getEntityId(), pos); - ((CraftPlayer) player).getHandle().connection.send(packet); - } - - @Override - public void playHurtSound(LivingEntity entity) { - var nmsEntity = ((CraftLivingEntity) entity).getHandle(); - var sound = nmsEntity.getHurtSound(nmsEntity.damageSources().generic()); - - if (sound == null || nmsEntity.isSilent()) return; - nmsEntity.level().playSound( - null, - nmsEntity.blockPosition(), - sound, - nmsEntity.getSoundSource(), - nmsEntity.getSoundVolume(), - nmsEntity.getVoicePitch() - ); - } - - @Override - public void sendToastEffect(Player receiver, ItemStack icon, AdvancementDisplay.Frame frameType, Component text) { - var iconNms = CraftItemStack.asTemplate(icon); - var textNms = PaperAdventure.asVanilla(text); - var description = PaperAdventure.asVanilla(Component.empty()); - AdvancementType frame; - try { - frame = AdvancementType.valueOf(frameType.name()); - } catch (IllegalArgumentException ignored) { - frame = AdvancementType.TASK; - } - - AdvancementHolder advancement = Advancement.Builder.advancement() - .display(iconNms, textNms, description, null, frame, true, false, true) - .addCriterion("impossible", new Criterion<>(new ImpossibleTrigger(), new ImpossibleTrigger.TriggerInstance())) - .build(TOAST_KEY); - AdvancementProgress progress = new AdvancementProgress(); - progress.update(new AdvancementRequirements(List.of(List.of("impossible")))); - progress.grantProgress("impossible"); - - ServerPlayer player = ((CraftPlayer) receiver).getHandle(); - player.connection.send(new ClientboundUpdateAdvancementsPacket( - false, - Collections.singleton(advancement), - Collections.emptySet(), - Collections.singletonMap(TOAST_KEY, progress), - true - )); - player.connection.send(new ClientboundUpdateAdvancementsPacket( - false, - Collections.emptySet(), - Collections.singleton(TOAST_KEY), - Collections.emptyMap(), - true - )); - } - - @Override - public byte getEntityMetadata(Entity entity) { - return ((CraftEntity) entity).getHandle().getEntityData().get(DATA_SHARED_FLAGS_ID); - } - - @Override - public Entity getEntityFromId(World world, int id) { - var entity = ((CraftWorld) world).getHandle().moonrise$getEntityLookup().get(id); - return entity == null ? null : entity.getBukkitEntity(); - } - - @Override - public GlowManager getGlowManager() { - return new VolatileGlowManager_v26_2(helper); - } - - @Override - public long countGlobalRegionSchedulerTasks() { - Plugin plugin = helper.getPlugin(); - - return GLOBAL_REGION_TASKS.values().stream() - .flatMap(List::stream) - .filter(task -> task.getOwningPlugin() == plugin) - .count(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public long countEntitySchedulerTasks() { - EntityScheduler.EntitySchedulerTickList entitySchedulerTickList = MinecraftServer.getServer().entitySchedulerTickList; - EntityScheduler[] schedulers = entitySchedulerTickList.getAllSchedulers(); - Plugin plugin = helper.getPlugin(); - - int count = 0; - for (EntityScheduler scheduler : schedulers) { - Long2ObjectOpenHashMap oneTimeDelayed = (Long2ObjectOpenHashMap) ONE_TIME_DELAYED_HANDLE.get(scheduler); - ArrayDeque currentlyExecuting = (ArrayDeque) CURRENTLY_EXECUTING_HANDLE.get(scheduler); - - for (List taskList : oneTimeDelayed.values()) { - for (Object taskObject : taskList) { - ScheduledTask task = (ScheduledTask) (Consumer) RUN_HANDLE.get(taskObject); - if (task.getOwningPlugin() == plugin) count++; - } - } - - for (Object taskObject : currentlyExecuting) { - ScheduledTask task = (ScheduledTask) (Consumer) RUN_HANDLE.get(taskObject); - if (task.getOwningPlugin() == plugin) count++; - } - } - - return count; - } - - @Override - public @Nullable Object getVolatileParticleData( - Particle particle, - Supplier geyserWaterBlocks, - Supplier geyserBurstImpulse - ) { - Class type = particle.getDataType(); - - if (type == Particle.Geyser.class) { - Integer waterBlocks = geyserWaterBlocks.get(); - if (waterBlocks == null) return null; - - return new Particle.Geyser(waterBlocks); - } - - if (type == Particle.GeyserBase.class) { - Integer waterBlocks = geyserWaterBlocks.get(); - Float burstImpulse = geyserBurstImpulse.get(); - if (waterBlocks == null || burstImpulse == null) return null; - - return new Particle.GeyserBase(waterBlocks, burstImpulse); - } - - return null; - } - - @Override - public @Nullable String getCommandStorageString(Key containerId, String tagKey) { - Tag tag = getCommandStorage(containerId).get(tagKey); - return tag == null ? null : tag.asString().orElse(tag.toString()); - } - - @Override - public @Nullable Double getCommandStorageDouble(Key containerId, String tagKey) { - return getCommandStorage(containerId).getDouble(tagKey).orElse(null); - } - - private CompoundTag getCommandStorage(Key id) { - MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer(); - return server.getCommandStorage().get(PaperAdventure.asVanilla(id)); - } - -} diff --git a/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileGlowManager_v26_2.java b/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileGlowManager_v26_2.java deleted file mode 100644 index 755054dca..000000000 --- a/nms/v26_2/src/main/java/com/nisovin/magicspells/volatilecode/v26_2/VolatileGlowManager_v26_2.java +++ /dev/null @@ -1,317 +0,0 @@ -package com.nisovin.magicspells.volatilecode.v26_2; - -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.lang.invoke.MethodType; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; - -import io.netty.channel.ChannelPromise; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandlerAdapter; - -import net.minecraft.world.scores.TeamColor; -import net.minecraft.network.protocol.Packet; -import net.minecraft.world.scores.PlayerTeam; -import net.minecraft.world.scores.Scoreboard; -import net.minecraft.util.StringRepresentable; -import net.minecraft.world.scores.Team.Visibility; -import net.minecraft.world.scores.Team.CollisionRule; -import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.network.syncher.EntityDataSerializers; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; -import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.scoreboard.Team; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.configuration.ConfigurationSection; - -import com.nisovin.magicspells.util.glow.LibsDisguiseHelper; -import com.nisovin.magicspells.volatilecode.VolatileCodeHelper; -import com.nisovin.magicspells.util.glow.PacketBasedGlowManager; - -public class VolatileGlowManager_v26_2 extends PacketBasedGlowManager, ClientboundSetEntityDataPacket, ClientboundSetPlayerTeamPacket> { - - private static final EntityDataAccessor DATA_SHARED_FLAGS_ID = new EntityDataAccessor<>(0, EntityDataSerializers.BYTE); - - private final Set> handled = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>())); - private final MethodHandle teamPacketHandle; - private final VolatileCodeHelper helper; - - public VolatileGlowManager_v26_2(VolatileCodeHelper helper) { - this.helper = helper; - - try { - teamPacketHandle = MethodHandles - .privateLookupIn(ClientboundSetPlayerTeamPacket.class, MethodHandles.lookup()) - .findConstructor( - ClientboundSetPlayerTeamPacket.class, - MethodType.methodType(void.class, String.class, int.class, Optional.class, Collection.class) - ); - } catch (Exception e) { - throw new RuntimeException("Encountered an error while initializing " + getClass().getSimpleName(), e); - } - - helper.registerEvents(this); - } - - @Override - public void load() { - super.load(); - - Bukkit.getOnlinePlayers().forEach(this::addGlowChannelHandler); - } - - @Override - public synchronized void unload() { - Bukkit.getOnlinePlayers().forEach(this::removeGlowChannelHandler); - - super.unload(); - handled.clear(); - } - - @Override - protected Collection createAddTeamPackets() { - List teamPackets = new ArrayList<>(); - - ConfigurationSection config = helper.getMainConfig(); - boolean seeFriendlyInvisibles = config.getBoolean("general.glow-spell-scoreboard-teams.see-friendly-invisibles", false); - CollisionRule collision = getStringOption("collision-rule", CollisionRule.ALWAYS, StringRepresentable.createNameLookup(CollisionRule.values()), config, helper::error); - Visibility visibility = getStringOption("name-tag-visibility", Visibility.ALWAYS, StringRepresentable.createNameLookup(Visibility.values()), config, helper::error); - - Scoreboard scoreboard = new Scoreboard(); - for (TeamColor color : TeamColor.values()) { - PlayerTeam team = new PlayerTeam(scoreboard, "magicspells:" + color.getSerializedName()); - team.setSeeFriendlyInvisibles(seeFriendlyInvisibles); - team.setNameTagVisibility(visibility); - team.setCollisionRule(collision); - team.setColor(Optional.of(color)); - - teamPackets.add(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(team, true)); - } - - return teamPackets; - } - - @Override - protected Collection createRemoveTeamPackets() { - List packets = new ArrayList<>(); - - Scoreboard scoreboard = new Scoreboard(); - for (TeamColor color : TeamColor.values()) { - PlayerTeam team = new PlayerTeam(scoreboard, "magicspells:" + color.getSerializedName()); - packets.add(ClientboundSetPlayerTeamPacket.createRemovePacket(team)); - } - - return packets; - } - - @Override - protected ClientboundSetEntityDataPacket createEntityDataPacket(@NotNull Entity entity, boolean forceGlow) { - byte metadata = ((CraftEntity) entity).getHandle().getEntityData().get(DATA_SHARED_FLAGS_ID); - if (forceGlow) metadata |= 0x40; - - return new ClientboundSetEntityDataPacket( - entity.getEntityId(), - list(new SynchedEntityData.DataValue<>( - 0, - EntityDataSerializers.BYTE, - metadata - )) - ); - } - - @Override - protected Collection createJoinTeamPacket(@NotNull GlowData data) { - return data.lastScoreboardEntry().map(entry -> { - try { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - "magicspells:" + data.color(), - 3, - Optional.empty(), - list(entry) - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }); - } - - @Override - protected Collection createResetTeamPacket(org.bukkit.scoreboard.@NotNull Scoreboard scoreboard, @NotNull GlowData data) { - return data.lastScoreboardEntry().map(entry -> { - try { - Team team = scoreboard.getEntryTeam(entry); - if (team != null) { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - team.getName(), - 3, - Optional.empty(), - list(entry) - ); - } - - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - "magicspells:" + data.color(), - 4, - Optional.empty(), - list(entry) - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }); - } - - @Override - protected void sendPacket(@NotNull Player player, @NotNull Packet packet) { - if (!(packet instanceof ClientboundSetPlayerTeamPacket teamPacket) || teamPacket.getTeamAction() == null) - handled.add(packet); - - ServerGamePacketListenerImpl connection = ((CraftPlayer) player).getHandle().connection; - connection.send(packet); - } - - @Override - protected void registerEvents(Listener listener) { - helper.registerEvents(listener); - } - - @Override - protected void cancelTask(int taskId) { - helper.cancelTask(taskId); - } - - @Override - public int scheduleDelayedTask(Runnable runnable, long delay) { - return helper.scheduleDelayedTask(runnable, delay); - } - - private void addGlowChannelHandler(Player player) { - ChannelPipeline pipeline = ((CraftPlayer) player).getHandle().connection.connection.channel.pipeline(); - pipeline.addBefore("unbundler", "magicspells:glow_channel_handler", new GlowChannelHandler(player)); - } - - private void removeGlowChannelHandler(Player player) { - ChannelPipeline pipeline = ((CraftPlayer) player).getHandle().connection.connection.channel.pipeline(); - - if (pipeline.get("magicspells:glow_channel_handler") != null) - pipeline.remove("magicspells:glow_channel_handler"); - } - - private List list(T element) { - List list = new ArrayList<>(1); - list.add(element); - - return list; - } - - @Override - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - super.onPlayerJoin(event); - addGlowChannelHandler(event.getPlayer()); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - removeGlowChannelHandler(event.getPlayer()); - } - - private class GlowChannelHandler extends ChannelOutboundHandlerAdapter { - - private final Player player; - - private GlowChannelHandler(Player player) { - this.player = player; - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - if (msg instanceof Packet p && handled.contains(p)) { - super.write(ctx, msg, promise); - return; - } - - synchronized (VolatileGlowManager_v26_2.this) { - if (glows.isEmpty() && perPlayerGlows.isEmpty()) { - super.write(ctx, msg, promise); - return; - } - } - - switch (msg) { - case ClientboundSetEntityDataPacket packet -> handleEntityData(packet); - case ClientboundSetPlayerTeamPacket packet -> { - msg = handleTeamPacket(packet); - if (msg == null) return; - } - default -> {} - } - - super.write(ctx, msg, promise); - } - - private void handleEntityData(ClientboundSetEntityDataPacket packet) { - List> packedItems = packet.packedItems(); - if (packedItems.isEmpty()) return; - - SynchedEntityData.DataValue item = packedItems.getFirst(); - if (item.id() != 0) return; - - byte flags = (byte) item.value(); - if ((flags & 0x40) > 0) return; - - UUID uuid; - if (!libsDisguisesLoaded || packet.id() != LibsDisguiseHelper.getSelfDisguiseId()) { - var entity = ((CraftPlayer) player).getHandle().level().moonrise$getEntityLookup().get(packet.id()); - if (entity == null) return; - - uuid = entity.getUUID(); - } else uuid = player.getUniqueId(); - - GlowData data = getGlowData(player.getUniqueId(), uuid); - if (data == null) return; - - flags |= 0x40; - packedItems.set(0, new SynchedEntityData.DataValue<>(0, EntityDataSerializers.BYTE, flags)); - } - - private ClientboundSetPlayerTeamPacket handleTeamPacket(ClientboundSetPlayerTeamPacket packet) { - ClientboundSetPlayerTeamPacket.Action playerAction = packet.getPlayerAction(); - if (playerAction == null || packet.getTeamAction() != null) return packet; - - Collection entries = packet.getPlayers(); - if (entries.isEmpty()) return packet; - - Collection filtered = filterTeamEntries(player, entries); - if (filtered == null) return packet; - if (filtered.isEmpty()) return null; - - try { - return (ClientboundSetPlayerTeamPacket) teamPacketHandle.invoke( - packet.getName(), - playerAction == ClientboundSetPlayerTeamPacket.Action.ADD ? 3 : 4, - packet.getParameters(), - filtered - ); - } catch (Throwable e) { - throw new RuntimeException(e); - } - } - - } - -} diff --git a/settings.gradle.kts b/settings.gradle.kts index 30c6bc5c0..7d86ea860 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -9,8 +9,6 @@ include("towny") include(":nms:shared") include(":nms:latest") -include(":nms:v26_1_2") -include(":nms:v26_2") pluginManagement { repositories { diff --git a/shop/build.gradle b/shop/build.gradle index 1f35827e0..9fb30200e 100644 --- a/shop/build.gradle +++ b/shop/build.gradle @@ -1,6 +1,6 @@ dependencies { compileOnly project(":core") - compileOnly("org.incendo:cloud-paper:2.0.0-beta.16") + compileOnly("org.incendo:cloud-paper:2.0.1") compileOnly("net.milkbowl.vault:VaultAPI:1.7") }