diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 5b08a0950..33c0f8d85 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -55,5 +55,6 @@ jobs: uses: SkriptLang/skript-test-action@v1.1 with: test_script_directory: src/test/scripts - skript_repo_ref: 2.9.5 + skript_repo_ref: 2.10.0-pre1 extra_plugins_directory: extra-plugins/ + run_vanilla_tests: 'false' # temporarily disable diff --git a/README.md b/README.md index 8582f07af..3b80e2e32 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,12 @@ See the [**Wiki**](https://github.com/ShaneBeee/SkBee/wiki) for more detailed in Are you running an **outdated** version of Minecraft and looking for an **outdated** build of SkBee that will work on your **outdated** server? Well look no further, here is a list of **outdated** builds of SkBee for your **outdated** server. Keep in mind, these **outdated** builds for **outdated** servers are not supported and you will not get support/bug fixes, because they're **outdated**! +### Skript 2.9.5 (and below) +Due to changes in Skript 2.10's API, SkBee 3.7.0+ will only work on Skript 2.10+ +If you need SkBee to work on an older version of Skript this is the last version that will work: +[**SkBee 3.6.6**](https://github.com/SkriptHub/SkBee/releases/tag/3.6.6) +(Just like any other **outdated** build, this one is no longer supported) + ### Skript 2.6.4 (and below) Due to changes in Skript 2.7's API, SkBee 3.0.0+ will only work on Skript 2.7+ If you need SkBee to work on an older version of Skript this is the last version that will work: diff --git a/build.gradle b/build.gradle index abf2eeb38..b699fe8e3 100644 --- a/build.gradle +++ b/build.gradle @@ -37,7 +37,7 @@ dependencies { compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") // Skript - compileOnly(group: 'com.github.SkriptLang', name: 'Skript', version: '2.8.7') { + compileOnly(group: 'com.github.SkriptLang', name: 'Skript', version: '2.10.0-pre1') { transitive = false } @@ -54,7 +54,7 @@ dependencies { implementation("fr.mrmicky:fastboard:2.1.3") // Virtual Furnace - implementation("com.github.ShaneBeeStudios:VirtualFurnace:1.0.0") { + implementation("com.github.ShaneBeeStudios:VirtualFurnace:1.1.1") { transitive = false } diff --git a/src/main/java/com/shanebeestudios/skbee/AddonLoader.java b/src/main/java/com/shanebeestudios/skbee/AddonLoader.java index 9ee3211b0..5f20ee6be 100644 --- a/src/main/java/com/shanebeestudios/skbee/AddonLoader.java +++ b/src/main/java/com/shanebeestudios/skbee/AddonLoader.java @@ -4,7 +4,6 @@ import ch.njol.skript.SkriptAddon; import ch.njol.skript.localization.Noun; import ch.njol.skript.registrations.Classes; -import ch.njol.skript.test.runner.TestMode; import ch.njol.skript.util.Version; import com.shanebeestudios.skbee.api.listener.EntityListener; import com.shanebeestudios.skbee.api.listener.NBTListener; @@ -62,9 +61,9 @@ boolean canLoadPlugin() { return false; } Version skriptVersion = Skript.getVersion(); - if (skriptVersion.isSmallerThan(new Version(2, 7))) { + if (skriptVersion.isSmallerThan(new Version(2, 9, 999))) { Util.log("&cDependency Skript outdated, plugin disabling."); - Util.log("&eSkBee requires Skript 2.7+ but found Skript " + skriptVersion); + Util.log("&eSkBee requires Skript 2.10+ but found Skript " + skriptVersion); return false; } if (!Skript.isAcceptRegistrations()) { @@ -323,8 +322,7 @@ private void loadStructureElements() { } private void loadVirtualFurnaceElements() { - // Force load if running tests as this is defaulted to false in the config - if (!this.config.ELEMENTS_VIRTUAL_FURNACE && !TestMode.ENABLED) { + if (!this.config.ELEMENTS_VIRTUAL_FURNACE) { Util.logLoading("&5Virtual Furnace Elements &cdisabled via config"); return; } @@ -501,6 +499,10 @@ private void loadParticleElements() { } private void loadTagElements() { + if (Util.IS_RUNNING_SKRIPT_2_10) { + Util.logLoading("&5Minecraft Tag elements &cdisabled &r(&7now in Skript&r)"); + return; + } if (!this.config.ELEMENTS_MINECRAFT_TAG) { Util.logLoading("&5Minecraft Tag elements &cdisabled via config"); return; diff --git a/src/main/java/com/shanebeestudios/skbee/api/generator/BiomeGenerator.java b/src/main/java/com/shanebeestudios/skbee/api/generator/BiomeGenerator.java index bc7231cac..59f515baf 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/generator/BiomeGenerator.java +++ b/src/main/java/com/shanebeestudios/skbee/api/generator/BiomeGenerator.java @@ -3,6 +3,7 @@ import ch.njol.skript.lang.Trigger; import com.shanebeestudios.skbee.api.generator.event.BiomeGenEvent; import org.bukkit.Location; +import org.bukkit.Registry; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BiomeProvider; @@ -30,10 +31,11 @@ public void setTrigger(Trigger trigger) { return biomeGenEvent.getBiome(); } + @SuppressWarnings({"deprecation", "UnstableApiUsage", "removal"}) @Override public @NotNull List getBiomes(@NotNull WorldInfo worldInfo) { List biomes = new ArrayList<>(); - for (Biome biome : Biome.values()) { + for (Biome biome : Registry.BIOME) { if (biome != Biome.CUSTOM) biomes.add(biome); } return biomes; diff --git a/src/main/java/com/shanebeestudios/skbee/api/listener/ScriptListener.java b/src/main/java/com/shanebeestudios/skbee/api/listener/ScriptListener.java index 48227e91e..287a67a53 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/listener/ScriptListener.java +++ b/src/main/java/com/shanebeestudios/skbee/api/listener/ScriptListener.java @@ -49,7 +49,7 @@ private void processCommand(Cancellable event, CommandSender sender, String comm static { } - @SuppressWarnings("UnstableApiUsage") + @SuppressWarnings({"UnstableApiUsage", "removal"}) @EventHandler private void onLoadScript(PreScriptLoadEvent event) { List scriptsToRemove = new ArrayList<>(); diff --git a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomBlock.java b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomBlock.java index cca2be9a8..3c2552318 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomBlock.java +++ b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomBlock.java @@ -17,6 +17,7 @@ public class NBTCustomBlock extends NBTContainer { private final NBTCompound chunkData; private final boolean canSave; + @SuppressWarnings("deprecation") public NBTCustomBlock(Block block) { this.block = block; this.blockTag = String.format("%s_%s_%s", block.getX(), block.getY(), block.getZ()); @@ -51,6 +52,7 @@ protected void saveCompound() { blockCompound.mergeCompound(this); } + @SuppressWarnings("deprecation") @Override public String toString() { NBTContainer tag = new NBTContainer(); diff --git a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomItemStack.java b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomItemStack.java index 44d222604..e210cf304 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomItemStack.java +++ b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomItemStack.java @@ -18,7 +18,7 @@ public class NBTCustomItemStack extends NBTContainer { private final boolean isFull; public NBTCustomItemStack(ItemStack itemStack, boolean isCustomData, boolean isVanilla, boolean isFull) { - super(getInitialContainer(itemStack, isCustomData, isVanilla, isFull).toString()); + super(getInitialContainer(itemStack, isCustomData, isVanilla, isFull).getCompound()); this.originalItemStack = itemStack; this.isCustomData = isCustomData; this.isFull = isFull; @@ -32,7 +32,10 @@ private static NBTCompound getInitialContainer(ItemStack itemStack, boolean isCu nbtContainer = NBTItem.convertItemtoNBT(itemStack); } if (nbtContainer == null) nbtContainer = new NBTContainer(); - return getContainer(nbtContainer, isCustomData, isFull); + // Create a clone (Minecraft seems to freak out without doing this) + NBTCompound clone = new NBTContainer(); + clone.mergeCompound(getContainer(nbtContainer, isCustomData, isFull)); + return clone; } private static NBTCompound getContainer(NBTCompound itemContainer, boolean isCustomData, boolean isFull) { diff --git a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomOfflinePlayer.java b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomOfflinePlayer.java index 9116622d9..0e15a14a1 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomOfflinePlayer.java +++ b/src/main/java/com/shanebeestudios/skbee/api/nbt/NBTCustomOfflinePlayer.java @@ -18,10 +18,11 @@ public class NBTCustomOfflinePlayer extends NBTFile implements NBTCustom { private static final String PLAYER_FOLDER; static { - String worldFolder = Bukkit.getWorlds().get(0).getWorldFolder().getPath(); + String worldFolder = Bukkit.getWorlds().getFirst().getWorldFolder().getPath(); PLAYER_FOLDER = worldFolder + "/playerdata/"; } + @SuppressWarnings("deprecation") public NBTCustomOfflinePlayer(OfflinePlayer offlinePlayer) throws IOException { super(new File(PLAYER_FOLDER + offlinePlayer.getUniqueId() + ".dat")); } @@ -88,6 +89,7 @@ public String toString() { return getCopy().toString(); } + @SuppressWarnings("deprecation") @Override public @NotNull NBTCompound getCopy() { try { diff --git a/src/main/java/com/shanebeestudios/skbee/api/recipe/RecipeUtil.java b/src/main/java/com/shanebeestudios/skbee/api/recipe/RecipeUtil.java index 8a35736cb..f7b702739 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/recipe/RecipeUtil.java +++ b/src/main/java/com/shanebeestudios/skbee/api/recipe/RecipeUtil.java @@ -113,7 +113,7 @@ public static void logCookingRecipe(CookingRecipe recipe) { if (HAS_CATEGORY) { log(" - &7Category: &r\"&6%s&r\"", recipe.getCategory()); } - log(" - &7CookTime: &b%s", Timespan.fromTicks(recipe.getCookingTime())); + log(" - &7CookTime: &b%s", new Timespan(Timespan.TimePeriod.TICK, recipe.getCookingTime())); log(" - &7Experience: &b%s", recipe.getExperience()); log(" - &7Ingredients: %s", getFancy(recipe.getInputChoice())); } diff --git a/src/main/java/com/shanebeestudios/skbee/api/reflection/ChatReflection.java b/src/main/java/com/shanebeestudios/skbee/api/reflection/ChatReflection.java index 783b3a452..ebe0167e9 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/reflection/ChatReflection.java +++ b/src/main/java/com/shanebeestudios/skbee/api/reflection/ChatReflection.java @@ -50,6 +50,7 @@ public class ChatReflection { * (usually spaces) * @return Pretty string of NBTCompound */ + @SuppressWarnings("deprecation") public static @Nullable String getPrettyNBT(NBTCompound compound, String split) { Object nmsNBT = new NBTContainer(compound.toString()).getCompound(); String s = split != null ? split : ""; diff --git a/src/main/java/com/shanebeestudios/skbee/api/util/ObjectConverter.java b/src/main/java/com/shanebeestudios/skbee/api/util/ObjectConverter.java index 38ad5f4d9..e72038a8f 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/util/ObjectConverter.java +++ b/src/main/java/com/shanebeestudios/skbee/api/util/ObjectConverter.java @@ -88,7 +88,12 @@ public static String getAllNames() { } static { - register(Advancement.class, Registry.ADVANCEMENT); + register(Advancement.class, new ObjectConverter<>() { + @Override + public @Nullable Advancement get(NamespacedKey key) { + return Bukkit.getAdvancement(key); + } + }); register(Attribute.class, Registry.ATTRIBUTE); register(Biome.class, Registry.BIOME); if (Skript.classExists("org.bukkit.damage.DamageType")) { diff --git a/src/main/java/com/shanebeestudios/skbee/api/util/Util.java b/src/main/java/com/shanebeestudios/skbee/api/util/Util.java index 721a5a7bc..5abc1fd6c 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/util/Util.java +++ b/src/main/java/com/shanebeestudios/skbee/api/util/Util.java @@ -33,6 +33,7 @@ public class Util { // Shortcut for finding stuff to remove later public static final boolean IS_RUNNING_SKRIPT_2_9 = Skript.getVersion().isLargerThan(new Version(2, 8, 999)); + public static final boolean IS_RUNNING_SKRIPT_2_10 = Skript.getVersion().isLargerThan(new Version(2, 9, 999)); public static final boolean IS_RUNNING_MC_1_21 = Skript.isRunningMinecraft(1, 21); @SuppressWarnings("deprecation") // Paper deprecation diff --git a/src/main/java/com/shanebeestudios/skbee/api/wrapper/ComponentWrapper.java b/src/main/java/com/shanebeestudios/skbee/api/wrapper/ComponentWrapper.java index a9a6c6dce..72148a547 100644 --- a/src/main/java/com/shanebeestudios/skbee/api/wrapper/ComponentWrapper.java +++ b/src/main/java/com/shanebeestudios/skbee/api/wrapper/ComponentWrapper.java @@ -14,6 +14,7 @@ import net.kyori.adventure.key.Key; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.format.TextColor; @@ -156,7 +157,7 @@ public static ComponentWrapper fromTranslate(String translate) { * @param objects Objects to add into translation * @return Component from translation */ - public static ComponentWrapper fromTranslate(String translate, Object... objects) { + public static ComponentWrapper fromTranslate(String translate, @Nullable String fallback, Object... objects) { List comps = new ArrayList<>(); for (Object object : objects) { if (object instanceof ComponentWrapper component) { @@ -174,7 +175,7 @@ public static ComponentWrapper fromTranslate(String translate, Object... objects comps.add(Component.text(objectString)); } } - return new ComponentWrapper(Component.translatable(translate, comps)); + return new ComponentWrapper(Component.translatable(translate, fallback, comps)); } /** @@ -196,7 +197,7 @@ private static Component getItem(Object object) { itemStack = is; } else if (object instanceof ItemType itemType) { itemStack = itemType.getRandom(); - material = itemStack.getType(); + if (itemStack != null) material = itemStack.getType(); } else if (object instanceof Slot slot) { itemStack = slot.getItem(); } @@ -354,7 +355,7 @@ public Color getColor() { if (skriptColor != null) { return skriptColor; } - return new ColorRGB(textColor.red(), textColor.green(), textColor.blue()); + return ColorRGB.fromRGB(textColor.red(), textColor.green(), textColor.blue()); } public void setBold(boolean bold) { @@ -411,6 +412,19 @@ public String getFont() { } } + public void setFallback(String fallback) { + if (this.component instanceof TranslatableComponent translatable) { + this.component = translatable.fallback(fallback); + } + } + + public String getFallback() { + if (this.component instanceof TranslatableComponent translatable) { + return translatable.fallback(); + } + return null; + } + public void setInsertion(String insertion) { this.component = this.component.insertion(insertion); } @@ -542,6 +556,7 @@ public void setEntityName(Entity entity, boolean alwaysVisible) { * * @param inventory Inventory to change name */ + @SuppressWarnings("deprecation") public void setInventoryName(Inventory inventory) { List viewers = inventory.getViewers(); if (viewers.isEmpty()) return; diff --git a/src/main/java/com/shanebeestudios/skbee/config/Config.java b/src/main/java/com/shanebeestudios/skbee/config/Config.java index ac05bf79b..31e439ed1 100644 --- a/src/main/java/com/shanebeestudios/skbee/config/Config.java +++ b/src/main/java/com/shanebeestudios/skbee/config/Config.java @@ -1,5 +1,6 @@ package com.shanebeestudios.skbee.config; +import ch.njol.skript.test.runner.TestMode; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import com.shanebeestudios.skbee.SkBee; @@ -115,6 +116,7 @@ private boolean getSetting(String setting) { } private boolean getElement(String element) { + if (TestMode.ENABLED) return true; return this.config.getBoolean("elements." + element); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/advancement/event/SimpleEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/advancement/event/SimpleEvents.java index 56f5e5da6..a97dbc3e3 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/advancement/event/SimpleEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/advancement/event/SimpleEvents.java @@ -3,10 +3,8 @@ import ch.njol.skript.Skript; import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.advancement.Advancement; import org.bukkit.event.player.PlayerAdvancementDoneEvent; -import org.jetbrains.annotations.Nullable; @SuppressWarnings("unused") public class SimpleEvents extends SimpleEvent { @@ -14,24 +12,13 @@ public class SimpleEvents extends SimpleEvent { static { // Player Advancement Event Skript.registerEvent("Player Advancement", SimpleEvents.class, PlayerAdvancementDoneEvent.class, - "[player] advancement done") - .description("Called when a player has completed all criteria in an advancement.") - .examples("") - .since("1.17.0"); + "[player] advancement done") + .description("Called when a player has completed all criteria in an advancement.") + .examples("") + .since("1.17.0"); - EventValues.registerEventValue(PlayerAdvancementDoneEvent.class, String.class, new Getter<>() { - @Override - public @Nullable String get(PlayerAdvancementDoneEvent event) { - return event.getAdvancement().getKey().toString(); - } - }, 0); - - EventValues.registerEventValue(PlayerAdvancementDoneEvent.class, Advancement.class, new Getter<>() { - @Override - public @Nullable Advancement get(PlayerAdvancementDoneEvent event) { - return event.getAdvancement(); - } - }, 0); + EventValues.registerEventValue(PlayerAdvancementDoneEvent.class, String.class, event -> event.getAdvancement().getKey().toString(), EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerAdvancementDoneEvent.class, Advancement.class, PlayerAdvancementDoneEvent::getAdvancement, EventValues.TIME_NOW); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/bound/events/BoundEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/bound/events/BoundEvents.java index 63c9fad53..66e6d76e6 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/bound/events/BoundEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/bound/events/BoundEvents.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import com.shanebeestudios.skbee.SkBee; import com.shanebeestudios.skbee.api.bound.Bound; import com.shanebeestudios.skbee.api.event.bound.BoundEnterEvent; @@ -24,21 +23,6 @@ public class BoundEvents extends SkriptEvent { private static BoundBorderListener boundBorderListener; static { - - EventValues.registerEventValue(BoundEvent.class, Bound.class, new Getter<>() { - @Override - public @Nullable Bound get(BoundEvent event) { - return event.getBound(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(BoundEvent.class, String.class, new Getter<>() { - @Override - public @Nullable String get(BoundEvent event) { - return event.getBound().getId(); - } - }, EventValues.TIME_NOW); - Skript.registerEvent("Bound - Enter", BoundEvents.class, BoundEnterEvent.class, "(bound enter|enter bound) [with id %-string%]") .description("Called when a player enters a bound. Optional ID of bound. 'event-string' = bound ID.", "NOTE: Due to breaking changes in Bukkit API, enter/exit events will not be called when a player mounts/dismounts an entity if running SkBee 3.5.0+ on MC 1.20.4 and below.") @@ -49,13 +33,6 @@ public class BoundEvents extends SkriptEvent { "\tcancel event") .since("1.0.0, 1.12.2 (Bound IDs)"); - EventValues.registerEventValue(BoundEnterEvent.class, Player.class, new Getter<>() { - @Override - public Player get(BoundEnterEvent event) { - return event.getPlayer(); - } - }, 0); - Skript.registerEvent("Bound - Exit", BoundEvents.class, BoundExitEvent.class, "(bound exit|exit bound) [with id %-string%]") .description("Called when a player exits a bound. Optional ID of bound. 'event-string' = bound ID.", "NOTE: Due to breaking changes in Bukkit API, enter/exit events will not be called when a player mounts/dismounts an entity if running SkBee 3.5.0+ on MC 1.20.4 and below.") @@ -67,18 +44,15 @@ public Player get(BoundEnterEvent event) { "\tcancel event") .since("1.0.0, 1.12.2 (Bound IDs)"); - EventValues.registerEventValue(BoundExitEvent.class, Player.class, new Getter<>() { - @Override - public Player get(BoundExitEvent event) { - return event.getPlayer(); - } - }, 0); - + EventValues.registerEventValue(BoundEvent.class, Bound.class, BoundEvent::getBound, EventValues.TIME_NOW); + EventValues.registerEventValue(BoundEvent.class, String.class, event -> event.getBound().getId(), EventValues.TIME_NOW); + EventValues.registerEventValue(BoundEnterEvent.class, Player.class, BoundEnterEvent::getPlayer, 0); + EventValues.registerEventValue(BoundExitEvent.class, Player.class, BoundExitEvent::getPlayer, 0); } private Literal boundID; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult) { boundID = (Literal) args[0]; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/bound/expressions/ExprBoundCoords.java b/src/main/java/com/shanebeestudios/skbee/elements/bound/expressions/ExprBoundCoords.java index bca5d56c0..f339400e0 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/bound/expressions/ExprBoundCoords.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/bound/expressions/ExprBoundCoords.java @@ -9,8 +9,7 @@ import ch.njol.skript.expressions.base.PropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; -import ch.njol.skript.lang.SkriptParser; -import ch.njol.skript.util.Getter; +import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import com.shanebeestudios.skbee.SkBee; @@ -42,9 +41,9 @@ public class ExprBoundCoords extends PropertyExpression { private boolean LESSER; private int parse; - @SuppressWarnings({"unchecked", "null", "NullableProblems"}) + @SuppressWarnings("unchecked") @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean kleenean, SkriptParser.ParseResult parseResult) { + public boolean init(Expression[] exprs, int matchedPattern, Kleenean kleenean, ParseResult parseResult) { setExpr((Expression) exprs[0]); this.WORLD = matchedPattern == 2; this.LESSER = matchedPattern == 0; @@ -52,21 +51,17 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean kleenean return true; } - @SuppressWarnings("NullableProblems") @Override protected Object[] get(Event event, Bound[] bounds) { - return get(bounds, new Getter<>() { - @Override - public Object get(Bound bound) { - if (WORLD) { - return bound.getWorld(); - } else { - return switch (parse) { - case 0 -> LESSER ? bound.getLesserX() : bound.getGreaterX(); - case 1 -> LESSER ? bound.getLesserY() : bound.getGreaterY(); - default -> LESSER ? bound.getLesserZ() : bound.getGreaterZ(); - }; - } + return get(bounds, bound -> { + if (WORLD) { + return bound.getWorld(); + } else { + return switch (parse) { + case 0 -> LESSER ? bound.getLesserX() : bound.getGreaterX(); + case 1 -> LESSER ? bound.getLesserY() : bound.getGreaterY(); + default -> LESSER ? bound.getLesserZ() : bound.getGreaterZ(); + }; } }); } @@ -80,7 +75,6 @@ public Object get(Bound bound) { } } - @SuppressWarnings("NullableProblems") @Override public Class[] acceptChange(ChangeMode mode) { if (!WORLD && (mode == ChangeMode.SET || mode == ChangeMode.ADD || mode == ChangeMode.REMOVE)) { @@ -89,7 +83,6 @@ public Class[] acceptChange(ChangeMode mode) { return null; } - @SuppressWarnings("NullableProblems") @Override public void change(Event e, Object[] delta, ChangeMode mode) { BoundConfig boundConfig = SkBee.getPlugin().getBoundConfig(); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/fishing/conditions/CondFishHookInOpenWater.java b/src/main/java/com/shanebeestudios/skbee/elements/fishing/conditions/CondFishHookInOpenWater.java index b92701da7..5b1bf7026 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/fishing/conditions/CondFishHookInOpenWater.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/fishing/conditions/CondFishHookInOpenWater.java @@ -5,20 +5,24 @@ import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.Entity; import org.bukkit.entity.FishHook; import org.jetbrains.annotations.NotNull; @Name("Fish Hook - In Open Water") @Description({"Check if the fish hook is in open water.", - "Open water is defined by a 5x4x5 area of water, air and lily pads.", - "If in open water, treasure items may be caught."}) + "Open water is defined by a 5x4x5 area of water, air and lily pads.", + "If in open water, treasure items may be caught.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples("if fish hook is in open water:") @Since("2.8.0") public class CondFishHookInOpenWater extends PropertyCondition { static { - register(CondFishHookInOpenWater.class, "in open water", "entities"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(CondFishHookInOpenWater.class, "in open water", "entities"); + } } @Override diff --git a/src/main/java/com/shanebeestudios/skbee/elements/fishing/expressions/ExprFishHookWaitTime.java b/src/main/java/com/shanebeestudios/skbee/elements/fishing/expressions/ExprFishHookWaitTime.java index 853f56196..4408afae3 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/fishing/expressions/ExprFishHookWaitTime.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/fishing/expressions/ExprFishHookWaitTime.java @@ -19,13 +19,13 @@ @Name("Fish Hook - Wait time") @Description({"Represents the min/max wait time for a fish hook to catch a fish.", - "\nNOTE: this is before applying lure.", - "\nNOTE: min wait time must be less than max wait time. Both must be greater than 0.", - "\nDefaults: min = 100 ticks (5 seconds), max = 600 ticks (30 seconds)."}) + "\nNOTE: this is before applying lure.", + "\nNOTE: min wait time must be less than max wait time. Both must be greater than 0.", + "\nDefaults: min = 100 ticks (5 seconds), max = 600 ticks (30 seconds)."}) @Examples({"on fish:", - "\tif fish state = fishing:", - "\t\tset min wait time of fish hook to 1 second", - "\t\tset max wait time of fish hook to 2 seconds"}) + "\tif fish state = fishing:", + "\t\tset min wait time of fish hook to 1 second", + "\t\tset max wait time of fish hook to 2 seconds"}) @Since("2.8.0") public class ExprFishHookWaitTime extends SimplePropertyExpression { @@ -35,7 +35,7 @@ public class ExprFishHookWaitTime extends SimplePropertyExpression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { setExpr((Expression) exprs[0]); @@ -47,12 +47,11 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye public @Nullable Timespan convert(Entity entity) { if (entity instanceof FishHook fishHook) { int wait = this.max ? fishHook.getMaxWaitTime() : fishHook.getMinWaitTime(); - return Timespan.fromTicks(wait); + return new Timespan(Timespan.TimePeriod.TICK, wait); } return null; } - @SuppressWarnings("NullableProblems") @Override public @Nullable Class[] acceptChange(ChangeMode mode) { return switch (mode) { @@ -61,10 +60,9 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye }; } - @SuppressWarnings({"NullableProblems", "ConstantValue"}) @Override public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { - int changeValue = delta != null && delta[0] != null ? (int) ((Timespan) delta[0]).getTicks() : 0; + int changeValue = delta != null && delta[0] != null ? (int) ((Timespan) delta[0]).getAs(Timespan.TimePeriod.TICK) : 0; for (Entity entity : getExpr().getArray(event)) { if (entity instanceof FishHook fishHook) { int value = this.max ? fishHook.getMaxWaitTime() : fishHook.getMinWaitTime(); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/gameevent/events/EvtGameEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/gameevent/events/EvtGameEvents.java index abd2d5bea..646286c37 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/gameevent/events/EvtGameEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/gameevent/events/EvtGameEvents.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.GameEvent; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -15,90 +14,59 @@ import org.bukkit.event.world.GenericGameEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.skriptlang.skript.lang.converter.Converter; @SuppressWarnings("unused") public class EvtGameEvents extends SkriptEvent { static { Skript.registerEvent("Generic Game Event", EvtGameEvents.class, GenericGameEvent.class, - "[generic] game[ ]event [%-gameevent%]") - .description("Called when a Minecraft game event is fired. These events are provided directly by Minecraft.", - "NOTE: Cancelling this event will not cancel the action, only cancel broadcasting event to blocks.", - "Requires MC 1.17+") - .examples("on game event splash:", - "\tset {_e} to event-entity", - "\tif {_e} is a player:", - "\t\tpush {_e} up with speed 0.5") - .since("1.14.0"); + "[generic] game[ ]event [%-gameevent%]") + .description("Called when a Minecraft game event is fired. These events are provided directly by Minecraft.", + "NOTE: Cancelling this event will not cancel the action, only cancel broadcasting event to blocks.", + "Requires MC 1.17+") + .examples("on game event splash:", + "\tset {_e} to event-entity", + "\tif {_e} is a player:", + "\t\tpush {_e} up with speed 0.5") + .since("1.14.0"); Skript.registerEvent("Block Receive Game Event", EvtGameEvents.class, BlockReceiveGameEvent.class, - "block receive game[ ]event [%-gameevent%]") - .description("Called when a block receives a Minecraft game event.", - "As of now the only block that receives game events are sculk shrieker, sculk sensor, and calibrated sculk sensor.", - "Requires MC 1.17+") - .examples("on block receive game event:", - "\tset {_e} to event-entity", - "\tif {_e} is a player:", - "\t\tif event-block is set:", - "\t\t\tdamage {_e} by 0.5") - .since("1.14.0"); + "block receive game[ ]event [%-gameevent%]") + .description("Called when a block receives a Minecraft game event.", + "As of now the only block that receives game events are sculk shrieker, sculk sensor, and calibrated sculk sensor.", + "Requires MC 1.17+") + .examples("on block receive game event:", + "\tset {_e} to event-entity", + "\tif {_e} is a player:", + "\t\tif event-block is set:", + "\t\t\tdamage {_e} by 0.5") + .since("1.14.0"); - EventValues.registerEventValue(GenericGameEvent.class, Entity.class, new Getter<>() { + EventValues.registerEventValue(GenericGameEvent.class, Entity.class, new Converter<>() { @Nullable @Override - public Entity get(GenericGameEvent event) { + public Entity convert(GenericGameEvent event) { return event.getEntity(); } - }, 0); + }, EventValues.TIME_NOW); - EventValues.registerEventValue(GenericGameEvent.class, GameEvent.class, new Getter<>() { - @Override - public GameEvent get(GenericGameEvent event) { - return event.getEvent(); - } - }, 0); - - EventValues.registerEventValue(GenericGameEvent.class, Location.class, new Getter<>() { - @Override - public Location get(GenericGameEvent event) { - return event.getLocation(); - } - }, 0); - - EventValues.registerEventValue(GenericGameEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(GenericGameEvent event) { - if (event.getEntity() instanceof Player player) return player; - return null; - } - }, 0); - - EventValues.registerEventValue(BlockReceiveGameEvent.class, Entity.class, new Getter<>() { - @Nullable - @Override - public Entity get(BlockReceiveGameEvent event) { - return event.getEntity(); - } - }, 0); - - EventValues.registerEventValue(BlockReceiveGameEvent.class, GameEvent.class, new Getter<>() { - @Override - public GameEvent get(BlockReceiveGameEvent event) { - return event.getEvent(); - } - }, 0); - - EventValues.registerEventValue(BlockReceiveGameEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(BlockReceiveGameEvent event) { - if (event.getEntity() instanceof Player player) return player; - return null; - } - }, 0); + EventValues.registerEventValue(GenericGameEvent.class, GameEvent.class, GenericGameEvent::getEvent, EventValues.TIME_NOW); + EventValues.registerEventValue(GenericGameEvent.class, Location.class, GenericGameEvent::getLocation, EventValues.TIME_NOW); + EventValues.registerEventValue(GenericGameEvent.class, Player.class, event -> { + if (event.getEntity() instanceof Player player) return player; + return null; + }, EventValues.TIME_NOW); + EventValues.registerEventValue(BlockReceiveGameEvent.class, Entity.class, BlockReceiveGameEvent::getEntity, EventValues.TIME_NOW); + EventValues.registerEventValue(BlockReceiveGameEvent.class, GameEvent.class, BlockReceiveGameEvent::getEvent, EventValues.TIME_NOW); + EventValues.registerEventValue(BlockReceiveGameEvent.class, Player.class, event -> { + if (event.getEntity() instanceof Player player) return player; + return null; + }, EventValues.TIME_NOW); } private Literal gameEvents; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult) { if (args[0] != null) { @@ -107,7 +75,6 @@ public boolean init(Literal[] args, int matchedPattern, ParseResult parseResu return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (event instanceof GenericGameEvent) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/generator/structure/StrucChunkGen.java b/src/main/java/com/shanebeestudios/skbee/elements/generator/structure/StrucChunkGen.java index 84688b983..c47e99900 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/generator/structure/StrucChunkGen.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/generator/structure/StrucChunkGen.java @@ -29,76 +29,76 @@ @Name("ChunkGenerator - Register Generator") @Description({"Register a chunk generator to manipulate the world layout to your liking.", - "ENTRIES:", - "(These are all optional, and will default to false)", - "`vanilla decor` = Whether Minecraft will decorate the surface based on biomes.", - "`vanilla caves` = Whether Minecraft will carve caves.", - "`vanilla structures` = Whether Minecraft will generate structures based on biomes.", - "`vanilla mobs` = Whether Minecraft will spawn mobs based on biomes.", - "SECTIONS:", - "(These are all optional, but some do rely on others. `height gen` and `block pop` require `chunk gen`)", - "`biome gen` = Generate the biomes to be placed in the world.", - "`chunk gen` = Generate your surface layer of your world.", - "`height gen` = Tell Minecraft where the highest block in a chunk is for generating structures.", - "`block pop` = Used to decorate after initial surface is generated (Structures can be placed during this stage).", - "NOTES:", - "- `world-creator` needs to be enabled in the config", - "- Please see the [**Chunk Generator**](https://github.com/ShaneBeee/SkBee/wiki/Chunk-Generator) wiki for further details."}) + "ENTRIES:", + "(These are all optional, and will default to false)", + "`vanilla decor` = Whether Minecraft will decorate the surface based on biomes.", + "`vanilla caves` = Whether Minecraft will carve caves.", + "`vanilla structures` = Whether Minecraft will generate structures based on biomes.", + "`vanilla mobs` = Whether Minecraft will spawn mobs based on biomes.", + "SECTIONS:", + "(These are all optional, but some do rely on others. `height gen` and `block pop` require `chunk gen`)", + "`biome gen` = Generate the biomes to be placed in the world.", + "`chunk gen` = Generate your surface layer of your world.", + "`height gen` = Tell Minecraft where the highest block in a chunk is for generating structures.", + "`block pop` = Used to decorate after initial surface is generated (Structures can be placed during this stage).", + "NOTES:", + "- `world-creator` needs to be enabled in the config", + "- Please see the [**Chunk Generator**](https://github.com/ShaneBeee/SkBee/wiki/Chunk-Generator) wiki for further details."}) @Examples({"register chunk generator with id \"mars\":", - "\tvanilla decor: false", - "\tvanilla caves: false", - "\tvanilla structures: false", - "\tvanilla mobs: false", - "\tchunk gen:", - "\t\tloop 16 times:", - "\t\t\tloop 16 times:", - "\t\t\t\tset {_x} to (loop-number-1) - 1", - "\t\t\t\tset {_z} to (loop-number-2) - 1", - "", - "\t\t\t\t# This is just an expression I created with reflect to give you an idea how it can work", - "\t\t\t\tset {_y} to biome noise at vector({_x} + (chunkdata chunk x * 16), 1, {_z} + (chunkdata chunk z * 16))", - "\t\t\t\t# Fill blocks from 0 to y level with concrete", - "\t\t\t\tset chunkdata blocks within vector({_x}, 0, {_z}) and vector({_x}, {_y}, {_z}) to red_concrete[]", - "\t\t\t\t# Set the surface layer to concrete powder", - "\t\t\t\tset chunkdata block at vector({_x}, {_y}, {_z}) to red_concrete_powder[]", - "", - "\tbiome gen:", - "\t\t# Set our biome to something mars like", - "\t\tset chunkdata biome to crimson forest"}) + "\tvanilla decor: false", + "\tvanilla caves: false", + "\tvanilla structures: false", + "\tvanilla mobs: false", + "\tchunk gen:", + "\t\tloop 16 times:", + "\t\t\tloop 16 times:", + "\t\t\t\tset {_x} to (loop-number-1) - 1", + "\t\t\t\tset {_z} to (loop-number-2) - 1", + "", + "\t\t\t\t# This is just an expression I created with reflect to give you an idea how it can work", + "\t\t\t\tset {_y} to biome noise at vector({_x} + (chunkdata chunk x * 16), 1, {_z} + (chunkdata chunk z * 16))", + "\t\t\t\t# Fill blocks from 0 to y level with concrete", + "\t\t\t\tset chunkdata blocks within vector({_x}, 0, {_z}) and vector({_x}, {_y}, {_z}) to red_concrete[]", + "\t\t\t\t# Set the surface layer to concrete powder", + "\t\t\t\tset chunkdata block at vector({_x}, {_y}, {_z}) to red_concrete_powder[]", + "", + "\tbiome gen:", + "\t\t# Set our biome to something mars like", + "\t\tset chunkdata biome to crimson forest"}) @Since("3.5.0") public class StrucChunkGen extends Structure { static { EntryValidator validator = EntryValidator.builder() - .addEntryData(new LiteralEntryData<>("vanilla decor", false, true, Boolean.class)) - .addEntryData(new LiteralEntryData<>("vanilla caves", false, true, Boolean.class)) - .addEntryData(new LiteralEntryData<>("vanilla structures", false, true, Boolean.class)) - .addEntryData(new LiteralEntryData<>("vanilla mobs", false, true, Boolean.class)) - .addSection("chunk gen", true) - .addSection("biome gen", true) - .addSection("height gen", true) - .addSection("block pop", true) - .build(); + .addEntryData(new LiteralEntryData<>("vanilla decor", false, true, Boolean.class)) + .addEntryData(new LiteralEntryData<>("vanilla caves", false, true, Boolean.class)) + .addEntryData(new LiteralEntryData<>("vanilla structures", false, true, Boolean.class)) + .addEntryData(new LiteralEntryData<>("vanilla mobs", false, true, Boolean.class)) + .addSection("chunk gen", true) + .addSection("biome gen", true) + .addSection("height gen", true) + .addSection("block pop", true) + .build(); Skript.registerStructure(StrucChunkGen.class, validator, "register chunk generator with id %string%"); } private Literal id; + private EntryContainer entryContainer; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult, EntryContainer entryContainer) { this.id = (Literal) args[0]; + this.entryContainer = entryContainer; return true; } @Override public boolean load() { - EntryContainer entryContainer = getEntryContainer(); - - SectionNode chunkNode = entryContainer.getOptional("chunk gen", SectionNode.class, false); - SectionNode biomeNode = entryContainer.getOptional("biome gen", SectionNode.class, false); - SectionNode heightNode = entryContainer.getOptional("height gen", SectionNode.class, false); - SectionNode blockNode = entryContainer.getOptional("block pop", SectionNode.class, false); + SectionNode chunkNode = this.entryContainer.getOptional("chunk gen", SectionNode.class, false); + SectionNode biomeNode = this.entryContainer.getOptional("biome gen", SectionNode.class, false); + SectionNode heightNode = this.entryContainer.getOptional("height gen", SectionNode.class, false); + SectionNode blockNode = this.entryContainer.getOptional("block pop", SectionNode.class, false); Script currentScript = getParser().getCurrentScript(); ChunkGen chunkGen = ChunkGenManager.registerOrGetGenerator(this.id.getSingle(), chunkNode != null, biomeNode != null); @@ -106,13 +106,13 @@ public boolean load() { if (chunkNode != null) { ChunkGenerator chunkGenerator = chunkGen.getChunkGenerator(); if (chunkGenerator != null) { - boolean vanillaDecor = Boolean.TRUE.equals(entryContainer.getOptional("vanilla decor", Boolean.class, true)); + boolean vanillaDecor = Boolean.TRUE.equals(this.entryContainer.getOptional("vanilla decor", Boolean.class, true)); chunkGenerator.setVanillaDecor(vanillaDecor); - boolean vanillaCaves = Boolean.TRUE.equals(entryContainer.getOptional("vanilla caves", Boolean.class, true)); + boolean vanillaCaves = Boolean.TRUE.equals(this.entryContainer.getOptional("vanilla caves", Boolean.class, true)); chunkGenerator.setVanillaCaves(vanillaCaves); - boolean vanillaStructures = Boolean.TRUE.equals(entryContainer.getOptional("vanilla structures", Boolean.class, true)); + boolean vanillaStructures = Boolean.TRUE.equals(this.entryContainer.getOptional("vanilla structures", Boolean.class, true)); chunkGenerator.setVanillaStructures(vanillaStructures); - boolean vanillaMobs = Boolean.TRUE.equals(entryContainer.getOptional("vanilla mobs", Boolean.class, true)); + boolean vanillaMobs = Boolean.TRUE.equals(this.entryContainer.getOptional("vanilla mobs", Boolean.class, true)); chunkGenerator.setVanillaMobs(vanillaMobs); getParser().setCurrentEvent("ChunkGenSection", ChunkGenEvent.class); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/generator/type/GenEventValues.java b/src/main/java/com/shanebeestudios/skbee/elements/generator/type/GenEventValues.java index ed238d6f8..fc460c2f7 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/generator/type/GenEventValues.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/generator/type/GenEventValues.java @@ -1,28 +1,15 @@ package com.shanebeestudios.skbee.elements.generator.type; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import com.shanebeestudios.skbee.api.generator.event.BiomeGenEvent; import com.shanebeestudios.skbee.api.generator.event.HeightGenEvent; import org.bukkit.Location; -import org.jetbrains.annotations.Nullable; public class GenEventValues { static { - EventValues.registerEventValue(BiomeGenEvent.class, Location.class, new Getter<>() { - @Override - public Location get(BiomeGenEvent event) { - return event.getLocation(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(HeightGenEvent.class, Location.class, new Getter<>() { - @Override - public @Nullable Location get(HeightGenEvent event) { - return event.getLocation(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(BiomeGenEvent.class, Location.class, BiomeGenEvent::getLocation, EventValues.TIME_NOW); + EventValues.registerEventValue(HeightGenEvent.class, Location.class, HeightGenEvent::getLocation, EventValues.TIME_NOW); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/itemcomponent/sections/SecFoodComponent.java b/src/main/java/com/shanebeestudios/skbee/elements/itemcomponent/sections/SecFoodComponent.java index 4f3b6d2c5..4dd1ace57 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/itemcomponent/sections/SecFoodComponent.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/itemcomponent/sections/SecFoodComponent.java @@ -180,7 +180,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye food.setSaturation(saturation); food.setCanAlwaysEat(canAlwaysEat); if (HAS_EAT_SECONDS && eatTime != null) { - setEatSeconds(food, (float) eatTime.getTicks() / 20); + setEatSeconds(food, (float) eatTime.getAs(Timespan.TimePeriod.TICK) / 20); } if (HAS_CONVERT && usingConvertsTo != null) { setUsingConverts(food, usingConvertsTo); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprBlankNBTCompound.java b/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprBlankNBTCompound.java index b60640e93..e868a90e8 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprBlankNBTCompound.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprBlankNBTCompound.java @@ -19,22 +19,21 @@ @Name("NBT - Empty Compound") @Description("Returns an empty/new NBT compound.") @Examples({"set {_n} to blank nbt compound", - "set tag \"points\" of {_n} to 10"}) + "set tag \"points\" of {_n} to 10"}) @Since("2.8.0") public class ExprBlankNBTCompound extends SimpleExpression { static { Skript.registerExpression(ExprBlankNBTCompound.class, NBTCompound.class, ExpressionType.SIMPLE, - "[a[n]] (blank|empty|new) nbt compound"); + "[a[n]] (blank|empty|new) nbt compound"); } - @SuppressWarnings("NullableProblems") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { return true; } - @SuppressWarnings("NullableProblems") + @SuppressWarnings("deprecation") @Override protected @Nullable NBTCompound[] get(Event event) { return new NBTCompound[]{new NBTContainer()}; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprNbtCompound.java b/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprNbtCompound.java index 7fd971cb1..5d815cb25 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprNbtCompound.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/nbt/expressions/ExprNbtCompound.java @@ -101,6 +101,7 @@ public boolean init(Expression @NotNull [] exprs, int matchedPattern, @NotNul return LiteralUtils.canInitSafely(expr); } + @SuppressWarnings("deprecation") @Override protected NBTCompound @NotNull [] get(@NotNull Event e, Object @NotNull [] source) { return get(source, object -> { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/nbt/types/SkriptTypes.java b/src/main/java/com/shanebeestudios/skbee/elements/nbt/types/SkriptTypes.java index c657bdd6a..25d63c1dc 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/nbt/types/SkriptTypes.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/nbt/types/SkriptTypes.java @@ -18,7 +18,6 @@ import java.io.StreamCorruptedException; -@SuppressWarnings({"unused", "NullableProblems"}) public class SkriptTypes { public static final Changer NBT_COMPOUND_CHANGER = new Changer<>() { @@ -52,105 +51,107 @@ public void change(NBTCompound[] what, @Nullable Object[] delta, ChangeMode mode static { Classes.registerClass(new ClassInfo<>(NBTCustomType.class, "nbttype") - .user("nbt ?types?") - .name("NBT - Tag Type") - .description("Represents a type of NBT tag.", - "You can read more about NBT types:", - "\nMcWiki [**NBT Data Types**](https://minecraft.wiki/w/NBT_format#Data_types)", - "\nSkBee Wiki [**NBT Data Types**](https://github.com/ShaneBeee/SkBee/wiki/NBT-Intro#datatypes-in-nbt)") - .usage(NBTCustomType.getNames()) - .examples("set byte tag \"points\" of {_nbt} to 1", - "set compound tag \"tool\" of {_nbt} to nbt compound of player's tool") - .since("1.10.0") - .parser(new Parser() { - - @Nullable - @Override - public NBTCustomType parse(String s, ParseContext context) { - return NBTCustomType.fromName(s); - } + .user("nbt ?types?") + .name("NBT - Tag Type") + .description("Represents a type of NBT tag.", + "You can read more about NBT types:", + "\nMcWiki [**NBT Data Types**](https://minecraft.wiki/w/NBT_format#Data_types)", + "\nSkBee Wiki [**NBT Data Types**](https://github.com/ShaneBeee/SkBee/wiki/NBT-Intro#datatypes-in-nbt)") + .usage(NBTCustomType.getNames()) + .examples("set byte tag \"points\" of {_nbt} to 1", + "set compound tag \"tool\" of {_nbt} to nbt compound of player's tool") + .since("1.10.0") + .parser(new Parser() { + + @Nullable + @Override + public NBTCustomType parse(String s, ParseContext context) { + return NBTCustomType.fromName(s); + } - @Override - public String toString(NBTCustomType nbtCustomType, int i) { - return nbtCustomType.getName(); - } + @Override + public String toString(NBTCustomType nbtCustomType, int i) { + return nbtCustomType.getName(); + } - @Override - public String toVariableNameString(NBTCustomType nbtCustomType) { - return toString(nbtCustomType, 0); - } + @Override + public String toVariableNameString(NBTCustomType nbtCustomType) { + return toString(nbtCustomType, 0); + } - public String getVariableNamePattern() { - return "\\S"; - } - })); + public String getVariableNamePattern() { + return "\\S"; + } + })); Classes.registerClass(new ClassInfo<>(NBTCompound.class, "nbtcompound") - .user("nbt ?compound") - .name("NBT - Compound") - .description("Represents the NBT compound of an entity/block/item/file/string.", - "NBT compounds can be merged by adding together, see examples.") - .usage("{id:\"minecraft:netherite_axe\",tag:{Damage:0,Enchantments:[{id:\"minecraft:unbreaking\",lvl:2s}]},Count:1b}") - .examples("set {_a} to nbt compound of player", - "set {_nbt} to nbt compound of last spawned entity", - "set {_n} to nbt compound from \"{Invisible:1b}\"", - "add {_n} to nbt of target entity") - .since("1.6.0") - .parser(new Parser<>() { - - @Override - public boolean canParse(@NotNull ParseContext context) { - return false; - } + .user("nbt ?compound") + .name("NBT - Compound") + .description("Represents the NBT compound of an entity/block/item/file/string.", + "NBT compounds can be merged by adding together, see examples.") + .usage("{id:\"minecraft:netherite_axe\",tag:{Damage:0,Enchantments:[{id:\"minecraft:unbreaking\",lvl:2s}]},Count:1b}") + .examples("set {_a} to nbt compound of player", + "set {_nbt} to nbt compound of last spawned entity", + "set {_n} to nbt compound from \"{Invisible:1b}\"", + "add {_n} to nbt of target entity") + .since("1.6.0") + .parser(new Parser<>() { + + @Override + public boolean canParse(@NotNull ParseContext context) { + return false; + } - @Override - public String toString(@NotNull NBTCompound nbt, int flags) { - return getNBTString(nbt); - } + @Override + public String toString(@NotNull NBTCompound nbt, int flags) { + return getNBTString(nbt); + } - @Override - public String toVariableNameString(@NotNull NBTCompound nbt) { - return "nbt:" + toString(nbt, 0); - } - }) - .serializer(new Serializer<>() { - @Override - public @NotNull Fields serialize(@NotNull NBTCompound nbt) { - Fields fields = new Fields(); - fields.putObject("nbt", getNBTString(nbt)); - return fields; - } + @Override + public String toVariableNameString(@NotNull NBTCompound nbt) { + return "nbt:" + toString(nbt, 0); + } + }) + .serializer(new Serializer<>() { + @Override + public @NotNull Fields serialize(@NotNull NBTCompound nbt) { + Fields fields = new Fields(); + fields.putObject("nbt", getNBTString(nbt)); + return fields; + } - @Override - public void deserialize(@NotNull NBTCompound o, @NotNull Fields f) { - assert false; - } + @Override + public void deserialize(@NotNull NBTCompound o, @NotNull Fields f) { + assert false; + } - @Override - protected NBTCompound deserialize(@NotNull Fields fields) throws StreamCorruptedException { - String nbt = fields.getObject("nbt", String.class); - if (nbt == null) { - throw new StreamCorruptedException("NBT string is null"); - } - try { - return new NBTContainer(nbt); - } catch (Exception ex) { - throw new StreamCorruptedException("Invalid nbt data: " + nbt); - } + @SuppressWarnings("deprecation") + @Override + protected NBTCompound deserialize(@NotNull Fields fields) throws StreamCorruptedException { + String nbt = fields.getObject("nbt", String.class); + if (nbt == null) { + throw new StreamCorruptedException("NBT string is null"); } - - @Override - public boolean mustSyncDeserialization() { - return true; + try { + return new NBTContainer(nbt); + } catch (Exception ex) { + throw new StreamCorruptedException("Invalid nbt data: " + nbt); } + } - @Override - protected boolean canBeInstantiated() { - return false; - } - }) - .changer(NBT_COMPOUND_CHANGER)); + @Override + public boolean mustSyncDeserialization() { + return true; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + }) + .changer(NBT_COMPOUND_CHANGER)); } + @SuppressWarnings("deprecation") private static final String NBT_EMPTY = new NBTContainer("{}").toString(); private static String getNBTString(@NotNull NBTCompound nbtCompound) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondBlockCanRandomTick.java b/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondBlockCanRandomTick.java index 55444df65..094a75351 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondBlockCanRandomTick.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondBlockCanRandomTick.java @@ -9,7 +9,6 @@ import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.Material; import org.bukkit.block.Block; @@ -20,17 +19,17 @@ @Name("Block Can Random Tick") @Description({"Gets if this block is ticked randomly in the world. The blocks current state may change this value.", - "Requires Paper 1.19+"}) + "Requires Paper 1.19+"}) @Examples({"on right click:", - "\tif clicked block can random tick:", - "\t\trandom tick clicked block"}) + "\tif clicked block can random tick:", + "\t\trandom tick clicked block"}) @Since("3.0.0") public class CondBlockCanRandomTick extends Condition { static { Skript.registerCondition(CondBlockCanRandomTick.class, - "%blocks/blockdatas/itemtypes% can random[ly] tick", - "%blocks/blockdatas/itemtypes% (can't|cannot) random[ly] tick"); + "%blocks/blockdatas/itemtypes% can random[ly] tick", + "%blocks/blockdatas/itemtypes% (can't|cannot) random[ly] tick"); } private Expression blocks; @@ -49,7 +48,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye @Override public boolean check(@NotNull Event event) { - return this.blocks.check(event, (Checker) object -> { + return this.blocks.check(event, object -> { if (object instanceof Block block) return block.getBlockData().isRandomlyTicked(); else if (object instanceof BlockData blockData) return blockData.isRandomlyTicked(); else if (object instanceof ItemType itemType) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondEntityTicking.java b/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondEntityTicking.java index 9d5fd88fc..5f6a97201 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondEntityTicking.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/conditions/CondEntityTicking.java @@ -9,11 +9,14 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.Entity; import org.jetbrains.annotations.NotNull; @Name("Entity - Is Ticking") -@Description("Check if an entity is currently ticking. If they're in a chunk that is not ticking, this will be false.") +@Description({"Check if an entity is currently ticking.", + "If they're in a chunk that is not ticking, this will be false.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples("loop all entities where [input is ticking]:") @Since("2.6.0") public class CondEntityTicking extends PropertyCondition { @@ -21,7 +24,9 @@ public class CondEntityTicking extends PropertyCondition { private static final boolean TICKING_METHOD_EXISTS = Skript.methodExists(Entity.class, "isTicking"); static { - register(CondEntityTicking.class, "ticking", "entities"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(CondEntityTicking.class, "ticking", "entities"); + } } @SuppressWarnings("NullableProblems") diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffEntityBlockStorage.java b/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffEntityBlockStorage.java index db26f268f..65d6b5695 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffEntityBlockStorage.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffEntityBlockStorage.java @@ -46,7 +46,7 @@ public class EffEntityBlockStorage extends Effect { private Expression var; private boolean release; - @SuppressWarnings({"unchecked", "NullableProblems"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) { this.entities = i == 0 ? null : (Expression) exprs[0]; @@ -57,15 +57,19 @@ public boolean init(Expression[] exprs, int i, Kleenean kleenean, SkriptParse return true; } - @SuppressWarnings({"unchecked", "NullableProblems"}) + @SuppressWarnings("unchecked") @Override protected void execute(Event event) { if (this.release) { if (this.blocks == null) return; - long ticks = this.timespan != null ? this.timespan.getSingle(event).getTicks() : 0; + long ticks = 0; + if (this.timespan != null) { + Timespan timespan = this.timespan.getSingle(event); + if (timespan != null) ticks = timespan.getAs(Timespan.TimePeriod.TICK); + } for (Block block : this.blocks.getArray(event)) { BlockState state = block.getState(); - if (state instanceof EntityBlockStorage) { + if (state instanceof EntityBlockStorage st) { List entities = ((EntityBlockStorage) state).releaseEntities(); for (Entity entity : entities) { if (entity instanceof Bee && ticks > 0) { @@ -94,7 +98,6 @@ protected void execute(Event event) { } } - @SuppressWarnings("NullableProblems") @Override public String toString(Event e, boolean d) { String time = this.timespan != null ? " for " + this.timespan.toString(e, d) : ""; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffOpenRealInventory.java b/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffOpenRealInventory.java index 300df4628..0695072c4 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffOpenRealInventory.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/effects/EffOpenRealInventory.java @@ -65,7 +65,7 @@ enum InventoryViewType { private Expression name; private Expression players; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.viewType = InventoryViewType.values()[matchedPattern]; @@ -79,7 +79,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return true; } - @SuppressWarnings("NullableProblems") + @SuppressWarnings("deprecation") @Override protected void execute(Event event) { Location location = this.location != null ? this.location.getSingle(event) : null; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtDamageByBlock.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtDamageByBlock.java index 7fa293f80..9abdbeda6 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtDamageByBlock.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtDamageByBlock.java @@ -7,7 +7,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; @@ -20,31 +19,26 @@ public class EvtDamageByBlock extends SkriptEvent { static { Skript.registerEvent("Damage By Block", EvtDamageByBlock.class, EntityDamageByBlockEvent.class, - "damag(e|ing) [of %-entitydata%] (by|from) (block|%itemtypes/blockdatas%)") - .description("Called when an entity is damaged by a block.", - "Anything that works in vanilla Skript's damage event (victim/damage cause/damage/final damage)", - "will all work in this event too.", - "\n`victim` = Same as vanilla Skript, `victim` is used to get the damaged entity.", - "\n`event-block` = The block that damaged the entity") - .examples("on damage of player by sweet berry bush:", - "\tcancel event", - "", - "on damage by block:", - "\tbroadcast \"%victim% was damaged by %type of event-block%\"") - .since("3.0.2"); + "damag(e|ing) [of %-entitydata%] (by|from) (block|%itemtypes/blockdatas%)") + .description("Called when an entity is damaged by a block.", + "Anything that works in vanilla Skript's damage event (victim/damage cause/damage/final damage)", + "will all work in this event too.", + "\n`victim` = Same as vanilla Skript, `victim` is used to get the damaged entity.", + "\n`event-block` = The block that damaged the entity") + .examples("on damage of player by sweet berry bush:", + "\tcancel event", + "", + "on damage by block:", + "\tbroadcast \"%victim% was damaged by %type of event-block%\"") + .since("3.0.2"); - EventValues.registerEventValue(EntityDamageByBlockEvent.class, Block.class, new Getter<>() { - @Override - public @Nullable Block get(EntityDamageByBlockEvent event) { - return event.getDamager(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(EntityDamageByBlockEvent.class, Block.class, EntityDamageByBlockEvent::getDamager, EventValues.TIME_NOW); } private Literal> entityType; private Literal blockType; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult) { this.entityType = (Literal>) args[0]; @@ -52,7 +46,6 @@ public boolean init(Literal[] args, int matchedPattern, ParseResult parseResu return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (event instanceof EntityDamageByBlockEvent damageEvent) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtEntitiesLoad.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtEntitiesLoad.java index c0c0d2c7f..2327a4aa4 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtEntitiesLoad.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtEntitiesLoad.java @@ -5,14 +5,12 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import ch.njol.util.coll.CollectionUtils; import org.bukkit.entity.Entity; import org.bukkit.event.Event; import org.bukkit.event.world.EntitiesLoadEvent; import org.bukkit.event.world.EntitiesUnloadEvent; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class EvtEntitiesLoad extends SkriptEvent { static { @@ -29,19 +27,8 @@ public class EvtEntitiesLoad extends SkriptEvent { "\t\tbroadcast \"REMOVED ENTITIES!\"") .since("3.5.0"); - EventValues.registerEventValue(EntitiesLoadEvent.class, Entity[].class, new Getter<>() { - @Override - public Entity @Nullable [] get(EntitiesLoadEvent event) { - return event.getEntities().toArray(new Entity[0]); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(EntitiesUnloadEvent.class, Entity[].class, new Getter<>() { - @Override - public Entity @Nullable [] get(EntitiesUnloadEvent event) { - return event.getEntities().toArray(new Entity[0]); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(EntitiesLoadEvent.class, Entity[].class, event -> event.getEntities().toArray(new Entity[0]), EventValues.TIME_NOW); + EventValues.registerEventValue(EntitiesUnloadEvent.class, Entity[].class, event -> event.getEntities().toArray(new Entity[0]), EventValues.TIME_NOW); } private boolean load; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerInteract.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerInteract.java index 426010cbc..1e4d26c4e 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerInteract.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerInteract.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import ch.njol.util.coll.CollectionUtils; import org.bukkit.Location; import org.bukkit.event.Event; @@ -17,84 +16,57 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.skriptlang.skript.lang.converter.Converter; public class EvtPlayerInteract extends SkriptEvent { static { Skript.registerEvent("Player Interact", EvtPlayerInteract.class, - CollectionUtils.array(PlayerInteractEvent.class, PlayerInteractAtEntityEvent.class), - "player interact", "player interact (at|on) entity") - .description("Called when a player interacts (clicks) a block or entity.", - "This is similar to Skript's click event, but more verbose giving you more freedom.", - "Note: This event may be called once for each hand.", - "`event-vector` = An offset from the location of the clicked block/entity.", - "`event-equipmentslot` = The slot (hand_slot, off_hand_slot) used to click (may be null).", - "`event-blockaction` = The action that happened, such as (left_click_air, physical, right_click_block).") - .examples("on player interact:", - "\tif all:", - "\t\tevent-equipmentslot = off_hand_slot", - "\t\tevent-blockaction = right_click_block", - "\t\ttype of event-item = torch", - "\t\tname of event-item = \"Mr Torchie\"", - "\t\tplayer is sneaking", - "\tthen:", - "\t\tcancel event", - "\t\tset {_l} to (exact location of clicked block) ~ event-vector", - "\t\tmake 5 of dust using dustOption(red, 1) at {_l}", - "", - "on player interact on entity:", - "\tif all:", - "\t\tevent-equipmentslot = off_hand_slot", - "\t\ttype of event-item = leash", - "\t\tname of event-item = \"Mr Leashie\"", - "\tthen:", - "\t\tcancel event", - "\t\tkill clicked entity") - .since("3.4.0"); + CollectionUtils.array(PlayerInteractEvent.class, PlayerInteractAtEntityEvent.class), + "player interact", "player interact (at|on) entity") + .description("Called when a player interacts (clicks) a block or entity.", + "This is similar to Skript's click event, but more verbose giving you more freedom.", + "Note: This event may be called once for each hand.", + "`event-vector` = An offset from the location of the clicked block/entity.", + "`event-equipmentslot` = The slot (hand_slot, off_hand_slot) used to click (may be null).", + "`event-blockaction` = The action that happened, such as (left_click_air, physical, right_click_block).") + .examples("on player interact:", + "\tif all:", + "\t\tevent-equipmentslot = off_hand_slot", + "\t\tevent-blockaction = right_click_block", + "\t\ttype of event-item = torch", + "\t\tname of event-item = \"Mr Torchie\"", + "\t\tplayer is sneaking", + "\tthen:", + "\t\tcancel event", + "\t\tset {_l} to (exact location of clicked block) ~ event-vector", + "\t\tmake 5 of dust using dustOption(red, 1) at {_l}", + "", + "on player interact on entity:", + "\tif all:", + "\t\tevent-equipmentslot = off_hand_slot", + "\t\ttype of event-item = leash", + "\t\tname of event-item = \"Mr Leashie\"", + "\tthen:", + "\t\tcancel event", + "\t\tkill clicked entity") + .since("3.4.0"); - EventValues.registerEventValue(PlayerInteractEvent.class, EquipmentSlot.class, new Getter<>() { + EventValues.registerEventValue(PlayerInteractEvent.class, EquipmentSlot.class, new Converter<>() { @Override - public @Nullable EquipmentSlot get(PlayerInteractEvent event) { + public @Nullable EquipmentSlot convert(PlayerInteractEvent event) { return event.getHand(); } }, EventValues.TIME_NOW); - EventValues.registerEventValue(PlayerInteractEvent.class, Action.class, new Getter<>() { - @Override - public Action get(PlayerInteractEvent event) { - return event.getAction(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PlayerInteractEvent.class, Vector.class, new Getter<>() { - @SuppressWarnings("deprecation") - @Override - public @Nullable Vector get(PlayerInteractEvent event) { - return event.getClickedPosition(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PlayerInteractEntityEvent.class, EquipmentSlot.class, new Getter<>() { - @Override - public EquipmentSlot get(PlayerInteractEntityEvent event) { - return event.getHand(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PlayerInteractAtEntityEvent.class, Location.class, new Getter<>() { - @Override - public Location get(PlayerInteractAtEntityEvent event) { - Location location = event.getRightClicked().getLocation(); - return location.add(event.getClickedPosition()); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PlayerInteractAtEntityEvent.class, Vector.class, new Getter<>() { - @Override - public Vector get(PlayerInteractAtEntityEvent event) { - return event.getClickedPosition(); - } + EventValues.registerEventValue(PlayerInteractEvent.class, Action.class, PlayerInteractEvent::getAction, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerInteractEvent.class, Vector.class, PlayerInteractEvent::getClickedPosition, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerInteractEntityEvent.class, EquipmentSlot.class, PlayerInteractEntityEvent::getHand, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerInteractAtEntityEvent.class, Location.class, event -> { + Location location = event.getRightClicked().getLocation(); + return location.add(event.getClickedPosition()); }, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerInteractAtEntityEvent.class, Vector.class, PlayerInteractAtEntityEvent::getClickedPosition, EventValues.TIME_NOW); } private int pattern; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerUseUnknown.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerUseUnknown.java index f5251ff86..6595812e4 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerUseUnknown.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPlayerUseUnknown.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; import org.bukkit.event.Event; import org.bukkit.inventory.EquipmentSlot; @@ -19,34 +18,26 @@ public class EvtPlayerUseUnknown extends SkriptEvent { static { if (Skript.classExists("com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent")) { Skript.registerEvent("Player Click Unknown Entity", EvtPlayerUseUnknown.class, PlayerUseUnknownEntityEvent.class, - "[player] click unknown entity [with (main|:off) hand]", - "[player] right[( |-)]click unknown entity [with (main|:off) hand]", - "[player] left[( |-)]click unknown entity [with (main|:off) hand]") - .description("Represents an event that is called when a player right-clicks an unknown entity.", - "Useful for dealing with virtual entities (entities that aren't actually spawned on the server).", - "This event may be called multiple times per interaction (this is a server issue).", - "\n`event-vector` = Returns the position relative to the entity that was clicked if available. (Requires Paper 1.20.1+)", - "\n`event-number` = Returns the entity id of the unknown entity that was interacted with. (Not sure if this usefull or not)", - "\nRequires PaperMC.") - .examples("oh right click unknown entity:", - "\tteleport player to spawn of world \"world\"") - .since("2.17.0"); + "[player] click unknown entity [with (main|:off) hand]", + "[player] right[( |-)]click unknown entity [with (main|:off) hand]", + "[player] left[( |-)]click unknown entity [with (main|:off) hand]") + .description("Represents an event that is called when a player right-clicks an unknown entity.", + "Useful for dealing with virtual entities (entities that aren't actually spawned on the server).", + "This event may be called multiple times per interaction (this is a server issue).", + "\n`event-vector` = Returns the position relative to the entity that was clicked if available. (Requires Paper 1.20.1+)", + "\n`event-number` = Returns the entity id of the unknown entity that was interacted with. (Not sure if this usefull or not)", + "\nRequires PaperMC.") + .examples("oh right click unknown entity:", + "\tteleport player to spawn of world \"world\"") + .since("2.17.0"); - EventValues.registerEventValue(PlayerUseUnknownEntityEvent.class, Number.class, new Getter<>() { - @Override - public @NotNull Number get(PlayerUseUnknownEntityEvent event) { - return event.getEntityId(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerUseUnknownEntityEvent.class, Number.class, PlayerUseUnknownEntityEvent::getEntityId, EventValues.TIME_NOW); if (Skript.methodExists(PlayerUseUnknownEntityEvent.class, "getClickedRelativePosition")) { - EventValues.registerEventValue(PlayerUseUnknownEntityEvent.class, Vector.class, new Getter<>() { - @Override - public @Nullable Vector get(PlayerUseUnknownEntityEvent event) { - try { - return event.getClickedRelativePosition(); - } catch (NullPointerException ignore) { - return null; - } + EventValues.registerEventValue(PlayerUseUnknownEntityEvent.class, Vector.class, event -> { + try { + return event.getClickedRelativePosition(); + } catch (NullPointerException ignore) { + return null; } }, EventValues.TIME_NOW); } @@ -57,7 +48,6 @@ public class EvtPlayerUseUnknown extends SkriptEvent { private boolean attack; private boolean offHand; - @SuppressWarnings("NullableProblems") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult) { this.pattern = matchedPattern; @@ -66,7 +56,6 @@ public boolean init(Literal[] args, int matchedPattern, ParseResult parseResu return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (event instanceof PlayerUseUnknownEntityEvent useEvent) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPotionEffect.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPotionEffect.java index c0a4a1195..2d81445f4 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPotionEffect.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPotionEffect.java @@ -5,94 +5,68 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityPotionEffectEvent; import org.bukkit.event.entity.EntityPotionEffectEvent.Action; import org.bukkit.event.entity.EntityPotionEffectEvent.Cause; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @SuppressWarnings({"unused", "ConstantConditions"}) public class EvtPotionEffect extends SkriptEvent { static { Skript.registerEvent("Entity Potion Effect", EvtPotionEffect.class, EntityPotionEffectEvent.class, - "[entity] potion effect added", - "[entity] potion effect changed", - "[entity] potion effect cleared", - "[entity] potion effect removed") - .description("Called when a potion effect is modified on an entity.", - "ADDED = When the potion effect is added because the entity didn't have it's type.", - "CHANGED = When the entity already had the potion effect type, but the effect is changed.", - "CLEARED = When the effect is removed due to all effects being removed.", - "REMOVED = When the potion effect type is completely removed.", - "event-potioneffect = new effect.", - "past event-potioneffect = old effect.", - "event-potioneffecttype = type of potion effect.") - .examples("on potion effect added:", - "\tif event-potioneffecttype = night vision:", - "\t\tcancel event", - "\t\tsend \"NO NIGHT VISION FOR YOU!!!\"", - "", - "on potion effect added:", - "\tif event-potioneffectcause = totem_effect:", - "\t\tteleport player to {spawn}", - "", - "on potion effect changed:", - "\tremove event-potioneffecttype from player", - "\t", - "on potion effect cleared:", - "\tif event-entity is a player:", - "\t\tbroadcast \"ALL EFFECTS CLEARED FOR: %event-entity%\"", - "", - "on potion effect removed:", - "\tif event-potioneffecttype = night vision:", - "\t\tkill event-entity") - .since("1.17.0"); - - EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffect.class, new Getter<>() { - @Override - public @Nullable PotionEffect get(EntityPotionEffectEvent event) { - return event.getOldEffect(); - } - }, -1); - - EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffect.class, new Getter<>() { - @Override - public @Nullable PotionEffect get(EntityPotionEffectEvent event) { - return event.getNewEffect(); - } - }, 0); - - EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffectType.class, new Getter<>() { - @Override - public @Nullable PotionEffectType get(EntityPotionEffectEvent event) { - return event.getModifiedType(); - } - }, 0); + "[entity] potion effect added", + "[entity] potion effect changed", + "[entity] potion effect cleared", + "[entity] potion effect removed") + .description("Called when a potion effect is modified on an entity.", + "ADDED = When the potion effect is added because the entity didn't have it's type.", + "CHANGED = When the entity already had the potion effect type, but the effect is changed.", + "CLEARED = When the effect is removed due to all effects being removed.", + "REMOVED = When the potion effect type is completely removed.", + "event-potioneffect = new effect.", + "past event-potioneffect = old effect.", + "event-potioneffecttype = type of potion effect.") + .examples("on potion effect added:", + "\tif event-potioneffecttype = night vision:", + "\t\tcancel event", + "\t\tsend \"NO NIGHT VISION FOR YOU!!!\"", + "", + "on potion effect added:", + "\tif event-potioneffectcause = totem_effect:", + "\t\tteleport player to {spawn}", + "", + "on potion effect changed:", + "\tremove event-potioneffecttype from player", + "\t", + "on potion effect cleared:", + "\tif event-entity is a player:", + "\t\tbroadcast \"ALL EFFECTS CLEARED FOR: %event-entity%\"", + "", + "on potion effect removed:", + "\tif event-potioneffecttype = night vision:", + "\t\tkill event-entity") + .since("1.17.0"); - EventValues.registerEventValue(EntityPotionEffectEvent.class, Cause.class, new Getter<>() { - @Override - public @Nullable Cause get(EntityPotionEffectEvent event) { - return event.getCause(); - } - }, 0); + EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffect.class, EntityPotionEffectEvent::getOldEffect, EventValues.TIME_PAST); + EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffect.class, EntityPotionEffectEvent::getNewEffect, EventValues.TIME_NOW); + EventValues.registerEventValue(EntityPotionEffectEvent.class, PotionEffectType.class, EntityPotionEffectEvent::getModifiedType, EventValues.TIME_NOW); + EventValues.registerEventValue(EntityPotionEffectEvent.class, Cause.class, EntityPotionEffectEvent::getCause, EventValues.TIME_NOW); } private static final Action[] ACTIONS = new Action[]{Action.ADDED, Action.CHANGED, Action.CLEARED, Action.REMOVED}; private int eventAction; - @SuppressWarnings("NullableProblems") @Override public boolean init(Literal[] args, int matchedPattern, ParseResult parseResult) { this.eventAction = matchedPattern; return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (event instanceof EntityPotionEffectEvent potionEvent) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPreSpawn.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPreSpawn.java index daa0f6cb0..e06dfed0e 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPreSpawn.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtPreSpawn.java @@ -7,7 +7,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import com.destroystokyo.paper.event.entity.PhantomPreSpawnEvent; import com.destroystokyo.paper.event.entity.PreCreatureSpawnEvent; import com.destroystokyo.paper.event.entity.PreSpawnerSpawnEvent; @@ -29,91 +28,63 @@ public class EvtPreSpawn extends SkriptEvent { // Paper - PreCreatureSpawnEvent if (HAS_PRE_CREATURE_SPAWN_EVENT) { Skript.registerEvent("Pre Creature Spawn", EvtPreSpawn.class, PreCreatureSpawnEvent.class, - "pre [creature] spawn[ing] [of %entitydatas%]") - .description("Called before an entity is spawned into the world. Requires a PaperMC server.", - "\nNote: The spawning entity does not exist when this event is called only the entitytype exists.", - "This event is called very frequently, and can cause server lag, use it sparingly.", - "\n`event-spawnreason` = the reason the entity is spawned.", - "\n`event-location` = the location the spawned entity will appear.", - "\n`event-entitytype` = the type of entity being spawned.") - .examples("on pre spawn of a pig:", - "\tbroadcast \"a %event-entitytype% is spawning in\"") - .since("2.16.0"); - - EventValues.registerEventValue(PreCreatureSpawnEvent.class, Location.class, new Getter<>() { - @Override - public Location get(PreCreatureSpawnEvent event) { - return event.getSpawnLocation(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PreCreatureSpawnEvent.class, EntityData.class, new Getter<>() { - @Override - public EntityData get(PreCreatureSpawnEvent event) { - return EntityUtils.toSkriptEntityData(event.getType()); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PreCreatureSpawnEvent.class, SpawnReason.class, new Getter<>() { - @Override - public SpawnReason get(PreCreatureSpawnEvent event) { - return event.getReason(); - } - }, EventValues.TIME_NOW); + "pre [creature] spawn[ing] [of %entitydatas%]") + .description("Called before an entity is spawned into the world. Requires a PaperMC server.", + "\nNote: The spawning entity does not exist when this event is called only the entitytype exists.", + "This event is called very frequently, and can cause server lag, use it sparingly.", + "\n`event-spawnreason` = the reason the entity is spawned.", + "\n`event-location` = the location the spawned entity will appear.", + "\n`event-entitytype` = the type of entity being spawned.") + .examples("on pre spawn of a pig:", + "\tbroadcast \"a %event-entitytype% is spawning in\"") + .since("2.16.0"); + + EventValues.registerEventValue(PreCreatureSpawnEvent.class, Location.class, PreCreatureSpawnEvent::getSpawnLocation, EventValues.TIME_NOW); + EventValues.registerEventValue(PreCreatureSpawnEvent.class, EntityData.class, event -> EntityUtils.toSkriptEntityData(event.getType()), EventValues.TIME_NOW); + EventValues.registerEventValue(PreCreatureSpawnEvent.class, SpawnReason.class, PreCreatureSpawnEvent::getReason, EventValues.TIME_NOW); } // Paper - PreSpawnerSpawnEvent if (HAS_PRE_SPAWNER_SPAWN_EVENT) { Skript.registerEvent("Pre Spawner Spawn", EvtPreSpawn.class, PreSpawnerSpawnEvent.class, - "pre spawner spawn[ing] [of %entitydatas%]") - .description("Called before an entity is spawned via a spawner. Requires a PaperMC server.", - "\nNote: The spawned entity does not exist when this event is called only the entitytype exists.", - "\nView the pre creature spawn event for more event values.", - "\n`event-block` = the block location of the spawner spawning the entity.") - .examples("on pre spawner spawn of a zombie:", - "\tbroadcast \"%event-entitytype% is spawning in\"") - .since("2.16.0"); - - EventValues.registerEventValue(PreSpawnerSpawnEvent.class, Block.class, new Getter<>() { - @Override - public Block get(PreSpawnerSpawnEvent event) { - return event.getSpawnerLocation().getBlock(); - } - }, EventValues.TIME_NOW); + "pre spawner spawn[ing] [of %entitydatas%]") + .description("Called before an entity is spawned via a spawner. Requires a PaperMC server.", + "\nNote: The spawned entity does not exist when this event is called only the entitytype exists.", + "\nView the pre creature spawn event for more event values.", + "\n`event-block` = the block location of the spawner spawning the entity.") + .examples("on pre spawner spawn of a zombie:", + "\tbroadcast \"%event-entitytype% is spawning in\"") + .since("2.16.0"); + + EventValues.registerEventValue(PreSpawnerSpawnEvent.class, Block.class, event -> event.getSpawnerLocation().getBlock(), EventValues.TIME_NOW); } // Paper - PhantomPreSpawnEvent if (HAS_PRE_PHANTOM_SPAWN_EVENT) { Skript.registerEvent("Pre Phantom Spawn", EvtPreSpawn.class, PhantomPreSpawnEvent.class, - "pre phantom spawn[ing]") - .description("Called before a phantom is spawned for an entity. Requires a PaperMC server.", - "\nNote: The phantom entity does not exist when this event is called only the entitytype exists.", - "\nView the pre creature spawn event for more event values.", - "\n`event-entity` = the entity the spawned phantom is spawning for.") - .examples("on pre phantom spawn:", - "\tbroadcast \"Watch out %event-entity% a phantom is coming!\"") - .since("2.16.0"); - - EventValues.registerEventValue(PhantomPreSpawnEvent.class, Entity.class, new Getter<>() { - @Override - public Entity get(PhantomPreSpawnEvent event) { - return event.getSpawningEntity(); - } - }, EventValues.TIME_NOW); + "pre phantom spawn[ing]") + .description("Called before a phantom is spawned for an entity. Requires a PaperMC server.", + "\nNote: The phantom entity does not exist when this event is called only the entitytype exists.", + "\nView the pre creature spawn event for more event values.", + "\n`event-entity` = the entity the spawned phantom is spawning for.") + .examples("on pre phantom spawn:", + "\tbroadcast \"Watch out %event-entity% a phantom is coming!\"") + .since("2.16.0"); + + EventValues.registerEventValue(PhantomPreSpawnEvent.class, Entity.class, event -> event.getSpawningEntity(), EventValues.TIME_NOW); } } private Literal> spawnedEntities; - @SuppressWarnings({"unchecked", "NullableProblems"}) + @SuppressWarnings({"unchecked"}) @Override public boolean init(Literal[] literals, int matchedPattern, ParseResult parseResult) { this.spawnedEntities = (Literal>) literals[0]; return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (this.spawnedEntities == null) return true; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtSpawnerSpawn.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtSpawnerSpawn.java index 3d6930ee6..b4de9e909 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtSpawnerSpawn.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/EvtSpawnerSpawn.java @@ -6,7 +6,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.block.Block; import org.bukkit.block.CreatureSpawner; import org.bukkit.entity.Entity; @@ -19,33 +18,29 @@ public class EvtSpawnerSpawn extends SkriptEvent { static { Skript.registerEvent("Spawner Spawn", EvtSpawnerSpawn.class, SpawnerSpawnEvent.class, - "spawner spawn[ing] [of %entitydatas%]") - .description("Called whenever an entity is spawned via a spawner.") - .examples("on spawner spawn of zombie:", - "\treset spawner timer of event-block") - .since("2.16.0"); - - EventValues.registerEventValue(SpawnerSpawnEvent.class, Block.class, new Getter<>() { - @Override - public @Nullable Block get(SpawnerSpawnEvent event) { - CreatureSpawner spawner = event.getSpawner(); - if (spawner != null) return spawner.getBlock(); - return null; - } + "spawner spawn[ing] [of %entitydatas%]") + .description("Called whenever an entity is spawned via a spawner.") + .examples("on spawner spawn of zombie:", + "\treset spawner timer of event-block") + .since("2.16.0"); + + EventValues.registerEventValue(SpawnerSpawnEvent.class, Block.class, event -> { + CreatureSpawner spawner = event.getSpawner(); + if (spawner != null) return spawner.getBlock(); + return null; }, EventValues.TIME_NOW); } private Literal> spawnedEntities; - @SuppressWarnings({"unchecked", "NullableProblems"}) + @SuppressWarnings("unchecked") @Override public boolean init(Literal[] literals, int matchedPattern, ParseResult parseResult) { this.spawnedEntities = (Literal>) literals[0]; return true; } - @SuppressWarnings("NullableProblems") @Override public boolean check(Event event) { if (this.spawnedEntities == null) return true; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/OtherEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/OtherEvents.java index 5c12617a3..c10a7a426 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/OtherEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/OtherEvents.java @@ -146,41 +146,43 @@ public Player get(PrepareAnvilEvent event) { .since("1.8.0"); // Entity Breed Event - Skript.registerEvent("Entity Breed", OtherEvents.class, EntityBreedEvent.class, - "entity breed") - .description("Called when one Entity breeds with another Entity.") - .examples("on entity breed:", "\nif breeding mother is a sheep:", - "\n\nkill breeding player") - .since("1.17.0"); - - EventValues.registerEventValue(EntityBreedEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(EntityBreedEvent breedEvent) { - LivingEntity breeder = breedEvent.getBreeder(); - if (breeder instanceof Player player) { - return player; + if (!Util.IS_RUNNING_SKRIPT_2_10) { + Skript.registerEvent("Entity Breed", OtherEvents.class, EntityBreedEvent.class, + "entity breed") + .description("Called when one Entity breeds with another Entity.") + .examples("on entity breed:", "\nif breeding mother is a sheep:", + "\n\nkill breeding player") + .since("1.17.0"); + + EventValues.registerEventValue(EntityBreedEvent.class, Player.class, new Getter<>() { + @Override + public @Nullable Player get(EntityBreedEvent breedEvent) { + LivingEntity breeder = breedEvent.getBreeder(); + if (breeder instanceof Player player) { + return player; + } + return null; } - return null; - } - }, EventValues.TIME_NOW); + }, EventValues.TIME_NOW); - EventValues.registerEventValue(EntityBreedEvent.class, Entity.class, new Getter<>() { - @Override - public Entity get(EntityBreedEvent breedEvent) { - return breedEvent.getEntity(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(EntityBreedEvent.class, Entity.class, new Getter<>() { + @Override + public Entity get(EntityBreedEvent breedEvent) { + return breedEvent.getEntity(); + } + }, EventValues.TIME_NOW); - EventValues.registerEventValue(EntityBreedEvent.class, ItemType.class, new Getter<>() { - @Override - public @Nullable ItemType get(EntityBreedEvent breedEvent) { - ItemStack bredWith = breedEvent.getBredWith(); - if (bredWith != null) { - return new ItemType(bredWith); + EventValues.registerEventValue(EntityBreedEvent.class, ItemType.class, new Getter<>() { + @Override + public @Nullable ItemType get(EntityBreedEvent breedEvent) { + ItemStack bredWith = breedEvent.getBredWith(); + if (bredWith != null) { + return new ItemType(bredWith); + } + return null; } - return null; - } - }, EventValues.TIME_NOW); + }, EventValues.TIME_NOW); + } // Entity Change Block Event Skript.registerEvent("Entity Change Block", OtherEvents.class, EntityChangeBlockEvent.class, @@ -204,49 +206,51 @@ public Entity get(EntityBreedEvent breedEvent) { }, EventValues.TIME_NOW); // Block Drop Item Event - Skript.registerEvent("Block Drop Item", OtherEvents.class, BlockDropItemEvent.class, - "block drop item") - .description("This event is called if a block broken by a player drops an item.", - "`event-player` = Player who broke the block.", - "`event-entities` = Item entities which were dropped (may include drops of attached blocks, like a torch).", - "`past event-block` = The block that was broken (This event is called after the block actually breaks).", - "`event-block` = Current state of block after broken (Probably will just be air).") - .examples("on block drop item:", - "\tif past event-block is any ore:", - "\t\tteleport event-entities to player", - "\t\tset {_data} to blockdata of past event-block", - "\t\tset event-block to bedrock", - "\t\twait 2 seconds", - "\t\tset event-block to {_data}") - .since("2.6.0"); - - EventValues.registerEventValue(BlockDropItemEvent.class, Player.class, new Getter<>() { - @Override - public Player get(BlockDropItemEvent event) { - return event.getPlayer(); - } - }, EventValues.TIME_NOW); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + Skript.registerEvent("Block Drop Item", OtherEvents.class, BlockDropItemEvent.class, + "block drop item") + .description("This event is called if a block broken by a player drops an item.", + "`event-player` = Player who broke the block.", + "`event-entities` = Item entities which were dropped (may include drops of attached blocks, like a torch).", + "`past event-block` = The block that was broken (This event is called after the block actually breaks).", + "`event-block` = Current state of block after broken (Probably will just be air).") + .examples("on block drop item:", + "\tif past event-block is any ore:", + "\t\tteleport event-entities to player", + "\t\tset {_data} to blockdata of past event-block", + "\t\tset event-block to bedrock", + "\t\twait 2 seconds", + "\t\tset event-block to {_data}") + .since("2.6.0"); + + EventValues.registerEventValue(BlockDropItemEvent.class, Player.class, new Getter<>() { + @Override + public Player get(BlockDropItemEvent event) { + return event.getPlayer(); + } + }, EventValues.TIME_NOW); - EventValues.registerEventValue(BlockDropItemEvent.class, Block.class, new Getter<>() { - @Override - public Block get(BlockDropItemEvent event) { - return event.getBlock(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(BlockDropItemEvent.class, Block.class, new Getter<>() { + @Override + public Block get(BlockDropItemEvent event) { + return event.getBlock(); + } + }, EventValues.TIME_NOW); - EventValues.registerEventValue(BlockDropItemEvent.class, Block.class, new Getter<>() { - @Override - public Block get(BlockDropItemEvent event) { - return new BlockStateBlock(event.getBlockState()); - } - }, EventValues.TIME_PAST); + EventValues.registerEventValue(BlockDropItemEvent.class, Block.class, new Getter<>() { + @Override + public Block get(BlockDropItemEvent event) { + return new BlockStateBlock(event.getBlockState()); + } + }, EventValues.TIME_PAST); - EventValues.registerEventValue(BlockDropItemEvent.class, Item[].class, new Getter<>() { - @Override - public Item @Nullable [] get(BlockDropItemEvent event) { - return event.getItems().toArray(new Item[0]); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(BlockDropItemEvent.class, Item[].class, new Getter<>() { + @Override + public Item @Nullable [] get(BlockDropItemEvent event) { + return event.getItems().toArray(new Item[0]); + } + }, EventValues.TIME_NOW); + } // Block Damage Abort Event if (Skript.classExists("org.bukkit.event.block.BlockDamageAbortEvent")) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/PaperEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/PaperEvents.java index 01f6e08d2..94680dcde 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/PaperEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/PaperEvents.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.registrations.EventValues; import ch.njol.skript.util.Experience; -import ch.njol.skript.util.Getter; import com.destroystokyo.paper.event.block.BeaconEffectEvent; import com.destroystokyo.paper.event.entity.EntityAddToWorldEvent; import com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent; @@ -17,6 +16,7 @@ import com.destroystokyo.paper.event.player.PlayerElytraBoostEvent; import com.destroystokyo.paper.event.player.PlayerPickupExperienceEvent; import com.destroystokyo.paper.event.player.PlayerRecipeBookClickEvent; +import com.shanebeestudios.skbee.api.util.Util; import io.papermc.paper.event.block.BeaconActivatedEvent; import io.papermc.paper.event.block.BeaconDeactivatedEvent; import io.papermc.paper.event.entity.EntityInsideBlockEvent; @@ -33,8 +33,6 @@ import org.bukkit.event.player.PlayerAttemptPickupItemEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @SuppressWarnings({"unused", "unchecked"}) @@ -46,150 +44,100 @@ public class PaperEvents extends SimpleEvent { // Player Recipe Book Click Event if (Skript.classExists("com.destroystokyo.paper.event.player.PlayerRecipeBookClickEvent")) { Skript.registerEvent("Recipe Book Click Event", PaperEvents.class, PlayerRecipeBookClickEvent.class, "[player] recipe book click") - .description("Called when the player clicks on a recipe in their recipe book. Requires Paper 1.15+") - .examples("on recipe book click:", - "\tif event-string = \"minecraft:diamond_sword\":", - "\t\tcancel event") - .since("1.5.0"); - - EventValues.registerEventValue(PlayerRecipeBookClickEvent.class, String.class, new Getter<>() { - @Override - public @NotNull String get(@NotNull PlayerRecipeBookClickEvent event) { - return event.getRecipe().toString(); - } - }, 0); + .description("Called when the player clicks on a recipe in their recipe book. Requires Paper 1.15+") + .examples("on recipe book click:", + "\tif event-string = \"minecraft:diamond_sword\":", + "\t\tcancel event") + .since("1.5.0"); + + EventValues.registerEventValue(PlayerRecipeBookClickEvent.class, String.class, event -> event.getRecipe().toString(), EventValues.TIME_NOW); } // Player Pickup XP Event if (Skript.classExists("com.destroystokyo.paper.event.player.PlayerPickupExperienceEvent")) { Skript.registerEvent("Player Pickup Experience Orb", PaperEvents.class, PlayerPickupExperienceEvent.class, - "player pickup (experience|xp) [orb]") - .description("Fired when a player is attempting to pick up an experience orb. Requires Paper 1.12.2+", - "\n`event-experience` represents the experience picked up (This is Skript's version of XP).", - "\n`event-number` represents the experience picked up as a number.", - "\n`event-entity` represents the experience orb entity.") - .examples("on player pickup xp:", - "\tadd 10 to level of player") - .since("1.8.0"); - - EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Experience.class, new Getter<>() { - @Override - public Experience get(PlayerPickupExperienceEvent event) { - return new Experience(event.getExperienceOrb().getExperience()); - } - }, 0); - - EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Number.class, new Getter<>() { - @Override - public Number get(PlayerPickupExperienceEvent event) { - return event.getExperienceOrb().getExperience(); - } - }, 0); - - EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Entity.class, new Getter<>() { - @Override - public Entity get(PlayerPickupExperienceEvent event) { - return event.getExperienceOrb(); - } - }, 0); + "player pickup (experience|xp) [orb]") + .description("Fired when a player is attempting to pick up an experience orb. Requires Paper 1.12.2+", + "\n`event-experience` represents the experience picked up (This is Skript's version of XP).", + "\n`event-number` represents the experience picked up as a number.", + "\n`event-entity` represents the experience orb entity.") + .examples("on player pickup xp:", + "\tadd 10 to level of player") + .since("1.8.0"); + + EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Experience.class, event -> new Experience(event.getExperienceOrb().getExperience()), EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Number.class, event -> event.getExperienceOrb().getExperience(), EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerPickupExperienceEvent.class, Entity.class, PlayerPickupExperienceEvent::getExperienceOrb, EventValues.TIME_NOW); } // Player Elytra Boost Event if (Skript.classExists("com.destroystokyo.paper.event.player.PlayerElytraBoostEvent")) { Skript.registerEvent("Player Elytra Boost", PaperEvents.class, PlayerElytraBoostEvent.class, "[player] elytra boost") - .description("Fired when a player boosts elytra flight with a firework. Requires Paper 1.13.2+") - .examples("on elytra boost:", - "\tpush player forward at speed 50") - .since("1.8.0"); - EventValues.registerEventValue(PlayerElytraBoostEvent.class, ItemType.class, new Getter<>() { - @Override - public ItemType get(PlayerElytraBoostEvent e) { - return new ItemType(e.getItemStack()); - } - }, 0); + .description("Fired when a player boosts elytra flight with a firework. Requires Paper 1.13.2+") + .examples("on elytra boost:", + "\tpush player forward at speed 50") + .since("1.8.0"); + EventValues.registerEventValue(PlayerElytraBoostEvent.class, ItemType.class, e -> new ItemType(e.getItemStack()), EventValues.TIME_NOW); } // Player Stop Using Item Event if (Skript.classExists("io.papermc.paper.event.player.PlayerStopUsingItemEvent")) { Skript.registerEvent("Player Stop Using Item", PaperEvents.class, PlayerStopUsingItemEvent.class, "[player] stop using item") - .description("Called when the server detects a player stopping using an item.", - "Examples of this are letting go of the interact button when holding a bow, an edible item, or a spyglass.", - "event-number is the number of ticks the item was held for. Requires Paper 1.18+.") - .examples("on player stop using item:", - "\tif event-item is a spyglass:", - "\t\tkill player") - .since("1.17.0"); - EventValues.registerEventValue(PlayerStopUsingItemEvent.class, ItemType.class, new Getter<>() { - @Override - public ItemType get(PlayerStopUsingItemEvent event) { - return new ItemType(event.getItem()); - } - }, 0); - EventValues.registerEventValue(PlayerStopUsingItemEvent.class, Number.class, new Getter<>() { - @Override - public Number get(PlayerStopUsingItemEvent event) { - return event.getTicksHeldFor(); - } - }, 0); + .description("Called when the server detects a player stopping using an item.", + "Examples of this are letting go of the interact button when holding a bow, an edible item, or a spyglass.", + "event-number is the number of ticks the item was held for. Requires Paper 1.18+.") + .examples("on player stop using item:", + "\tif event-item is a spyglass:", + "\t\tkill player") + .since("1.17.0"); + EventValues.registerEventValue(PlayerStopUsingItemEvent.class, ItemType.class, event -> new ItemType(event.getItem()), EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerStopUsingItemEvent.class, Number.class, PlayerStopUsingItemEvent::getTicksHeldFor, EventValues.TIME_NOW); } // Player Change Beacon Effect Event if (Skript.classExists("io.papermc.paper.event.player.PlayerChangeBeaconEffectEvent")) { - Skript.registerEvent("Beacon - Player Change Effect", PaperEvents.class, PlayerChangeBeaconEffectEvent.class, "[player] change beacon [potion] effect[s]", "beacon [potion] effect change") - .description("Called when a player changes the current potion effects of a beacon.") - .examples("on beacon potion effect change:", - "\tprimary beacon effect of event-block is jump boost", - "\tset primary beacon effect of event-block to levitation") - .since("2.16.0"); + Skript.registerEvent("Beacon - Player Change Effect", PaperEvents.class, PlayerChangeBeaconEffectEvent.class, + "[player] change beacon [potion] effect[s]", + "beacon [potion] effect change") + .description("Called when a player changes the current potion effects of a beacon.") + .examples("on beacon potion effect change:", + "\tprimary beacon effect of event-block is jump boost", + "\tset primary beacon effect of event-block to levitation") + .since("2.16.0"); - EventValues.registerEventValue(PlayerChangeBeaconEffectEvent.class, Block.class, new Getter<>() { - @Override - public Block get(PlayerChangeBeaconEffectEvent event) { - return event.getBeacon(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerChangeBeaconEffectEvent.class, Block.class, PlayerChangeBeaconEffectEvent::getBeacon, EventValues.TIME_NOW); } // Player Chunk Load Event if (Skript.classExists("io.papermc.paper.event.packet.PlayerChunkLoadEvent")) { Skript.registerEvent("Player Chunk Load", PaperEvents.class, PlayerChunkLoadEvent.class, - "player chunk (send|load)") - .description("Is called when a Player receives a Chunk.", - "Can for example be used for spawning a fake entity when the player receives a chunk. ", - "Should only be used for packet/clientside related stuff. Not intended for modifying server side state.", - "\nRequires a PaperMC server.") - .examples("on player chunk send:", - "\tloop all blocks in event-chunk:", - "\t\tif loop-block is diamond ore:", - "\t\t\tmake player see loop-block as stone") - .since("2.6.1"); - - EventValues.registerEventValue(PlayerChunkLoadEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(PlayerChunkLoadEvent event) { - return event.getPlayer(); - } - }, 0); + "player chunk (send|load)") + .description("Is called when a Player receives a Chunk.", + "Can for example be used for spawning a fake entity when the player receives a chunk. ", + "Should only be used for packet/clientside related stuff. Not intended for modifying server side state.", + "\nRequires a PaperMC server.") + .examples("on player chunk send:", + "\tloop all blocks in event-chunk:", + "\t\tif loop-block is diamond ore:", + "\t\t\tmake player see loop-block as stone") + .since("2.6.1"); + + EventValues.registerEventValue(PlayerChunkLoadEvent.class, Player.class, PlayerChunkLoadEvent::getPlayer, EventValues.TIME_NOW); } // Player Chunk Unload Event if (Skript.classExists("io.papermc.paper.event.packet.PlayerChunkUnloadEvent")) { Skript.registerEvent("Player Chunk Unload", PaperEvents.class, PlayerChunkUnloadEvent.class, - "player chunk unload") - .description("Is called when a Player receives a chunk unload packet.", - "Should only be used for packet/clientside related stuff. Not intended for modifying server side.", - "\nRequires a PaperMC server.") - .examples("on player chunk unload:", - "\tsend \"looks like you lost your chunk cowboy!\" to player") - .since("2.6.1"); - - EventValues.registerEventValue(PlayerChunkUnloadEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(PlayerChunkUnloadEvent event) { - return event.getPlayer(); - } - }, 0); + "player chunk unload") + .description("Is called when a Player receives a chunk unload packet.", + "Should only be used for packet/clientside related stuff. Not intended for modifying server side.", + "\nRequires a PaperMC server.") + .examples("on player chunk unload:", + "\tsend \"looks like you lost your chunk cowboy!\" to player") + .since("2.6.1"); + + EventValues.registerEventValue(PlayerChunkUnloadEvent.class, Player.class, PlayerChunkUnloadEvent::getPlayer, EventValues.TIME_NOW); } // == ENTITY EVENTS == // @@ -197,181 +145,141 @@ public Block get(PlayerChangeBeaconEffectEvent event) { // Entity Pathfind Event if (Skript.classExists("com.destroystokyo.paper.event.entity.EntityPathfindEvent")) { Skript.registerEvent("Entity Pathfind Event", PaperEvents.class, new Class[]{EntityPathfindEvent.class, SlimePathfindEvent.class}, "entity start[s] pathfinding") - .description("Called when an Entity decides to start moving towards a location. This event does not fire for the entities " + - "actual movement. Only when it is choosing to start moving to a location. Requires Paper.") - .examples("on entity starts pathfinding:", - "\tif event-entity is a sheep:", - "\t\tcancel event") - .since("1.5.0"); - - EventValues.registerEventValue(EntityPathfindEvent.class, Location.class, new Getter<>() { - @Override - public @NotNull Location get(@NotNull EntityPathfindEvent event) { - return event.getLoc(); - } - }, 0); + .description("Called when an Entity decides to start moving towards a location. This event does not fire for the entities " + + "actual movement. Only when it is choosing to start moving to a location. Requires Paper.") + .examples("on entity starts pathfinding:", + "\tif event-entity is a sheep:", + "\t\tcancel event") + .since("1.5.0"); + + EventValues.registerEventValue(EntityPathfindEvent.class, Location.class, EntityPathfindEvent::getLoc, EventValues.TIME_NOW); } // Skeleton Horse Trap Event if (Skript.classExists("com.destroystokyo.paper.event.entity.SkeletonHorseTrapEvent")) { Skript.registerEvent("Skeleton Horse Trap Event", PaperEvents.class, SkeletonHorseTrapEvent.class, "skeleton horse trap") - .description("Called when a player gets close to a skeleton horse and triggers the lightning trap. Requires Paper 1.13+") - .examples("on skeleton horse trap:", - "\tloop all players in radius 10 around event-entity:", - "\t\tif loop-player is an op:", - "\t\t\tcancel event") - .since("1.5.0"); + .description("Called when a player gets close to a skeleton horse and triggers the lightning trap. Requires Paper 1.13+") + .examples("on skeleton horse trap:", + "\tloop all players in radius 10 around event-entity:", + "\t\tif loop-player is an op:", + "\t\t\tcancel event") + .since("1.5.0"); } // Entity Zap Event if (Skript.classExists("com.destroystokyo.paper.event.entity.EntityZapEvent")) { Skript.registerEvent("Entity Zap", PaperEvents.class, EntityZapEvent.class, "entity (zap|struck by lightning)") - .description("Fired when lightning strikes an entity. Requires Paper 1.10.2+") - .examples("on entity zap:", - "\tif event-entity is a pig:", - "\t\tspawn 3 zombie pigmen at event-location") - .since("1.8.0"); - EventValues.registerEventValue(EntityZapEvent.class, Location.class, new Getter<>() { - @Override - public Location get(EntityZapEvent e) { - return e.getEntity().getLocation(); - } - }, 0); + .description("Fired when lightning strikes an entity. Requires Paper 1.10.2+") + .examples("on entity zap:", + "\tif event-entity is a pig:", + "\t\tspawn 3 zombie pigmen at event-location") + .since("1.8.0"); + EventValues.registerEventValue(EntityZapEvent.class, Location.class, e -> e.getEntity().getLocation(), EventValues.TIME_NOW); } // Entity Knockback Event if (Skript.classExists("com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent")) { Skript.registerEvent("Entity Knockback", PaperEvents.class, EntityKnockbackByEntityEvent.class, "entity knockback") - .description("Fired when an Entity is knocked back by the hit of another Entity. " + - "If this event is cancelled, the entity is not knocked back. Requires Paper 1.12.2+") - .examples("on entity knockback:", "\tif event-entity is a cow:", "\t\tcancel event") - .since("1.8.0"); + .description("Fired when an Entity is knocked back by the hit of another Entity. " + + "If this event is cancelled, the entity is not knocked back. Requires Paper 1.12.2+") + .examples("on entity knockback:", "\tif event-entity is a cow:", "\t\tcancel event") + .since("1.8.0"); } // Experience Orb Merge Event if (Skript.classExists("com.destroystokyo.paper.event.entity.ExperienceOrbMergeEvent")) { Skript.registerEvent("Experience Orb Merge", PaperEvents.class, ExperienceOrbMergeEvent.class, "(experience|[e]xp) orb merge") - .description("Fired anytime the server is about to merge 2 experience orbs into one. Requires Paper 1.12.2+") - .examples("on xp merge:", - "\tcancel event") - .since("1.8.0"); + .description("Fired anytime the server is about to merge 2 experience orbs into one. Requires Paper 1.12.2+") + .examples("on xp merge:", + "\tcancel event") + .since("1.8.0"); } // Entity Add To World Event if (Skript.classExists("com.destroystokyo.paper.event.entity.EntityAddToWorldEvent")) { Skript.registerEvent("Entity Add to World", PaperEvents.class, EntityAddToWorldEvent.class, - "entity add[ed] to world") - .description("Fired any time an entity is being added to the world for any reason.", - "Not to be confused with entity spawn event. This will fire anytime a chunk is reloaded too. Requires a PaperMC server.") - .examples("on entity added to world:", - "\tdelete event-entity") - .since("2.7.2"); + "entity add[ed] to world") + .description("Fired any time an entity is being added to the world for any reason.", + "Not to be confused with entity spawn event. This will fire anytime a chunk is reloaded too. Requires a PaperMC server.") + .examples("on entity added to world:", + "\tdelete event-entity") + .since("2.7.2"); } // == BLOCK EVENTS == // // Beacon Effect Event - if (Skript.classExists("com.destroystokyo.paper.event.block.BeaconEffectEvent")) { - Skript.registerEvent("Beacon Effect", PaperEvents.class, BeaconEffectEvent.class, "beacon effect") - .description("Called when a beacon effect is being applied to a player. Requires Paper 1.9+") + if (!Util.IS_RUNNING_SKRIPT_2_10) { + if (Skript.classExists("com.destroystokyo.paper.event.block.BeaconEffectEvent")) { + Skript.registerEvent("Beacon Effect", PaperEvents.class, BeaconEffectEvent.class, "beacon effect") + .description("Called when a beacon effect is being applied to a player.", + "Removed if running Skript 2.10+ (now included in Skript).", + "Requires Paper 1.9+") .examples("on beacon effect:", - "\tif event-player does not have permission \"my.server.beacons\":", - "\t\tcancel event") + "\tif event-player does not have permission \"my.server.beacons\":", + "\t\tcancel event") .since("1.8.4"); - EventValues.registerEventValue(BeaconEffectEvent.class, Player.class, new Getter<>() { - @Override - public Player get(BeaconEffectEvent e) { - return e.getPlayer(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(BeaconEffectEvent.class, PotionEffectType.class, new Getter<>() { - @Override - public PotionEffectType get(BeaconEffectEvent e) { - return e.getEffect().getType(); - } - }, EventValues.TIME_NOW); - EventValues.registerEventValue(BeaconEffectEvent.class, PotionEffect.class, new Getter<>() { - @Override - public @NotNull PotionEffect get(BeaconEffectEvent e) { - return e.getEffect(); - } - }, EventValues.TIME_NOW); - } + EventValues.registerEventValue(BeaconEffectEvent.class, Player.class, BeaconEffectEvent::getPlayer, EventValues.TIME_NOW); + + EventValues.registerEventValue(BeaconEffectEvent.class, PotionEffectType.class, beaconEffectEvent -> beaconEffectEvent.getEffect().getType(), EventValues.TIME_NOW); + EventValues.registerEventValue(BeaconEffectEvent.class, PotionEffect.class, BeaconEffectEvent::getEffect, EventValues.TIME_NOW); + } - // Beacon Deactivated Event - if (Skript.classExists("io.papermc.paper.event.block.BeaconDeactivatedEvent")) { - Skript.registerEvent("Beacon Deactivation", PaperEvents.class, BeaconDeactivatedEvent.class, "beacon (deactivate|deactivation)") - .description("Called when a beacon is deactivated from breaking or losing required amount blocks.") + + // Beacon Deactivated Event + if (Skript.classExists("io.papermc.paper.event.block.BeaconDeactivatedEvent")) { + Skript.registerEvent("Beacon Deactivation", PaperEvents.class, BeaconDeactivatedEvent.class, "beacon (deactivate|deactivation)") + .description("Called when a beacon is deactivated from breaking or losing required amount blocks.", + "Removed if running Skript 2.10+ (now included in Skript).") .examples("on beacon deactivation:", - "\tbroadcast \"%event-block% is no longer activated, :cry:\""); + "\tbroadcast \"%event-block% is no longer activated, :cry:\""); - } + } - // Beacon Activated Event - if (Skript.classExists("io.papermc.paper.event.block.BeaconActivatedEvent")) { - Skript.registerEvent("Beacon Activation", PaperEvents.class, BeaconActivatedEvent.class, "beacon (activate|activation)") - .description("Called when a beacon is successfully activated by having correct amount of blocks.") + // Beacon Activated Event + if (Skript.classExists("io.papermc.paper.event.block.BeaconActivatedEvent")) { + Skript.registerEvent("Beacon Activation", PaperEvents.class, BeaconActivatedEvent.class, "beacon (activate|activation)") + .description("Called when a beacon is successfully activated by having correct amount of blocks.", + "Removed if running Skript 2.10+ (now included in Skript).") .examples("on beacon activation", - "\tset primary effect of event-block to strength") + "\tset primary effect of event-block to strength") .since("2.16.0"); + } } if (Skript.classExists("io.papermc.paper.event.entity.EntityInsideBlockEvent")) { Skript.registerEvent("Entity Inside Block", PaperEvents.class, EntityInsideBlockEvent.class, "entity inside block") - .description("Called when an entity enters the hitbox of a block.", - "Only called for blocks that react when an entity is inside.", - "If cancelled, any action that would have resulted from that entity being in the block will not happen (such as extinguishing an entity in a cauldron).", - "Currently called for: Big dripleaf, Bubble column, Buttons, Cactus, Campfire, Cauldron, Crops, Ender Portal, Fires, Frogspawn, Honey, Hopper, Detector rails,", - "Nether portals, Pitcher crop, Powdered snow, Pressure plates, Sweet berry bush, Tripwire, Waterlily, Web, Wither rose") - .examples("on entity inside block:", - "\tif event-block is a cactus:", - "\t\tcancel event", - "\t\tbroadcast \"OUCHIE\"") - .since("3.4.0"); - - EventValues.registerEventValue(EntityInsideBlockEvent.class, Block.class, new Getter<>() { - @Override - public Block get(EntityInsideBlockEvent event) { - return event.getBlock(); - } - }, EventValues.TIME_NOW); + .description("Called when an entity enters the hitbox of a block.", + "Only called for blocks that react when an entity is inside.", + "If cancelled, any action that would have resulted from that entity being in the block will not happen (such as extinguishing an entity in a cauldron).", + "Currently called for: Big dripleaf, Bubble column, Buttons, Cactus, Campfire, Cauldron, Crops, Ender Portal, Fires, Frogspawn, Honey, Hopper, Detector rails,", + "Nether portals, Pitcher crop, Powdered snow, Pressure plates, Sweet berry bush, Tripwire, Waterlily, Web, Wither rose") + .examples("on entity inside block:", + "\tif event-block is a cactus:", + "\t\tcancel event", + "\t\tbroadcast \"OUCHIE\"") + .since("3.4.0"); + + EventValues.registerEventValue(EntityInsideBlockEvent.class, Block.class, EntityInsideBlockEvent::getBlock, EventValues.TIME_NOW); } // PlayerAttemptPickupItemEvent if (Skript.classExists("org.bukkit.event.player.PlayerAttemptPickupItemEvent")) { Skript.registerEvent("Player Attempt Item Pickup", PaperEvents.class, PlayerAttemptPickupItemEvent.class, "player attempt item pickup") - .description("Called when a player attempts to pick an item up from the ground. Requires PaperMC.", - "`event-number` = Represents the amount that will remain on the ground, if any.", - "`past event-number` = Represents the item amount of the dropped item before pickup.", - "`event-dropped item` = Represents the dropped item entity that is attempting to pickup.") - .examples("on player attempt item pickup:", - "\tif event-number > 0:", - "\t\twait 1 tick", - "\t\tadd (item of event-dropped item) to enderchest of player", - "\t\tkill event-dropped item") - .since("3.5.0"); - - EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Number.class, new Getter<>() { - @Override - public Number get(PlayerAttemptPickupItemEvent event) { - return event.getRemaining(); - } - }, EventValues.TIME_NOW); - - EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Number.class, new Getter<>() { - @Override - public Number get(PlayerAttemptPickupItemEvent event) { - return event.getItem().getItemStack().getAmount(); - } - }, EventValues.TIME_PAST); - - EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Item.class, new Getter<>() { - @Override - public Item get(PlayerAttemptPickupItemEvent event) { - return event.getItem(); - } - }, EventValues.TIME_NOW); + .description("Called when a player attempts to pick an item up from the ground. Requires PaperMC.", + "`event-number` = Represents the amount that will remain on the ground, if any.", + "`past event-number` = Represents the item amount of the dropped item before pickup.", + "`event-dropped item` = Represents the dropped item entity that is attempting to pickup.") + .examples("on player attempt item pickup:", + "\tif event-number > 0:", + "\t\twait 1 tick", + "\t\tadd (item of event-dropped item) to enderchest of player", + "\t\tkill event-dropped item") + .since("3.5.0"); + + EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Number.class, PlayerAttemptPickupItemEvent::getRemaining, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Number.class, event -> event.getItem().getItemStack().getAmount(), EventValues.TIME_PAST); + EventValues.registerEventValue(PlayerAttemptPickupItemEvent.class, Item.class, PlayerAttemptPickupItemEvent::getItem, EventValues.TIME_NOW); } // PlayerTrackEntityEvent @@ -387,12 +295,7 @@ public Item get(PlayerAttemptPickupItemEvent event) { "\t\tcancel event") .since("3.5.1"); - EventValues.registerEventValue(PlayerTrackEntityEvent.class, Entity.class, new Getter<>() { - @Override - public Entity get(PlayerTrackEntityEvent event) { - return event.getEntity(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerTrackEntityEvent.class, Entity.class, PlayerTrackEntityEvent::getEntity, EventValues.TIME_NOW); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/events/TabEvent.java b/src/main/java/com/shanebeestudios/skbee/elements/other/events/TabEvent.java index 8d9dc849e..7a9e73cb9 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/events/TabEvent.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/events/TabEvent.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; @@ -19,37 +18,27 @@ public class TabEvent extends SkriptEvent { static { Skript.registerEvent("Tab Complete", TabEvent.class, TabCompleteEvent.class, - "[skbee] tab complete [(of|for) %strings%]") - .description("Called when a player attempts to tab complete the arguments of a command. ", - "\nNOTE: Tab complete event is only called for the ARGUMENTS of a command, NOT the command itself.", - "\nevent-string = the command.") - .examples("on tab complete of \"/mycommand\":", - "\tset tab completions for position 1 to \"one\", \"two\" and \"three\"", - "\tset tab completions for position 2 to 1, 2 and 3", - "\tset tab completions for position 3 to all players", - "\tset tab completions for position 4 to (indexes of {blocks::*})", "", - "on tab complete:", - "\tif event-string contains \"/ver\":", - "\t\tclear tab completions") - .since("1.7.0"); - EventValues.registerEventValue(TabCompleteEvent.class, Player.class, new Getter<>() { - @Nullable - @Override - public Player get(@NotNull TabCompleteEvent event) { - CommandSender sender = event.getSender(); - if (sender instanceof Player) { - return ((Player) sender).getPlayer(); - } - return null; + "[skbee] tab complete [(of|for) %strings%]") + .description("Called when a player attempts to tab complete the arguments of a command. ", + "\nNOTE: Tab complete event is only called for the ARGUMENTS of a command, NOT the command itself.", + "\nevent-string = the command.") + .examples("on tab complete of \"/mycommand\":", + "\tset tab completions for position 1 to \"one\", \"two\" and \"three\"", + "\tset tab completions for position 2 to 1, 2 and 3", + "\tset tab completions for position 3 to all players", + "\tset tab completions for position 4 to (indexes of {blocks::*})", "", + "on tab complete:", + "\tif event-string contains \"/ver\":", + "\t\tclear tab completions") + .since("1.7.0"); + EventValues.registerEventValue(TabCompleteEvent.class, Player.class, event -> { + CommandSender sender = event.getSender(); + if (sender instanceof Player) { + return ((Player) sender).getPlayer(); } - }, 0); - EventValues.registerEventValue(TabCompleteEvent.class, String.class, new Getter<>() { - @Nullable - @Override - public String get(@NotNull TabCompleteEvent event) { - return event.getBuffer().split(" ")[0]; - } - }, 0); + return null; + }, EventValues.TIME_NOW); + EventValues.registerEventValue(TabCompleteEvent.class, String.class, event -> event.getBuffer().split(" ")[0], EventValues.TIME_NOW); } private String[] commands; @@ -67,7 +56,7 @@ public boolean check(@NotNull Event event) { TabCompleteEvent tabEvent = ((TabCompleteEvent) event); String command = tabEvent.getBuffer().split(" ")[0]; - if (command.length() == 0) return false; + if (command.isEmpty()) return false; if (command.charAt(0) == '/') { command = command.substring(1); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBiomeKeyLocation.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBiomeKeyLocation.java index 77a19f2b3..b1f703e0c 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBiomeKeyLocation.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBiomeKeyLocation.java @@ -7,6 +7,9 @@ import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; +import ch.njol.skript.lang.Expression; +import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -14,6 +17,7 @@ import org.bukkit.RegionAccessor; import org.bukkit.UnsafeValues; import org.bukkit.World; +import org.bukkit.block.Biome; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -40,6 +44,15 @@ public class ExprBiomeKeyLocation extends SimplePropertyExpression[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { + if (Biome.class.isInterface()) { + Skript.warning("Deprecated, you can just set the biome now."); + } + return super.init(expressions, matchedPattern, isDelayed, parseResult); + } + + @SuppressWarnings("removal") @Override public @Nullable NamespacedKey convert(Location from) { World world = from.getWorld(); @@ -49,14 +62,13 @@ public class ExprBiomeKeyLocation extends SimplePropertyExpression @Nullable [] acceptChange(ChangeMode mode) { if (mode == ChangeMode.SET) return CollectionUtils.array(NamespacedKey.class); return null; } - @SuppressWarnings({"NullableProblems", "ConstantValue"}) + @SuppressWarnings("removal") @Override public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { if (delta != null && delta[0] instanceof NamespacedKey key) { @@ -64,7 +76,7 @@ public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { World world = loc.getWorld(); if (world != null) { try { - UNSAFE.setBiomeKey(world, loc.blockX(), loc.blockY(), loc.blockZ(), key); + UNSAFE.setBiomeKey(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), key); } catch (IllegalStateException ignore) { } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBreedEntities.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBreedEntities.java index c7efb604d..317d8ef78 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBreedEntities.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprBreedEntities.java @@ -12,6 +12,7 @@ import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.skript.log.ErrorQuality; import ch.njol.util.Kleenean; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.Entity; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityBreedEvent; @@ -19,17 +20,20 @@ import org.jetbrains.annotations.Nullable; @Name("Breed Event Entities") -@Description("Get the entities involved in a breed event.") +@Description({"Get the entities involved in a breed event.", + "Removed if running Skript 2.10+ (now included in Skript).",}) @Examples({"on entity breed:", - "\tif breeding mother is a sheep:", - "\t\tkill breeding player"}) + "\tif breeding mother is a sheep:", + "\t\tkill breeding player"}) @Since("1.17.0") public class ExprBreedEntities extends SimpleExpression { static { - Skript.registerExpression(ExprBreedEntities.class, Entity.class, ExpressionType.SIMPLE, + if (!Util.IS_RUNNING_SKRIPT_2_10) { + Skript.registerExpression(ExprBreedEntities.class, Entity.class, ExpressionType.SIMPLE, "[the] breed[ing] parents", "[the] breed[ing] (mother|1:father|2:baby|3:player)"); + } } private int pattern; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprEntityVisibility.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprEntityVisibility.java index d60aeb12d..52d3114a2 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprEntityVisibility.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprEntityVisibility.java @@ -9,7 +9,6 @@ import ch.njol.skript.expressions.base.PropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.util.Getter; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.entity.ArmorStand; @@ -24,8 +23,8 @@ @Name("Entity Visibility") @Description("Get/set visibility for entities. Armor stands on all versions, ItemFrames on 1.15+ and LivingEntities on 1.16.3+") @Examples({"set visibility of target entity to false", - "set {_v} to visibility of target entity", - "if visibility of target entity is true:"}) + "set {_v} to visibility of target entity", + "if visibility of target entity is true:"}) @Since("1.7.0") public class ExprEntityVisibility extends PropertyExpression { @@ -47,23 +46,18 @@ public boolean init(Expression @NotNull [] exprs, int matchedPattern, @NotNul @Override protected Boolean @NotNull [] get(@NotNull Event e, Entity @NotNull [] source) { - return get(source, new Getter<>() { - @Nullable - @Override - public Boolean get(@NotNull Entity entity) { - if (entity instanceof ArmorStand armorStand) { - return armorStand.isVisible(); - } else if (entity instanceof ItemFrame itemFrame && ITEM_FRAME) { - return itemFrame.isVisible(); - } else if (entity instanceof LivingEntity livingEntity && LIVING_ENTITY) { - return !livingEntity.isInvisible(); - } - return null; + return get(source, entity -> { + if (entity instanceof ArmorStand armorStand) { + return armorStand.isVisible(); + } else if (entity instanceof ItemFrame itemFrame && ITEM_FRAME) { + return itemFrame.isVisible(); + } else if (entity instanceof LivingEntity livingEntity && LIVING_ENTITY) { + return !livingEntity.isInvisible(); } + return null; }); } - @SuppressWarnings("NullableProblems") @Override public Class[] acceptChange(@NotNull ChangeMode mode) { if (mode == ChangeMode.SET) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlags.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlags.java index cd1d8e7e0..af5772df5 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlags.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlags.java @@ -11,6 +11,7 @@ import ch.njol.skript.lang.SkriptParser; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.event.Event; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.meta.ItemMeta; @@ -22,20 +23,23 @@ import java.util.Set; @Name("ItemFlag - ItemFlags of Items") -@Description("Get/Set the ItemFlags of an item.") +@Description({"Get/Set the ItemFlags of an item.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples({"set {_flags::*} to item flags of player's tool", - "add hide enchants to item flags of player's tool", - "add hide attributes to item flags of player's tool", - "add hide enchants and hide attributes to item flags of player's tool", - "remove hide enchants from item flags of player's tool", - "remove hide attributes from item flags of player's tool", - "delete item flags of player's tool", - "reset item flags of player's tool"}) + "add hide enchants to item flags of player's tool", + "add hide attributes to item flags of player's tool", + "add hide enchants and hide attributes to item flags of player's tool", + "remove hide enchants from item flags of player's tool", + "remove hide attributes from item flags of player's tool", + "delete item flags of player's tool", + "reset item flags of player's tool"}) @Since("3.4.0") public class ExprItemFlags extends PropertyExpression { static { - register(ExprItemFlags.class, ItemFlag.class, "item[ ]flags", "itemtypes"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(ExprItemFlags.class, ItemFlag.class, "item[ ]flags", "itemtypes"); + } } @SuppressWarnings({"NullableProblems", "unchecked"}) diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlagsItem.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlagsItem.java index abcf5ddb0..a08e9ebf3 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlagsItem.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFlagsItem.java @@ -11,6 +11,7 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.event.Event; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.meta.ItemMeta; @@ -18,21 +19,24 @@ import org.jetbrains.annotations.Nullable; @Name("ItemFlag - Item with ItemFlags") -@Description("Get an item with ItemFlags.") +@Description({"Get an item with ItemFlags.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples({"set {_sword} to diamond sword with all item flags", - "set {_sword} to diamond sword of sharpness 3 with hide enchants item flag", - "set {_sword} to diamond sword of sharpness 3 with item flag hide enchants", - "give player fishing rod of lure 10 with item flag hide enchants", - "give player potion of extended regeneration with hide enchants itemflag", - "give player netherite leggings with itemflag hide attributes"}) + "set {_sword} to diamond sword of sharpness 3 with hide enchants item flag", + "set {_sword} to diamond sword of sharpness 3 with item flag hide enchants", + "give player fishing rod of lure 10 with item flag hide enchants", + "give player potion of extended regeneration with hide enchants itemflag", + "give player netherite leggings with itemflag hide attributes"}) @Since("3.4.0") public class ExprItemFlagsItem extends SimpleExpression { static { - Skript.registerExpression(ExprItemFlagsItem.class, ItemType.class, ExpressionType.COMBINED, + if (!Util.IS_RUNNING_SKRIPT_2_10) { + Skript.registerExpression(ExprItemFlagsItem.class, ItemType.class, ExpressionType.COMBINED, "%itemtype% with all item[ ]flags", "%itemtype% with item[ ]flag[s] %itemflags%", "%itemtype% with %itemflags% item[ ]flag[s]"); + } } private int pattern; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFromNamespacedKey.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFromNamespacedKey.java index 2bfa31d93..efc38e3cd 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFromNamespacedKey.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprItemFromNamespacedKey.java @@ -2,7 +2,6 @@ import ch.njol.skript.Skript; import ch.njol.skript.aliases.ItemType; -import ch.njol.skript.bukkitutil.BukkitUnsafe; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; @@ -14,6 +13,7 @@ import ch.njol.util.Kleenean; import org.bukkit.Material; import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.block.data.BlockData; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; @@ -25,31 +25,29 @@ @Name("ItemType From NamespacedKey/BlockData") @Description("Get an ItemType from a Minecraft namespaced key or BlockData.") @Examples({"set {_i} to itemtype from namespaced key from \"minecraft:stone\"", - "set {_i} to itemtype from block data of target block"}) + "set {_i} to itemtype from block data of target block"}) @Since("2.10.0") public class ExprItemFromNamespacedKey extends SimpleExpression { static { Skript.registerExpression(ExprItemFromNamespacedKey.class, ItemType.class, ExpressionType.PROPERTY, - "item[ ]type[s] (from|of) %namespacedkeys/blockdatas%"); + "item[ ]type[s] (from|of) %namespacedkeys/blockdatas%"); } private Expression objects; - @SuppressWarnings({"NullableProblems"}) @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.objects = exprs[0]; return true; } - @SuppressWarnings("NullableProblems") @Override protected @Nullable ItemType[] get(Event event) { List itemTypes = new ArrayList<>(); for (Object object : this.objects.getArray(event)) { if (object instanceof NamespacedKey namespacedKey) { - Material material = BukkitUnsafe.getMaterialFromMinecraftId(namespacedKey.toString()); + Material material = Registry.MATERIAL.get(namespacedKey); if (material == null) continue; itemTypes.add(new ItemType(material)); } else if (object instanceof BlockData blockData) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprLastDeathLocation.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprLastDeathLocation.java index dec867c46..8f67f7f9f 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprLastDeathLocation.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprLastDeathLocation.java @@ -7,6 +7,7 @@ import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.util.coll.CollectionUtils; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -15,15 +16,19 @@ import org.jetbrains.annotations.Nullable; @Name("Death Location of Player") -@Description("Represents the last death location of player. Set/Delete will only work for online players not offline players.") +@Description({"Represents the last death location of player.", + "Set/Delete will only work for online players not offline players.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples({"command /death:", - "\ttrigger:", - "\t\tteleport player to last death location of player"}) + "\ttrigger:", + "\t\tteleport player to last death location of player"}) @Since("2.8.5") public class ExprLastDeathLocation extends SimplePropertyExpression { static { - register(ExprLastDeathLocation.class, Location.class, "[last ]death location", "offlineplayers"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(ExprLastDeathLocation.class, Location.class, "[last ]death location", "offlineplayers"); + } } @Override diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPlayerTime.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPlayerTime.java index 1423a7b9b..2632a6018 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPlayerTime.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPlayerTime.java @@ -19,23 +19,23 @@ @Name("Player Time") @Description({"Represents the current time on the player's client.", - "When relative is used the player's time will be kept synchronized to its world time with the specified offset.", - "When using non-relative time the player's time will stay fixed at the specified time parameter.", - "It's up to the caller to continue updating the player's time.", - "To restore player time to normal use reset.", - "Both Time and TimeSpan can be used for this. It is best to use Time for non-relative and TimeSpan for relative.", - "Relative will return as a TimeSpan (the offset from world time), non-relative will return as a Time."}) + "When relative is used the player's time will be kept synchronized to its world time with the specified offset.", + "When using non-relative time the player's time will stay fixed at the specified time parameter.", + "It's up to the caller to continue updating the player's time.", + "To restore player time to normal use reset.", + "Both Time and TimeSpan can be used for this. It is best to use Time for non-relative and TimeSpan for relative.", + "Relative will return as a TimeSpan (the offset from world time), non-relative will return as a Time."}) @Examples({"set player time of player to 12:00am", - "set player time of all players to 6pm", - "set relative player time of player to 12000 ticks", - "set relative player time of player to 10 minutes", - "set relative player time of all players to 6000 ticks", - "add 10 minutes to player time of player", - "add 1 minute to relative player time of player", - "remove 10 minutes from player time of all players", - "remove 1 minute from relative player time of player", - "reset player time of player", - "reset player time of all players"}) + "set player time of all players to 6pm", + "set relative player time of player to 12000 ticks", + "set relative player time of player to 10 minutes", + "set relative player time of all players to 6000 ticks", + "add 10 minutes to player time of player", + "add 1 minute to relative player time of player", + "remove 10 minutes from player time of all players", + "remove 1 minute from relative player time of player", + "reset player time of player", + "reset player time of all players"}) @Since("3.3.0") public class ExprPlayerTime extends SimplePropertyExpression { @@ -56,7 +56,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye @Override public @Nullable Object convert(Player player) { if (this.relative) { - return Timespan.fromTicks(player.getPlayerTimeOffset()); + return new Timespan(Timespan.TimePeriod.TICK, player.getPlayerTimeOffset()); } return new Time((int) player.getPlayerTime()); } @@ -72,7 +72,6 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return null; } - @SuppressWarnings({"NullableProblems", "ConstantValue"}) @Override public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { if (mode == ChangeMode.RESET) { @@ -82,7 +81,7 @@ public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { } else if (delta != null) { int ticks = 0; if (delta[0] instanceof Timespan timespan) { - ticks = (int) timespan.getTicks(); + ticks = (int) timespan.getAs(Timespan.TimePeriod.TICK); } else if (delta[0] instanceof Time time) { ticks = time.getTicks(); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPotionEffectDuration.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPotionEffectDuration.java index f64442cce..b162e3094 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPotionEffectDuration.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprPotionEffectDuration.java @@ -12,7 +12,7 @@ @Name("Potion Effect Duration") @Description({"Get the duration of a potion effect. If running 1.19.4+ and the potion is infinite,", - "it will return as the max available time."}) + "it will return as the max available time."}) @Examples("set {_duration::*} to potion duration of active potion effects of player") @Since("2.8.5") public class ExprPotionEffectDuration extends SimplePropertyExpression { @@ -26,7 +26,7 @@ public class ExprPotionEffectDuration extends SimplePropertyExpression= 20. Default is 10 ticks.", - "\nUnsaturated = When they have no saturation and their food level >= 18. Default is 80 ticks."}) + "\nSaturated = When they have saturation and their food level >= 20. Default is 10 ticks.", + "\nUnsaturated = When they have no saturation and their food level >= 18. Default is 80 ticks."}) @Examples({"set {_regen} to saturated regen rate of player", - "set unsaturated regen rate of player to 10 ticks", - "add 1 second to unsaturated regen rate of player"}) + "set unsaturated regen rate of player to 10 ticks", + "add 1 second to unsaturated regen rate of player"}) @Since("3.0.2") public class ExprRegenRate extends SimplePropertyExpression { static { if (Skript.methodExists(HumanEntity.class, "getSaturatedRegenRate")) { register(ExprRegenRate.class, Timespan.class, - "[:un]saturated regen[eration] rate", "players"); + "[:un]saturated regen[eration] rate", "players"); } } private boolean saturated; - @SuppressWarnings("NullableProblems") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.saturated = !parseResult.hasTag("un"); @@ -47,10 +46,9 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye @Override public @Nullable Timespan convert(Player player) { int ticks = this.saturated ? player.getSaturatedRegenRate() : player.getUnsaturatedRegenRate(); - return Timespan.fromTicks(ticks); + return new Timespan(Timespan.TimePeriod.TICK, ticks); } - @SuppressWarnings("NullableProblems") @Override public Class @Nullable [] acceptChange(ChangeMode mode) { return switch (mode) { @@ -60,13 +58,12 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye }; } - @SuppressWarnings({"NullableProblems", "ConstantValue"}) @Override public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { int changeValue; if (mode == ChangeMode.RESET) changeValue = this.saturated ? 10 : 80; else if (delta != null && delta[0] instanceof Timespan timespan) { - changeValue = (int) timespan.getTicks(); + changeValue = (int) timespan.getAs(Timespan.TimePeriod.TICK); } else return; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprSpawnerSpawnDelay.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprSpawnerSpawnDelay.java index f78ef2f8a..e352d6292 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprSpawnerSpawnDelay.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprSpawnerSpawnDelay.java @@ -20,13 +20,13 @@ @Name("Spawner - Spawn Delay") @Description({"The delay between a spawner spawning a new entity.", - "Maximum default is 800 ticks (40 seconds).", - "Minimum default is 200 ticks (10 seconds)."}) + "Maximum default is 800 ticks (40 seconds).", + "Minimum default is 200 ticks (10 seconds)."}) @Examples({"on place of mob spawner:", - "\tset spawner spawn delay of event-block to 3 seconds", - "\tadd 100 to max spawn delay of event-block", - "\tremove 1 second from min spawn delay of event-block", - "\treset spawn delay of event-block"}) + "\tset spawner spawn delay of event-block to 3 seconds", + "\tadd 100 to max spawn delay of event-block", + "\tremove 1 second from min spawn delay of event-block", + "\treset spawn delay of event-block"}) @Since("2.16.0") public class ExprSpawnerSpawnDelay extends SimplePropertyExpression { @@ -53,7 +53,7 @@ public Timespan convert(Block block) { case TRUE -> spawner.getMaxSpawnDelay(); default -> spawner.getDelay(); }; - return Timespan.fromTicks(delay); + return new Timespan(Timespan.TimePeriod.TICK, delay); } return null; } @@ -61,7 +61,7 @@ public Timespan convert(Block block) { @Override public @Nullable Class[] acceptChange(ChangeMode mode) { return switch (mode) { - case SET, ADD, REMOVE -> CollectionUtils.array(Timespan.class, Integer.class); + case SET, ADD, REMOVE -> CollectionUtils.array(Timespan.class, Number.class); case RESET -> CollectionUtils.array(); default -> null; }; @@ -71,7 +71,8 @@ public Timespan convert(Block block) { public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { int changeValue = 0; if (delta != null) { - changeValue += delta[0] instanceof Timespan timespan ? timespan.getTicks() : ((Integer) delta[0]); + if (delta[0] instanceof Timespan timespan) changeValue = (int) timespan.getAs(Timespan.TimePeriod.TICK); + else if (delta[0] instanceof Number number) changeValue = number.intValue(); } else { changeValue = switch (action) { case TRUE -> DEFAULT_MAX_TICKS; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTimeSpanNumbers.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTimeSpanNumbers.java index bb6c284e5..996198261 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTimeSpanNumbers.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTimeSpanNumbers.java @@ -28,7 +28,7 @@ public class ExprTimeSpanNumbers extends SimplePropertyExpression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.pattern = parseResult.mark; @@ -38,7 +38,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye @Override public @Nullable Number convert(Timespan timespan) { - long ticks = timespan.getTicks(); + long ticks = timespan.getAs(Timespan.TimePeriod.TICK); return switch (pattern) { case 1 -> (ticks / 20); case 2 -> (ticks / 20 / 60); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTransferCookie.java b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTransferCookie.java index 621946eb3..e8144b78d 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTransferCookie.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/expressions/ExprTransferCookie.java @@ -8,20 +8,22 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser.ParseResult; +import ch.njol.skript.lang.parser.ParserInstance; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; +import com.shanebeestudios.skbee.elements.other.sections.SecTransferCookieRetrieve; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Name("Transfer - Transfer Cookie") -@Description("Represents the cookie data in a transfer section.") +@Description("Represents the cookie data in a retrieve cookie section.") @Examples({"command /server :", "\ttrigger:", "\t\tstore cookie \"%uuid of player%-transfer\" with key \"transfer\" on player", "\t\ttransfer player to arg-1", "", - "on join:", + "on connect:", "\t# only do a cookie check if player was transferred", "\tif player is transferred:", "\t\tretrieve cookie with key \"transfer\" from player:", @@ -47,6 +49,10 @@ public static void setLastTransferCookie(String transferCookie) { @SuppressWarnings("NullableProblems") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { + if (!ParserInstance.get().isCurrentSection(SecTransferCookieRetrieve.class)) { + Skript.error("'transfer cookie' can only be used in a 'retrieve cookie' section."); + return false; + } return true; } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecRunTaskLater.java b/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecRunTaskLater.java index ce9b0e73c..af8af8cb4 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecRunTaskLater.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecRunTaskLater.java @@ -9,7 +9,6 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.Section; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.Trigger; import ch.njol.skript.lang.TriggerItem; import ch.njol.skript.lang.parser.ParserInstance; import ch.njol.skript.util.Timespan; @@ -28,24 +27,24 @@ @Name("Task - Run Task Later") @Description({"Run a task later. Similar to Skript's delay effect, with the difference being everything in the", - "section is run later. All code after your section will keep running as normal without a delay.", - "This can be very useful in loops, to prevent halting the loop.", - "You can optionally have your task repeat until cancelled.", - "You can optionally run your code async/on another thread.", - "\nNOTE: A good chunk of Bukkit/Minecraft stuff can NOT be run async. It may throw console errors.", - "Please be careful when running async, this is generally reserved for heavy math/functions that could cause lag.", - "Simply waiting a tick, or running a new non-async section will put your code back on the main thread."}) + "section is run later. All code after your section will keep running as normal without a delay.", + "This can be very useful in loops, to prevent halting the loop.", + "You can optionally have your task repeat until cancelled.", + "You can optionally run your code async/on another thread.", + "\nNOTE: A good chunk of Bukkit/Minecraft stuff can NOT be run async. It may throw console errors.", + "Please be careful when running async, this is generally reserved for heavy math/functions that could cause lag.", + "Simply waiting a tick, or running a new non-async section will put your code back on the main thread."}) @Examples({"on explode:", - "\tloop exploded blocks:", - "\t\tset {_loc} to location of loop-block", - "\t\tset {_data} to block data of loop-block", - "\t\trun 2 seconds later:", - "\t\t\tset block at {_loc} to {_data}\n", - "", - "run 0 ticks later repeating every second:", - "\tadd 1 to {_a}", - "\tif {_a} > 10:", - "\t\tstop current task"}) + "\tloop exploded blocks:", + "\t\tset {_loc} to location of loop-block", + "\t\tset {_data} to block data of loop-block", + "\t\trun 2 seconds later:", + "\t\t\tset block at {_loc} to {_data}\n", + "", + "run 0 ticks later repeating every second:", + "\tadd 1 to {_a}", + "\tif {_a} > 10:", + "\t\tstop current task"}) @Since("3.0.0") public class SecRunTaskLater extends Section { @@ -57,16 +56,15 @@ public static void cancelTasks() { static { Skript.registerSection(SecRunTaskLater.class, - "[:async] (run|execute) [task] %timespan% later [repeating every %-timespan%]"); + "[:async] (run|execute) [task] %timespan% later [repeating every %-timespan%]"); } private boolean async; private Expression timespan; private Expression repeating; - private Trigger trigger; private int currentTaskId; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult, SectionNode sectionNode, List triggerItems) { this.async = parseResult.hasTag("async"); @@ -80,17 +78,16 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return true; } - @SuppressWarnings({"NullableProblems", "DataFlowIssue"}) @Override protected @Nullable TriggerItem walk(Event event) { Object localVars = Variables.copyLocalVariables(event); Timespan timespan = this.timespan.getSingle(event); - long delay = timespan != null ? timespan.getTicks() : 0; + long delay = timespan != null ? timespan.getAs(Timespan.TimePeriod.TICK) : 0; long repeat = 0; if (this.repeating != null) { Timespan repeatingTimespan = this.repeating.getSingle(event); - if (repeatingTimespan != null) repeat = repeatingTimespan.getTicks(); + if (repeatingTimespan != null) repeat = repeatingTimespan.getAs(Timespan.TimePeriod.TICK); } BukkitScheduler scheduler = Bukkit.getScheduler(); @@ -125,7 +122,6 @@ public int getCurrentTaskId() { return this.currentTaskId; } - @SuppressWarnings("DataFlowIssue") @Override public @NotNull String toString(@Nullable Event e, boolean d) { String async = this.async ? "async " : ""; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecTransferCookieRetrieve.java b/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecTransferCookieRetrieve.java index cb7797f02..b97ab0665 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecTransferCookieRetrieve.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/sections/SecTransferCookieRetrieve.java @@ -6,6 +6,7 @@ import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; +import ch.njol.skript.effects.Delay; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.Section; import ch.njol.skript.lang.SkriptParser.ParseResult; @@ -27,14 +28,13 @@ @Description({"Retrieve a cookie from a player. Requires Minecraft 1.20.5+", "Due to the retrieval process happening async, this will delay proceeding code.", "While the cookie is being retrieved, the following code will wait.", - "If there is no available cookie, the section will not execute.", "NOTE: Cookies are stored across server transfers."}) @Examples({"command /server :", "\ttrigger:", "\t\tstore cookie \"%uuid of player%-transfer\" with key \"transfer\" on player", "\t\ttransfer player to arg-1", "", - "on join:", + "on connect:", "\t# only do a cookie check if player was transferred", "\tif player is transferred:", "\t\tretrieve cookie with key \"transfer\" from player:", @@ -47,8 +47,10 @@ public class SecTransferCookieRetrieve extends Section { static { + if (Skript.methodExists(Player.class, "retrieveCookie", NamespacedKey.class)) { Skript.registerSection(SecTransferCookieRetrieve.class, - "retrieve cookie with key %namespacedkey/string% from %player%"); + "retrieve cookie with key %namespacedkey/string% [from %player%]"); + } } private Expression key; @@ -73,49 +75,44 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye protected @Nullable TriggerItem walk(Event event) { TriggerItem next = getNext(); - //Let's save you guys for later after the cookie has loaded - Object localVars = Variables.removeLocals(event); + // Let's save you guys for later after the cookie has loaded + Object localVars = Variables.copyLocalVariables(event); Player player = this.player.getSingle(event); Object keyObject = this.key.getSingle(event); if (player == null || keyObject == null) return next; - NamespacedKey key; + NamespacedKey key = null; if (keyObject instanceof String string) { key = Util.getNamespacedKey(string, false); } else if (keyObject instanceof NamespacedKey namespacedKey) { key = namespacedKey; - } else { - return next; } if (key == null) return next; player.retrieveCookie(key).thenAccept(bytes -> { - String cookie = new String(bytes); - ExprTransferCookie.setLastTransferCookie(cookie); - walkNext(localVars, event, first, next); + Delay.addDelayedEvent(event); // Delay event to make sure kick effect still works + ExprTransferCookie.setLastTransferCookie(new String(bytes)); + // Walk the section + walkNext(localVars, event, first); + // Clear cookie data before moving on + ExprTransferCookie.setLastTransferCookie(null); }).exceptionally(throwable -> { - walkNext(localVars, event, null, next); + // Walk the section even if no cookie was found + walkNext(localVars, event, first); return null; }); return null; } - private static void walkNext(Object localVars, Event event, @Nullable TriggerItem sec, TriggerItem next) { - //re-set local variables + private static void walkNext(Object localVars, Event event, @Nullable TriggerItem triggerItem) { + // re-set local variables if (localVars != null) Variables.setLocalVariables(event, localVars); - // walk section - if (sec != null) { - // walk the section - TriggerItem.walk(sec, event); - // Clear cookie data before moving on - ExprTransferCookie.setLastTransferCookie(null); + if (triggerItem != null) { + TriggerItem.walk(triggerItem, event); } - // walk next trigger - else if (next != null) TriggerItem.walk(next, event); - // remove local vars as we're now done Variables.removeLocals(event); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/other/type/Types.java b/src/main/java/com/shanebeestudios/skbee/elements/other/type/Types.java index a0fdc2c40..2cad11676 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/other/type/Types.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/other/type/Types.java @@ -58,18 +58,21 @@ public class Types { public static boolean HAS_CHUNK_LOAD_LEVEL = Skript.classExists("org.bukkit.Chunk$LoadLevel"); static { - if (Classes.getExactClassInfo(ItemFlag.class) == null) { - EnumWrapper ITEM_FLAGS = new EnumWrapper<>(ItemFlag.class); - Classes.registerClass(ITEM_FLAGS.getClassInfo("itemflag") - .user("item ?flags?") - .name("ItemFlag") - .description("Represents the different ItemFlags that can be applied to an item.", - "NOTE: Underscores aren't required, you CAN use spaces.", - "NOTE: These are auto-generated and may differ between server versions.") - .since("3.4.0")); - } else { - Util.logLoading("It looks like another addon registered 'itemflag' already."); - Util.logLoading("You may have to use their ItemFlags in SkBee's 'Item Flags' expressions."); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + if (Classes.getExactClassInfo(ItemFlag.class) == null) { + EnumWrapper ITEM_FLAGS = new EnumWrapper<>(ItemFlag.class); + Classes.registerClass(ITEM_FLAGS.getClassInfo("itemflag") + .user("item ?flags?") + .name("ItemFlag") + .description("Represents the different ItemFlags that can be applied to an item.", + "Removed if running Skript 2.10+ (now included in Skript).", + "NOTE: Underscores aren't required, you CAN use spaces.", + "NOTE: These are auto-generated and may differ between server versions.") + .since("3.4.0")); + } else { + Util.logLoading("It looks like another addon registered 'itemflag' already."); + Util.logLoading("You may have to use their ItemFlags in SkBee's 'Item Flags' expressions."); + } } // Only register if no other addons have registered this class @@ -88,17 +91,20 @@ public class Types { // Only register if no other addons have registered this class // EntityPotionEffectEvent.Cause - if (Classes.getExactClassInfo(Cause.class) == null) { - EnumWrapper POTION_EFFECT_EVENT_CAUSE = new EnumWrapper<>(Cause.class, "", "effect"); - Classes.registerClass(POTION_EFFECT_EVENT_CAUSE.getClassInfo("potioneffectcause") - .user("potion ?effect ?causes?") - .name("Potion Effect Cause") - .description("Represents the different causes of an entity potion effect event.", - "NOTE: These are auto-generated and may differ between server versions.") - .since("1.17.0")); - } else { - Util.logLoading("It looks like another addon registered 'potioneffectcause' already."); - Util.logLoading("You may have to use their potion effect causes in SkBee's 'Entity Potion Effect' event."); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + if (Classes.getExactClassInfo(Cause.class) == null) { + EnumWrapper POTION_EFFECT_EVENT_CAUSE = new EnumWrapper<>(Cause.class, "", "effect"); + Classes.registerClass(POTION_EFFECT_EVENT_CAUSE.getClassInfo("potioneffectcause") + .user("potion ?effect ?causes?") + .name("Potion Effect Cause") + .description("Represents the different causes of an entity potion effect event.", + "Removed if running Skript 2.10+ (now included in Skript).", + "NOTE: These are auto-generated and may differ between server versions.") + .since("1.17.0")); + } else { + Util.logLoading("It looks like another addon registered 'potioneffectcause' already."); + Util.logLoading("You may have to use their potion effect causes in SkBee's 'Entity Potion Effect' event."); + } } if (Classes.getExactClassInfo(NamespacedKey.class) == null) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/particle/type/Types.java b/src/main/java/com/shanebeestudios/skbee/elements/particle/type/Types.java index c414819ae..44b21d28b 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/particle/type/Types.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/particle/type/Types.java @@ -38,8 +38,6 @@ public class Types { .after("itemtype") .since("1.9.0") .parser(new Parser<>() { - - @SuppressWarnings("NullableProblems") @Nullable @Override public Particle parse(String s, ParseContext context) { @@ -48,7 +46,7 @@ public Particle parse(String s, ParseContext context) { @Override public @NotNull String toString(Particle particle, int flags) { - return "" + ParticleUtil.getName(particle); + return ParticleUtil.getName(particle); } @Override @@ -65,7 +63,6 @@ public Particle parse(String s, ParseContext context) { Classes.registerClass(new ClassInfo<>(Particle.DustOptions.class, "dustoption") .name(ClassInfo.NO_DOC).user("dust ?options?") .parser(new Parser<>() { - @SuppressWarnings("NullableProblems") @Override public boolean canParse(ParseContext context) { return false; @@ -123,7 +120,6 @@ public boolean canParse(ParseContext context) { new Parameter<>("color", DefaultClasses.COLOR, true, null), new Parameter<>("size", DefaultClasses.NUMBER, true, null) }, Classes.getExactClassInfo(Particle.DustOptions.class), true) { - @SuppressWarnings("NullableProblems") @Override public Particle.DustOptions[] executeSimple(Object[][] params) { org.bukkit.Color color = ((Color) params[0][0]).asBukkitColor(); @@ -143,7 +139,6 @@ public Particle.DustOptions[] executeSimple(Object[][] params) { new Parameter<>("toColor", DefaultClasses.COLOR, true, null), new Parameter<>("size", DefaultClasses.NUMBER, true, null) }, Classes.getExactClassInfo(DustTransition.class), true) { - @SuppressWarnings("NullableProblems") @Override public DustTransition[] executeSimple(Object[][] params) { org.bukkit.Color fromColor = ((Color) params[0][0]).asBukkitColor(); @@ -163,7 +158,6 @@ public DustTransition[] executeSimple(Object[][] params) { new Parameter<>("to", DefaultClasses.LOCATION, true, null), new Parameter<>("arrivalTime", DefaultClasses.TIMESPAN, true, null) }, Classes.getExactClassInfo(Vibration.class), true) { - @SuppressWarnings({"NullableProblems", "removal"}) @Override public Vibration[] executeSimple(Object[][] params) { if (params[0].length == 0 || params[1].length == 0) { @@ -172,7 +166,7 @@ public Vibration[] executeSimple(Object[][] params) { // Apparently original location makes no difference Location origin = new Location(null, 0, 0, 0); Location destination = (Location) params[0][0]; - int arrivalTime = (int) ((Timespan) params[1][0]).getTicks(); + int arrivalTime = (int) ((Timespan) params[1][0]).getAs(Timespan.TimePeriod.TICK); Vibration vibration = new Vibration(origin, new Vibration.Destination.BlockDestination(destination), arrivalTime); return new Vibration[]{vibration}; } @@ -184,19 +178,17 @@ public Vibration[] executeSimple(Object[][] params) { .since("1.11.1")); if (ParticleUtil.HAS_TRAIL) { - //noinspection DataFlowIssue Functions.registerFunction(new SimpleJavaFunction<>("trail", new Parameter[]{ new Parameter<>("target", DefaultClasses.LOCATION, true, null), new Parameter<>("color", DefaultClasses.COLOR, true, null), new Parameter<>("duration", DefaultClasses.TIMESPAN, true, null) }, Classes.getExactClassInfo(Particle.Trail.class), true) { - @SuppressWarnings("NullableProblems") @Override public Particle.Trail[] executeSimple(Object[][] params) { Location target = (Location) params[0][0]; org.bukkit.Color color = ((Color) params[1][0]).asBukkitColor(); Timespan timespan = (Timespan) params[2][0]; - return new Particle.Trail[]{new Particle.Trail(target, color, (int) timespan.getTicks())}; + return new Particle.Trail[]{new Particle.Trail(target, color, (int) timespan.getAs(Timespan.TimePeriod.TICK))}; } }).description("Creates a new trail to be used with 'trail' particle.", "Takes in a location for the target (where the trail heads to), the color and duration.", diff --git a/src/main/java/com/shanebeestudios/skbee/elements/recipe/effects/EffCookingRecipe.java b/src/main/java/com/shanebeestudios/skbee/elements/recipe/effects/EffCookingRecipe.java index 4505ef31a..35ba7d645 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/recipe/effects/EffCookingRecipe.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/recipe/effects/EffCookingRecipe.java @@ -30,18 +30,17 @@ import org.bukkit.inventory.RecipeChoice.MaterialChoice; import org.bukkit.inventory.SmokingRecipe; -@SuppressWarnings({"NullableProblems", "ConstantConditions"}) @Name("Recipe - Cooking") @Description({"Register new cooking recipes. On 1.13+ you can register recipes for furnaces.", - "On 1.14+ you can also register recipes for smokers, blast furnaces and campfires.", - "The ID will be the name given to this recipe. IDs may only contain letters, numbers, periods, hyphens, a single colon and underscores,", - "NOT SPACES!!! By default, if no namespace is provided, recipes will start with the namespace \"skbee:\",", - "this can be changed in the config to whatever you want. IDs are used for recipe discovery/unlocking recipes for players.", - "You may also include an optional group for recipes. These will group the recipes together in the recipe book.",}) + "On 1.14+ you can also register recipes for smokers, blast furnaces and campfires.", + "The ID will be the name given to this recipe. IDs may only contain letters, numbers, periods, hyphens, a single colon and underscores,", + "NOT SPACES!!! By default, if no namespace is provided, recipes will start with the namespace \"skbee:\",", + "this can be changed in the config to whatever you want. IDs are used for recipe discovery/unlocking recipes for players.", + "You may also include an optional group for recipes. These will group the recipes together in the recipe book.",}) @Examples({"on skript load:", - "\tregister new furnace recipe for diamond using dirt with id \"furnace_diamond\"", - "\tregister new blasting recipe for emerald using dirt with id \"my_recipes:blasting_emerald\"", - "\tregister new smoking recipe for cooked cod named \"Hot Cod\" using puffer fish with id \"smoking_cod\""}) + "\tregister new furnace recipe for diamond using dirt with id \"furnace_diamond\"", + "\tregister new blasting recipe for emerald using dirt with id \"my_recipes:blasting_emerald\"", + "\tregister new smoking recipe for cooked cod named \"Hot Cod\" using puffer fish with id \"smoking_cod\""}) @RequiredPlugins("1.13+ for furnaces. 1.14+ for smokers, blast furnaces and campfires.") @Since("1.0.0") public class EffCookingRecipe extends Effect { @@ -50,12 +49,11 @@ public class EffCookingRecipe extends Effect { static { Skript.registerEffect(EffCookingRecipe.class, - "register [new] (furnace|1:(blast furnace|blasting)|2:smok(er|ing)|3:campfire) recipe for %itemtype% " + - "(using|with ingredient) %itemtype/recipechoice% with id %string% [[and ]with exp[erience] %-number%] " + - "[[and ]with cook[ ]time %-timespan%] [in group %-string%]"); + "register [new] (furnace|1:(blast furnace|blasting)|2:smok(er|ing)|3:campfire) recipe for %itemtype% " + + "(using|with ingredient) %itemtype/recipechoice% with id %string% [[and ]with exp[erience] %-number%] " + + "[[and ]with cook[ ]time %-timespan%] [in group %-string%]"); } - @SuppressWarnings("null") private Expression item; private Expression ingredient; private Expression key; @@ -81,6 +79,7 @@ public boolean init(Expression[] exprs, int i, Kleenean kleenean, ParseResult protected void execute(Event event) { ItemType res = this.item.getSingle(event); Object ing = this.ingredient.getSingle(event); + String keyString = this.key.getSingle(event); if (res == null) { RecipeUtil.error("Error registering cooking recipe - result is null"); RecipeUtil.error("Current Item: §6" + this.toString(event, true)); @@ -91,11 +90,16 @@ protected void execute(Event event) { RecipeUtil.error("Current Item: §6" + this.toString(event, true)); return; } + if (keyString == null) { + RecipeUtil.error("Error registering cooking recipe - key is null"); + RecipeUtil.error("Current Item: §6" + this.toString(event, true)); + } ItemStack result = res.getRandom(); RecipeChoice ingredient; - if (ing instanceof ItemType) { - ItemStack itemStack = ((ItemType) ing).getRandom(); + if (ing instanceof ItemType itemType) { + ItemStack itemStack = itemType.getRandom(); + assert itemStack != null; Material material = itemStack.getType(); // If ingredient isn't a custom item, just register the material @@ -110,14 +114,14 @@ protected void execute(Event event) { return; } String group = this.group != null ? this.group.getSingle(event) : ""; - NamespacedKey key = Util.getNamespacedKey(this.key.getSingle(event), false); + NamespacedKey key = Util.getNamespacedKey(keyString, false); if (key == null) { RecipeUtil.error("Current Item: §6'" + toString(event, true) + "'"); return; } float xp = experience != null ? experience.getSingle(event).floatValue() : 0; - int cookTime = this.cookTime != null ? (int) this.cookTime.getSingle(event).getTicks() : getDefaultCookTime(recipeType); + int cookTime = this.cookTime != null ? (int) this.cookTime.getSingle(event).getAs(Timespan.TimePeriod.TICK) : getDefaultCookTime(recipeType); // Remove duplicates on script reload Bukkit.removeRecipe(key); @@ -128,13 +132,13 @@ protected void execute(Event event) { private void cookingRecipe(ItemStack result, RecipeChoice ingredient, String group, NamespacedKey key, float xp, int cookTime) { CookingRecipe recipe = switch (recipeType) { case 1 -> // BLASTING - new BlastingRecipe(key, result, ingredient, xp, cookTime); + new BlastingRecipe(key, result, ingredient, xp, cookTime); case 2 -> // SMOKING - new SmokingRecipe(key, result, ingredient, xp, cookTime); + new SmokingRecipe(key, result, ingredient, xp, cookTime); case 3 -> // CAMPFIRE - new CampfireRecipe(key, result, ingredient, xp, cookTime); + new CampfireRecipe(key, result, ingredient, xp, cookTime); default -> // FURNACE - new FurnaceRecipe(key, result, ingredient, xp, cookTime); + new FurnaceRecipe(key, result, ingredient, xp, cookTime); }; recipe.setGroup(group); @@ -147,11 +151,11 @@ private void cookingRecipe(ItemStack result, RecipeChoice ingredient, String gro private int getDefaultCookTime(int t) { return switch (t) { // BLASTING case 1, 2 -> // SMOKING - 100; + 100; case 3 -> // CAMPFIRE - 600; + 600; default -> // FURNACE - 200; + 200; }; } @@ -166,7 +170,7 @@ public String toString(Event e, boolean d) { String xp = experience != null ? " and with xp " + experience.toString(e, d) : ""; String cook = cookTime != null ? " and with cooktime " + cookTime.toString(e, d) : ""; return "register new " + type + " recipe for " + item.toString(e, d) + " using " + ingredient.toString(e, d) + - " with id " + key.toString(e, d) + xp + cook; + " with id " + key.toString(e, d) + xp + cook; } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/recipe/events/EvtRecipe.java b/src/main/java/com/shanebeestudios/skbee/elements/recipe/events/EvtRecipe.java index 5d2688d19..78c8caccf 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/recipe/events/EvtRecipe.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/recipe/events/EvtRecipe.java @@ -3,31 +3,23 @@ import ch.njol.skript.Skript; import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; -import com.shanebeestudios.skbee.elements.other.events.OtherEvents; import org.bukkit.event.block.CrafterCraftEvent; import org.bukkit.event.player.PlayerRecipeDiscoverEvent; -import org.jetbrains.annotations.NotNull; public class EvtRecipe extends SimpleEvent { static { Skript.registerEvent("Recipe - Discover Event", EvtRecipe.class, PlayerRecipeDiscoverEvent.class, - "recipe discover[y]") - .description("Called when a player unlocks a recipe. ", - "`event-string` = the recipe namespace (this will also include either \"minecraft:\" or \"mykeyhere:\")", - "Requires MC 1.13+") - .examples("on recipe discover:", - "\tif event-string = \"minecraft:diamond_block\"", - "\t\tcancel event") - .requiredPlugins("1.13+") - .since("1.0.0"); - EventValues.registerEventValue(PlayerRecipeDiscoverEvent.class, String.class, new Getter() { - @Override - public String get(PlayerRecipeDiscoverEvent event) { - return event.getRecipe().toString(); - } - }, 0); + "recipe discover[y]") + .description("Called when a player unlocks a recipe. ", + "`event-string` = the recipe namespace (this will also include either \"minecraft:\" or \"mykeyhere:\")", + "Requires MC 1.13+") + .examples("on recipe discover:", + "\tif event-string = \"minecraft:diamond_block\"", + "\t\tcancel event") + .requiredPlugins("1.13+") + .since("1.0.0"); + EventValues.registerEventValue(PlayerRecipeDiscoverEvent.class, String.class, event -> event.getRecipe().toString(), EventValues.TIME_NOW); if (Skript.classExists("org.bukkit.event.block.CrafterCraftEvent")) { Skript.registerEvent("Recipe - Crafter Craft Event", EvtRecipe.class, CrafterCraftEvent.class, "crafter craft") @@ -46,12 +38,7 @@ public String get(PlayerRecipeDiscoverEvent event) { "\t\tset name of recipe result to \"&cMr Shovel\"") .since("3.6.1"); - EventValues.registerEventValue(CrafterCraftEvent.class, String.class, new Getter<>() { - @Override - public @NotNull String get(CrafterCraftEvent event) { - return event.getRecipe().getKey().toString(); - } - }, EventValues.TIME_NOW); + EventValues.registerEventValue(CrafterCraftEvent.class, String.class, event -> event.getRecipe().getKey().toString(), EventValues.TIME_NOW); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprMaterialChoice.java b/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprMaterialChoice.java index fdd3d3bc0..6087c4b2f 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprMaterialChoice.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprMaterialChoice.java @@ -10,10 +10,9 @@ import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; +import ch.njol.skript.util.LiteralUtils; import ch.njol.util.Kleenean; -import com.shanebeestudios.skbee.SkBee; import com.shanebeestudios.skbee.api.recipe.RecipeUtil; -import com.shanebeestudios.skbee.elements.tag.type.Types; import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.event.Event; @@ -25,34 +24,31 @@ @Name("Recipe Choice - Material Choice") @Description({"A material choice is a list of items or a minecraft tag, that can be used as an option in some recipes.", - "Will return as a RecipeChoice.", - "When using the 'every' item type, this will grab all relatable items in a list, ie: 'every sword'.", - "This allows you to have one specific slot of a recipe to accept multiple items, without having to create multiple recipes.", - "Do note that material choices do not accept custom items (ie: items with names, lore, enchants, etc). Requires Minecraft 1.13+"}) + "Will return as a RecipeChoice.", + "When using the 'every' item type, this will grab all relatable items in a list, ie: 'every sword'.", + "This allows you to have one specific slot of a recipe to accept multiple items, without having to create multiple recipes.", + "Do note that material choices do not accept custom items (ie: items with names, lore, enchants, etc). Requires Minecraft 1.13+"}) @Examples({"set {_a} to material choice of diamond sword, diamond shovel and diamond hoe", - "set {_choice} to material choice of every sword", - "set {_choice} to material choice of every sword and every axe", - "set {_choice} to material choice of minecraft tag \"minecraft:planks\""}) + "set {_choice} to material choice of every sword", + "set {_choice} to material choice of every sword and every axe", + "set {_choice} to material choice of minecraft tag \"minecraft:planks\""}) @Since("1.10.0") public class ExprMaterialChoice extends SimpleExpression { - private static final boolean HAS_TAGS = SkBee.getPlugin().getPluginConfig().ELEMENTS_MINECRAFT_TAG && Types.HAS_TAG; - static { Skript.registerExpression(ExprMaterialChoice.class, MaterialChoice.class, ExpressionType.COMBINED, - HAS_TAGS ? "material choice of %itemtypes/minecrafttags%" : "material choice of %itemtypes%"); + "material choice of %itemtypes/minecrafttags%"); } private Expression objects; - @SuppressWarnings("NullableProblems") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { - this.objects = exprs[0]; + this.objects = LiteralUtils.defendExpression(exprs[0]); return true; } - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override protected MaterialChoice @Nullable [] get(Event event) { List materials = new ArrayList<>(); @@ -62,7 +58,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye Material material = itemStack.getType(); if (!materials.contains(material)) materials.add(material); }); - } else if (HAS_TAGS && RecipeUtil.isMaterialTag(object)) { + } else if (RecipeUtil.isMaterialTag(object)) { MaterialChoice materialChoice = new MaterialChoice((Tag) object); materialChoice.getChoices().forEach(material -> { if (!materials.contains(material)) materials.add(material); @@ -80,13 +76,11 @@ public boolean isSingle() { return true; } - @SuppressWarnings("NullableProblems") @Override public Class getReturnType() { return MaterialChoice.class; } - @SuppressWarnings("NullableProblems") @Override public String toString(@Nullable Event e, boolean d) { return "material choice of " + this.objects.toString(e, d); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprRecipeCookTime.java b/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprRecipeCookTime.java index f13f4345b..de98c0742 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprRecipeCookTime.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/recipe/expressions/ExprRecipeCookTime.java @@ -11,7 +11,6 @@ import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.skript.util.Timespan; import ch.njol.util.Kleenean; -import com.shanebeestudios.skbee.api.recipe.RecipeUtil; import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; @@ -32,19 +31,18 @@ public class ExprRecipeCookTime extends SimpleExpression { static { Skript.registerExpression(ExprRecipeCookTime.class, Timespan.class, ExpressionType.COMBINED, - "cook[ ]time of recipe[s] [with id[s]] %strings%"); + "cook[ ]time of recipe[s] [with id[s]] %strings%"); } private Expression key; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.key = (Expression) exprs[0]; return true; } - @SuppressWarnings("NullableProblems") @Override protected @Nullable Timespan[] get(Event event) { List cookTimes = new ArrayList<>(); @@ -54,7 +52,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye Recipe recipe = Bukkit.getRecipe(namespacedKey); if (recipe instanceof CookingRecipe cookingRecipe) - cookTimes.add(Timespan.fromTicks(cookingRecipe.getCookingTime())); + cookTimes.add(new Timespan(Timespan.TimePeriod.TICK, cookingRecipe.getCookingTime())); } return cookTimes.toArray(new Timespan[0]); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/recipe/sections/SecRecipeCooking.java b/src/main/java/com/shanebeestudios/skbee/elements/recipe/sections/SecRecipeCooking.java index f3dae2d71..ec0279d75 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/recipe/sections/SecRecipeCooking.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/recipe/sections/SecRecipeCooking.java @@ -41,42 +41,42 @@ @Name("Recipe - Register Cooking Recipe") @Description({"This section allows you to register any cooking recipe and define special properties.", - "\n`id` = The ID for your recipe. This is used for recipe discovery and Minecraft's /recipe command.", - "\n`result` = The resulting ItemStack of this recipe.", - "\n`input` = The item the recipe requires as an input to output the result (Accepts an ItemStack or RecipeChoice) (Required).", - "\n`cooktime` = How long the recipe will take to finish cooking before result is given (Optional).", - "\n`experience` = The amount of experience gained when the recipe is finished cooking (Optional).", - "Default cook times are, furnace = 10 seconds, smoking/blasting = 5 seconds and campfire = 30 seconds.", - "\n`group` = You can define a group in which all recipes under this are sorted together in the recipe book (Optional).", - "Examples of this in game are beds and wood types.", - "\n`category` = Which category in the recipe book this recipe should appear within (Optional 1.19.4+).", - "Valid category types are \"food\", \"blocks\", \"misc\", if no category is defined it defaults to \"misc\"."}) + "\n`id` = The ID for your recipe. This is used for recipe discovery and Minecraft's /recipe command.", + "\n`result` = The resulting ItemStack of this recipe.", + "\n`input` = The item the recipe requires as an input to output the result (Accepts an ItemStack or RecipeChoice) (Required).", + "\n`cooktime` = How long the recipe will take to finish cooking before result is given (Optional).", + "\n`experience` = The amount of experience gained when the recipe is finished cooking (Optional).", + "Default cook times are, furnace = 10 seconds, smoking/blasting = 5 seconds and campfire = 30 seconds.", + "\n`group` = You can define a group in which all recipes under this are sorted together in the recipe book (Optional).", + "Examples of this in game are beds and wood types.", + "\n`category` = Which category in the recipe book this recipe should appear within (Optional 1.19.4+).", + "Valid category types are \"food\", \"blocks\", \"misc\", if no category is defined it defaults to \"misc\"."}) @Examples({"register new furnace recipe:", - "\tid: \"sieve:gravel_to_sand\"", - "\tresult: sand", - "\tinput: gravel", - "\tgroup: \"sieve\"", - "\tcooktime: 1 minecraft day # 20 minutes", - "\texperience: 6", - "\tcategory: \"blocks\"", - "", - "register new campfire recipe:", - "\tid: \"sieve:cobblestone_to_gravel\"", - "\tresult: gravel", - "\tinput: cobblestone", - "\tgroup: \"sieve\"", - "\tcategory: \"blocks\"", - "", - "register new smoking recipe:", - "\tid: \"chef:beef_jerky\"", - "\tresult: cooked mutton named \"&oBeef&r Jerky\"", - "\tinput: rotten flesh", - "\tcategory: \"food\"", - "", - "register a new blasting recipe:", - "\tid: \"firery_sword\"", - "\tresult: diamond sword of fire aspect named \"Flaming Sword\"", - "\tinput: diamond sword"}) + "\tid: \"sieve:gravel_to_sand\"", + "\tresult: sand", + "\tinput: gravel", + "\tgroup: \"sieve\"", + "\tcooktime: 1 minecraft day # 20 minutes", + "\texperience: 6", + "\tcategory: \"blocks\"", + "", + "register new campfire recipe:", + "\tid: \"sieve:cobblestone_to_gravel\"", + "\tresult: gravel", + "\tinput: cobblestone", + "\tgroup: \"sieve\"", + "\tcategory: \"blocks\"", + "", + "register new smoking recipe:", + "\tid: \"chef:beef_jerky\"", + "\tresult: cooked mutton named \"&oBeef&r Jerky\"", + "\tinput: rotten flesh", + "\tcategory: \"food\"", + "", + "register a new blasting recipe:", + "\tid: \"firery_sword\"", + "\tresult: diamond sword of fire aspect named \"Flaming Sword\"", + "\tinput: diamond sword"}) @Since("3.0.0") public class SecRecipeCooking extends Section { @@ -129,7 +129,6 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return true; } - @SuppressWarnings("NullableProblems") @Override protected @Nullable TriggerItem walk(Event event) { execute(event); @@ -146,7 +145,7 @@ private void execute(Event event) { ItemStack result = this.result.getSingle(event); // #getConvertedExpression() is used to prevent the famous 'UnparsedLiterals must be converted before use' RecipeChoice input = this.input.getSingle(event); - int cookTime = this.cookTime != null ? (int) this.cookTime.getSingle(event).getTicks() : this.recipeType.getCookTime(); + int cookTime = this.cookTime != null ? (int) this.cookTime.getSingle(event).getAs(Timespan.TimePeriod.TICK) : this.recipeType.getCookTime(); float experience = this.experience != null ? this.experience.getSingle(event).floatValue() : 0; if (namespacedKey == null) { diff --git a/src/main/java/com/shanebeestudios/skbee/elements/tag/type/Types.java b/src/main/java/com/shanebeestudios/skbee/elements/tag/type/Types.java index 6ed5845cc..edb15fc4b 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/tag/type/Types.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/tag/type/Types.java @@ -21,8 +21,6 @@ public class Types { .description("Represents a Minecraft Tag.") .since("2.6.0") .parser(new Parser<>() { - - @SuppressWarnings("NullableProblems") @Override public boolean canParse(ParseContext context) { return false; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/text/effects/EffSendComponentTitle.java b/src/main/java/com/shanebeestudios/skbee/elements/text/effects/EffSendComponentTitle.java index c2006ff6d..d3c564293 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/text/effects/EffSendComponentTitle.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/text/effects/EffSendComponentTitle.java @@ -13,27 +13,27 @@ import com.shanebeestudios.skbee.api.wrapper.ComponentWrapper; import org.bukkit.entity.Player; import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Name("TextComponent - Send Title") @Description({"Send titles containing components. Supports strings as well.", - "If you are using variables and the title won't send, make sure to add `component`."}) + "If you are using variables and the title won't send, make sure to add `component`."}) @Examples({"send title mini message from \"OOO RAINBOW TITLE\"", - "send title component {_comp} for 10 seconds with fadein 5 ticks and fadeout 10 ticks"}) + "send title component {_comp} for 10 seconds with fadein 5 ticks and fadeout 10 ticks"}) @Since("2.4.0") public class EffSendComponentTitle extends Effect { static { Skript.registerEffect(EffSendComponentTitle.class, - "send title [component] %textcomponent/string% [with subtitle [component] %-textcomponent/string%] [to %players%] [for %-timespan%] [with fade[(-| )]in %-timespan%] [(and|with) fade[(-| )]out %-timespan%]"); + "send title [component] %textcomponent/string% [with subtitle [component] %-textcomponent/string%] [to %players%] [for %-timespan%] [with fade[(-| )]in %-timespan%] [(and|with) fade[(-| )]out %-timespan%]"); } private Expression title, subtitle; private Expression players; private Expression stay, fadeIn, fadeOut; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) { this.title = (Expression) exprs[0]; @@ -45,7 +45,6 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return true; } - @SuppressWarnings("NullableProblems") @Override protected void execute(Event event) { Object title = this.title.getSingle(event); @@ -61,19 +60,19 @@ protected void execute(Event event) { if (this.stay != null) { Timespan staySingle = this.stay.getSingle(event); if (staySingle != null) { - stay = staySingle.getTicks(); + stay = staySingle.getAs(Timespan.TimePeriod.TICK); } } if (this.fadeIn != null) { Timespan fadeInSingle = this.fadeIn.getSingle(event); if (fadeInSingle != null) { - fadeIn = fadeInSingle.getTicks(); + fadeIn = fadeInSingle.getAs(Timespan.TimePeriod.TICK); } } if (this.fadeOut != null) { Timespan fadeOutSingle = this.fadeOut.getSingle(event); if (fadeOutSingle != null) { - fadeOut = fadeOutSingle.getTicks(); + fadeOut = fadeOutSingle.getAs(Timespan.TimePeriod.TICK); } } ComponentWrapper.sendTitle(players, title, subtitle, stay, fadeIn, fadeOut); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprComponentFormat.java b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprComponentFormat.java index 6145b2581..147b0084e 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprComponentFormat.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprComponentFormat.java @@ -1,6 +1,5 @@ package com.shanebeestudios.skbee.elements.text.expressions; -import ch.njol.skript.Skript; import ch.njol.skript.classes.Changer.ChangeMode; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -15,33 +14,29 @@ import com.shanebeestudios.skbee.api.wrapper.ComponentWrapper; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; @Name("TextComponent - Format") -@Description({"Change formatting options of text components. Most of these are pretty straight forward. Insertion means the text ", - "that will copy to chat when a player shift-clicks the component (Might not be available on all versions). Color supports color ", - "names as well as RGB color codes via Skript's RGB function (RGB = Minecraft 1.16+) (see examples)."}) +@Description({"Change formatting options of text components. Most of these are pretty straight forward. ", + "Insertion means the text that will copy to chat when a player shift-clicks the component (Might not be available on all versions). ", + "Color supports color names as well as RGB color codes via Skript's RGB function (see examples).", + "Fallback is the fallback text used in a translation component when the client cannot find said translation."}) @Examples({"set {_t} to text component from \"my fancy text component\"", - "set bold format of {_t} to true", - "set color format of {_t} to aqua", - "set color format of {_t} to rgb(100, 0, 160)", - "set insertion format of {_t} to \"ooooo\""}) + "set bold format of {_t} to true", + "set color format of {_t} to aqua", + "set color format of {_t} to rgb(100, 0, 160)", + "set insertion format of {_t} to \"ooooo\"", + "set fallback format of {_t} to \"Le Fallback\""}) @Since("1.5.1") public class ExprComponentFormat extends PropertyExpression { - private static final int COLOR = 0, BOLD = 1, ITALIC = 2, OBFUSCATED = 3, STRIKETHROUGH = 4, UNDERLINE = 5, FONT = 6, INSERT = 7; + private static final int COLOR = 0, BOLD = 1, ITALIC = 2, OBFUSCATED = 3, STRIKETHROUGH = 4, + UNDERLINE = 5, FONT = 6, INSERT = 7, FALLBACK = 8; static { - if (Skript.methodExists(ComponentWrapper.class, "setInsertion", String.class)) { - register(ExprComponentFormat.class, Object.class, - "(color|1:bold|2:italic|3:(obfuscate[d]|magic)|4:strikethrough|5:underline[d]|6:font|7:insert[ion]) format", - "textcomponents"); - } else { - register(ExprComponentFormat.class, Object.class, - "(color|1:bold|2:italic|3:(obfuscate[d]|magic)|4:strikethrough|5:underline[d]|6:font) format", - "textcomponents"); - } + register(ExprComponentFormat.class, Object.class, + "(color|1:bold|2:italic|3:(obfuscate[d]|magic)|4:strikethrough|5:underline[d]|6:font|7:insert[ion]|8:fallback) format", + "textcomponents"); } private int pattern; @@ -65,17 +60,19 @@ public boolean init(Expression @NotNull [] exprs, int matchedPattern, @NotNul case UNDERLINE -> component.isUnderlined(); case FONT -> component.getFont(); case INSERT -> component.getInsertion(); + case FALLBACK -> component.getFallback(); default -> null; }); } - @SuppressWarnings("NullableProblems") + @SuppressWarnings({"NullableProblems", "DataFlowIssue"}) @Override public Class[] acceptChange(@NotNull ChangeMode mode) { - if (mode == ChangeMode.SET) return CollectionUtils.array(Object.class); + if (mode == ChangeMode.SET) return CollectionUtils.array(getReturnType()); return null; } + @SuppressWarnings({"NullableProblems", "ConstantValue"}) @Override public void change(@NotNull Event e, @Nullable Object[] delta, @NotNull ChangeMode mode) { Object object = delta != null ? delta[0] : null; @@ -130,6 +127,11 @@ public void change(@NotNull Event e, @Nullable Object[] delta, @NotNull ChangeMo component.setInsertion(insert); } break; + case FALLBACK: + String fallback = object instanceof String ? ((String) object) : object.toString(); + for (ComponentWrapper component : getExpr().getArray(e)) { + component.setFallback(fallback); + } } } @@ -137,14 +139,14 @@ public void change(@NotNull Event e, @Nullable Object[] delta, @NotNull ChangeMo public @NotNull Class getReturnType() { return switch (pattern) { case COLOR -> Color.class; - case INSERT, FONT -> String.class; + case INSERT, FONT, FALLBACK -> String.class; default -> Boolean.class; }; } @Override public @NotNull String toString(@Nullable Event e, boolean d) { - String[] type = new String[]{"color", "bold", "italic", "obfuscated", "strikethrough", "underline", "font", "insertion"}; + String[] type = new String[]{"color", "bold", "italic", "obfuscated", "strikethrough", "underline", "font", "insertion", "fallback"}; return type[pattern] + " format of " + getExpr().toString(e, d); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprSignLines.java b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprSignLines.java index 831ca65f1..e74e3211c 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprSignLines.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprSignLines.java @@ -9,28 +9,26 @@ import ch.njol.skript.expressions.base.PropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.util.Getter; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import com.shanebeestudios.skbee.api.wrapper.ComponentWrapper; import org.bukkit.block.Block; import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -@SuppressWarnings("NullableProblems") @Name("TextComponent - Sign Line") @Description({"Get/set lines of a sign with text components. Optionally set the front/back of a sign. (Defaults to front)", - "\nNOTE: Setting the back of a sign requires Minecraft 1.20+"}) + "\nNOTE: Setting the back of a sign requires Minecraft 1.20+"}) @Examples({"set sign line 1 of target block to mini message from \"LINE ONE\"", - "set sign line 2 of target block to translate component from \"item.minecraft.diamond_sword\"", - "set {_line1} to sign line 1 of target block", - "set {_line1} to front sign line 1 of target block", - "set back sign line 1 of {_sign} to mini message from \"LINE ONE\""}) + "set sign line 2 of target block to translate component from \"item.minecraft.diamond_sword\"", + "set {_line1} to sign line 1 of target block", + "set {_line1} to front sign line 1 of target block", + "set back sign line 1 of {_sign} to mini message from \"LINE ONE\""}) @Since("2.4.0, 2.11.0 (front|back)") public class ExprSignLines extends PropertyExpression { - private static final boolean HAS_SIDES = Skript.isRunningMinecraft(1,20); + private static final boolean HAS_SIDES = Skript.isRunningMinecraft(1, 20); static { register(ExprSignLines.class, ComponentWrapper.class, "[(front|:back)] sign line %number%", "blocks"); @@ -39,7 +37,7 @@ public class ExprSignLines extends PropertyExpression { private Expression signLine; private boolean front; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { setExpr((Expression) exprs[1]); @@ -52,7 +50,6 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye return true; } - @SuppressWarnings("NullableProblems") @Override protected ComponentWrapper[] get(Event event, Block[] source) { Number signLineSingle = this.signLine.getSingle(event); @@ -60,12 +57,7 @@ protected ComponentWrapper[] get(Event event, Block[] source) { int signLine = signLineSingle.intValue(); if (signLine > 4 || signLine < 1) return null; - return get(source, new Getter<>() { - @Override - public @Nullable ComponentWrapper get(Block block) { - return ComponentWrapper.getSignLine(block, signLine - 1, front); - } - }); + return get(source, block -> ComponentWrapper.getSignLine(block, signLine - 1, front)); } @Override diff --git a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprTextComponent.java b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprTextComponent.java index 2859209d2..6458ca49e 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprTextComponent.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/text/expressions/ExprTextComponent.java @@ -26,11 +26,12 @@ "Text: Just a plain old text component from a string.", "Rawtext: Same as text, but color codes will be visible.", "Keybind: Will use Minecraft's keybind system.", - "Translate: Will use Minecraft's lang file keys. ", - " - You can find these in your Minecraft jar 'assets/minecraft/lang/.json'.", + "Translate: Will use Minecraft's lang file keys.", + " - You can find these in your Minecraft jar `assets/minecraft/lang/.json`.", " - Also supports getting translations for objects such as ItemTypes, Entities and PotionEffectTypes.", " - When sent to the client, the client will translate based on the lang they've picked.", - " - Some lang file entries take in other objects, thats what the optional `using %objects%` is for.", + " - Some lang file entries take in other arguments, that's what the optional `using args %objects%` is for.", + " - Optionally you can add a fallback, this is the text sent to the client if the client cannot find the translation key.", "", "Json: Will deserialize a json string back into a component.", " - Minecraft stores components in NBT as json components (ex: name of a held item)."}) @@ -40,31 +41,36 @@ "send component {_comp::*} to player", "", "set {_t} to translate component from player's tool", "set {_t} to translate component from \"item.minecraft.milk_bucket\"", - "set {_death} to translate component from \"death.fell.accident.ladder\" using player's name", - "set {_assist} to translate component from \"death.fell.assist\" using victim's name and attacker's name", + "set {_death} to translate component from \"death.fell.accident.ladder\" using args player's name", + "set {_assist} to translate component from \"death.fell.assist\" using args victim's name and attacker's name", + "set {_custom} to translate component from \"my.custom.key\" with fallback \"Some Message\"", "set {_key} to keybind component of \"key.jump\"", "set {_name} to json component from (string tag \"custom_name\" of nbt of target block)"}) @Since("1.5.0") public class ExprTextComponent extends SimpleExpression { + static { Skript.registerExpression(ExprTextComponent.class, ComponentWrapper.class, ExpressionType.COMBINED, "[a] [new] (text|:rawtext) component[s] (from|of) %strings%", "[a] [new] key[ ]bind component[s] (from|of) %strings%", - "[a] [new] translate component[s] (from|of) %objects% [(with|using) %-objects%]", + "[a] [new] translate component[s] (from|of) %objects% [args:(with|using) arg[ument]s %-objects%] [fallback:with fallback %-string%]", "[a] [new] json component (from|of) %strings%"); } private int pattern; private Expression translation; private Expression objects; + private Expression fallback; private boolean raw; + @SuppressWarnings("unchecked") @Override public boolean init(Expression @NotNull [] exprs, int matchedPattern, @NotNull Kleenean isDelayed, @NotNull ParseResult parseResult) { this.pattern = matchedPattern; this.translation = LiteralUtils.defendExpression(exprs[0]); - this.objects = pattern == 2 ? LiteralUtils.defendExpression(exprs[1]) : null; + this.objects = pattern == 2 && parseResult.hasTag("args") ? LiteralUtils.defendExpression(exprs[1]) : null; this.raw = parseResult.hasTag("rawtext"); + this.fallback = pattern == 2 && parseResult.hasTag("fallback") ? (Expression) exprs[2] : null; if (this.objects != null) { return LiteralUtils.canInitSafely(this.translation, this.objects); } @@ -84,11 +90,12 @@ protected ComponentWrapper[] get(@NotNull Event e) { components.add(ComponentWrapper.fromKeybind((String) object)); } else if (this.pattern == 2) { String translate = ChatUtil.getTranslation(object); + String fallback = this.fallback != null ? this.fallback.getSingle(e) : null; if (translate != null) { if (this.objects != null) { - components.add(ComponentWrapper.fromTranslate(translate, this.objects.getArray(e))); + components.add(ComponentWrapper.fromTranslate(translate, fallback, this.objects.getArray(e))); } else { - components.add(ComponentWrapper.fromTranslate(translate)); + components.add(ComponentWrapper.fromTranslate(translate, fallback)); } } } else if (this.pattern == 3) { @@ -117,8 +124,9 @@ public boolean isSingle() { default -> this.raw ? "rawtext" : "text"; }; String trans = this.translation.toString(e, d); - String obj = this.objects != null ? "using " + this.objects.toString(e, d) : ""; - return String.format("a new %s component from %s %s", comp, trans, obj); + String obj = this.objects != null ? "with arguments " + this.objects.toString(e, d) : ""; + String fallback = this.fallback != null ? "with fallback " + this.fallback.toString(e, d) : ""; + return String.format("a new %s component from %s %s %s", comp, trans, obj, fallback); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/text/sections/SecClickEventCallback.java b/src/main/java/com/shanebeestudios/skbee/elements/text/sections/SecClickEventCallback.java index 28b8ae74d..6ae46afd1 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/text/sections/SecClickEventCallback.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/text/sections/SecClickEventCallback.java @@ -29,29 +29,29 @@ @Name("TextComponent - Click Event Callback") @Description({"Create a click event, that when clicked will run the code in this section.", - "\nNOTE: Internally this just makes the player run a special command", - "so you will see console messages where a player runs the command \"/paper callback\" in your console.", - "\nNOTE: Paper didn't make this command available by default", - "so you'll have to give your players the permission `bukkit.command.paper.callback`.", - "(As of PaperMC 1.20.1[build-169], the permission is no longer required).", - "\n`uses` = The amount of times the player can click this. Defaults to 1. Use `-1` for unlimited uses.", - "\n`lifetime` = How long the player has til they can't click it. Defaults to 12 hours."}) + "\nNOTE: Internally this just makes the player run a special command", + "so you will see console messages where a player runs the command \"/paper callback\" in your console.", + "\nNOTE: Paper didn't make this command available by default", + "so you'll have to give your players the permission `bukkit.command.paper.callback`.", + "(As of PaperMC 1.20.1[build-169], the permission is no longer required).", + "\n`uses` = The amount of times the player can click this. Defaults to 1. Use `-1` for unlimited uses.", + "\n`lifetime` = How long the player has til they can't click it. Defaults to 12 hours."}) @Examples({"set {_t} to mini message from \"JOIN US AT SPAWN FOR A SPECIAL EVENT (10 SECONDS REMAINING!)\"", - "create callback for {_t} with a duration of 10 seconds:", - "\tteleport player to spawn of world \"world\"", - "send component {_t} to all players", - "", - "set {_t} to text component from \"&cDONT CLICK ME\"", - "create callback for {_t} with (size of players) uses:", - "\tkill player", - "\tbroadcast \"&b%player% &eclicked it &cAND DIED&7!!!\"", - "send component {_t} to all players", - "", - "set {_t} to text component from \"Hey you! Click this for a free item.\"", - "set {_t2} to text component from \"&e&lONE TIME USE!\"", - "create a callback for {_t}:", - "\tgive player random item out of available item types", - "send components (merge components {_t} and {_t2} with \" \") to players"}) + "create callback for {_t} with a duration of 10 seconds:", + "\tteleport player to spawn of world \"world\"", + "send component {_t} to all players", + "", + "set {_t} to text component from \"&cDONT CLICK ME\"", + "create callback for {_t} with (size of players) uses:", + "\tkill player", + "\tbroadcast \"&b%player% &eclicked it &cAND DIED&7!!!\"", + "send component {_t} to all players", + "", + "set {_t} to text component from \"Hey you! Click this for a free item.\"", + "set {_t2} to text component from \"&e&lONE TIME USE!\"", + "create a callback for {_t}:", + "\tgive player random item out of available item types", + "send components (merge components {_t} and {_t2} with \" \") to players"}) @Since("2.17.0") public class SecClickEventCallback extends Section { @@ -70,8 +70,8 @@ public ComponentCallbackEvent(Player player) { static { Skript.registerSection(SecClickEventCallback.class, - "create [a] [new] [click event] callback for %textcomponent% " + - "[with %-number% use[s]] [[and] with [a] (lifetime|duration) of %-timespan%]"); + "create [a] [new] [click event] callback for %textcomponent% " + + "[with %-number% use[s]] [[and] with [a] (lifetime|duration) of %-timespan%]"); } private Expression component; @@ -79,7 +79,7 @@ public ComponentCallbackEvent(Player player) { private Expression lifeTime; private Trigger trigger; - @SuppressWarnings({"unchecked", "NullableProblems"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult, SectionNode sectionNode, List triggerItems) { @@ -103,7 +103,8 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye Duration lifeTime = ClickCallback.DEFAULT_LIFETIME; if (this.lifeTime != null) { Timespan lifeTimeSpan = this.lifeTime.getSingle(event); - if (lifeTimeSpan != null) lifeTime = Duration.ofMillis(lifeTimeSpan.getMilliSeconds()); + if (lifeTimeSpan != null) + lifeTime = Duration.ofMillis(lifeTimeSpan.getAs(Timespan.TimePeriod.MILLISECOND)); } Object localVariables = Variables.copyLocalVariables(event); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickSprint.java b/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickSprint.java index 3ae9f6c47..893674f87 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickSprint.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickSprint.java @@ -19,29 +19,28 @@ @Name("Server Tick - Sprint") @Description({"Attempts to initiate a sprint, which executes all server ticks at a faster rate then normal.", - Util.MCWIKI_TICK_COMMAND, "Requires Minecraft 1.20.4+"}) + Util.MCWIKI_TICK_COMMAND, "Requires Minecraft 1.20.4+"}) @Examples({"request game to sprint 10 ticks", - "stop sprinting game"}) + "stop sprinting game"}) @Since("3.1.0") public class EffServerTickSprint extends Effect { static { Skript.registerEffect(EffServerTickSprint.class, - "request (game|server) to sprint %timespan%", - "stop sprinting (game|server)"); + "request (game|server) to sprint %timespan%", + "stop sprinting (game|server)"); } private Expression ticks; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.ticks = matchedPattern == 0 ? (Expression) exprs[0] : null; return true; } - @SuppressWarnings("NullableProblems") @Override protected void execute(Event event) { ServerTickManager tickManager = Bukkit.getServerTickManager(); @@ -50,7 +49,7 @@ protected void execute(Event event) { } else { Timespan timespan = this.ticks.getSingle(event); if (timespan != null) { - tickManager.requestGameToSprint((int) timespan.getTicks()); + tickManager.requestGameToSprint((int) timespan.getAs(Timespan.TimePeriod.TICK)); } } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickStep.java b/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickStep.java index e493b36d7..657c457b0 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickStep.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/tickmanager/effects/EffServerTickStep.java @@ -19,30 +19,29 @@ @Name("Server Tick - Step Server") @Description({"Steps the game a certain amount of ticks if the server is currently frozen.", - "Steps occur when the server is in a frozen state which can be started by either using", - "the in game `/tick freeze` command or the `server frozen state` expression.", - Util.MCWIKI_TICK_COMMAND, "Requires Minecraft 1.20.4+"}) + "Steps occur when the server is in a frozen state which can be started by either using", + "the in game `/tick freeze` command or the `server frozen state` expression.", + Util.MCWIKI_TICK_COMMAND, "Requires Minecraft 1.20.4+"}) @Examples({"step game if frozen 10 ticks", - "stop stepping game"}) + "stop stepping game"}) @Since("3.1.0") public class EffServerTickStep extends Effect { static { Skript.registerEffect(EffServerTickStep.class, - "step (game|server) [if frozen] [by] %timespan%", - "stop stepping (game|server)"); + "step (game|server) [if frozen] [by] %timespan%", + "stop stepping (game|server)"); } private Expression ticks; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { this.ticks = matchedPattern == 0 ? (Expression) exprs[0] : null; return true; } - @SuppressWarnings("NullableProblems") @Override protected void execute(Event event) { ServerTickManager tickManager = Bukkit.getServerTickManager(); @@ -51,7 +50,7 @@ protected void execute(Event event) { } else { Timespan timespan = this.ticks.getSingle(event); if (timespan != null) { - tickManager.stepGameIfFrozen((int) timespan.getTicks()); + tickManager.stepGameIfFrozen((int) timespan.getAs(Timespan.TimePeriod.TICK)); } } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/villager/event/SimpleEvents.java b/src/main/java/com/shanebeestudios/skbee/elements/villager/event/SimpleEvents.java index 735ada91f..8109c59f3 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/villager/event/SimpleEvents.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/villager/event/SimpleEvents.java @@ -3,7 +3,6 @@ import ch.njol.skript.Skript; import ch.njol.skript.lang.util.SimpleEvent; import ch.njol.skript.registrations.EventValues; -import ch.njol.skript.util.Getter; import io.papermc.paper.event.player.PlayerPurchaseEvent; import io.papermc.paper.event.player.PlayerTradeEvent; import org.bukkit.entity.Entity; @@ -13,82 +12,45 @@ import org.bukkit.inventory.Merchant; import org.bukkit.inventory.MerchantInventory; import org.bukkit.inventory.MerchantRecipe; -import org.jetbrains.annotations.Nullable; public class SimpleEvents extends SimpleEvent { static { Skript.registerEvent("Trade Select", SimpleEvents.class, TradeSelectEvent.class, "trade select") - .description("This event is called whenever a player clicks a new trade on the trades sidebar.", - "This event allows the user to get the index of the trade, letting them get the MerchantRecipe via the Merchant.", - "`event-number` = Used to get the index of the trade the player clicked on.", - "`event-merchantrecipe` = The merchant recipe of the trade that the player clicked on.") - .examples("") - .since("1.17.0"); - - EventValues.registerEventValue(TradeSelectEvent.class, MerchantInventory.class, new Getter<>() { - @Override - public @Nullable MerchantInventory get(TradeSelectEvent event) { - return event.getInventory(); - } - }, 0); - - EventValues.registerEventValue(TradeSelectEvent.class, Number.class, new Getter<>() { - @Override - public @Nullable Number get(TradeSelectEvent event) { - return event.getIndex(); - } - }, 0); - - EventValues.registerEventValue(TradeSelectEvent.class, Merchant.class, new Getter<>() { - @Override - public @Nullable Merchant get(TradeSelectEvent event) { - return event.getMerchant(); - } - }, 0); - - EventValues.registerEventValue(TradeSelectEvent.class, MerchantRecipe.class, new Getter<>() { - @Override - public @Nullable MerchantRecipe get(TradeSelectEvent event) { - return event.getInventory().getSelectedRecipe(); + .description("This event is called whenever a player clicks a new trade on the trades sidebar.", + "This event allows the user to get the index of the trade, letting them get the MerchantRecipe via the Merchant.", + "`event-number` = Used to get the index of the trade the player clicked on.", + "`event-merchantrecipe` = The merchant recipe of the trade that the player clicked on.") + .examples("") + .since("1.17.EventValues.TIME_NOW"); + + EventValues.registerEventValue(TradeSelectEvent.class, MerchantInventory.class, TradeSelectEvent::getInventory, EventValues.TIME_NOW); + EventValues.registerEventValue(TradeSelectEvent.class, Number.class, TradeSelectEvent::getIndex, EventValues.TIME_NOW); + EventValues.registerEventValue(TradeSelectEvent.class, Merchant.class, TradeSelectEvent::getMerchant, EventValues.TIME_NOW); + EventValues.registerEventValue(TradeSelectEvent.class, MerchantRecipe.class, event -> event.getInventory().getSelectedRecipe(), EventValues.TIME_NOW); + EventValues.registerEventValue(TradeSelectEvent.class, Player.class, event -> { + HumanEntity trader = event.getMerchant().getTrader(); + if (trader instanceof Player player) { + return player; } - }, 0); - - EventValues.registerEventValue(TradeSelectEvent.class, Player.class, new Getter<>() { - @Override - public @Nullable Player get(TradeSelectEvent event) { - HumanEntity trader = event.getMerchant().getTrader(); - if (trader instanceof Player player) { - return player; - } - return null; - } - }, 0); + return null; + }, EventValues.TIME_NOW); if (Skript.classExists("io.papermc.paper.event.player.PlayerPurchaseEvent")) { Skript.registerEvent("Player Purchase", SimpleEvents.class, PlayerPurchaseEvent.class, - "player purchase") - .description("Called when a player trades with a standalone merchant/villager GUI. Requires PaperMC.") - .examples("on player purchase:", - "\tignite event-entity for 1 minute") - .since("1.17.1"); - - EventValues.registerEventValue(PlayerPurchaseEvent.class, MerchantRecipe.class, new Getter<>() { - @Override - public @Nullable MerchantRecipe get(PlayerPurchaseEvent event) { - return event.getTrade(); + "player purchase") + .description("Called when a player trades with a standalone merchant/villager GUI. Requires PaperMC.") + .examples("on player purchase:", + "\tignite event-entity for 1 minute") + .since("1.17.1"); + + EventValues.registerEventValue(PlayerPurchaseEvent.class, MerchantRecipe.class, PlayerPurchaseEvent::getTrade, EventValues.TIME_NOW); + EventValues.registerEventValue(PlayerPurchaseEvent.class, Entity.class, event -> { + if (event instanceof PlayerTradeEvent tradeEvent) { + return tradeEvent.getVillager(); } - }, 0); - - EventValues.registerEventValue(PlayerPurchaseEvent.class, Entity.class, new Getter<>() { - @Override - public @Nullable Entity get(PlayerPurchaseEvent event) { - if (event instanceof PlayerTradeEvent tradeEvent) { - return tradeEvent.getVillager(); - } - return null; - } - }, 0); + return null; + }, EventValues.TIME_NOW); } } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerLevel.java b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerLevel.java index b1a509967..86b41855a 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerLevel.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerLevel.java @@ -10,6 +10,7 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Villager; import org.bukkit.event.Event; @@ -18,17 +19,20 @@ @Name("Villager - Level/Experience") @Description({"Represents the level/experience of a villager.", - "Level is between 1 and 5.","" + - "Experience is a number greater than or equal to 0."}) + "Removed if running Skript 2.10+ (now included in Skript).", + "Level is between 1 and 5.", + "Experience is a number greater than or equal to 0."}) @Examples({"set villager level of target entity to 5", - "set villager experience of last spawned villager to 10", - "if villager level of target entity > 2:", - "if villager experience of target entity > 10:"}) + "set villager experience of last spawned villager to 10", + "if villager level of target entity > 2:", + "if villager experience of target entity > 10:"}) @Since("1.17.0") public class ExprVillagerLevel extends SimplePropertyExpression { static { - register(ExprVillagerLevel.class, Number.class, "villager (level|1:experience)", "livingentities"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(ExprVillagerLevel.class, Number.class, "villager (level|1:experience)", "livingentities"); + } } private int pattern; diff --git a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerProfession.java b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerProfession.java index b9b4075c9..0ace0e7ec 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerProfession.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerProfession.java @@ -8,21 +8,25 @@ import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.util.coll.CollectionUtils; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Villager; import org.bukkit.entity.Villager.Profession; import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Name("Villager - Profession") -@Description("Represents the profession of a villager.") +@Description({"Represents the profession of a villager.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples("set profession of target entity to nitwit profession") @Since("1.17.0") public class ExprVillagerProfession extends SimplePropertyExpression { static { - register(ExprVillagerProfession.class, Profession.class, "profession", "livingentities"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(ExprVillagerProfession.class, Profession.class, "profession", "livingentities"); + } } @Override diff --git a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerType.java b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerType.java index 8f212b371..a7fc9987b 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerType.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/villager/expressions/ExprVillagerType.java @@ -7,22 +7,26 @@ import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.util.coll.CollectionUtils; +import com.shanebeestudios.skbee.api.util.Util; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Villager; import org.bukkit.entity.Villager.Type; import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Name("Villager - Type") -@Description("Represents the type of villager. Resetting will set a villager to a plains villager.") +@Description({"Represents the type of villager. Resetting will set a villager to a plains villager.", + "Removed if running Skript 2.10+ (now included in Skript)."}) @Examples({"set {_t} to villager type of last spawned villager", - "set villager type of target entity to desert villager"}) + "set villager type of target entity to desert villager"}) @Since("1.17.0") public class ExprVillagerType extends SimplePropertyExpression { static { - register(ExprVillagerType.class, Type.class, "villager type", "livingentities"); + if (!Util.IS_RUNNING_SKRIPT_2_10) { + register(ExprVillagerType.class, Type.class, "villager type", "livingentities"); + } } @Override diff --git a/src/main/java/com/shanebeestudios/skbee/elements/villager/type/Types.java b/src/main/java/com/shanebeestudios/skbee/elements/villager/type/Types.java index 1e85e46af..bb9a59efe 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/villager/type/Types.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/villager/type/Types.java @@ -25,34 +25,38 @@ public class Types { static { - // VILLAGER PROFESSION - // Only register if no other addons have registered this class - if (Classes.getExactClassInfo(Profession.class) == null) { - Classes.registerClass(RegistryClassInfo.create(Registry.VILLAGER_PROFESSION, - Profession.class, "profession", "", "profession") - .user("professions?") - .name("Villager Profession") - .description("Represent the types of professions for villagers.", - "Due to not parsing correctly, the professions are suffixed with 'profession'.") - .since("1.17.0")); - } else { - Util.logLoading("It looks like another addon registered 'profession' already."); - Util.logLoading("You may have to use their profession in SkBee's 'Villager Profession' expression."); - } + if (!Util.IS_RUNNING_SKRIPT_2_10) { + // VILLAGER PROFESSION + // Only register if no other addons have registered this class + if (Classes.getExactClassInfo(Profession.class) == null) { + Classes.registerClass(RegistryClassInfo.create(Registry.VILLAGER_PROFESSION, + Profession.class, "profession", "", "profession") + .user("professions?") + .name("Villager Profession") + .description("Represent the types of professions for villagers.", + "Removed if running Skript 2.10+ (now included in Skript).", + "Due to not parsing correctly, the professions are suffixed with 'profession'.") + .since("1.17.0")); + } else { + Util.logLoading("It looks like another addon registered 'profession' already."); + Util.logLoading("You may have to use their profession in SkBee's 'Villager Profession' expression."); + } - // VILLAGER TYPE - // Only register if no other addons have registered this class - if (Classes.getExactClassInfo(Type.class) == null) { - Classes.registerClass(RegistryClassInfo.create(Registry.VILLAGER_TYPE, - Type.class, "villagertype", "", "villager") - .user("villager ?types?") - .name("Villager Type") - .description("Represents the types of villagers.", - "Due to possible overlaps with biomes, types are suffixed with 'villager'.") - .since("1.17.0")); - } else { - Util.logLoading("It looks like another addon registered 'villagertype' already."); - Util.logLoading("You may have to use their villagertype in SkBee's 'Villager Type' expression."); + // VILLAGER TYPE + // Only register if no other addons have registered this class + if (Classes.getExactClassInfo(Type.class) == null) { + Classes.registerClass(RegistryClassInfo.create(Registry.VILLAGER_TYPE, + Type.class, "villagertype", "", "villager") + .user("villager ?types?") + .name("Villager Type") + .description("Represents the types of villagers.", + "Removed if running Skript 2.10+ (now included in Skript).", + "Due to possible overlaps with biomes, types are suffixed with 'villager'.") + .since("1.17.0")); + } else { + Util.logLoading("It looks like another addon registered 'villagertype' already."); + Util.logLoading("You may have to use their villagertype in SkBee's 'Villager Type' expression."); + } } // MERCHANT diff --git a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceFuel.java b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceFuel.java index dd624cf3e..0f298e603 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceFuel.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceFuel.java @@ -62,7 +62,7 @@ protected void execute(Event e) { } } else { Material fuel = this.fuel.getSingle(e).getMaterial(); - int burn = (int) this.burn.getSingle(e).getTicks(); + int burn = (int) this.burn.getSingle(e).getAs(Timespan.TimePeriod.TICK); String key = "fuel_" + fuel.toString() + "_" + burn; Fuel f = new Fuel(Util.getKey(key), fuel, burn); RECIPE_MANAGER.registerFuel(f); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceRecipe.java b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceRecipe.java index f7dac1bd7..542556de9 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceRecipe.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/effects/EffFurnaceRecipe.java @@ -80,7 +80,7 @@ protected void execute(Event event) { } else { Material ing = this.ingredient.getSingle(event).getMaterial(); Material result = this.result.getSingle(event).getMaterial(); - int cook = this.cookTime != null ? (int) this.cookTime.getSingle(event).getTicks() : 200; + int cook = this.cookTime != null ? (int) this.cookTime.getSingle(event).getAs(Timespan.TimePeriod.TICK) : 200; String key = "recipe_" + ing.toString() + "_" + result.toString() + "_" + cook; FurnaceRecipe recipe = new FurnaceRecipe(Util.getKey(key), ing, result, cook); RECIPE_MANAGER.registerFurnaceRecipe(recipe); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceAllFurnaces.java b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceAllFurnaces.java index 7b5330216..7b3b95115 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceAllFurnaces.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceAllFurnaces.java @@ -27,19 +27,17 @@ public class ExprVirtualFurnaceAllFurnaces extends SimpleExpression { static { Skript.registerExpression(ExprVirtualFurnaceAllFurnaces.class, Machine.class, ExpressionType.SIMPLE, - "all virtual (machines|furnaces)"); + "all virtual (machines|furnaces)"); } - @SuppressWarnings("NullableProblems") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { return true; } - @SuppressWarnings("NullableProblems") @Override protected @Nullable Machine[] get(Event event) { - List machines = new ArrayList<>(Types.FURNACE_MANAGER.getAllFurnaces()); + List machines = new ArrayList<>(Types.FURNACE_MANAGER.getAllMachines()); return machines.toArray(new Machine[0]); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceMachineFromID.java b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceMachineFromID.java index a3bf8b054..6f97658b2 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceMachineFromID.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/expressions/ExprVirtualFurnaceMachineFromID.java @@ -52,8 +52,8 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye } catch (IllegalArgumentException ignore) { } if (uuid == null) continue; - Furnace furnace = Types.FURNACE_MANAGER.getByID(uuid); - machines.add(furnace); + Machine machine = Types.FURNACE_MANAGER.getByID(uuid); + machines.add(machine); } return machines.toArray(new Machine[0]); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/type/Types.java b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/type/Types.java index 66f86c320..9cabbc2e6 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/type/Types.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/virtualfurnace/type/Types.java @@ -1,8 +1,10 @@ package com.shanebeestudios.skbee.elements.virtualfurnace.type; +import ch.njol.skript.classes.Changer; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.classes.Serializer; import ch.njol.skript.registrations.Classes; +import ch.njol.util.coll.CollectionUtils; import ch.njol.yggdrasil.Fields; import com.shanebeestudios.skbee.SkBee; import com.shanebeestudios.skbee.api.util.SkriptUtils; @@ -11,6 +13,7 @@ import com.shanebeestudios.vf.api.machine.Machine; import com.shanebeestudios.vf.api.property.Properties; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.StreamCorruptedException; import java.util.UUID; @@ -21,62 +24,82 @@ public class Types { static { Classes.registerClass(new ClassInfo<>(Machine.class, "machine") - .user("machines?") - .name("VirtualFurnace - Machine") - .description("Represents a virtual machine. These machines tick on their own like a regular", - "vanilla Minecraft furnace except they can be loaded from anywhere and don't rely on chunks.") - .since("3.3.0") - .parser(SkriptUtils.getDefaultParser()) - .serializer(new Serializer<>() { - @Override - public @NotNull Fields serialize(Machine machine) { - Fields fields = new Fields(); + .user("machines?") + .name("VirtualFurnace - Machine") + .description("Represents a virtual machine. These machines tick on their own like a regular", + "vanilla Minecraft furnace except they can be loaded from anywhere and don't rely on chunks.") + .since("3.3.0") + .parser(SkriptUtils.getDefaultParser()) + .changer(new Changer<>() { + @SuppressWarnings({"NullableProblems", "DataFlowIssue"}) + @Override + @Nullable + public Class[] acceptChange(@NotNull ChangeMode changeMode) { + if (changeMode == ChangeMode.DELETE) return CollectionUtils.array(); + return null; + } - // Might add new machines in the future - if (machine instanceof Furnace furnace) { - fields.putObject("type", "furnace"); - } - fields.putObject("id", machine.getUniqueID().toString()); - return fields; - } + @SuppressWarnings("NullableProblems") + @Override + public void change(Machine[] machines, @Nullable Object[] objects, ChangeMode changeMode) { + if (changeMode != ChangeMode.DELETE) return; - @SuppressWarnings("NullableProblems") - @Override - public void deserialize(Machine o, Fields f) { + for (Machine machine : machines) { + FURNACE_MANAGER.removeMachine(machine, false); } + FURNACE_MANAGER.saveConfig(); + } + }) + .serializer(new Serializer<>() { + @Override + public @NotNull Fields serialize(Machine machine) { + Fields fields = new Fields(); - @SuppressWarnings("NullableProblems") - @Override - protected Machine deserialize(Fields fields) throws StreamCorruptedException { - String type = fields.getObject("type", String.class); - assert type != null; - if (type.equals("furnace")) { - String uuid = fields.getObject("id", String.class); - assert uuid != null; - Furnace furnace = FURNACE_MANAGER.getByID(UUID.fromString(uuid)); - if (furnace != null) return furnace; - throw new StreamCorruptedException("Invalid machine with id: " + uuid); - } - throw new StreamCorruptedException("Invalid machine type: " + type); + // Might add new machines in the future + if (machine instanceof Furnace furnace) { + fields.putObject("type", "furnace"); } + fields.putObject("id", machine.getUniqueID().toString()); + return fields; + } - @Override - public boolean mustSyncDeserialization() { - return false; - } + @SuppressWarnings("NullableProblems") + @Override + public void deserialize(Machine o, Fields f) { + } - @Override - protected boolean canBeInstantiated() { - return false; + @SuppressWarnings("NullableProblems") + @Override + protected Machine deserialize(Fields fields) throws StreamCorruptedException { + String type = fields.getObject("type", String.class); + assert type != null; + if (type.equals("furnace")) { + String uuid = fields.getObject("id", String.class); + assert uuid != null; + Machine machine = FURNACE_MANAGER.getByID(UUID.fromString(uuid)); + if (machine != null) return machine; + throw new StreamCorruptedException("Invalid machine with id: " + uuid); } - })); + throw new StreamCorruptedException("Invalid machine type: " + type); + } + + @Override + public boolean mustSyncDeserialization() { + return false; + } + + @Override + protected boolean canBeInstantiated() { + return false; + } + })); Classes.registerClass(new ClassInfo<>(Properties.class, "machineproperty") - .user("machine ?propert(y|ies)") - .name("VirtualFurnace - Machine Properties") - .description("Represents the machine properties of a virtual machine.") - .since("3.3.0") - .parser(SkriptUtils.getDefaultParser()) + .user("machine ?propert(y|ies)") + .name("VirtualFurnace - Machine Properties") + .description("Represents the machine properties of a virtual machine.") + .since("3.3.0") + .parser(SkriptUtils.getDefaultParser()) ); } diff --git a/src/main/java/com/shanebeestudios/skbee/elements/worldborder/effects/EffWorldBorderExpand.java b/src/main/java/com/shanebeestudios/skbee/elements/worldborder/effects/EffWorldBorderExpand.java index 021b381ac..78e7a51f8 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/worldborder/effects/EffWorldBorderExpand.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/worldborder/effects/EffWorldBorderExpand.java @@ -37,7 +37,7 @@ public class EffWorldBorderExpand extends Effect { private Expression size; private Expression timeSpan; - @SuppressWarnings({"NullableProblems", "unchecked"}) + @SuppressWarnings("unchecked") @Override public boolean init(Expression[] exprs, int i, Kleenean kleenean, ParseResult parseResult) { this.expand = parseResult.mark == 0; @@ -48,7 +48,6 @@ public boolean init(Expression[] exprs, int i, Kleenean kleenean, ParseResult return true; } - @SuppressWarnings("NullableProblems") @Override protected void execute(Event event) { Number sizeNum = this.size.getSingle(event); @@ -57,7 +56,7 @@ protected void execute(Event event) { long speed = 0; if (this.timeSpan != null) { Timespan timeSpan = this.timeSpan.getSingle(event); - if (timeSpan != null) speed = timeSpan.getTicks() / 20; + if (timeSpan != null) speed = timeSpan.getAs(Timespan.TimePeriod.TICK) / 20; } int size = sizeNum.intValue(); diff --git a/src/main/java/com/shanebeestudios/skbee/elements/worldborder/expressions/ExprWorldBorderWarningTime.java b/src/main/java/com/shanebeestudios/skbee/elements/worldborder/expressions/ExprWorldBorderWarningTime.java index 8e859062b..965a575c7 100644 --- a/src/main/java/com/shanebeestudios/skbee/elements/worldborder/expressions/ExprWorldBorderWarningTime.java +++ b/src/main/java/com/shanebeestudios/skbee/elements/worldborder/expressions/ExprWorldBorderWarningTime.java @@ -10,8 +10,8 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.WorldBorder; import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Name("WorldBorder - Warning Time") @Description("Get/set the warning time of a world border.") @@ -21,28 +21,26 @@ public class ExprWorldBorderWarningTime extends SimplePropertyExpression[] acceptChange(ChangeMode mode) { if (mode == ChangeMode.SET) return CollectionUtils.array(Timespan.class); return null; } - @SuppressWarnings("NullableProblems") @Override public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { Timespan timespan = (Timespan) delta[0]; if (timespan == null) return; - int seconds = (int)(timespan.getTicks() / 20); + int seconds = (int) (timespan.getAs(Timespan.TimePeriod.TICK) / 20); for (WorldBorder border : getExpr().getArray(event)) { border.setWarningTime(seconds); } diff --git a/src/test/scripts/elements/expressions/ExprItemFlags.sk b/src/test/scripts/elements/expressions/ExprItemFlags.sk index fe6911ff0..a79d5f431 100644 --- a/src/test/scripts/elements/expressions/ExprItemFlags.sk +++ b/src/test/scripts/elements/expressions/ExprItemFlags.sk @@ -1,4 +1,4 @@ -test "item flags of item": +test "SkBee - item flags of item": set {_i} to diamond sword of unbreaking 3 with hide enchants item flag assert size of (item flags of {_i}) = 1 with "size of item flags should have been 1" assert item flags of {_i} contains hide enchants with "item flags of item should have enchanted 'hide_enchants'" diff --git a/src/test/scripts/elements/expressions/ExprMemoryValue.sk b/src/test/scripts/elements/expressions/ExprMemoryValue.sk index 04015008b..5be59b926 100644 --- a/src/test/scripts/elements/expressions/ExprMemoryValue.sk +++ b/src/test/scripts/elements/expressions/ExprMemoryValue.sk @@ -1,4 +1,4 @@ -test "memory value": +test "SkBee - memory value": set {_l} to location(1,100,1) spawn a villager at {_l} diff --git a/src/test/scripts/general/nbt-test.sk b/src/test/scripts/general/nbt-test.sk index b289fd6a4..6bb361e9f 100644 --- a/src/test/scripts/general/nbt-test.sk +++ b/src/test/scripts/general/nbt-test.sk @@ -23,20 +23,24 @@ test "SkBee - simple nbt compound": delete {_n} set {_i} to diamond sword with custom model data 1 + set max damage of {_i} to 25 set {_n} to nbt of {_i} # Test that tag of item nbt is set - assert int tag "minecraft:custom_model_data" of {_n} is set with "tag ""minecraft:custom_model_data"" of an item should be set" - assert int tag "minecraft:custom_model_data" of {_n} = 1 with "tag ""minecraft:custom_model_data"" of an item should be 1" + assert int tag "minecraft:max_damage" of {_n} = 25 with "tag 'minecraft:max_damage' of an item should be 25" + set int tag "minecraft:max_damage" of {_n} to 10 + assert max damage of {_i} is 10 with "Updating the 'minecraft:max_damage' tag should update the item" # Test that vanilla NBT of an item works - set {_vn} to vanilla nbt of {_i} - assert {_vn} is set with "Vanilla NBT of an item should work" + assert vanilla nbt of {_i} is set with "Vanilla NBT of an item should work" + assert int tag "minecraft:damage" of vanilla nbt of {_i} is 0 with "Tag 'minecraft:damage' should be 0 on a new item" + damage {_i} by 10 + assert int tag "minecraft:damage" of vanilla nbt of {_i} is 10 with "Tag 'minecraft:damage' should be 10 after damaging an item" # Test that Pretty nbt works set {_pretty} to pretty nbt of {_n} assert {_pretty} is set with "Pretty NBT should have worked" - set {_vp} to pretty nbt of {_vn} + set {_vp} to pretty nbt of vanilla nbt of {_i} assert {_vp} is set with "Pretty NBT of vanilla nbt should have worked" # Test adding/removing to/from lists diff --git a/src/test/scripts/general/recipe-test.sk b/src/test/scripts/general/recipe-test.sk index d9b308e36..ddf8a45f7 100644 --- a/src/test/scripts/general/recipe-test.sk +++ b/src/test/scripts/general/recipe-test.sk @@ -23,7 +23,7 @@ test "SkBee - shaped recipe section": result: 4 of string shape: "a" ingredients: - set ingredient of "a" to material choice of all wool + set ingredient of "a" to material choice of red wool and yellow wool register shaped recipe: id: "custom:bee_2" @@ -38,7 +38,7 @@ test "SkBee - shapeless recipe section": id: "custom:string" result: 4 string ingredients: - add material choice of every wool to ingredients + add material choice of minecraft item tag "minecraft:wools" to ingredients register shapeless recipe: id: "custom:totem_of_undying" @@ -47,7 +47,7 @@ test "SkBee - shapeless recipe section": category: "redstone" ingredients: add diamond block to ingredients - add material choice of every plank to ingredients + add material choice of minecraft item tag "minecraft:planks" to ingredients add emerald block to ingredients add end rod to ingredients add wither skeleton skull to ingredients @@ -92,7 +92,7 @@ test "SkBee - cooking recipe section": test "SkBee - brewer recipe section": register brewing recipe: id: "custom:brew_glow_diamond" - result: diamond of unbreaking with all item flags + result: diamond of unbreaking with item flag hide enchants ingredient: glowstone dust input: potato @@ -100,4 +100,4 @@ test "SkBee - brewer recipe section": id: "custom:yummy_soup" result: mushroom stew named "&bYummy Soup" ingredient: glowstone dust - input: water bottle + input: potion diff --git a/src/test/scripts/general/text-component-test.sk b/src/test/scripts/general/text-component-test.sk index 54941e53f..7ac66fffa 100644 --- a/src/test/scripts/general/text-component-test.sk +++ b/src/test/scripts/general/text-component-test.sk @@ -3,8 +3,62 @@ test "SkBee - text component test": # These tests are more so to check if anything fails # They can't really do anything + # Create a mini message set {_m} to mini message from "well who cares what is here" - assert {_m} is set with "Welp, i guess the mini message didnt work" + assert {_m} is set with "Welp, I guess the mini message didn't work" + # Component replace text effect + assert "%{_m}%" contains "cares" with "'cares' should be in there" + component replace "cares" with "" in {_m} + assert "%{_m}%" does not contain "cares" with "'cares' should have been removed" + + # Click event + assert click event of {_m} is not set with "component should not have a click event yet" + add click event to run command "/some command" to {_m} + assert click event of {_m} is set with "component should have a click event" + + # Hover event + assert hover event of {_m} is not set with "component should not have a hover event yet" + add hover event showing "test" to {_m} + assert hover event of {_m} is set with "component should have a hover event" + + # Component item name/lore + set {_i} to 1 of diamond sword + assert lore of {_i} is not set with "The item shouldn't have lore yet" + set component item lore of {_i} to {_m} + assert lore of {_i} is set with "The item should have lore now" + assert name of {_i} is not set with "The item shouldn't have a name yet" + set component display name of {_i} to {_m} + assert name of {_i} is set with "The item should have a name now" + + # Send to console + send component {_m} to console + + # Create a text component set {_t} to text component from "test" - assert {_t} is set with "Welp, i guess the text component didnt work" + assert {_t} is set with "Welp, I guess the text component didn't work" + + # Component formats + set color format of {_t} to red + # TODO Skript 2.9.x currently cannot compare a color to a color + # TODO I think this is fixed in 2.10.x + # assert color format of {_t} = red with "The color format should be red" + set bold format of {_t} to true + assert bold format of {_t} = true with "The bold format should be true" + + # Merge + Set {_merge} to merge components {_m} and {_t} with "s" + assert {_merge} is set with "Merging components should return a new component" + + # Translatable components with fallback + set {_trans} to translate component from "test.test" with fallback "some fallback" + assert fallback format of {_trans} is set with "Fallback of component should be set" + assert fallback format of {_trans} = "some fallback" with "Fallback of component should be 'some fallback'" + set fallback format of {_trans} to "a new fallback" + assert fallback format of {_trans} = "a new fallback" with "Fallback of component should be 'a new fallback'" + set {_m} to mini message from "test" + set fallback format of {_m} to "this is a fallback" + assert fallback format of {_m} is not set with "Fallback of non-translatable component should not be set" + delete {_trans} + set {_trans} to translate component from "Test.test" with args "some arg" with fallback "some fallback" + assert {_trans} is set with "Component with args and fallback should be set" diff --git a/src/test/scripts/general/virtual-furnace-test.sk b/src/test/scripts/general/virtual-furnace-test.sk index b27b13d00..ce63013cd 100644 --- a/src/test/scripts/general/virtual-furnace-test.sk +++ b/src/test/scripts/general/virtual-furnace-test.sk @@ -15,3 +15,4 @@ test "SkBee - virtual furnace elements": set machine name of {_furnace} to "&bSlow Furny" assert machine name of {_furnace} = "&bSlow Furny" with "Name of furnace should have been Slow Furny" + delete machine within {_furnace}