From d2f6e0a1c89367cfdbe218a0270c7996ce45c3e0 Mon Sep 17 00:00:00 2001 From: Lesley Dom Date: Tue, 8 Sep 2020 15:13:52 +0200 Subject: [PATCH] 1.14+ support & Recode --- src/com/arcaniax/buildersutilities/Main.java | 122 + .../buildersutilities/NoClipManager.java | 68 + .../arcaniax/buildersutilities/Settings.java | 36 + .../commands/AdvancedFlyCommand.java | 26 + .../commands/BannerCommand.java | 23 + .../commands/ColorCommand.java | 21 + .../commands/HelpCommand.java | 21 + .../commands/NightVisionCommand.java | 30 + .../commands/NoClipCommand.java | 32 + .../commands/SecretBlockCommand.java | 21 + .../commands/UtilsCommand.java | 24 + .../aliases/ConvexSelectionAliasCommand.java | 21 + .../commands/aliases/CopyAliasCommand.java | 27 + .../aliases/CuboidSelectionAliasCommand.java | 21 + .../aliases/DeformRotateAliasCommand.java | 49 + .../commands/aliases/FlipAliasCommand.java | 27 + .../aliases/FlySpeedAliasCommand.java | 27 + .../commands/aliases/PasteAliasCommand.java | 27 + .../commands/aliases/PosOneAliasCommand.java | 22 + .../commands/aliases/PosTwoAliasCommand.java | 21 + .../commands/aliases/ReplaceAliasCommand.java | 27 + .../commands/aliases/ScaleAliasCommand.java | 35 + .../commands/aliases/SetAliasCommand.java | 27 + .../commands/aliases/TwistAliasCommand.java | 46 + .../aliases/WalkSpeedAliasCommand.java | 28 + .../commands/system/CommandForwarder.java | 72 + .../commands/system/ICommand.java | 9 + .../listeners/BlockBreakListener.java | 67 + .../listeners/BlockPhysicsListener.java | 53 + .../listeners/ExplosionListener.java | 17 + .../listeners/IronTrapdoorListener.java | 59 + .../listeners/LeafDecayListener.java | 16 + .../listeners/PlayerInteractListener.java | 41 + .../listeners/PlayerMoveListener.java | 72 + .../listeners/PlayerQuitAndJoinListener.java | 39 + .../listeners/TeleportListener.java | 21 + .../listeners/TerracottaInteractListener.java | 66 + .../listeners/WeatherChangeListener.java | 15 + .../menus/BannerMenuProvider.java | 12 + .../menus/ColorMenuProvider.java | 133 ++ .../buildersutilities/menus/Menus.java | 61 + .../menus/SecretBlockMenuProvider.java | 30 + .../menus/UtilitiesMenuProvider.java | 216 ++ .../bannermenus/BannerColorMenuProvider.java | 35 + .../menus/bannermenus/BannerMenuProvider.java | 36 + .../BannerPatternMenuProvider.java | 36 + .../menus/inv/ClickableItem.java | 35 + .../menus/inv/InventoryListener.java | 23 + .../menus/inv/InventoryManager.java | 251 ++ .../menus/inv/SmartInventory.java | 215 ++ .../menus/inv/content/InventoryContents.java | 262 +++ .../menus/inv/content/InventoryProvider.java | 12 + .../menus/inv/content/Pagination.java | 124 + .../menus/inv/content/SlotIterator.java | 217 ++ .../menus/inv/content/SlotPos.java | 45 + .../inv/opener/ChestInventoryOpener.java | 34 + .../menus/inv/opener/InventoryOpener.java | 27 + .../inv/opener/SpecialInventoryOpener.java | 43 + .../buildersutilities/utils/BannerUtil.java | 197 ++ .../buildersutilities/utils/CustomConfig.java | 110 + .../buildersutilities/utils/Items.java | 81 + .../buildersutilities/utils/Metrics.java | 720 ++++++ .../buildersutilities/utils/NmsManager.java | 41 + .../buildersutilities/utils/Utility.java | 27 + .../buildersutilities/utils/XMaterial.java | 2088 +++++++++++++++++ 65 files changed, 6487 insertions(+) create mode 100644 src/com/arcaniax/buildersutilities/Main.java create mode 100644 src/com/arcaniax/buildersutilities/NoClipManager.java create mode 100644 src/com/arcaniax/buildersutilities/Settings.java create mode 100644 src/com/arcaniax/buildersutilities/commands/AdvancedFlyCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/BannerCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/ColorCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/HelpCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/NightVisionCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/NoClipCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/SecretBlockCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/UtilsCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/ConvexSelectionAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/CopyAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/CuboidSelectionAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/DeformRotateAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/FlipAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/FlySpeedAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/PasteAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/PosOneAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/PosTwoAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/ReplaceAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/ScaleAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/SetAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/TwistAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/aliases/WalkSpeedAliasCommand.java create mode 100644 src/com/arcaniax/buildersutilities/commands/system/CommandForwarder.java create mode 100644 src/com/arcaniax/buildersutilities/commands/system/ICommand.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/BlockBreakListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/BlockPhysicsListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/ExplosionListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/IronTrapdoorListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/LeafDecayListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/PlayerInteractListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/PlayerMoveListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/PlayerQuitAndJoinListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/TeleportListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/TerracottaInteractListener.java create mode 100644 src/com/arcaniax/buildersutilities/listeners/WeatherChangeListener.java create mode 100644 src/com/arcaniax/buildersutilities/menus/BannerMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/ColorMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/Menus.java create mode 100644 src/com/arcaniax/buildersutilities/menus/SecretBlockMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/UtilitiesMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/bannermenus/BannerColorMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/bannermenus/BannerMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/bannermenus/BannerPatternMenuProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/ClickableItem.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/InventoryListener.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/InventoryManager.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/SmartInventory.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/content/InventoryContents.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/content/InventoryProvider.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/content/Pagination.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/content/SlotIterator.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/content/SlotPos.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/opener/ChestInventoryOpener.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/opener/InventoryOpener.java create mode 100644 src/com/arcaniax/buildersutilities/menus/inv/opener/SpecialInventoryOpener.java create mode 100644 src/com/arcaniax/buildersutilities/utils/BannerUtil.java create mode 100644 src/com/arcaniax/buildersutilities/utils/CustomConfig.java create mode 100644 src/com/arcaniax/buildersutilities/utils/Items.java create mode 100644 src/com/arcaniax/buildersutilities/utils/Metrics.java create mode 100644 src/com/arcaniax/buildersutilities/utils/NmsManager.java create mode 100644 src/com/arcaniax/buildersutilities/utils/Utility.java create mode 100644 src/com/arcaniax/buildersutilities/utils/XMaterial.java diff --git a/src/com/arcaniax/buildersutilities/Main.java b/src/com/arcaniax/buildersutilities/Main.java new file mode 100644 index 0000000..a01da5d --- /dev/null +++ b/src/com/arcaniax/buildersutilities/Main.java @@ -0,0 +1,122 @@ +package com.arcaniax.buildersutilities; + +import com.arcaniax.buildersutilities.commands.system.CommandForwarder; +import com.arcaniax.buildersutilities.listeners.*; +import com.arcaniax.buildersutilities.menus.inv.InventoryManager; +import com.arcaniax.buildersutilities.utils.CustomConfig; +import com.arcaniax.buildersutilities.utils.Metrics; +import com.arcaniax.buildersutilities.utils.NmsManager; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.java.JavaPlugin; + +public final class Main extends JavaPlugin { + public static final String MSG_PREFIX = ChatColor.DARK_AQUA + "BuildersUtils> " + ChatColor.AQUA; + public static final String MSG_ERROR = ChatColor.DARK_RED + "Error: " + ChatColor.RED; + private static Main instance; + + private Metrics metrics; + private Settings settings; + private NoClipManager noClipManager; + + + + private InventoryManager inventoryManager; + private NmsManager nmsManager; + + @Override + public void onEnable() { + instance = this; + + this.settings = new Settings(new CustomConfig(this, "config.yml")); + this.noClipManager = new NoClipManager(); + this.nmsManager = new NmsManager(); + this.inventoryManager = new InventoryManager(this); + this.inventoryManager.init(); + + this.metrics = new Metrics(this, /*plugin id*/ 5168); + + this.getServer().getPluginManager().registerEvents(new BlockBreakListener(), this); + this.getServer().getPluginManager().registerEvents(new BlockPhysicsListener(), this); + this.getServer().getPluginManager().registerEvents(new ExplosionListener(), this); + this.getServer().getPluginManager().registerEvents(new IronTrapdoorListener(), this); + this.getServer().getPluginManager().registerEvents(new LeafDecayListener(), this); + this.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), this); + this.getServer().getPluginManager().registerEvents(new PlayerMoveListener(), this); + this.getServer().getPluginManager().registerEvents(new PlayerQuitAndJoinListener(), this); + this.getServer().getPluginManager().registerEvents(new TeleportListener(), this); + this.getServer().getPluginManager().registerEvents(new TerracottaInteractListener(), this); + this.getServer().getPluginManager().registerEvents(new WeatherChangeListener(), this); + + + CommandForwarder executor = new CommandForwarder(); + this.getCommand("bu").setExecutor(executor); + this.getCommand("buildersutils").setExecutor(executor); + this.getCommand("builders").setExecutor(executor); + this.getCommand("utils").setExecutor(executor); + this.getCommand("util").setExecutor(executor); + + CommandExecutor commandExecutor = new CommandExecutor() { + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + String[] commandArgs = new String[strings.length + 1]; + commandArgs[0] = s; + for (int i = 0; i < strings.length; i++) { + commandArgs[i + 1] = strings[i]; + } + executor.onCommand(commandSender, command, s, commandArgs); + return true; + } + }; + + getCommand("banner").setExecutor(commandExecutor); + getCommand("armorcolor").setExecutor(commandExecutor); + getCommand("blocks").setExecutor(commandExecutor); + getCommand("n").setExecutor(commandExecutor); + getCommand("nc").setExecutor(commandExecutor); + getCommand("/1").setExecutor(commandExecutor); + getCommand("/2").setExecutor(commandExecutor); + getCommand("/cuboid").setExecutor(commandExecutor); + getCommand("/convex").setExecutor(commandExecutor); + getCommand("/s").setExecutor(commandExecutor); + getCommand("/r").setExecutor(commandExecutor); + getCommand("/f").setExecutor(commandExecutor); + getCommand("/pa").setExecutor(commandExecutor); + getCommand("/c").setExecutor(commandExecutor); + getCommand("ws").setExecutor(commandExecutor); + getCommand("fs").setExecutor(commandExecutor); + getCommand("af").setExecutor(commandExecutor); + getCommand("advfly").setExecutor(commandExecutor); + getCommand("/derot").setExecutor(commandExecutor); + getCommand("/scale").setExecutor(commandExecutor); + getCommand("/twist").setExecutor(commandExecutor); + getCommand("butil").setExecutor(commandExecutor); + } + + @Override + public void onDisable() { + // Plugin shutdown logic + } + + public Settings getSettings() { + return settings; + } + + public NoClipManager getNoClipManager() { + return noClipManager; + } + + public InventoryManager getInventoryManager() { + return inventoryManager; + } + + public NmsManager getNmsManager() { + return nmsManager; + } + + public static Main getInstance() { + return instance; + } +} diff --git a/src/com/arcaniax/buildersutilities/NoClipManager.java b/src/com/arcaniax/buildersutilities/NoClipManager.java new file mode 100644 index 0000000..4fb410a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/NoClipManager.java @@ -0,0 +1,68 @@ +package com.arcaniax.buildersutilities; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.*; + +public class NoClipManager { + public static Set noClipPlayerIds; + + public NoClipManager() { + noClipPlayerIds = new HashSet<>(); + Bukkit.getScheduler().runTaskTimer(Main.getInstance(), this::checkForBlocks, 1L, 1L); + } + + private void checkForBlocks() { + for (UUID name : noClipPlayerIds) { + Player player = Bukkit.getPlayer(name); + if (player != null && player.isOnline()) { + if (player.getGameMode().equals(GameMode.CREATIVE)) { + boolean noClip; + if (player.getLocation().add(0, -0.1, 0).getBlock().getType() != Material.AIR && player.isSneaking()) { + noClip = true; + } else { + noClip = isNoClip(player); + } + if (noClip) { + player.setGameMode(GameMode.SPECTATOR); + } + } else if (player.getGameMode().equals(GameMode.SPECTATOR)) { + boolean noClip; + if (player.getLocation().add(0, -0.1, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } else noClip = isNoClip(player); + if (!noClip) { + player.setGameMode(GameMode.CREATIVE); + } + } + } + } + } + + private boolean isNoClip(Player player) { + boolean noClip = false; + if (player.getLocation().add(+0.4, 0, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(-0.4, 0, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(0, 0, +0.4).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(0, 0, -0.4).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(+0.4, 1, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(-0.4, 1, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(0, 1, +0.4).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(0, 1, -0.4).getBlock().getType() != Material.AIR) { + noClip = true; + } else if (player.getLocation().add(0, +1.9, 0).getBlock().getType() != Material.AIR) { + noClip = true; + } + return noClip; + } +} diff --git a/src/com/arcaniax/buildersutilities/Settings.java b/src/com/arcaniax/buildersutilities/Settings.java new file mode 100644 index 0000000..3801edd --- /dev/null +++ b/src/com/arcaniax/buildersutilities/Settings.java @@ -0,0 +1,36 @@ +package com.arcaniax.buildersutilities; + +import com.arcaniax.buildersutilities.utils.CustomConfig; + +public class Settings { + public static boolean disableWeatherChanges; + public static boolean disableRedstone; + public static boolean disablePhysics; + public static boolean disableGravityPhysics; + public static boolean disableExplosions; + public static boolean disableSoilTrample; + public static boolean disableLeavesDecay; + public static boolean fixAttackSpeed; + public static boolean preventDragonEggTeleport; + public static boolean sendErrorMessages; + + private final CustomConfig customConfig; + + public Settings(CustomConfig customConfig) { + this.customConfig = customConfig; + reloadSettings(); + } + + public void reloadSettings(){ + disableWeatherChanges = customConfig.get("disable-weather-changes", Boolean.class, true); + disableRedstone = customConfig.get("disable-redstone", Boolean.class, false); + disablePhysics = customConfig.get("disable-physics", Boolean.class, true); + disableGravityPhysics = customConfig.get("disable-gravity-physics", Boolean.class, false); + disableExplosions = customConfig.get("disable-explosions", Boolean.class, true); + disableSoilTrample = customConfig.get("disable-soil-trample", Boolean.class, true); + disableLeavesDecay = customConfig.get("disable-leaves-decay", Boolean.class, true); + fixAttackSpeed = customConfig.get("fix-attackspeed", Boolean.class, false); + preventDragonEggTeleport = customConfig.get("prevent-dragon-egg-teleport", Boolean.class, true); + sendErrorMessages = customConfig.get("send-error-messages", Boolean.class, true); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/AdvancedFlyCommand.java b/src/com/arcaniax/buildersutilities/commands/AdvancedFlyCommand.java new file mode 100644 index 0000000..79b2532 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/AdvancedFlyCommand.java @@ -0,0 +1,26 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import com.arcaniax.buildersutilities.listeners.PlayerMoveListener; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class AdvancedFlyCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.advancedfly")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (PlayerMoveListener.togglePlayer(player)) { + player.sendMessage(Main.MSG_PREFIX + "Advanced Fly " + ChatColor.GREEN + ChatColor.ITALIC + "Enabled"); + } else { + player.sendMessage(Main.MSG_PREFIX + "Advanced Fly " + ChatColor.RED + ChatColor.ITALIC + "Disabled"); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/BannerCommand.java b/src/com/arcaniax/buildersutilities/commands/BannerCommand.java new file mode 100644 index 0000000..e7c997a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/BannerCommand.java @@ -0,0 +1,23 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import com.arcaniax.buildersutilities.menus.Menus; +import org.bukkit.entity.Player; + +public class BannerCommand implements ICommand { + + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.banner")) { + if(Settings.sendErrorMessages){ + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Menus.BANNER_MENU.open(player); + } + +} diff --git a/src/com/arcaniax/buildersutilities/commands/ColorCommand.java b/src/com/arcaniax/buildersutilities/commands/ColorCommand.java new file mode 100644 index 0000000..b656927 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/ColorCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import com.arcaniax.buildersutilities.menus.Menus; +import org.bukkit.entity.Player; + +public class ColorCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.color")) { + if(Settings.sendErrorMessages){ + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Menus.COLOR_MENU.open(player); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/HelpCommand.java b/src/com/arcaniax/buildersutilities/commands/HelpCommand.java new file mode 100644 index 0000000..efa6b5a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/HelpCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.CommandForwarder; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class HelpCommand implements ICommand { + + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.help")) { + if(Settings.sendErrorMessages){ + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/commands/NightVisionCommand.java b/src/com/arcaniax/buildersutilities/commands/NightVisionCommand.java new file mode 100644 index 0000000..0a2208d --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/NightVisionCommand.java @@ -0,0 +1,30 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class NightVisionCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.nightvision")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) { + player.removePotionEffect(PotionEffectType.NIGHT_VISION); + player.sendMessage(Main.MSG_PREFIX + "Night Vision " + ChatColor.RED + ChatColor.ITALIC + "Disabled"); + } else { + player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, true, false)); + player.sendMessage(Main.MSG_PREFIX + "Night Vision " + ChatColor.GREEN + ChatColor.ITALIC + "Enabled"); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/NoClipCommand.java b/src/com/arcaniax/buildersutilities/commands/NoClipCommand.java new file mode 100644 index 0000000..e6ad1ca --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/NoClipCommand.java @@ -0,0 +1,32 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.NoClipManager; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; + +public class NoClipCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.noclip")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (NoClipManager.noClipPlayerIds.contains(player.getUniqueId())) { + NoClipManager.noClipPlayerIds.remove(player.getUniqueId()); + player.sendMessage(Main.MSG_PREFIX + "NoClip " + ChatColor.RED + ChatColor.ITALIC + "Disabled"); + if (player.getGameMode() == GameMode.SPECTATOR) { + player.setGameMode(GameMode.CREATIVE); + } + } else { + NoClipManager.noClipPlayerIds.add(player.getUniqueId()); + player.sendMessage(Main.MSG_PREFIX + "NoClip " + ChatColor.GREEN + ChatColor.ITALIC + "Enabled"); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/SecretBlockCommand.java b/src/com/arcaniax/buildersutilities/commands/SecretBlockCommand.java new file mode 100644 index 0000000..2e20e2b --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/SecretBlockCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import com.arcaniax.buildersutilities.menus.Menus; +import org.bukkit.entity.Player; + +public class SecretBlockCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.secretblocks")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Menus.SECRET_BLOCK_MENU.open(player); + } +} \ No newline at end of file diff --git a/src/com/arcaniax/buildersutilities/commands/UtilsCommand.java b/src/com/arcaniax/buildersutilities/commands/UtilsCommand.java new file mode 100644 index 0000000..580a752 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/UtilsCommand.java @@ -0,0 +1,24 @@ +package com.arcaniax.buildersutilities.commands; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import com.arcaniax.buildersutilities.menus.Menus; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class UtilsCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.gui")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Menus.TOGGLE_MENU.open(player); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/ConvexSelectionAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/ConvexSelectionAliasCommand.java new file mode 100644 index 0000000..328922f --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/ConvexSelectionAliasCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class ConvexSelectionAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Main.getInstance().getServer().dispatchCommand(player, "/sel convex"); + + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/CopyAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/CopyAliasCommand.java new file mode 100644 index 0000000..3b19314 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/CopyAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class CopyAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "/copy " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/CuboidSelectionAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/CuboidSelectionAliasCommand.java new file mode 100644 index 0000000..5f69f6e --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/CuboidSelectionAliasCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class CuboidSelectionAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Main.getInstance().getServer().dispatchCommand(player, "/sel cuboid"); + + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/DeformRotateAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/DeformRotateAliasCommand.java new file mode 100644 index 0000000..d8a1e0b --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/DeformRotateAliasCommand.java @@ -0,0 +1,49 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class DeformRotateAliasCommand implements ICommand { + private final float radiansPerDegree = 0.0174533f; + + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (args.length != 2) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//derot [axis] [degrees]"); + return; + } + + int degrees; + try { + degrees = Integer.parseInt(args[1]); + } catch (Exception e) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//derot [axis] [degrees]"); + return; + } +// Old: +// float radian = (float) (((float) degrees / (float) 360) * 2 * Math.PI); + + //Use the degree to radian conversion number: "0.0174533" radians per degree + float radian = degrees * radiansPerDegree; + + if (args[0].equalsIgnoreCase("x")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(y,z," + radian + ")"); + } else if (args[0].equalsIgnoreCase("y")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(x,z," + radian + ")"); + } else if (args[0].equalsIgnoreCase("z")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(x,y," + radian + ")"); + } else { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//derot [axis] [degrees]"); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/FlipAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/FlipAliasCommand.java new file mode 100644 index 0000000..b661f89 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/FlipAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class FlipAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "/flip " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/FlySpeedAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/FlySpeedAliasCommand.java new file mode 100644 index 0000000..3d48f0f --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/FlySpeedAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class FlySpeedAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "speed fly " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/PasteAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/PasteAliasCommand.java new file mode 100644 index 0000000..f30a9f4 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/PasteAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class PasteAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "/paste " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/PosOneAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/PosOneAliasCommand.java new file mode 100644 index 0000000..0ec02c3 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/PosOneAliasCommand.java @@ -0,0 +1,22 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class PosOneAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Main.getInstance().getServer().dispatchCommand(player, "/pos1"); + + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/PosTwoAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/PosTwoAliasCommand.java new file mode 100644 index 0000000..52a68e9 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/PosTwoAliasCommand.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class PosTwoAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + Main.getInstance().getServer().dispatchCommand(player, "/pos2"); + + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/ReplaceAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/ReplaceAliasCommand.java new file mode 100644 index 0000000..c7c9a6d --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/ReplaceAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class ReplaceAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "/replace " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/ScaleAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/ScaleAliasCommand.java new file mode 100644 index 0000000..c1babc1 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/ScaleAliasCommand.java @@ -0,0 +1,35 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class ScaleAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (args.length != 1) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//scale [size]"); + return; + } + + + double size; + try { + size = Double.parseDouble(args[0]); + } catch (Exception e) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//scale [size]"); + return; + } + + Main.getInstance().getServer().dispatchCommand(player, "/deform x/=" + size + ";y/=" + size + ";z/=" + size); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/SetAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/SetAliasCommand.java new file mode 100644 index 0000000..a63320a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/SetAliasCommand.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.entity.Player; + +public class SetAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "/set " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/TwistAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/TwistAliasCommand.java new file mode 100644 index 0000000..f216294 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/TwistAliasCommand.java @@ -0,0 +1,46 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class TwistAliasCommand implements ICommand { + private final float radiansPerDegree = 0.0174533f; + + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + if (args.length != 2) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//twist [axis] [degrees]"); + return; + } + + int degrees; + try { + degrees = Integer.parseInt(args[1]); + } catch (Exception e) { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//twist [axis] [degrees]"); + return; + } + + float radian = degrees * radiansPerDegree; + + if (args[0].equalsIgnoreCase("x")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(y,z," + radian / 2 + "*(x+1))"); + } else if (args[0].equalsIgnoreCase("y")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(x,z," + radian / 2 + "*(y+1))"); + } else if (args[0].equalsIgnoreCase("z")) { + Main.getInstance().getServer().dispatchCommand(player, "/deform rotate(x,y," + radian / 2 + "*(z+1))"); + } else { + player.sendMessage(Main.MSG_PREFIX + ChatColor.RED + "//twist [axis] [degrees]"); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/aliases/WalkSpeedAliasCommand.java b/src/com/arcaniax/buildersutilities/commands/aliases/WalkSpeedAliasCommand.java new file mode 100644 index 0000000..09a576f --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/aliases/WalkSpeedAliasCommand.java @@ -0,0 +1,28 @@ +package com.arcaniax.buildersutilities.commands.aliases; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.Settings; +import com.arcaniax.buildersutilities.commands.system.ICommand; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class WalkSpeedAliasCommand implements ICommand { + @Override + public void execute(Player player, String[] args) { + if (!player.hasPermission("builders.util.aliases")) { + if (Settings.sendErrorMessages) { + player.sendMessage(Main.MSG_ERROR + "You do not have access to this command."); + } + return; + } + + StringBuilder builder = new StringBuilder(); + if (args.length != 0) { + for (String arg : args) { + builder.append(arg).append(" "); + } + } + + Main.getInstance().getServer().dispatchCommand(player, "speed walk " + builder.toString()); + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/system/CommandForwarder.java b/src/com/arcaniax/buildersutilities/commands/system/CommandForwarder.java new file mode 100644 index 0000000..23643c1 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/system/CommandForwarder.java @@ -0,0 +1,72 @@ +package com.arcaniax.buildersutilities.commands.system; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.commands.*; +import com.arcaniax.buildersutilities.commands.aliases.*; +import org.bukkit.ChatColor; +import org.bukkit.block.Banner; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class CommandForwarder implements CommandExecutor { + private final Map commands; + + public CommandForwarder() { + commands = new HashMap<>(); + registerCommand(new HelpCommand(), "help", "h", "?"); + registerCommand(new AdvancedFlyCommand(), "af", "advancedfly"); + registerCommand(new BannerCommand(), "banner"); + registerCommand(new ColorCommand(), "color", "ac", "armorcolor"); + registerCommand(new SecretBlockCommand(), "secretblock", "secretblocks", "blocks"); + registerCommand(new NoClipCommand(), "noclip", "nc"); + registerCommand(new NightVisionCommand(), "nv", "nightvision", "n"); + registerCommand(new UtilsCommand(), "utils", "u", "util", "gui", "inventory"); + registerCommand(new PosOneAliasCommand(), "p1", "1", "one", "pos1"); + registerCommand(new PosTwoAliasCommand(), "p2", "2", "two", "pos2"); + registerCommand(new CuboidSelectionAliasCommand(), "cuboid", "cube"); + registerCommand(new ConvexSelectionAliasCommand(), "convex", "conv"); + registerCommand(new SetAliasCommand(), "set", "s"); + registerCommand(new ReplaceAliasCommand(), "replace", "r", "repl", "rep"); + registerCommand(new PasteAliasCommand(), "paste", "pa"); + registerCommand(new FlipAliasCommand(), "flip", "f"); + registerCommand(new CopyAliasCommand(), "copy", "c", "clone"); + registerCommand(new DeformRotateAliasCommand(), "deformrotate", "defrot", "dr"); + registerCommand(new TwistAliasCommand(), "twist", "tw", "t"); + registerCommand(new ScaleAliasCommand(), "scale", "sc"); + registerCommand(new WalkSpeedAliasCommand(), "walkspeed", "ws"); + registerCommand(new FlySpeedAliasCommand(), "flyspeed", "fs"); + } + + private void registerCommand(ICommand iCommand, String... aliases) { + for (String alias : aliases) { + commands.put(alias.toLowerCase(), iCommand); + } + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + //Make it player-only + Player player = sender instanceof Player ? ((Player) sender) : null; + if (player == null) { + sender.sendMessage(Main.MSG_ERROR + "Sorry this command can only be used by a player."); + return false; + } + + if (args.length == 0) { + new HelpCommand().execute(player, args); + return true; + } + + ICommand iCommand = commands.get(args[0].toLowerCase()); + if (iCommand != null) { + iCommand.execute(player, Arrays.copyOfRange(args, 1, args.length)); + } + return true; + } +} diff --git a/src/com/arcaniax/buildersutilities/commands/system/ICommand.java b/src/com/arcaniax/buildersutilities/commands/system/ICommand.java new file mode 100644 index 0000000..2948f89 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/commands/system/ICommand.java @@ -0,0 +1,9 @@ +package com.arcaniax.buildersutilities.commands.system; + +import org.bukkit.entity.Player; + +public interface ICommand { + + public void execute(Player player, String[] args); + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/BlockBreakListener.java b/src/com/arcaniax/buildersutilities/listeners/BlockBreakListener.java new file mode 100644 index 0000000..0c6bf83 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/BlockBreakListener.java @@ -0,0 +1,67 @@ +package com.arcaniax.buildersutilities.listeners; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.type.Slab; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; + +import java.util.*; + +public class BlockBreakListener implements Listener { + public static Set slabIds; + + public BlockBreakListener(){ + slabIds = new HashSet<>(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onBlockBreak(BlockBreakEvent e) { + if (e.isCancelled()) { + return; + } + if (slabIds.contains(e.getPlayer().getUniqueId())) { + return; + } + if (!e.getPlayer().getGameMode().equals(GameMode.CREATIVE)) { + return; + } + Material type = e.getPlayer().getInventory().getItemInMainHand().getType(); + if (type.toString().toLowerCase().contains("slab")) { + if (e.isCancelled()) { + return; + } + if (e.getBlock().getType().toString().toLowerCase().contains("slab")) { + if (isTop(e.getPlayer(), e.getBlock())) { + Slab blockdata = (Slab) e.getBlock().getBlockData(); + if (blockdata.getType().equals(Slab.Type.DOUBLE)) { + blockdata.setType(Slab.Type.BOTTOM); + e.getBlock().setBlockData(blockdata, true); + e.setCancelled(true); + } + } else { + Slab blockdata = (Slab) e.getBlock().getBlockData(); + if (blockdata.getType().equals(Slab.Type.DOUBLE)) { + blockdata.setType(Slab.Type.TOP); + e.getBlock().setBlockData(blockdata, true); + e.setCancelled(true); + } + } + } + } + } + + private boolean isTop(Player player, Block block) { + Location start = player.getEyeLocation().clone(); + while ((!start.getBlock().equals(block)) && start.distance(player.getEyeLocation()) < 6) { + start.add(player.getLocation().getDirection().multiply(0.05)); + } + return start.getY() % 1 > 0.5; + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/BlockPhysicsListener.java b/src/com/arcaniax/buildersutilities/listeners/BlockPhysicsListener.java new file mode 100644 index 0000000..5bce16a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/BlockPhysicsListener.java @@ -0,0 +1,53 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPhysicsEvent; + +public class BlockPhysicsListener implements Listener { + @EventHandler + public void onPhysics(BlockPhysicsEvent e) { + try { + if (e.getChangedType().name().toLowerCase().contains("chest") || + e.getChangedType().name().toLowerCase().contains("fence") || + e.getChangedType().name().toLowerCase().contains("pane") || + e.getChangedType().name().toLowerCase().contains("wall") || + e.getChangedType().name().toLowerCase().contains("bar")) { + return; + } + } catch (Exception ex) { + return; + } + if (!Settings.disableRedstone) { + if (e.getChangedType().name().toLowerCase().contains("redstone") || + e.getChangedType().name().toLowerCase().contains("air") || + e.getChangedType().name().toLowerCase().contains("daylight") || + e.getChangedType().name().toLowerCase().contains("diode") || + e.getChangedType().name().toLowerCase().contains("note") || + e.getChangedType().name().toLowerCase().contains("lever") || + e.getChangedType().name().toLowerCase().contains("button") || + e.getChangedType().name().toLowerCase().contains("command") || + e.getChangedType().name().toLowerCase().contains("tripwire") || + e.getChangedType().name().toLowerCase().contains("plate") || + e.getChangedType().name().toLowerCase().contains("string") || + e.getChangedType().name().toLowerCase().contains("piston") || + e.getChangedType().name().toLowerCase().contains("observer")) { + if (!e.getBlock().getType().name().contains("air")) { + return; + } + } + } + + if (e.getChangedType().hasGravity()) { + if (Settings.disableGravityPhysics) { + e.setCancelled(true); + } + } else { + if (Settings.disablePhysics) { + e.setCancelled(true); + } + } + + } +} diff --git a/src/com/arcaniax/buildersutilities/listeners/ExplosionListener.java b/src/com/arcaniax/buildersutilities/listeners/ExplosionListener.java new file mode 100644 index 0000000..e4cb27c --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/ExplosionListener.java @@ -0,0 +1,17 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityExplodeEvent; + +public class ExplosionListener implements Listener { + @EventHandler + public void onExplode(EntityExplodeEvent event) { + if (Settings.disableExplosions) { + event.setCancelled(true); + } + } + + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/IronTrapdoorListener.java b/src/com/arcaniax/buildersutilities/listeners/IronTrapdoorListener.java new file mode 100644 index 0000000..d451e97 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/IronTrapdoorListener.java @@ -0,0 +1,59 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Main; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.type.TrapDoor; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; + +import java.util.*; + +public class IronTrapdoorListener implements Listener { + public static Set ironTrapdoorIds; + + public IronTrapdoorListener() { + ironTrapdoorIds = new HashSet<>(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void ironTrapDoorInteract(final PlayerInteractEvent e) { + if (e.isCancelled()) { + return; + } + if (ironTrapdoorIds.contains(e.getPlayer().getUniqueId())) { + return; + } + if (!e.getPlayer().getGameMode().equals(GameMode.CREATIVE)) { + return; + } + if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + return; + } + if (!e.getClickedBlock().getType().equals(Material.IRON_TRAPDOOR)) { + return; + } + if (Main.getInstance().getNmsManager().isAtLeastVersion(1, 9, 0)) { + if (!e.getHand().equals(EquipmentSlot.HAND)) { + return; + } + } + if (e.getPlayer().isSneaking()) { + return; + } + Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> { + Block b = e.getClickedBlock(); + TrapDoor trapDoor = (TrapDoor) b.getBlockData(); + trapDoor.setOpen(!trapDoor.isOpen()); + b.setBlockData(trapDoor); + }, 0L); + e.setCancelled(true); + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/LeafDecayListener.java b/src/com/arcaniax/buildersutilities/listeners/LeafDecayListener.java new file mode 100644 index 0000000..02266c5 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/LeafDecayListener.java @@ -0,0 +1,16 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.LeavesDecayEvent; + +public class LeafDecayListener implements Listener { + @EventHandler + public void onLeafDecay(LeavesDecayEvent event) { + if (Settings.disableLeavesDecay) { + event.setCancelled(true); + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/PlayerInteractListener.java b/src/com/arcaniax/buildersutilities/listeners/PlayerInteractListener.java new file mode 100644 index 0000000..22ed165 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/PlayerInteractListener.java @@ -0,0 +1,41 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class PlayerInteractListener implements Listener { + @EventHandler(priority = EventPriority.MONITOR) + public void onDragonEggTP(PlayerInteractEvent event) { + if (event.isCancelled()) { + return; + } + if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) + && event.getClickedBlock().getType().equals(Material.DRAGON_EGG) + && Settings.preventDragonEggTeleport) { + event.setCancelled(true); + } + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.isCancelled()) { + return; + } + if (Settings.disableSoilTrample) { + if (event.getAction() == Action.PHYSICAL) { + Block block = event.getClickedBlock(); + if (block != null && block.getType() == Material.FARMLAND) { + event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY); + event.setCancelled(true); + } + } + } + + } +} diff --git a/src/com/arcaniax/buildersutilities/listeners/PlayerMoveListener.java b/src/com/arcaniax/buildersutilities/listeners/PlayerMoveListener.java new file mode 100644 index 0000000..7ea0ad3 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/PlayerMoveListener.java @@ -0,0 +1,72 @@ +package com.arcaniax.buildersutilities.listeners; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.util.Vector; + +import java.util.*; + +public class PlayerMoveListener implements Listener { + private final HashMap lastVelocity = new HashMap<>(); + private static final List slower = new ArrayList<>(); + private static final List slower2 = new ArrayList<>(); + public static Set enabledPlayers = new HashSet<>(); + + public static boolean togglePlayer(Player p) { + if (enabledPlayers.contains(p.getUniqueId())) { + enabledPlayers.remove(p.getUniqueId()); + return false; + } else { + enabledPlayers.add(p.getUniqueId()); + return true; + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onMove(final PlayerMoveEvent e) { + if (e.getPlayer().isFlying()) { + if (!enabledPlayers.contains(e.getPlayer().getUniqueId())) { + return; + } + Double speed = e.getFrom().clone().add(0, -e.getFrom().getY(), 0).distance(e.getTo().clone().add(0, -e.getTo().getY(), 0)); + + if (Math.abs(e.getFrom().getYaw() - e.getTo().getYaw()) > 5) { + return; + } + if (Math.abs(e.getFrom().getPitch() - e.getTo().getPitch()) > 5) { + return; + } + if (lastVelocity.containsKey(e.getPlayer().getName())) { + Double lastSpeed = lastVelocity.get(e.getPlayer().getName()); + if (speed * 1.3 < lastSpeed) { + if (slower.contains(e.getPlayer().getName())) { + if (slower2.contains(e.getPlayer().getName())) { + Vector v = e.getPlayer().getVelocity().clone(); + v.setX(0); + v.setZ(0); + e.getPlayer().setVelocity(v); + lastVelocity.put(e.getPlayer().getName(), 0.0); + //No more if slower.contains** as if e.getPlayer().getName() isn't thhere, it won't get removed (: + slower.remove(e.getPlayer().getName()); + slower2.remove(e.getPlayer().getName()); + } else { + slower2.add(e.getPlayer().getName()); + } + } else { + slower.add(e.getPlayer().getName()); + } + } else if (speed > lastSpeed) { + lastVelocity.put(e.getPlayer().getName(), speed); + slower.remove(e.getPlayer().getName()); + slower2.remove(e.getPlayer().getName()); + } + } else { + lastVelocity.put(e.getPlayer().getName(), speed); + slower.remove(e.getPlayer().getName()); + } + } + } +} diff --git a/src/com/arcaniax/buildersutilities/listeners/PlayerQuitAndJoinListener.java b/src/com/arcaniax/buildersutilities/listeners/PlayerQuitAndJoinListener.java new file mode 100644 index 0000000..3fb994a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/PlayerQuitAndJoinListener.java @@ -0,0 +1,39 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.NoClipManager; +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerQuitAndJoinListener implements Listener { + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + Player player = event.getPlayer(); + NoClipManager.noClipPlayerIds.remove(player.getUniqueId()); + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + if (Main.getInstance().getNmsManager().isAtLeastVersion(1, 9, 0)) { + AttributeInstance attribute = event.getPlayer().getAttribute(Attribute.GENERIC_ATTACK_SPEED); + if (attribute == null) { + return; + } + + if (Settings.fixAttackSpeed) { + attribute.setBaseValue(1024.0D); + } else if (attribute.getBaseValue() == 1024.0D) { + attribute.setBaseValue(attribute.getDefaultValue()); + } + event.getPlayer().saveData(); + + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/TeleportListener.java b/src/com/arcaniax/buildersutilities/listeners/TeleportListener.java new file mode 100644 index 0000000..1f2e5b7 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/TeleportListener.java @@ -0,0 +1,21 @@ +package com.arcaniax.buildersutilities.listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class TeleportListener implements Listener { + @EventHandler + public void onTeleport(PlayerTeleportEvent event) { + if (event.isCancelled()) { + return; + } + if (event.getCause().equals(PlayerTeleportEvent.TeleportCause.SPECTATE)) { + //TODO what is this tpgm3 lol + if (!event.getPlayer().hasPermission("builders.util.tpgm3")) { + event.setCancelled(true); + } + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/TerracottaInteractListener.java b/src/com/arcaniax/buildersutilities/listeners/TerracottaInteractListener.java new file mode 100644 index 0000000..bef5554 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/TerracottaInteractListener.java @@ -0,0 +1,66 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Main; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Directional; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; + +import java.util.*; + +public class TerracottaInteractListener implements Listener { + public static Set terracottaIds; + + public TerracottaInteractListener() { + terracottaIds = new HashSet<>(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void GlazedTerracottaInteract(PlayerInteractEvent event) { + if (event.isCancelled()) { + return; + } + if (terracottaIds.contains(event.getPlayer().getUniqueId())) { + return; + } + if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + return; + } + if (!event.getHand().equals(EquipmentSlot.HAND)) { + return; + } + if (!event.getClickedBlock().getType().name().contains("GLAZED")) { + return; + } + if (!event.getPlayer().isSneaking()) { + return; + } + Material type = event.getPlayer().getInventory().getItemInHand().getType(); + if (!(type.equals(Material.AIR))) { + return; + } + Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> { + Block block = event.getClickedBlock(); + Directional directional = (Directional) block.getBlockData(); + if (directional.getFacing().equals(BlockFace.NORTH)) { + directional.setFacing(BlockFace.EAST); + } else if (directional.getFacing().equals(BlockFace.EAST)) { + directional.setFacing(BlockFace.SOUTH); + } else if (directional.getFacing().equals(BlockFace.SOUTH)) { + directional.setFacing(BlockFace.WEST); + } else if (directional.getFacing().equals(BlockFace.WEST)) { + directional.setFacing(BlockFace.NORTH); + } + block.setBlockData(directional); + }, 0L); + event.setCancelled(true); + } + +} diff --git a/src/com/arcaniax/buildersutilities/listeners/WeatherChangeListener.java b/src/com/arcaniax/buildersutilities/listeners/WeatherChangeListener.java new file mode 100644 index 0000000..25a9614 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/listeners/WeatherChangeListener.java @@ -0,0 +1,15 @@ +package com.arcaniax.buildersutilities.listeners; + +import com.arcaniax.buildersutilities.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.weather.WeatherChangeEvent; + +public class WeatherChangeListener implements Listener { + @EventHandler + public void onWeather(WeatherChangeEvent e) { + if (Settings.disableWeatherChanges) { + e.setCancelled(true); + } + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/BannerMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/BannerMenuProvider.java new file mode 100644 index 0000000..6b26022 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/BannerMenuProvider.java @@ -0,0 +1,12 @@ +package com.arcaniax.buildersutilities.menus; + +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import org.bukkit.entity.Player; + +public class BannerMenuProvider implements InventoryProvider { + @Override + public void init(Player player, InventoryContents contents) { + + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/ColorMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/ColorMenuProvider.java new file mode 100644 index 0000000..686f42b --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/ColorMenuProvider.java @@ -0,0 +1,133 @@ +package com.arcaniax.buildersutilities.menus; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class ColorMenuProvider implements InventoryProvider { + private static final float MULTIPLIER = 255f / 20f; + private static final String LORE = "&7__&7Left click to increase__&7Right click to decrease__&7Shift click to change by 5"; + + @Override + public void init(Player player, InventoryContents contents) { + setRedItem(player, contents, 10); + setRedRandomItem(player, contents); + setGreenItem(player, contents, 10); + setGreenRandomItem(player, contents); + setBlueItem(player, contents, 10); + setBlueRandomItem(player, contents); + + setLeatherItems(player, contents); + } + + private void setLeatherItems(Player player, InventoryContents contents) { + int r; + if(contents.get(3, 4).get().getItem().getType().equals(Material.RED_STAINED_GLASS)){ + r = 0; + }else{ + r = (int) (contents.get(3, 4).get().getItem().getAmount() * MULTIPLIER); + } + + int g; + if(contents.get(3, 5).get().getItem().getType().equals(Material.GREEN_STAINED_GLASS)){ + g = 0; + }else{ + g = (int) (contents.get(3, 5).get().getItem().getAmount() * MULTIPLIER); + } + + int b; + if(contents.get(3, 6).get().getItem().getType().equals(Material.BLUE_STAINED_GLASS)){ + b = 0; + }else{ + b = (int) (contents.get(3, 6).get().getItem().getAmount() * MULTIPLIER); + } + + contents.set(1, 1, ClickableItem.of(Items.color(new ItemStack(Material.LEATHER_HELMET), r, g, b), + inventoryClickEvent -> player.getInventory().addItem(Items.color(new ItemStack(Material.LEATHER_HELMET), r, g, b)))); + contents.set(2, 1, ClickableItem.of(Items.color(new ItemStack(Material.LEATHER_CHESTPLATE), r, g, b), + inventoryClickEvent -> player.getInventory().addItem(Items.color(new ItemStack(Material.LEATHER_CHESTPLATE), r, g, b)))); + contents.set(3, 1, ClickableItem.of(Items.color(new ItemStack(Material.LEATHER_LEGGINGS), r, g, b), + inventoryClickEvent -> player.getInventory().addItem(Items.color(new ItemStack(Material.LEATHER_LEGGINGS), r, g, b)))); + contents.set(4, 1, ClickableItem.of(Items.color(new ItemStack(Material.LEATHER_BOOTS), r, g, b), + inventoryClickEvent -> player.getInventory().addItem(Items.color(new ItemStack(Material.LEATHER_BOOTS), r, g, b)))); + } + + private void setRedItem(Player player, InventoryContents contents, int amount) { + contents.set(3, 4, ClickableItem.of( + amount == 0 ? Items.create(Material.RED_STAINED_GLASS, "&cRed", LORE) : + Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvM2Y0NmMzMWQ2ZWU2ZWE2MTlmNzJlNzg1MjMyY2IwNDhhYjI3MDQ2MmRiMGNiMTQ1NDUxNDQzNjI1MWMxYSJ9fX0=", + amount, "&cRed", LORE), inventoryClickEvent -> { + if (inventoryClickEvent.isShiftClick()) { + setRedItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 5, 20) : Math.max(amount - 5, 0)); + } else { + setRedItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 1, 20) : Math.max(amount - 1, 0)); + } + setLeatherItems(player, contents); + })); + } + + private void setRedRandomItem(Player player, InventoryContents contents) { + contents.set(2, 4, ClickableItem.of(Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTEzMWRlOGU5NTFmZGQ3YjlhM2QyMzlkN2NjM2FhM2U4NjU1YTMzNmI5OTliOWVkYmI0ZmIzMjljYmQ4NyJ9fX0=", + 1, "&cClick to randomize", ""), inventoryClickEvent -> { + setRedItem(player, contents, ThreadLocalRandom.current().nextInt(0, 21)); + setLeatherItems(player, contents); + })); + } + + private void setGreenItem(Player player, InventoryContents contents, int amount) { + contents.set(3, 5, ClickableItem.of( + amount == 0 ? Items.create(Material.GREEN_STAINED_GLASS, "&aGreen", LORE) : + Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzZmNjlmN2I3NTM4YjQxZGMzNDM5ZjM2NThhYmJkNTlmYWNjYTM2NmYxOTBiY2YxZDZkMGEwMjZjOGY5NiJ9fX0=", + amount, "&aGreen", LORE), inventoryClickEvent -> { + if (inventoryClickEvent.isShiftClick()) { + setGreenItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 5, 20) : Math.max(amount - 5, 0)); + } else { + setGreenItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 1, 20) : Math.max(amount - 1, 0)); + } + setLeatherItems(player, contents); + })); + } + + private void setGreenRandomItem(Player player, InventoryContents contents) { + contents.set(2, 5, ClickableItem.of(Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWMzY2VjNjg3NjlmZTljOTcxMjkxZWRiN2VmOTZhNGUzYjYwNDYyY2ZkNWZiNWJhYTFjYmIzYTcxNTEzZTdiIn19fQ==", + 1, "&aClick to randomize", ""), inventoryClickEvent -> { + setGreenItem(player, contents, ThreadLocalRandom.current().nextInt(0, 21)); + setLeatherItems(player, contents); + })); + } + + private void setBlueItem(Player player, InventoryContents contents, int amount) { + contents.set(3, 6, ClickableItem.of( + amount == 0 ? Items.create(Material.BLUE_STAINED_GLASS, "&bBlue", LORE) : + Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjgzOWUzODFkOWZlZGFiNmY4YjU5Mzk2YTI3NjQyMzhkY2ViMmY3ZWVhODU2ZGM2ZmM0NDc2N2RhMzgyZjEifX19", + amount, "&bBlue", LORE), inventoryClickEvent -> { + if (inventoryClickEvent.isShiftClick()) { + setBlueItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 5, 20) : Math.max(amount - 5, 0)); + } else { + setBlueItem(player, contents, + inventoryClickEvent.isLeftClick() ? Math.min(amount + 1, 20) : Math.max(amount - 1, 0)); + } + setLeatherItems(player, contents); + })); + } + + private void setBlueRandomItem(Player player, InventoryContents contents) { + contents.set(2, 6, ClickableItem.of(Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjMyOGYzNzhmMjhhOTg3MjIyNmY1Y2UwNGQ2ZTFkZmExMTE2MTg1ODdmNDhkZmExZmU4MmQwNDMyMTZhNWNmIn19fQ==", + 1, "&bClick to randomize", ""), inventoryClickEvent -> { + setBlueItem(player, contents, ThreadLocalRandom.current().nextInt(0, 21)); + setLeatherItems(player, contents); + })); + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/Menus.java b/src/com/arcaniax/buildersutilities/menus/Menus.java new file mode 100644 index 0000000..0bb4cdd --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/Menus.java @@ -0,0 +1,61 @@ +package com.arcaniax.buildersutilities.menus; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.menus.bannermenus.BannerMenuProvider; +import com.arcaniax.buildersutilities.menus.inv.InventoryListener; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryCloseEvent; + +public class Menus { + + private static final InventoryListener removeGhostItemsListener = + new InventoryListener<>(InventoryCloseEvent.class, inventoryCloseEvent -> { + Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> { + ((Player) inventoryCloseEvent.getPlayer()).updateInventory(); + }, 1L); + }); + + public static final SmartInventory BANNER_MENU = SmartInventory.builder() + .manager(Main.getInstance().getInventoryManager()) + .id("buildersutilsbanner") + .provider(new BannerMenuProvider()) + .size(6, 9) + .listener(removeGhostItemsListener) + .title(ChatColor.BLUE + "Select a base color") + .closeable(true) + .build(); + + public static final SmartInventory COLOR_MENU = SmartInventory.builder() + .manager(Main.getInstance().getInventoryManager()) + .id("buildersutilscolor") + .provider(new ColorMenuProvider()) + .size(6, 9) + .listener(removeGhostItemsListener) + .title(ChatColor.BLUE + "Armor Color Creator") + .closeable(true) + .build(); + + public static final SmartInventory SECRET_BLOCK_MENU = SmartInventory.builder() + .manager(Main.getInstance().getInventoryManager()) + .id("buildersutilssecretblock") + .provider(new SecretBlockMenuProvider()) + .size(1, 9) + .listener(removeGhostItemsListener) + .title(ChatColor.BLUE + "Secret Blocks") + .closeable(true) + .build(); + + public static final SmartInventory TOGGLE_MENU = SmartInventory.builder() + .manager(Main.getInstance().getInventoryManager()) + .id("buildersutilstoggle") + .provider(new UtilitiesMenuProvider()) + .size(3, 9) + .listener(removeGhostItemsListener) + .title(ChatColor.BLUE + "Builder's Utilities") + .closeable(true) + .build(); + +} diff --git a/src/com/arcaniax/buildersutilities/menus/SecretBlockMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/SecretBlockMenuProvider.java new file mode 100644 index 0000000..23ccc07 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/SecretBlockMenuProvider.java @@ -0,0 +1,30 @@ +package com.arcaniax.buildersutilities.menus; + +import com.arcaniax.buildersutilities.Main; +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class SecretBlockMenuProvider implements InventoryProvider { + private static ItemStack SPAWNER = Items.create(Material.SPAWNER, (short) 0, 1, ChatColor.DARK_AQUA + "Spawner Cage", ""); + private static ItemStack BARRIER = Items.create(Material.BARRIER, (short) 0, 1, ChatColor.DARK_AQUA + "Barrier", ""); + private static ItemStack DRAGON_EGG = Items.create(Material.DRAGON_EGG, (short) 0, 1, ChatColor.DARK_AQUA + "Dragon Egg", ""); + private static ItemStack GRASS_PATH = Items.create(Material.GRASS_PATH, (short) 0, 1, ChatColor.DARK_AQUA + "Grass Path", ""); + + @Override + public void init(Player player, InventoryContents contents) { + contents.set(0, 0, ClickableItem.of(SPAWNER, inventoryClickEvent -> player.getInventory().addItem(new ItemStack(Material.SPAWNER)))); + contents.set(0, 1, ClickableItem.of(BARRIER, inventoryClickEvent -> player.getInventory().addItem(new ItemStack(Material.BARRIER)))); + contents.set(0, 2, ClickableItem.of(DRAGON_EGG, inventoryClickEvent -> player.getInventory().addItem(new ItemStack(Material.DRAGON_EGG)))); + if (Main.getInstance().getNmsManager().isAtLeastVersion(1, 9, 0)) { + contents.set(0, 3, ClickableItem.of(GRASS_PATH, inventoryClickEvent -> player.getInventory().addItem(new ItemStack(Material.GRASS_PATH)))); + } + } + + +} diff --git a/src/com/arcaniax/buildersutilities/menus/UtilitiesMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/UtilitiesMenuProvider.java new file mode 100644 index 0000000..8fe9bcd --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/UtilitiesMenuProvider.java @@ -0,0 +1,216 @@ +package com.arcaniax.buildersutilities.menus; + +import com.arcaniax.buildersutilities.NoClipManager; +import com.arcaniax.buildersutilities.listeners.BlockBreakListener; +import com.arcaniax.buildersutilities.listeners.IronTrapdoorListener; +import com.arcaniax.buildersutilities.listeners.PlayerMoveListener; +import com.arcaniax.buildersutilities.listeners.TerracottaInteractListener; +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class UtilitiesMenuProvider implements InventoryProvider { + private static final ItemStack ENABLED = new ItemStack(Material.GREEN_STAINED_GLASS_PANE); + private static final ItemStack DISABLED = new ItemStack(Material.RED_STAINED_GLASS_PANE); + private static final ItemStack NO_PERMISSION = new ItemStack(Material.ORANGE_STAINED_GLASS_PANE); + + private static final String ENABLED_LORE = "&a&lEnabled__&7__&7Click to toggle"; + private static final String DISABLED_LORE = "&c&lDisabled__&7__&7Click to toggle"; + + @Override + public void init(Player player, InventoryContents contents) { + setIronTrapdoorItem(player, contents); + setSlabItem(player, contents); + setTerracottaItem(player, contents); + setNightVisionItem(player, contents); + setNoClipItem(player, contents); + setFlyItem(player, contents); + } + + private void setIronTrapdoorItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.irontrapdoor")) { + setNoPermission(1, contents); + contents.set(1, 1, ClickableItem.empty( + Items.create(Material.IRON_TRAPDOOR, "&6Iron Trapdoor Interaction", "&7&lNo Permission"))); + return; + } + + if (IronTrapdoorListener.ironTrapdoorIds.contains(player.getUniqueId())) { + setEnabledGlassPanes(1, true, contents); + contents.set(1, 1, ClickableItem.of(Items.create(Material.IRON_TRAPDOOR, + "&6Iron Trapdoor Interaction", ENABLED_LORE), + inventoryClickEvent -> { + IronTrapdoorListener.ironTrapdoorIds.remove(player.getUniqueId()); + setIronTrapdoorItem(player, contents); + })); + } else { + setEnabledGlassPanes(1, false, contents); + contents.set(1, 1, ClickableItem.of(Items.create(Material.IRON_TRAPDOOR, + "&6Iron Trapdoor Interaction", DISABLED_LORE), + inventoryClickEvent -> { + IronTrapdoorListener.ironTrapdoorIds.add(player.getUniqueId()); + setIronTrapdoorItem(player, contents); + })); + } + } + + private void setSlabItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.slabs")) { + setNoPermission(2, contents); + contents.set(1, 2, ClickableItem.empty( + Items.create(Material.STONE_SLAB, "&6Custom Slab Breaking", "&7&lNo Permission"))); + return; + } + + if (BlockBreakListener.slabIds.contains(player.getUniqueId())) { + setEnabledGlassPanes(2, true, contents); + contents.set(1, 2, ClickableItem.of(Items.create(Material.STONE_SLAB, + "&6Custom Slab Breaking", ENABLED_LORE), + inventoryClickEvent -> { + BlockBreakListener.slabIds.remove(player.getUniqueId()); + setSlabItem(player, contents); + })); + } else { + setEnabledGlassPanes(2, false, contents); + contents.set(1, 2, ClickableItem.of(Items.create(Material.STONE_SLAB, + "&6Custom Slab Breaking", DISABLED_LORE), + inventoryClickEvent -> { + BlockBreakListener.slabIds.add(player.getUniqueId()); + setSlabItem(player, contents); + })); + } + } + + private void setTerracottaItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.terracotta")) { + setNoPermission(3, contents); + contents.set(1, 3, ClickableItem.empty( + Items.create(Material.ORANGE_GLAZED_TERRACOTTA, "&6Glazed Terracotta Rotating", "&7&lNo Permission"))); + return; + } + + if (TerracottaInteractListener.terracottaIds.contains(player.getUniqueId())) { + setEnabledGlassPanes(3, true, contents); + contents.set(1, 3, ClickableItem.of(Items.create(Material.ORANGE_GLAZED_TERRACOTTA, + "&6Glazed Terracotta Rotating", ENABLED_LORE), + inventoryClickEvent -> { + TerracottaInteractListener.terracottaIds.remove(player.getUniqueId()); + setTerracottaItem(player, contents); + })); + } else { + setEnabledGlassPanes(3, false, contents); + contents.set(1, 3, ClickableItem.of(Items.create(Material.ORANGE_GLAZED_TERRACOTTA, + "&6Glazed Terracotta Rotating", DISABLED_LORE), + inventoryClickEvent -> { + TerracottaInteractListener.terracottaIds.add(player.getUniqueId()); + setTerracottaItem(player, contents); + })); + } + + } + + private void setNightVisionItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.nightvision")) { + setNoPermission(5, contents); + contents.set(1, 5, ClickableItem.empty( + Items.create(Material.ENDER_EYE, "&6Night Vision", "&7&lNo Permission"))); + return; + } + + if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) { + setEnabledGlassPanes(5, true, contents); + contents.set(1, 5, ClickableItem.of(Items.create(Material.ENDER_EYE, + "&6Night Vision", ENABLED_LORE), + inventoryClickEvent -> { + player.removePotionEffect(PotionEffectType.NIGHT_VISION); + setNightVisionItem(player, contents); + })); + } else { + setEnabledGlassPanes(5, false, contents); + contents.set(1, 5, ClickableItem.of(Items.create(Material.ENDER_EYE, + "&6Night Vision", DISABLED_LORE), + inventoryClickEvent -> { + player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, true, false)); + setNightVisionItem(player, contents); + })); + } + } + + private void setNoClipItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.noclip")) { + setNoPermission(6, contents); + contents.set(1, 6, ClickableItem.empty( + Items.create(Material.COMPASS, "&6No Clip", "&7&lNo Permission"))); + return; + } + + if (NoClipManager.noClipPlayerIds.contains(player.getUniqueId())) { + setEnabledGlassPanes(6, true, contents); + contents.set(1, 6, ClickableItem.of(Items.create(Material.COMPASS, + "&6No Clip", ENABLED_LORE), + inventoryClickEvent -> { + NoClipManager.noClipPlayerIds.remove(player.getUniqueId()); + setNoClipItem(player, contents); + })); + } else { + setEnabledGlassPanes(6, false, contents); + contents.set(1, 6, ClickableItem.of(Items.create(Material.COMPASS, + "&6No Clip", DISABLED_LORE), + inventoryClickEvent -> { + NoClipManager.noClipPlayerIds.add(player.getUniqueId()); + setNoClipItem(player, contents); + })); + } + } + + private void setFlyItem(Player player, InventoryContents contents) { + if (!player.hasPermission("builders.util.advancedfly")) { + setNoPermission(7, contents); + contents.set(1, 7, ClickableItem.empty( + Items.create(Material.FEATHER, "&6Advanced Fly", "&7&lNo Permission"))); + return; + } + + if (PlayerMoveListener.enabledPlayers.contains(player.getUniqueId())) { + setEnabledGlassPanes(7, true, contents); + contents.set(1, 7, ClickableItem.of(Items.create(Material.FEATHER, + "&6Advanced Fly", ENABLED_LORE), + inventoryClickEvent -> { + PlayerMoveListener.enabledPlayers.remove(player.getUniqueId()); + setFlyItem(player, contents); + })); + } else { + setEnabledGlassPanes(7, false, contents); + contents.set(1, 7, ClickableItem.of(Items.create(Material.FEATHER, + "&6Advanced Fly", DISABLED_LORE), + inventoryClickEvent -> { + PlayerMoveListener.enabledPlayers.add(player.getUniqueId()); + setFlyItem(player, contents); + })); + } + } + + /** + * Sets the glass panes above and below the center row to + * show if a feature is enabled or disabled. + * https://i.imgur.com/ETI22Py.png + * + * @param col the column to set the glass panes in + * @param enabled true if green panes, false if red panes + */ + private void setEnabledGlassPanes(int col, boolean enabled, InventoryContents contents) { + contents.set(0, col, ClickableItem.empty(enabled ? ENABLED : DISABLED)); + contents.set(2, col, ClickableItem.empty(enabled ? ENABLED : DISABLED)); + } + + private void setNoPermission(int col, InventoryContents contents) { + contents.set(0, col, ClickableItem.empty(NO_PERMISSION)); + contents.set(2, col, ClickableItem.empty(NO_PERMISSION)); + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerColorMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerColorMenuProvider.java new file mode 100644 index 0000000..1d3acfa --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerColorMenuProvider.java @@ -0,0 +1,35 @@ +package com.arcaniax.buildersutilities.menus.bannermenus; + +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class BannerColorMenuProvider implements InventoryProvider { + private static final ItemStack grayPane = Items.create(Material.LIGHT_GRAY_STAINED_GLASS_PANE, (short) 0, 1, "&7", ""); + private static final ItemStack head = Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzk3OTU1NDYyZTRlNTc2NjY0NDk5YWM0YTFjNTcyZjYxNDNmMTlhZDJkNjE5NDc3NjE5OGY4ZDEzNmZkYjIifX19", 1, "&7Click to randomise", ""); + + @Override + public void init(Player player, InventoryContents contents) { +// for (int x = 0; x < 54; x++) { +// contents.set(x / 9, x % 9, grayPane); +// } +// inv1.setItem(1, ); +// if (first) { +// inv1.setItem(4, bU.createBanner("&aClick to get the banner", 1, DyeColor.valueOf(clicked.getType().toString().replace("_BANNER", "")), "")); +// } else { +// inv1.setItem(4, bU.addPattern(inv.getItem(4), new Pattern(bU.getColorFromBanner(clicked), bU.getPatternType(clicked)))); +// } +// inv1.setItem(7, i.create(Material.BARRIER, (short) 0, 1, "&cClick to close", "")); +// for (int x = 19; x < 27; x++) { +// inv1.setItem(x, i.create(Material.LEGACY_INK_SACK, (short) (x - 19), 1, "&3" + bU.getAllColors().get(x - 19).toString().toLowerCase().replace("_", " "), "&7__&7click to select")); +// } +// for (int x = 28; x < 36; x++) { +// inv1.setItem(x, i.create(Material.LEGACY_INK_SACK, (short) (x - 20), 1, "&3" + bU.getAllColors().get(x - 20).toString().toLowerCase().replace("_", " "), "&7__&7click to select")); +// } + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerMenuProvider.java new file mode 100644 index 0000000..832a3df --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerMenuProvider.java @@ -0,0 +1,36 @@ +package com.arcaniax.buildersutilities.menus.bannermenus; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +//import com.arcaniax.buildersutilities.utils.BannerUtil; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class BannerMenuProvider implements InventoryProvider { + private static final ItemStack grayPane = Items.create(Material.LIGHT_GRAY_STAINED_GLASS_PANE, (short) 0, 1, "&7", ""); + private static final ItemStack randomizeHead = Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzk3OTU1NDYyZTRlNTc2NjY0NDk5YWM0YTFjNTcyZjYxNDNmMTlhZDJkNjE5NDc3NjE5OGY4ZDEzNmZkYjIifX19", 1, "&7Click to randomise", ""); +// private static final ItemStack currentColor = BannerUtil.createBanner("&a", 1, DyeColor.WHITE, ""); + private static final ItemStack closeButton = Items.create(Material.BARRIER, (short) 0, 1, "&cClick to close", ""); + + @Override + public void init(Player player, InventoryContents contents) { +// for (int x = 0; x < 54; x++) { +// contents.set(x / 9, x % 9, ClickableItem.empty(grayPane)); +// } +// contents.set(0, 1, ClickableItem.of(randomizeHead, NULL)); +// contents.set(0, 4, ClickableItem.empty(currentColor)); +// contents.set(0, 7, ClickableItem.of(closeButton, inventoryClickEvent -> contents.inventory().close(player))); +// for (int x = 19; x < 27; x++) { +// ItemStack banner = BannerUtil.createBanner("&3" + BannerUtil.allColors.get(x - 19).toString().toLowerCase().replace("_", " "), 1, BannerUtil.allColors.get(x - 19), "&7__&7click to select"); +// contents.set(x / 9, x % 9, ClickableItem.of(banner, NULL)); +// } +// for (int x = 28; x < 36; x++) { +// ItemStack banner = BannerUtil.createBanner("&3" + BannerUtil.allColors.get(x - 28 + 8).toString().toLowerCase().replace("_", " "), 1, BannerUtil.allColors.get(x - 28 + 8), "&7__&7click to select"); +// contents.set(x / 9, x % 9, ClickableItem.of(banner, NULL)); +// } + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerPatternMenuProvider.java b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerPatternMenuProvider.java new file mode 100644 index 0000000..08f21aa --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/bannermenus/BannerPatternMenuProvider.java @@ -0,0 +1,36 @@ +package com.arcaniax.buildersutilities.menus.bannermenus; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +//import com.arcaniax.buildersutilities.utils.BannerUtil; +import com.arcaniax.buildersutilities.utils.Items; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class BannerPatternMenuProvider implements InventoryProvider { + private static final ItemStack grayPane = Items.create(Material.LIGHT_GRAY_STAINED_GLASS_PANE, (short) 0, 1, "&7", ""); + private static final ItemStack randomizeHead = Items.createHead("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzk3OTU1NDYyZTRlNTc2NjY0NDk5YWM0YTFjNTcyZjYxNDNmMTlhZDJkNjE5NDc3NjE5OGY4ZDEzNmZkYjIifX19", 1, "&7Click to randomise", ""); +// private static final ItemStack currentColor = BannerUtil.createBanner("&a", 1, DyeColor.WHITE, ""); + private static final ItemStack closeButton = Items.create(Material.BARRIER, (short) 0, 1, "&cClick to close", ""); + + @Override + public void init(Player player, InventoryContents contents) { +// for (int x = 0; x < 54; x++) { +// contents.set(x / 9, x % 9, ClickableItem.empty(grayPane)); +// } +// contents.set(0, 1, ClickableItem.of(randomizeHead, NULL)); +// contents.set(0, 4, ClickableItem.empty(currentColor)); +// contents.set(0, 7, ClickableItem.of(closeButton, inventoryClickEvent -> contents.inventory().close(player))); +// for (int x = 19; x < 27; x++) { +// ItemStack banner = BannerUtil.createBanner("&3" + BannerUtil.allColors.get(x - 19).toString().toLowerCase().replace("_", " "), 1, BannerUtil.allColors.get(x - 19), "&7__&7click to select"); +// contents.set(x / 9, x % 9, ClickableItem.of(banner, NULL)); +// } +// for (int x = 28; x < 36; x++) { +// ItemStack banner = BannerUtil.createBanner("&3" + BannerUtil.allColors.get(x - 28 + 8).toString().toLowerCase().replace("_", " "), 1, BannerUtil.allColors.get(x - 28 + 8), "&7__&7click to select"); +// contents.set(x / 9, x % 9, ClickableItem.of(banner, NULL)); +// } + } +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/ClickableItem.java b/src/com/arcaniax/buildersutilities/menus/inv/ClickableItem.java new file mode 100644 index 0000000..45b4d0f --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/ClickableItem.java @@ -0,0 +1,35 @@ +package com.arcaniax.buildersutilities.menus.inv; + +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.function.Consumer; + +public class ClickableItem { + + private ItemStack item; + private Consumer consumer; + + private ClickableItem(ItemStack item, Consumer consumer) { + this.item = item; + this.consumer = consumer; + } + + public static ClickableItem empty(ItemStack item) { + return of(item, e -> { + }); + } + + public static ClickableItem of(ItemStack item, Consumer consumer) { + return new ClickableItem(item, consumer); + } + + public void run(InventoryClickEvent e) { + consumer.accept(e); + } + + public ItemStack getItem() { + return item; + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/InventoryListener.java b/src/com/arcaniax/buildersutilities/menus/inv/InventoryListener.java new file mode 100644 index 0000000..6b8e437 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/InventoryListener.java @@ -0,0 +1,23 @@ +package com.arcaniax.buildersutilities.menus.inv; + +import java.util.function.Consumer; + +public class InventoryListener { + + private Class type; + private Consumer consumer; + + public InventoryListener(Class type, Consumer consumer) { + this.type = type; + this.consumer = consumer; + } + + public void accept(T t) { + consumer.accept(t); + } + + public Class getType() { + return type; + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/InventoryManager.java b/src/com/arcaniax/buildersutilities/menus/inv/InventoryManager.java new file mode 100644 index 0000000..013ee51 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/InventoryManager.java @@ -0,0 +1,251 @@ +package com.arcaniax.buildersutilities.menus.inv; + +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.opener.ChestInventoryOpener; +import com.arcaniax.buildersutilities.menus.inv.opener.InventoryOpener; +import com.arcaniax.buildersutilities.menus.inv.opener.SpecialInventoryOpener; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.*; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; + +public class InventoryManager { + + private JavaPlugin plugin; + private PluginManager pluginManager; + + private Map inventories; + private Map contents; + + private List defaultOpeners; + private List openers; + + public InventoryManager(JavaPlugin plugin) { + this.plugin = plugin; + this.pluginManager = Bukkit.getPluginManager(); + + this.inventories = new HashMap<>(); + this.contents = new HashMap<>(); + + this.defaultOpeners = Arrays.asList( + new ChestInventoryOpener(), + new SpecialInventoryOpener() + ); + + this.openers = new ArrayList<>(); + } + + public void init() { + pluginManager.registerEvents(new InvListener(), plugin); + + new InvTask().runTaskTimer(plugin, 1, 1); + } + + public Optional findOpener(InventoryType type) { + Optional opInv = this.openers.stream() + .filter(opener -> opener.supports(type)) + .findAny(); + + if (!opInv.isPresent()) { + opInv = this.defaultOpeners.stream() + .filter(opener -> opener.supports(type)) + .findAny(); + } + + return opInv; + } + + public void registerOpeners(InventoryOpener... openers) { + this.openers.addAll(Arrays.asList(openers)); + } + + public List getOpenedPlayers(SmartInventory inv) { + List list = new ArrayList<>(); + + this.inventories.forEach((player, playerInv) -> { + if (inv.equals(playerInv)) + list.add(player); + }); + + return list; + } + + public Optional getInventory(Player p) { + return Optional.ofNullable(this.inventories.get(p)); + } + + protected void setInventory(Player p, SmartInventory inv) { + if (inv == null) + this.inventories.remove(p); + else + this.inventories.put(p, inv); + } + + public Optional getContents(Player p) { + return Optional.ofNullable(this.contents.get(p)); + } + + protected void setContents(Player p, InventoryContents contents) { + if (contents == null) + this.contents.remove(p); + else + this.contents.put(p, contents); + } + + @SuppressWarnings("unchecked") + class InvListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onInventoryClick(InventoryClickEvent e) { + Player p = (Player) e.getWhoClicked(); + + if (!inventories.containsKey(p)) + return; + + if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { + e.setCancelled(true); + } + + if (e.getAction() == InventoryAction.COLLECT_TO_CURSOR) { + e.setCancelled(true); + return; + } + + if (e.getAction() == InventoryAction.NOTHING && e.getClick() != ClickType.MIDDLE) { + e.setCancelled(true); + } + + if (e.getClickedInventory() == p.getOpenInventory().getTopInventory()) { + e.setCancelled(true); + + int row = e.getSlot() / 9; + int column = e.getSlot() % 9; + + if (row < 0 || column < 0) + return; + + SmartInventory inv = inventories.get(p); + + if (row >= inv.getRows() || column >= inv.getColumns()) + return; + + inv.getListeners().stream() + .filter(listener -> listener.getType() == InventoryClickEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + + contents.get(p).get(row, column).ifPresent(item -> item.run(e)); + + p.updateInventory(); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onInventoryDrag(InventoryDragEvent e) { + Player p = (Player) e.getWhoClicked(); + + if (!inventories.containsKey(p)) + return; + + SmartInventory inv = inventories.get(p); + + for (int slot : e.getRawSlots()) { + if (slot >= p.getOpenInventory().getTopInventory().getSize()) + continue; + + e.setCancelled(true); + break; + } + + inv.getListeners().stream() + .filter(listener -> listener.getType() == InventoryDragEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInventoryOpen(InventoryOpenEvent e) { + Player p = (Player) e.getPlayer(); + + if (!inventories.containsKey(p)) + return; + + SmartInventory inv = inventories.get(p); + + inv.getListeners().stream() + .filter(listener -> listener.getType() == InventoryOpenEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInventoryClose(InventoryCloseEvent e) { + Player p = (Player) e.getPlayer(); + + if (!inventories.containsKey(p)) + return; + + SmartInventory inv = inventories.get(p); + + inv.getListeners().stream() + .filter(listener -> listener.getType() == InventoryCloseEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + + if (inv.isCloseable()) { + e.getInventory().clear(); + + inventories.remove(p); + contents.remove(p); + } else + Bukkit.getScheduler().runTask(plugin, () -> p.openInventory(e.getInventory())); + } + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerQuit(PlayerQuitEvent e) { + Player p = e.getPlayer(); + + if (!inventories.containsKey(p)) + return; + + SmartInventory inv = inventories.get(p); + + inv.getListeners().stream() + .filter(listener -> listener.getType() == PlayerQuitEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + + inventories.remove(p); + contents.remove(p); + } + + @EventHandler(priority = EventPriority.LOW) + public void onPluginDisable(PluginDisableEvent e) { + new HashMap<>(inventories).forEach((player, inv) -> { + inv.getListeners().stream() + .filter(listener -> listener.getType() == PluginDisableEvent.class) + .forEach(listener -> ((InventoryListener) listener).accept(e)); + + inv.close(player); + }); + + inventories.clear(); + contents.clear(); + } + + } + + class InvTask extends BukkitRunnable { + + @Override + public void run() { + new HashMap<>(inventories).forEach((player, inv) -> inv.getProvider().update(player, contents.get(player))); + } + + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/SmartInventory.java b/src/com/arcaniax/buildersutilities/menus/inv/SmartInventory.java new file mode 100644 index 0000000..cb8a8c4 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/SmartInventory.java @@ -0,0 +1,215 @@ +package com.arcaniax.buildersutilities.menus.inv; + +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryProvider; +import com.arcaniax.buildersutilities.menus.inv.opener.InventoryOpener; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@SuppressWarnings("unchecked") +public class SmartInventory { + + private String id; + private String title; + private InventoryType type; + private int rows, columns; + private boolean closeable; + + private InventoryProvider provider; + private SmartInventory parent; + + private List> listeners; + private InventoryManager manager; + + private SmartInventory(InventoryManager manager) { + this.manager = manager; + } + + public static Builder builder() { + return new Builder(); + } + + public Inventory open(Player player) { + return open(player, 0); + } + + public Inventory open(Player player, int page) { + Optional oldInv = this.manager.getInventory(player); + + oldInv.ifPresent(inv -> { + inv.getListeners().stream() + .filter(listener -> listener.getType() == InventoryCloseEvent.class) + .forEach(listener -> ((InventoryListener) listener) + .accept(new InventoryCloseEvent(player.getOpenInventory()))); + + this.manager.setInventory(player, null); + }); + + InventoryContents contents = new InventoryContents.Impl(this, player); + contents.pagination().page(page); + + this.manager.setContents(player, contents); + this.provider.init(player, contents); + + InventoryOpener opener = this.manager.findOpener(type) + .orElseThrow(() -> new IllegalStateException("No opener found for the inventory type " + type.name())); + Inventory handle = opener.open(this, player); + + this.manager.setInventory(player, this); + + return handle; + } + + @SuppressWarnings("unchecked") + public void close(Player player) { + listeners.stream() + .filter(listener -> listener.getType() == InventoryCloseEvent.class) + .forEach(listener -> ((InventoryListener) listener) + .accept(new InventoryCloseEvent(player.getOpenInventory()))); + + this.manager.setInventory(player, null); + player.closeInventory(); + + this.manager.setContents(player, null); + } + + public String getId() { + return id; + } + + public String getTitle() { + return title; + } + + public InventoryType getType() { + return type; + } + + public int getRows() { + return rows; + } + + public int getColumns() { + return columns; + } + + public boolean isCloseable() { + return closeable; + } + + public void setCloseable(boolean closeable) { + this.closeable = closeable; + } + + public InventoryProvider getProvider() { + return provider; + } + + public Optional getParent() { + return Optional.ofNullable(parent); + } + + public InventoryManager getManager() { + return manager; + } + + List> getListeners() { + return listeners; + } + + public static final class Builder { + + private String id = "unknown"; + private String title = ""; + private InventoryType type = InventoryType.CHEST; + private int rows = 6, columns = 9; + private boolean closeable = true; + + private InventoryManager manager; + private InventoryProvider provider; + private SmartInventory parent; + + private List> listeners = new ArrayList<>(); + + private Builder() { + } + + public Builder id(String id) { + this.id = id; + return this; + } + + public Builder title(String title) { + this.title = title; + return this; + } + + public Builder type(InventoryType type) { + this.type = type; + return this; + } + + public Builder size(int rows, int columns) { + this.rows = rows; + this.columns = columns; + return this; + } + + public Builder closeable(boolean closeable) { + this.closeable = closeable; + return this; + } + + public Builder provider(InventoryProvider provider) { + this.provider = provider; + return this; + } + + public Builder parent(SmartInventory parent) { + this.parent = parent; + return this; + } + + public Builder listener(InventoryListener listener) { + this.listeners.add(listener); + return this; + } + + public Builder manager(InventoryManager manager) { + this.manager = manager; + return this; + } + + public SmartInventory build() { + if (this.provider == null) + throw new IllegalStateException("The provider of the SmartInventory.Builder must be set."); + + InventoryManager manager = this.manager; + + if (manager == null) + throw new IllegalStateException("The manager of the SmartInventory.Builder must be set, " + + "or the SmartInvs should be loaded as a plugin."); + + SmartInventory inv = new SmartInventory(manager); + inv.id = this.id; + inv.title = this.title; + inv.type = this.type; + inv.rows = this.rows; + inv.columns = this.columns; + inv.closeable = this.closeable; + inv.provider = this.provider; + inv.parent = this.parent; + inv.listeners = this.listeners; + + return inv; + } + } + +} \ No newline at end of file diff --git a/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryContents.java b/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryContents.java new file mode 100644 index 0000000..214100a --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryContents.java @@ -0,0 +1,262 @@ +package com.arcaniax.buildersutilities.menus.inv.content; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public interface InventoryContents { + + SmartInventory inventory(); + + Pagination pagination(); + + Optional iterator(String id); + + SlotIterator newIterator(String id, SlotIterator.Type type, int startRow, int startColumn); + + SlotIterator newIterator(SlotIterator.Type type, int startRow, int startColumn); + + SlotIterator newIterator(String id, SlotIterator.Type type, SlotPos startPos); + + SlotIterator newIterator(SlotIterator.Type type, SlotPos startPos); + + ClickableItem[][] all(); + + Optional firstEmpty(); + + Optional get(int row, int column); + + Optional get(SlotPos slotPos); + + InventoryContents set(int row, int column, ClickableItem item); + + InventoryContents set(SlotPos slotPos, ClickableItem item); + + InventoryContents add(ClickableItem item); + + InventoryContents fill(ClickableItem item); + + InventoryContents fillRow(int row, ClickableItem item); + + InventoryContents fillColumn(int column, ClickableItem item); + + InventoryContents fillBorders(ClickableItem item); + + InventoryContents fillRect(int fromRow, int fromColumn, + int toRow, int toColumn, ClickableItem item); + + InventoryContents fillRect(SlotPos fromPos, SlotPos toPos, ClickableItem item); + + T property(String name); + + T property(String name, T def); + + InventoryContents setProperty(String name, Object value); + + class Impl implements InventoryContents { + + private SmartInventory inv; + private Player player; + + private ClickableItem[][] contents; + + private Pagination pagination = new Pagination.Impl(); + private Map iterators = new HashMap<>(); + private Map properties = new HashMap<>(); + + public Impl(SmartInventory inv, Player player) { + this.inv = inv; + this.player = player; + this.contents = new ClickableItem[inv.getRows()][inv.getColumns()]; + } + + @Override + public SmartInventory inventory() { + return inv; + } + + @Override + public Pagination pagination() { + return pagination; + } + + @Override + public Optional iterator(String id) { + return Optional.ofNullable(this.iterators.get(id)); + } + + @Override + public SlotIterator newIterator(String id, SlotIterator.Type type, int startRow, int startColumn) { + SlotIterator iterator = new SlotIterator.Impl(this, inv, + type, startRow, startColumn); + + this.iterators.put(id, iterator); + return iterator; + } + + @Override + public SlotIterator newIterator(String id, SlotIterator.Type type, SlotPos startPos) { + return newIterator(id, type, startPos.getRow(), startPos.getColumn()); + } + + @Override + public SlotIterator newIterator(SlotIterator.Type type, int startRow, int startColumn) { + return new SlotIterator.Impl(this, inv, type, startRow, startColumn); + } + + @Override + public SlotIterator newIterator(SlotIterator.Type type, SlotPos startPos) { + return newIterator(type, startPos.getRow(), startPos.getColumn()); + } + + @Override + public ClickableItem[][] all() { + return contents; + } + + @Override + public Optional firstEmpty() { + for (int row = 0; row < contents.length; row++) { + for (int column = 0; column < contents[0].length; column++) { + if (!this.get(row, column).isPresent()) + return Optional.of(new SlotPos(row, column)); + } + } + + return Optional.empty(); + } + + @Override + public Optional get(int row, int column) { + if (row >= contents.length) + return Optional.empty(); + if (column >= contents[row].length) + return Optional.empty(); + + return Optional.ofNullable(contents[row][column]); + } + + @Override + public Optional get(SlotPos slotPos) { + return get(slotPos.getRow(), slotPos.getColumn()); + } + + @Override + public InventoryContents set(int row, int column, ClickableItem item) { + if (row >= contents.length) + return this; + if (column >= contents[row].length) + return this; + + contents[row][column] = item; + update(row, column, item != null ? item.getItem() : null); + return this; + } + + @Override + public InventoryContents set(SlotPos slotPos, ClickableItem item) { + return set(slotPos.getRow(), slotPos.getColumn(), item); + } + + @Override + public InventoryContents add(ClickableItem item) { + for (int row = 0; row < contents.length; row++) { + for (int column = 0; column < contents[0].length; column++) { + if (contents[row][column] == null) { + set(row, column, item); + return this; + } + } + } + + return this; + } + + @Override + public InventoryContents fill(ClickableItem item) { + for (int row = 0; row < contents.length; row++) + for (int column = 0; column < contents[row].length; column++) + set(row, column, item); + + return this; + } + + @Override + public InventoryContents fillRow(int row, ClickableItem item) { + if (row >= contents.length) + return this; + + for (int column = 0; column < contents[row].length; column++) + set(row, column, item); + + return this; + } + + @Override + public InventoryContents fillColumn(int column, ClickableItem item) { + for (int row = 0; row < contents.length; row++) + set(row, column, item); + + return this; + } + + @Override + public InventoryContents fillBorders(ClickableItem item) { + fillRect(0, 0, inv.getRows() - 1, inv.getColumns() - 1, item); + return this; + } + + @Override + public InventoryContents fillRect(int fromRow, int fromColumn, int toRow, int toColumn, ClickableItem item) { + for (int row = fromRow; row <= toRow; row++) { + for (int column = fromColumn; column <= toColumn; column++) { + if (row != fromRow && row != toRow && column != fromColumn && column != toColumn) + continue; + + set(row, column, item); + } + } + + return this; + } + + @Override + public InventoryContents fillRect(SlotPos fromPos, SlotPos toPos, ClickableItem item) { + return fillRect(fromPos.getRow(), fromPos.getColumn(), toPos.getRow(), toPos.getColumn(), item); + } + + @SuppressWarnings("unchecked") + @Override + public T property(String name) { + return (T) properties.get(name); + } + + @SuppressWarnings("unchecked") + @Override + public T property(String name, T def) { + return properties.containsKey(name) ? (T) properties.get(name) : def; + } + + @Override + public InventoryContents setProperty(String name, Object value) { + properties.put(name, value); + return this; + } + + private void update(int row, int column, ItemStack item) { + if (!inv.getManager().getOpenedPlayers(inv).contains(player)) + return; + + Inventory topInventory = player.getOpenInventory().getTopInventory(); + topInventory.setItem(inv.getColumns() * row + column, item); + } + + } + +} \ No newline at end of file diff --git a/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryProvider.java b/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryProvider.java new file mode 100644 index 0000000..55def6e --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/content/InventoryProvider.java @@ -0,0 +1,12 @@ +package com.arcaniax.buildersutilities.menus.inv.content; + +import org.bukkit.entity.Player; + +public interface InventoryProvider { + + void init(Player player, InventoryContents contents); + + default void update(Player player, InventoryContents contents) { + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/content/Pagination.java b/src/com/arcaniax/buildersutilities/menus/inv/content/Pagination.java new file mode 100644 index 0000000..d32bd62 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/content/Pagination.java @@ -0,0 +1,124 @@ +package com.arcaniax.buildersutilities.menus.inv.content; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; + +import java.util.Arrays; + +public interface Pagination { + + ClickableItem[] getPageItems(); + + int getPage(); + + Pagination page(int page); + + boolean isFirst(); + + boolean isLast(); + + Pagination first(); + + Pagination previous(); + + Pagination next(); + + Pagination last(); + + Pagination addToIterator(SlotIterator iterator); + + Pagination setItems(ClickableItem... items); + + Pagination setItemsPerPage(int itemsPerPage); + + + class Impl implements Pagination { + + private int currentPage; + + private ClickableItem[] items = new ClickableItem[0]; + private int itemsPerPage = 5; + + @Override + public ClickableItem[] getPageItems() { + return Arrays.copyOfRange(items, + currentPage * itemsPerPage, + (currentPage + 1) * itemsPerPage); + } + + @Override + public int getPage() { + return this.currentPage; + } + + @Override + public Pagination page(int page) { + this.currentPage = page; + return this; + } + + @Override + public boolean isFirst() { + return this.currentPage == 0; + } + + @Override + public boolean isLast() { + int pageCount = (int) Math.ceil((double) this.items.length / this.itemsPerPage); + return this.currentPage >= pageCount - 1; + } + + @Override + public Pagination first() { + this.currentPage = 0; + return this; + } + + @Override + public Pagination previous() { + if (!isFirst()) + this.currentPage--; + + return this; + } + + @Override + public Pagination next() { + if (!isLast()) + this.currentPage++; + + return this; + } + + @Override + public Pagination last() { + this.currentPage = this.items.length / this.itemsPerPage; + return this; + } + + @Override + public Pagination addToIterator(SlotIterator iterator) { + for (ClickableItem item : getPageItems()) { + iterator.next().set(item); + + if (iterator.ended()) + break; + } + + return this; + } + + @Override + public Pagination setItems(ClickableItem... items) { + this.items = items; + return this; + } + + @Override + public Pagination setItemsPerPage(int itemsPerPage) { + this.itemsPerPage = itemsPerPage; + return this; + } + + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/content/SlotIterator.java b/src/com/arcaniax/buildersutilities/menus/inv/content/SlotIterator.java new file mode 100644 index 0000000..87feba1 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/content/SlotIterator.java @@ -0,0 +1,217 @@ +package com.arcaniax.buildersutilities.menus.inv.content; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +public interface SlotIterator { + + Optional get(); + + SlotIterator set(ClickableItem item); + + SlotIterator previous(); + + SlotIterator next(); + + SlotIterator blacklist(int row, int column); + + SlotIterator blacklist(SlotPos slotPos); + + int row(); + + SlotIterator row(int row); + + int column(); + + SlotIterator column(int column); + + boolean started(); + + boolean ended(); + + boolean doesAllowOverride(); + + SlotIterator allowOverride(boolean override); + + enum Type { + HORIZONTAL, + VERTICAL + } + + class Impl implements SlotIterator { + + private InventoryContents contents; + private SmartInventory inv; + + private Type type; + private boolean started = false; + private boolean allowOverride = true; + private int row, column; + + private Set blacklisted = new HashSet<>(); + + public Impl(InventoryContents contents, SmartInventory inv, + Type type, int startRow, int startColumn) { + + this.contents = contents; + this.inv = inv; + + this.type = type; + + this.row = startRow; + this.column = startColumn; + } + + public Impl(InventoryContents contents, SmartInventory inv, + Type type) { + + this(contents, inv, type, 0, 0); + } + + @Override + public Optional get() { + return contents.get(row, column); + } + + @Override + public SlotIterator set(ClickableItem item) { + if (canPlace()) + contents.set(row, column, item); + + return this; + } + + @Override + public SlotIterator previous() { + if (row == 0 && column == 0) { + this.started = true; + return this; + } + + do { + if (!this.started) { + this.started = true; + } else { + switch (type) { + case HORIZONTAL: + column--; + + if (column == 0) { + column = inv.getColumns() - 1; + row--; + } + break; + case VERTICAL: + row--; + + if (row == 0) { + row = inv.getRows() - 1; + column--; + } + break; + } + } + } + while (!canPlace() && (row != 0 || column != 0)); + + return this; + } + + @Override + public SlotIterator next() { + if (ended()) { + this.started = true; + return this; + } + + do { + if (!this.started) { + this.started = true; + } else { + switch (type) { + case HORIZONTAL: + column = ++column % inv.getColumns(); + + if (column == 0) + row++; + break; + case VERTICAL: + row = ++row % inv.getRows(); + + if (row == 0) + column++; + break; + } + } + } + while (!canPlace() && !ended()); + + return this; + } + + @Override + public SlotIterator blacklist(int row, int column) { + this.blacklisted.add(SlotPos.of(row, column)); + return this; + } + + @Override + public SlotIterator blacklist(SlotPos slotPos) { + return blacklist(slotPos.getRow(), slotPos.getColumn()); + } + + @Override + public int row() { + return row; + } + + @Override + public SlotIterator row(int row) { + this.row = row; + return this; + } + + @Override + public int column() { + return column; + } + + @Override + public SlotIterator column(int column) { + this.column = column; + return this; + } + + @Override + public boolean started() { + return this.started; + } + + @Override + public boolean ended() { + return row == inv.getRows() - 1 + && column == inv.getColumns() - 1; + } + + @Override + public boolean doesAllowOverride() { + return allowOverride; + } + + @Override + public SlotIterator allowOverride(boolean override) { + this.allowOverride = override; + return this; + } + + private boolean canPlace() { + return !blacklisted.contains(SlotPos.of(row, column)) && (allowOverride || !this.get().isPresent()); + } + + } + +} \ No newline at end of file diff --git a/src/com/arcaniax/buildersutilities/menus/inv/content/SlotPos.java b/src/com/arcaniax/buildersutilities/menus/inv/content/SlotPos.java new file mode 100644 index 0000000..92cdfdf --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/content/SlotPos.java @@ -0,0 +1,45 @@ +package com.arcaniax.buildersutilities.menus.inv.content; + +public class SlotPos { + + private final int row; + private final int column; + + public SlotPos(int row, int column) { + this.row = row; + this.column = column; + } + + public static SlotPos of(int row, int column) { + return new SlotPos(row, column); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + + SlotPos slotPos = (SlotPos) obj; + + return row == slotPos.row && column == slotPos.column; + } + + @Override + public int hashCode() { + int result = row; + result = 31 * result + column; + + return result; + } + + public int getRow() { + return row; + } + + public int getColumn() { + return column; + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/opener/ChestInventoryOpener.java b/src/com/arcaniax/buildersutilities/menus/inv/opener/ChestInventoryOpener.java new file mode 100644 index 0000000..6c4675b --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/opener/ChestInventoryOpener.java @@ -0,0 +1,34 @@ +package com.arcaniax.buildersutilities.menus.inv.opener; + +import com.arcaniax.buildersutilities.menus.inv.InventoryManager; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; +import com.google.common.base.Preconditions; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; + +public class ChestInventoryOpener implements InventoryOpener { + + @Override + public Inventory open(SmartInventory inv, Player player) { + Preconditions.checkArgument(inv.getColumns() == 9, + "The column count for the chest inventory must be 9, found: %s.", inv.getColumns()); + Preconditions.checkArgument(inv.getRows() >= 1 && inv.getRows() <= 6, + "The row count for the chest inventory must be between 1 and 6, found: %s", inv.getRows()); + + InventoryManager manager = inv.getManager(); + Inventory handle = Bukkit.createInventory(player, inv.getRows() * inv.getColumns(), inv.getTitle()); + + fill(handle, manager.getContents(player).get()); + + player.openInventory(handle); + return handle; + } + + @Override + public boolean supports(InventoryType type) { + return type == InventoryType.CHEST || type == InventoryType.ENDER_CHEST; + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/opener/InventoryOpener.java b/src/com/arcaniax/buildersutilities/menus/inv/opener/InventoryOpener.java new file mode 100644 index 0000000..b6f8d1c --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/opener/InventoryOpener.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.menus.inv.opener; + +import com.arcaniax.buildersutilities.menus.inv.ClickableItem; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; +import com.arcaniax.buildersutilities.menus.inv.content.InventoryContents; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; + +public interface InventoryOpener { + + Inventory open(SmartInventory inv, Player player); + + boolean supports(InventoryType type); + + default void fill(Inventory handle, InventoryContents contents) { + ClickableItem[][] items = contents.all(); + + for (int row = 0; row < items.length; row++) { + for (int column = 0; column < items[row].length; column++) { + if (items[row][column] != null) + handle.setItem(9 * row + column, items[row][column].getItem()); + } + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/menus/inv/opener/SpecialInventoryOpener.java b/src/com/arcaniax/buildersutilities/menus/inv/opener/SpecialInventoryOpener.java new file mode 100644 index 0000000..a484d7f --- /dev/null +++ b/src/com/arcaniax/buildersutilities/menus/inv/opener/SpecialInventoryOpener.java @@ -0,0 +1,43 @@ +package com.arcaniax.buildersutilities.menus.inv.opener; + +import com.arcaniax.buildersutilities.menus.inv.InventoryManager; +import com.arcaniax.buildersutilities.menus.inv.SmartInventory; +import com.google.common.collect.ImmutableList; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; + +import java.util.List; + +public class SpecialInventoryOpener implements InventoryOpener { + + private static final List SUPPORTED = ImmutableList.of( + InventoryType.FURNACE, + InventoryType.WORKBENCH, + InventoryType.DISPENSER, + InventoryType.DROPPER, + InventoryType.ENCHANTING, + InventoryType.BREWING, + InventoryType.ANVIL, + InventoryType.BEACON, + InventoryType.HOPPER + ); + + @Override + public Inventory open(SmartInventory inv, Player player) { + InventoryManager manager = inv.getManager(); + Inventory handle = Bukkit.createInventory(player, inv.getType(), inv.getTitle()); + + fill(handle, manager.getContents(player).get()); + + player.openInventory(handle); + return handle; + } + + @Override + public boolean supports(InventoryType type) { + return SUPPORTED.contains(type); + } + +} diff --git a/src/com/arcaniax/buildersutilities/utils/BannerUtil.java b/src/com/arcaniax/buildersutilities/utils/BannerUtil.java new file mode 100644 index 0000000..228a2cf --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/BannerUtil.java @@ -0,0 +1,197 @@ +//package com.arcaniax.buildersutilities.utils; +// +//import com.arcaniax.buildersutilities.Main; +//import org.bukkit.ChatColor; +//import org.bukkit.DyeColor; +//import org.bukkit.block.banner.Pattern; +//import org.bukkit.block.banner.PatternType; +//import org.bukkit.inventory.ItemStack; +//import org.bukkit.inventory.meta.BannerMeta; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Random; +// +//public class BannerUtil { +// public static final List allColors = new ArrayList<>(); +// public static final List allPatterns = new ArrayList<>(); +// private static final Random random = new Random(); +// +// { +// addColors(); +// addPatterns(); +// } +// +// private void addPatterns() { +// for (PatternType pt : PatternType.values()) { +// if (!pt.equals(PatternType.BASE)) { +// allPatterns.add(pt); +// } +// } +// } +// +// private void addColors() { +// allColors.add(DyeColor.BLACK); +// allColors.add(DyeColor.RED); +// allColors.add(DyeColor.GREEN); +// allColors.add(DyeColor.BROWN); +// allColors.add(DyeColor.BLUE); +// allColors.add(DyeColor.PURPLE); +// allColors.add(DyeColor.CYAN); +// allColors.add(DyeColor.LIGHT_GRAY); +// allColors.add(DyeColor.GRAY); +// allColors.add(DyeColor.PINK); +// allColors.add(DyeColor.LIME); +// allColors.add(DyeColor.YELLOW); +// allColors.add(DyeColor.LIGHT_BLUE); +// allColors.add(DyeColor.MAGENTA); +// allColors.add(DyeColor.ORANGE); +// allColors.add(DyeColor.WHITE); +// } +// +// public static ItemStack createBanner(String name, DyeColor base, String lore, List patterns) { +// ItemStack item = Items.create(XMaterial.fromString(base.toString() + "_BANNER").parseMaterial(), (short) 0, 1, name, ""); +// BannerMeta meta = (BannerMeta) item.getItemMeta(); +// if (Main.getInstance().getNmsManager().isAtLeastVersion(1, 11, 0)) { +// item.setDurability((short) allColors.indexOf(base)); +// } else { +// meta.setBaseColor(base); +// } +// +// meta.setPatterns(patterns); +// if (!lore.equals("")) { +// String[] loreListArray = lore.split("__"); +// List loreList = new ArrayList<>(); +// for (String s : loreListArray) { +// loreList.add(s.replace('&', ChatColor.COLOR_CHAR)); +// } +// meta.setLore(loreList); +// } +// item.setItemMeta(meta); +// return item; +// } +// +// public static ItemStack createBanner(String name, int amount, DyeColor base, String lore) { +// //TODO this might be how we fix it: +// XMaterial.matchXMaterial(base.toString() + "_BANNER").get().parseMaterial(); +// +// ItemStack item = Items.create(XMaterial.fromString(base.toString() + "_BANNER").parseMaterial(), (short) 0, 1, name, ""); +// BannerMeta meta = (BannerMeta) item.getItemMeta(); +// if (!lore.equals("")) { +// String[] loreListArray = lore.split("__"); +// List loreList = new ArrayList<>(); +// for (String s : loreListArray) { +// loreList.add(s.replace('&', ChatColor.COLOR_CHAR)); +// } +// meta.setLore(loreList); +// } +// item.setItemMeta(meta); +// return item; +// } +// +// public static ItemStack createBanner(String name, int amount, DyeColor base, String lore, Pattern pat) { +// ItemStack item = Items.create(XMaterial.fromString(base.toString() + "_BANNER").parseMaterial(), (short) 0, 1, name, ""); +// BannerMeta meta = (BannerMeta) item.getItemMeta(); +// meta.addPattern(pat); +// if (!lore.equals("")) { +// String[] loreListArray = lore.split("__"); +// List loreList = new ArrayList<>(); +// for (String s : loreListArray) { +// loreList.add(s.replace('&', ChatColor.COLOR_CHAR)); +// } +// meta.setLore(loreList); +// } +// item.setItemMeta(meta); +// return item; +// } +// +// public static ItemStack addPattern(ItemStack i, Pattern pat) { +// if (i.getType().toString().contains("BANNER")) { +// BannerMeta meta = (BannerMeta) i.getItemMeta(); +// List patterns = meta.getPatterns(); +// patterns.add(pat); +// meta.setPatterns(patterns); +// i.setItemMeta(meta); +// return i; +// } +// return null; +// } +// +// public static DyeColor getBaseColor(ItemStack i) { +// if (i.getType().toString().contains("BANNER")) { +// BannerMeta meta = (BannerMeta) i.getItemMeta(); +// if (Main.getInstance().getNmsManager().isAtLeastVersion(1, 11, 0)) { +// return allColors.get(i.getDurability()); +// } else { +// return meta.getBaseColor(); +// } +// +// } +// return null; +// } +// +// public static PatternType getPatternType(ItemStack i) { +// if (i.getType().toString().contains("BANNER")) { +// BannerMeta meta = (BannerMeta) i.getItemMeta(); +// return meta.getPattern(0).getPattern(); +// } +// return null; +// } +// +// public static DyeColor getColorFromBanner(ItemStack i) { +// if (i.getType().toString().contains("BANNER")) { +// BannerMeta meta = (BannerMeta) i.getItemMeta(); +// return meta.getPattern(0).getColor(); +// } +// return null; +// } +// +// public static DyeColor getRandomDye() { +// return allColors.get(random.nextInt(allColors.size())); +// } +// +// public static PatternType getRandomPattern() { +// return allPatterns.get(random.nextInt(allPatterns.size())); +// } +// +// DyeColor getDyeColor(ItemStack i) { +// switch (i.getType()) { +// case INK_SAC: +// return DyeColor.BLACK; +// case ROSE_RED: +// return DyeColor.RED; +// case CACTUS_GREEN: +// return DyeColor.GREEN; +// case COCOA_BEANS: +// return DyeColor.BROWN; +// case LAPIS_LAZULI: +// return DyeColor.BLUE; +// case PURPLE_DYE: +// return DyeColor.PURPLE; +// case CYAN_DYE: +// return DyeColor.CYAN; +// case LIGHT_GRAY_DYE: +// return DyeColor.LIGHT_GRAY; +// case GRAY_DYE: +// return DyeColor.GRAY; +// case PINK_DYE: +// return DyeColor.PINK; +// case LIME_DYE: +// return DyeColor.LIME; +// case DANDELION_YELLOW: +// return DyeColor.YELLOW; +// case LIGHT_BLUE_DYE: +// return DyeColor.LIGHT_BLUE; +// case MAGENTA_DYE: +// return DyeColor.MAGENTA; +// case ORANGE_DYE: +// return DyeColor.ORANGE; +// case BONE_MEAL: +// return DyeColor.WHITE; +// default: +// return DyeColor.BLACK; +// } +// } +// +// +//} diff --git a/src/com/arcaniax/buildersutilities/utils/CustomConfig.java b/src/com/arcaniax/buildersutilities/utils/CustomConfig.java new file mode 100644 index 0000000..1de8dde --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/CustomConfig.java @@ -0,0 +1,110 @@ +package com.arcaniax.buildersutilities.utils; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.naming.ConfigurationException; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class CustomConfig { + private final JavaPlugin plugin; + private final String fileName; + private FileConfiguration config; + private File configFile; + + public CustomConfig(JavaPlugin plugin, File folder, String fileName) { + this.plugin = plugin; + if (!fileName.endsWith(".yml")) { + fileName += ".yml"; + } + this.fileName = fileName; + configFile = new File(folder, fileName); + reloadConfig(); + } + + public CustomConfig(JavaPlugin plugin, String fileName) { + this(plugin, plugin.getDataFolder(), fileName); + } + + public void reloadConfig() { + if (!configFile.exists()) { + plugin.getLogger().info("Attempting to save resource: " + configFile.getName()); + plugin.saveResource(fileName, true); + } + config = YamlConfiguration.loadConfiguration(configFile); + } + + public void saveConfig() { + try { + config.save(configFile); + } catch (Exception e) { + plugin.getLogger().severe(String.format("Couldn't save '%s', because: '%s'", fileName, + e.getMessage())); + } + reloadConfig(); + } + + public void set(String path, Object value, boolean save) { + config.set(path, value); + if (save) { + saveConfig(); + } + } + + public void set(String path, Object value) { + set(path, value, false); + } + + public Set getKeys(boolean deep) { + return this.config.getKeys(deep); + } + + public ConfigurationSection getConfigurationSection(String path) { + return this.config.getConfigurationSection(path); + } + + public boolean has(String path) { + return config.contains(path); + } + + public T get(String path, Class tClass) { + return get(path, tClass, null); + } + + public T get(String path, Class tClass, T tDefault) { + if (tClass.isPrimitive()) { + throw new IllegalArgumentException(tClass + " is of a primitive type, please use the objectified version."); + } + if (!has(path)) { + if (tDefault == null) { + try { + throw new ConfigurationException("Configuration key doesn't exist and the default is null"); + } catch (ConfigurationException e) { + e.printStackTrace(); + } + } + return tDefault; + } + Object object = config.get(path); + if (object == null) { + return tDefault; + } + if (!tClass.isInstance(object)) { + throw new IllegalArgumentException(path + " is not of type " + tClass.getSimpleName()); + } + return tClass.cast(object); + } + + public List getStringList(String path) { + if (!has(path)) { + return new ArrayList<>(); + } + return config.getStringList(path); + } + +} diff --git a/src/com/arcaniax/buildersutilities/utils/Items.java b/src/com/arcaniax/buildersutilities/utils/Items.java new file mode 100644 index 0000000..1979875 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/Items.java @@ -0,0 +1,81 @@ +package com.arcaniax.buildersutilities.utils; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Items { + public static ItemStack create(Material mat, String name, String lore) { + return Items.create(mat, (short) 0, 1, name, lore); + } + + public static ItemStack create(Material mat, short data, int amount, String name, String lore) { + ItemStack is = new ItemStack(mat); + is.setAmount(amount); + ItemMeta meta = is.getItemMeta(); + if (!lore.equals("")) { + String[] loreListArray = lore.split("__"); + List loreList = new ArrayList<>(); + for (String s : loreListArray) { + loreList.add(s.replace('&', ChatColor.COLOR_CHAR)); + } + meta.setLore(loreList); + } + if (!name.equals("")) { + meta.setDisplayName(name.replace('&', ChatColor.COLOR_CHAR)); + } + is.setItemMeta(meta); + is.setDurability(data); + return is; + } + + public static ItemStack color(ItemStack is, int r, int g, int b) { + LeatherArmorMeta lam = (LeatherArmorMeta) is.getItemMeta(); + Color c = Color.fromRGB(r, g, b); + lam.setColor(c); + is.setItemMeta(lam); + return is; + } + + + public static ItemStack createHead(String data, int amount, String name, String lore) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + item.setAmount(amount); + ItemMeta meta = item.getItemMeta(); + if (!lore.equals("")) { + String[] loreListArray = lore.split("__"); + List loreList = new ArrayList<>(); + for (String s : loreListArray) { + loreList.add(s.replace('&', ChatColor.COLOR_CHAR)); + } + meta.setLore(loreList); + } + if (!name.equals("")) { + meta.setDisplayName(name.replace('&', ChatColor.COLOR_CHAR)); + } + item.setItemMeta(meta); + SkullMeta headMeta = (SkullMeta) item.getItemMeta(); + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + profile.getProperties().put("textures", new Property("textures", data)); + Field profileField; + try { + profileField = headMeta.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(headMeta, profile); + } catch (Exception ignored) { + } + item.setItemMeta(headMeta); + return item; + } +} diff --git a/src/com/arcaniax/buildersutilities/utils/Metrics.java b/src/com/arcaniax/buildersutilities/utils/Metrics.java new file mode 100644 index 0000000..08a44bb --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/Metrics.java @@ -0,0 +1,720 @@ +package com.arcaniax.buildersutilities.utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // The plugin id + private final int pluginId; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + * @param pluginId The id of the plugin. + * It can be found at What is my plugin id? + */ + public Metrics(Plugin plugin, int pluginId) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + this.pluginId = pluginId; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("id", pluginId); // Append the id of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(new JsonPrimitive(entry.getValue())); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(new JsonPrimitive(categoryValue)); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + +} \ No newline at end of file diff --git a/src/com/arcaniax/buildersutilities/utils/NmsManager.java b/src/com/arcaniax/buildersutilities/utils/NmsManager.java new file mode 100644 index 0000000..53eebe6 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/NmsManager.java @@ -0,0 +1,41 @@ +package com.arcaniax.buildersutilities.utils; + +import com.arcaniax.buildersutilities.Main; + +public class NmsManager { + private String version; + + public NmsManager() { + String packageString = Main.getInstance().getServer().getClass().getPackage().getName(); + version = packageString.substring(packageString.lastIndexOf('.') + 1); + } + + public boolean isVersion(String v) { + return version.equalsIgnoreCase(v); + } + + public boolean isVersion(int gameV, int releaseV, int subReleaseV) { + return version.equalsIgnoreCase("v" + gameV + "_" + releaseV + "_R" + subReleaseV); + } + + public boolean isAtLeastVersion(int gameV, int releaseV, int subReleaseV) { + String[] split = version.split("_"); + int game = Integer.parseInt(split[0].toLowerCase().replace("v", "")); + int release = Integer.parseInt(split[1]); + int subRelease = Integer.parseInt(split[2].toLowerCase().replace("r", "")); + + if (game > gameV) { + return true; + } else if (game < gameV) { + return false; + } else { + if (release > releaseV) { + return true; + } else if (release < releaseV) { + return false; + } else { + return subRelease >= subReleaseV; + } + } + } +} diff --git a/src/com/arcaniax/buildersutilities/utils/Utility.java b/src/com/arcaniax/buildersutilities/utils/Utility.java new file mode 100644 index 0000000..4bc44b5 --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/Utility.java @@ -0,0 +1,27 @@ +package com.arcaniax.buildersutilities.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class Utility { + + public static String readFileAsString(File file) { + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append(System.lineSeparator()); + line = br.readLine(); + } + return sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + return e.getMessage(); + } + } + +} diff --git a/src/com/arcaniax/buildersutilities/utils/XMaterial.java b/src/com/arcaniax/buildersutilities/utils/XMaterial.java new file mode 100644 index 0000000..197b8df --- /dev/null +++ b/src/com/arcaniax/buildersutilities/utils/XMaterial.java @@ -0,0 +1,2088 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018 Hex_27 + * Copyright (c) 2020 Crypto Morin + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.arcaniax.buildersutilities.utils; + +import com.google.common.base.Enums; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Maps; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.WordUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +/** + * XMaterial - Data Values/Pre-flattening
+ * 1.13 and above as priority. + *

+ * This class is mainly designed to support ItemStacks. + * If you want to use it on blocks you'll have to + * use XBlock + *

+ * Pre-flattening: https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening + * Materials: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html + * Materials (1.12): https://helpch.at/docs/1.12.2/index.html?org/bukkit/Material.html + * Material IDs: https://minecraft-ids.grahamedgecombe.com/ + * Material Source Code: https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse/src/main/java/org/bukkit/Material.java + * XMaterial v1: https://www.spigotmc.org/threads/329630/ + * + * @author Crypto Morin + * @version 5.0.1 + * @see Material + * @see ItemStack + */ +public enum XMaterial { + ACACIA_BOAT("BOAT_ACACIA"), + ACACIA_BUTTON("WOOD_BUTTON"), + ACACIA_DOOR("ACACIA_DOOR_ITEM", "ACACIA_DOOR"), + ACACIA_FENCE, + ACACIA_FENCE_GATE, + ACACIA_LEAVES("LEAVES_2"), + ACACIA_LOG("LOG_2"), + ACACIA_PLANKS(4, "WOOD"), + ACACIA_PRESSURE_PLATE("WOOD_PLATE"), + ACACIA_SAPLING(4, "SAPLING"), + ACACIA_SIGN("SIGN"), + ACACIA_SLAB(4, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + ACACIA_STAIRS, + ACACIA_TRAPDOOR("TRAP_DOOR"), + ACACIA_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + ACACIA_WOOD("LOG_2"), + ACTIVATOR_RAIL, + /** + * https://minecraft.gamepedia.com/Air + * + * + * @see #VOID_AIR + * @see #CAVE_AIR + */ + AIR, + ALLIUM(2, "RED_ROSE"), + ANCIENT_DEBRIS("1.16"), + ANDESITE(5, "STONE"), + ANDESITE_SLAB, + ANDESITE_STAIRS, + ANDESITE_WALL, + ANVIL, + APPLE, + ARMOR_STAND, + ARROW, + ATTACHED_MELON_STEM(7, "MELON_STEM"), + ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"), + AZURE_BLUET(3, "RED_ROSE"), + BAKED_POTATO, + BAMBOO("1.14", "SUGAR_CANE", ""), + BAMBOO_SAPLING("1.14"), + BARREL("1.14", "CHEST", ""), + BARRIER, + BASALT("1.16"), + BAT_SPAWN_EGG(65, "MONSTER_EGG"), + BEACON, + BEDROCK, + BEEF("RAW_BEEF"), + BEEHIVE("1.15"), + /** + * Beetroot is a known material in pre-1.13 + * Use XBlock when comparing block types. + */ + BEETROOT("BEETROOT_BLOCK"), + BEETROOTS("BEETROOT"), + BEETROOT_SEEDS, + BEETROOT_SOUP, + BEE_NEST("1.15"), + BEE_SPAWN_EGG("1.15"), + BELL("1.14"), + BIRCH_BOAT("BOAT_BIRCH"), + BIRCH_BUTTON("WOOD_BUTTON"), + BIRCH_DOOR("BIRCH_DOOR_ITEM", "BIRCH_DOOR"), + BIRCH_FENCE, + BIRCH_FENCE_GATE, + BIRCH_LEAVES(2, "LEAVES"), + BIRCH_LOG(2, "LOG"), + BIRCH_PLANKS(2, "WOOD"), + BIRCH_PRESSURE_PLATE("WOOD_PLATE"), + BIRCH_SAPLING(2, "SAPLING"), + BIRCH_SIGN("SIGN"), + BIRCH_SLAB(2, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + BIRCH_STAIRS("BIRCH_WOOD_STAIRS"), + BIRCH_TRAPDOOR("TRAP_DOOR"), + BIRCH_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + BIRCH_WOOD(2, "LOG"), + BLACKSTONE("1.16"), + BLACKSTONE_SLAB("1.16"), + BLACKSTONE_STAIRS("1.16"), + BLACKSTONE_WALL("1.16"), + BLACK_BANNER("BANNER", "STANDING_BANNER"), + BLACK_BED(15, "BED_BLOCK", "BED"), + BLACK_CARPET(15, "CARPET"), + BLACK_CONCRETE(15, "CONCRETE"), + BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"), + BLACK_DYE("1.14", "INK_SACK"), + BLACK_GLAZED_TERRACOTTA(15, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLACK_TERRACOTTA"), + BLACK_SHULKER_BOX, + BLACK_STAINED_GLASS(15, "STAINED_GLASS"), + BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"), + BLACK_TERRACOTTA(15, "HARD_CLAY", "STAINED_CLAY"), + BLACK_WALL_BANNER("WALL_BANNER"), + BLACK_WOOL(15, "WOOL"), + BLAST_FURNACE("1.14", "FURNACE", ""), + BLAZE_POWDER, + BLAZE_ROD, + BLAZE_SPAWN_EGG(61, "MONSTER_EGG"), + BLUE_BANNER(4, "BANNER", "STANDING_BANNER"), + BLUE_BED(11, "BED_BLOCK", "BED"), + BLUE_CARPET(11, "CARPET"), + BLUE_CONCRETE(11, "CONCRETE"), + BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"), + BLUE_DYE(4, "INK_SACK", "LAPIS_LAZULI"), + BLUE_GLAZED_TERRACOTTA(11, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLUE_TERRACOTTA"), + BLUE_ICE("1.13", "PACKED_ICE", ""), + BLUE_ORCHID(1, "RED_ROSE"), + BLUE_SHULKER_BOX, + BLUE_STAINED_GLASS(11, "STAINED_GLASS"), + BLUE_STAINED_GLASS_PANE(11, "THIN_GLASS", "STAINED_GLASS_PANE"), + BLUE_TERRACOTTA(11, "HARD_CLAY", "STAINED_CLAY"), + BLUE_WALL_BANNER(4, "WALL_BANNER"), + BLUE_WOOL(11, "WOOL"), + BONE, + BONE_BLOCK, + BONE_MEAL(15, "INK_SACK"), + BOOK, + BOOKSHELF, + BOW, + BOWL, + BRAIN_CORAL("1.13"), + BRAIN_CORAL_BLOCK("1.13"), + BRAIN_CORAL_FAN("1.13"), + BRAIN_CORAL_WALL_FAN, + BREAD, + BREWING_STAND("BREWING_STAND_ITEM"), + BRICK("CLAY_BRICK"), + BRICKS("BRICK"), + BRICK_SLAB(4, "STEP"), + BRICK_STAIRS, + BRICK_WALL, + BROWN_BANNER(3, "BANNER", "STANDING_BANNER"), + BROWN_BED(12, "BED_BLOCK", "BED"), + BROWN_CARPET(12, "CARPET"), + BROWN_CONCRETE(12, "CONCRETE"), + BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"), + BROWN_DYE(3, "INK_SACK", "COCOA", "COCOA_BEANS"), + BROWN_GLAZED_TERRACOTTA(12, "1.12", "HARD_CLAY", "STAINED_CLAY", "BROWN_TERRACOTTA"), + BROWN_MUSHROOM, + BROWN_MUSHROOM_BLOCK("BROWN_MUSHROOM", "HUGE_MUSHROOM_1"), + BROWN_SHULKER_BOX, + BROWN_STAINED_GLASS(12, "STAINED_GLASS"), + BROWN_STAINED_GLASS_PANE(12, "THIN_GLASS", "STAINED_GLASS_PANE"), + BROWN_TERRACOTTA(12, "STAINED_CLAY"), + BROWN_WALL_BANNER(3, "WALL_BANNER"), + BROWN_WOOL(12, "WOOL"), + BUBBLE_COLUMN("1.13"), + BUBBLE_CORAL("1.13"), + BUBBLE_CORAL_BLOCK("1.13"), + BUBBLE_CORAL_FAN("1.13"), + BUBBLE_CORAL_WALL_FAN, + BUCKET, + CACTUS, + CAKE("CAKE_BLOCK"), + CAMPFIRE("1.14"), + CARROT("CARROT_ITEM"), + CARROTS("CARROT"), + CARROT_ON_A_STICK("CARROT_STICK"), + CARTOGRAPHY_TABLE("1.14", "CRAFTING_TABLE", ""), + CARVED_PUMPKIN(1, "1.13", "PUMPKIN", ""), + CAT_SPAWN_EGG, + CAULDRON("CAULDRON_ITEM"), + /** + * 1.13 tag is not added because it's the same thing as {@link #AIR} + * + * @see #VOID_AIR + */ + CAVE_AIR("AIR"), + CAVE_SPIDER_SPAWN_EGG(59, "MONSTER_EGG"), + CHAIN("1.16"), + CHAINMAIL_BOOTS, + CHAINMAIL_CHESTPLATE, + CHAINMAIL_HELMET, + CHAINMAIL_LEGGINGS, + CHAIN_COMMAND_BLOCK("COMMAND", "COMMAND_CHAIN"), + CHARCOAL(1, "COAL"), + CHEST("LOCKED_CHEST"), + CHEST_MINECART("STORAGE_MINECART"), + CHICKEN("RAW_CHICKEN"), + CHICKEN_SPAWN_EGG(93, "MONSTER_EGG"), + CHIPPED_ANVIL(1, "ANVIL"), + CHISELED_NETHER_BRICKS(1, "NETHER_BRICKS"), + CHISELED_POLISHED_BLACKSTONE("1.16", "POLISHED_BLACKSTONE"), + CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"), + CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"), + CHISELED_SANDSTONE(1, "SANDSTONE"), + CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"), + CHORUS_FLOWER("1.9"), + CHORUS_FRUIT("1.9"), + CHORUS_PLANT("1.9"), + CLAY, + CLAY_BALL, + CLOCK("WATCH"), + COAL, + COAL_BLOCK, + COAL_ORE, + COARSE_DIRT(1, "DIRT"), + COBBLESTONE, + COBBLESTONE_SLAB(3, "STEP"), + COBBLESTONE_STAIRS, + COBBLESTONE_WALL("COBBLE_WALL"), + COBWEB("WEB"), + COCOA("1.15"), + COCOA_BEANS(3, "INK_SACK", "COCOA"), + COD("RAW_FISH"), + COD_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), + COD_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + COMMAND_BLOCK("COMMAND"), + COMMAND_BLOCK_MINECART("COMMAND_MINECART"), + /** + * Unlike redstone torch and redstone lamp... neither REDTONE_COMPARATOR_OFF nor REDSTONE_COMPARATOR_ON + * are items. REDSTONE_COMPARATOR is. + * + * @see #REDSTONE_TORCH + * @see #REDSTONE_LAMP + */ + COMPARATOR("REDSTONE_COMPARATOR_OFF", "REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR"), + COMPASS, + COMPOSTER("1.14", "CAULDRON", ""), + CONDUIT("1.13", "BEACON"), + COOKED_BEEF, + COOKED_CHICKEN, + COOKED_COD("COOKED_FISH"), + COOKED_MUTTON, + COOKED_PORKCHOP("PORK", "GRILLED_PORK"), + COOKED_RABBIT, + COOKED_SALMON(1, "COOKED_FISH"), + COOKIE, + CORNFLOWER(4, "1.14", "BLUE_DYE", ""), + COW_SPAWN_EGG(92, "MONSTER_EGG"), + CRACKED_NETHER_BRICKS(2, "NETHER_BRICKS"), + CRACKED_POLISHED_BLACKSTONE_BRICKS("1.16", "POLISHED_BLACKSTONE_BRICKS"), + CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"), + CRAFTING_TABLE("WORKBENCH"), + CREEPER_BANNER_PATTERN, + CREEPER_HEAD(4, "SKULL", "SKULL_ITEM"), + CREEPER_SPAWN_EGG(50, "MONSTER_EGG"), + CREEPER_WALL_HEAD(4, "SKULL", "SKULL_ITEM"), + CRIMSON_BUTTON("1.16"), + CRIMSON_DOOR("1.16"), + CRIMSON_FENCE("1.16"), + CRIMSON_FENCE_GATE("1.16"), + CRIMSON_FUNGUS("1.16"), + CRIMSON_HYPHAE("1.16"), + CRIMSON_NYLIUM("1.16"), + CRIMSON_PLANKS("1.16"), + CRIMSON_PRESSURE_PLATE("1.16"), + CRIMSON_ROOTS("1.16"), + CRIMSON_SIGN("1.16"), + CRIMSON_SLAB("1.16"), + CRIMSON_STAIRS("1.16"), + CRIMSON_STEM("1.16"), + CRIMSON_TRAPDOOR("1.16"), + CRIMSON_WALL_SIGN("1.16"), + CROSSBOW, + CRYING_OBSIDIAN("1.16"), + CUT_RED_SANDSTONE("1.13"), + CUT_RED_SANDSTONE_SLAB("STONE_SLAB2"), + CUT_SANDSTONE("1.13"), + CUT_SANDSTONE_SLAB("STEP"), + CYAN_BANNER(6, "BANNER", "STANDING_BANNER"), + CYAN_BED(9, "BED_BLOCK", "BED"), + CYAN_CARPET(9, "CARPET"), + CYAN_CONCRETE(9, "CONCRETE"), + CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"), + CYAN_DYE(6, "INK_SACK"), + CYAN_GLAZED_TERRACOTTA(9, "1.12", "HARD_CLAY", "STAINED_CLAY", "CYAN_TERRACOTTA"), + CYAN_SHULKER_BOX, + CYAN_STAINED_GLASS(9, "STAINED_GLASS"), + CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"), + CYAN_TERRACOTTA(9, "HARD_CLAY", "STAINED_CLAY"), + CYAN_WALL_BANNER(6, "WALL_BANNER"), + CYAN_WOOL(9, "WOOL"), + DAMAGED_ANVIL(2, "ANVIL"), + DANDELION("YELLOW_FLOWER"), + DARK_OAK_BOAT("BOAT_DARK_OAK"), + DARK_OAK_BUTTON("WOOD_BUTTON"), + DARK_OAK_DOOR("DARK_OAK_DOOR_ITEM", "DARK_OAK_DOOR"), + DARK_OAK_FENCE, + DARK_OAK_FENCE_GATE, + DARK_OAK_LEAVES(4, "LEAVES", "LEAVES_2"), + DARK_OAK_LOG(1, "LOG", "LOG_2"), + DARK_OAK_PLANKS(5, "WOOD"), + DARK_OAK_PRESSURE_PLATE("WOOD_PLATE"), + DARK_OAK_SAPLING(5, "SAPLING"), + DARK_OAK_SIGN("SIGN"), + DARK_OAK_SLAB(5, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + DARK_OAK_STAIRS, + DARK_OAK_TRAPDOOR("TRAP_DOOR"), + DARK_OAK_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + DARK_OAK_WOOD(1, "LOG", "LOG_2"), + DARK_PRISMARINE(1, "PRISMARINE"), + DARK_PRISMARINE_SLAB("1.13"), + DARK_PRISMARINE_STAIRS("1.13"), + DAYLIGHT_DETECTOR("DAYLIGHT_DETECTOR_INVERTED"), + DEAD_BRAIN_CORAL("1.13"), + DEAD_BRAIN_CORAL_BLOCK("1.13"), + DEAD_BRAIN_CORAL_FAN("1.13"), + DEAD_BRAIN_CORAL_WALL_FAN("1.13"), + DEAD_BUBBLE_CORAL("1.13"), + DEAD_BUBBLE_CORAL_BLOCK("1.13"), + DEAD_BUBBLE_CORAL_FAN("1.13"), + DEAD_BUBBLE_CORAL_WALL_FAN("1.13"), + DEAD_BUSH, + DEAD_FIRE_CORAL("1.13"), + DEAD_FIRE_CORAL_BLOCK("1.13"), + DEAD_FIRE_CORAL_FAN("1.13"), + DEAD_FIRE_CORAL_WALL_FAN("1.13"), + DEAD_HORN_CORAL("1.13"), + DEAD_HORN_CORAL_BLOCK("1.13"), + DEAD_HORN_CORAL_FAN("1.13"), + DEAD_HORN_CORAL_WALL_FAN("1.13"), + DEAD_TUBE_CORAL("1.13"), + DEAD_TUBE_CORAL_BLOCK("1.13"), + DEAD_TUBE_CORAL_FAN("1.13"), + DEAD_TUBE_CORAL_WALL_FAN("1.13"), + DEBUG_STICK("1.13", "STICK", ""), + DETECTOR_RAIL, + DIAMOND, + DIAMOND_AXE, + DIAMOND_BLOCK, + DIAMOND_BOOTS, + DIAMOND_CHESTPLATE, + DIAMOND_HELMET, + DIAMOND_HOE, + DIAMOND_HORSE_ARMOR("DIAMOND_BARDING"), + DIAMOND_LEGGINGS, + DIAMOND_ORE, + DIAMOND_PICKAXE, + DIAMOND_SHOVEL("DIAMOND_SPADE"), + DIAMOND_SWORD, + DIORITE(3, "STONE"), + DIORITE_SLAB, + DIORITE_STAIRS, + DIORITE_WALL, + DIRT, + DISPENSER, + DOLPHIN_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + DONKEY_SPAWN_EGG(32, "MONSTER_EGG"), + DRAGON_BREATH("DRAGONS_BREATH"), + DRAGON_EGG, + DRAGON_HEAD(5, "1.9", "SKULL", "SKULL_ITEM"), + DRAGON_WALL_HEAD(5, "SKULL", "SKULL_ITEM"), + DRIED_KELP("1.13"), + DRIED_KELP_BLOCK("1.13"), + DROPPER, + DROWNED_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + EGG, + ELDER_GUARDIAN_SPAWN_EGG(4, "MONSTER_EGG"), + ELYTRA, + EMERALD, + EMERALD_BLOCK, + EMERALD_ORE, + ENCHANTED_BOOK, + ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"), + ENCHANTING_TABLE("ENCHANTMENT_TABLE"), + ENDERMAN_SPAWN_EGG(58, "MONSTER_EGG"), + ENDERMITE_SPAWN_EGG(67, "MONSTER_EGG"), + ENDER_CHEST, + ENDER_EYE("EYE_OF_ENDER"), + ENDER_PEARL, + END_CRYSTAL, + END_GATEWAY("1.9"), + END_PORTAL("ENDER_PORTAL"), + END_PORTAL_FRAME("ENDER_PORTAL_FRAME"), + END_ROD("1.9", "BLAZE_ROD", ""), + END_STONE("ENDER_STONE"), + END_STONE_BRICKS("END_BRICKS"), + END_STONE_BRICK_SLAB(6, "STEP"), + END_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), + END_STONE_BRICK_WALL, + EVOKER_SPAWN_EGG(34, "MONSTER_EGG"), + EXPERIENCE_BOTTLE("EXP_BOTTLE"), + FARMLAND("SOIL"), + FEATHER, + FERMENTED_SPIDER_EYE, + FERN(1, "LONG_GRASS"), + /** + * For some reasons filled map items are really special. + * Their data value starts from 0 and every time a player + * creates a new map that maps data value increases. + */ + FILLED_MAP("MAP"), + FIRE, + FIREWORK_ROCKET("FIREWORK"), + FIREWORK_STAR("FIREWORK_CHARGE"), + FIRE_CHARGE("FIREBALL"), + FIRE_CORAL("1.13"), + FIRE_CORAL_BLOCK("1.13"), + FIRE_CORAL_FAN("1.13"), + FIRE_CORAL_WALL_FAN, + FISHING_ROD, + FLETCHING_TABLE("1.14", "CRAFTING_TABLE", ""), + FLINT, + FLINT_AND_STEEL, + FLOWER_BANNER_PATTERN, + FLOWER_POT("FLOWER_POT_ITEM"), + FOX_SPAWN_EGG("1.14"), + /** + * This special material cannot be obtained as an item. + */ + FROSTED_ICE("1.9", "PACKED_ICE", ""), + FURNACE("BURNING_FURNACE"), + FURNACE_MINECART("POWERED_MINECART"), + GHAST_SPAWN_EGG(56, "MONSTER_EGG"), + GHAST_TEAR, + GLASS, + GLASS_BOTTLE, + GLASS_PANE("THIN_GLASS"), + GLISTERING_MELON_SLICE("SPECKLED_MELON"), + GLOBE_BANNER_PATTERN, + GLOWSTONE, + GLOWSTONE_DUST, + GOLDEN_APPLE, + GOLDEN_AXE("GOLD_AXE"), + GOLDEN_BOOTS("GOLD_BOOTS"), + GOLDEN_CARROT, + GOLDEN_CHESTPLATE("GOLD_CHESTPLATE"), + GOLDEN_HELMET("GOLD_HELMET"), + GOLDEN_HOE("GOLD_HOE"), + GOLDEN_HORSE_ARMOR("GOLD_BARDING"), + GOLDEN_LEGGINGS("GOLD_LEGGINGS"), + GOLDEN_PICKAXE("GOLD_PICKAXE"), + GOLDEN_SHOVEL("GOLD_SPADE"), + GOLDEN_SWORD("GOLD_SWORD"), + GOLD_BLOCK, + GOLD_INGOT, + GOLD_NUGGET, + GOLD_ORE, + GRANITE(1, "STONE"), + GRANITE_SLAB, + GRANITE_STAIRS, + GRANITE_WALL, + GRASS, + GRASS_BLOCK("GRASS"), + GRASS_PATH, + GRAVEL, + GRAY_BANNER(8, "BANNER", "STANDING_BANNER"), + GRAY_BED(7, "BED_BLOCK", "BED"), + GRAY_CARPET(7, "CARPET"), + GRAY_CONCRETE(7, "CONCRETE"), + GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"), + GRAY_DYE(8, "INK_SACK"), + GRAY_GLAZED_TERRACOTTA(7, "1.12", "HARD_CLAY", "STAINED_CLAY", "GRAY_TERRACOTTA"), + GRAY_SHULKER_BOX, + GRAY_STAINED_GLASS(7, "STAINED_GLASS"), + GRAY_STAINED_GLASS_PANE(7, "THIN_GLASS", "STAINED_GLASS_PANE"), + GRAY_TERRACOTTA(7, "HARD_CLAY", "STAINED_CLAY"), + GRAY_WALL_BANNER(8, "WALL_BANNER"), + GRAY_WOOL(7, "WOOL"), + GREEN_BANNER(2, "BANNER", "STANDING_BANNER"), + GREEN_BED(13, "BED_BLOCK", "BED"), + GREEN_CARPET(13, "CARPET"), + GREEN_CONCRETE(13, "CONCRETE"), + GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"), + GREEN_DYE(2, "INK_SACK", "CACTUS_GREEN"), + GREEN_GLAZED_TERRACOTTA(13, "1.12", "HARD_CLAY", "STAINED_CLAY", "GREEN_TERRACOTTA"), + GREEN_SHULKER_BOX, + GREEN_STAINED_GLASS(13, "STAINED_GLASS"), + GREEN_STAINED_GLASS_PANE(13, "THIN_GLASS", "STAINED_GLASS_PANE"), + GREEN_TERRACOTTA(13, "HARD_CLAY", "STAINED_CLAY"), + GREEN_WALL_BANNER(2, "WALL_BANNER"), + GREEN_WOOL(13, "WOOL"), + GRINDSTONE("1.14", "ANVIL", ""), + GUARDIAN_SPAWN_EGG(68, "MONSTER_EGG"), + GUNPOWDER("SULPHUR"), + HAY_BLOCK, + HEART_OF_THE_SEA("1.13"), + HEAVY_WEIGHTED_PRESSURE_PLATE("IRON_PLATE"), + HOGLIN_SPAWN_EGG("1.16", "MONSTER_EGG"), + HONEYCOMB("1.15"), + HONEYCOMB_BLOCK("1.15"), + HONEY_BLOCK("1.15", "SLIME_BLOCK", ""), + HONEY_BOTTLE("1.15", "GLASS_BOTTLE", ""), + HOPPER, + HOPPER_MINECART, + HORN_CORAL("1.13"), + HORN_CORAL_BLOCK("1.13"), + HORN_CORAL_FAN("1.13"), + HORN_CORAL_WALL_FAN, + HORSE_SPAWN_EGG(100, "MONSTER_EGG"), + HUSK_SPAWN_EGG(23, "MONSTER_EGG"), + ICE, + INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS", "SMOOTH_BRICK"), + INFESTED_COBBLESTONE(1, "MONSTER_EGGS"), + INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS", "SMOOTH_BRICK"), + INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"), + INFESTED_STONE("MONSTER_EGGS"), + INFESTED_STONE_BRICKS(2, "MONSTER_EGGS", "SMOOTH_BRICK"), + INK_SAC("INK_SACK"), + IRON_AXE, + IRON_BARS("IRON_FENCE"), + IRON_BLOCK, + IRON_BOOTS, + IRON_CHESTPLATE, + IRON_DOOR("IRON_DOOR_BLOCK"), + IRON_HELMET, + IRON_HOE, + IRON_HORSE_ARMOR("IRON_BARDING"), + IRON_INGOT, + IRON_LEGGINGS, + IRON_NUGGET, + IRON_ORE, + IRON_PICKAXE, + IRON_SHOVEL("IRON_SPADE"), + IRON_SWORD, + IRON_TRAPDOOR, + ITEM_FRAME, + JACK_O_LANTERN, + JIGSAW("1.14", "COMMAND_BLOCK", "STRUCTURE_BLOCK", ""), + JUKEBOX, + JUNGLE_BOAT("BOAT_JUNGLE"), + JUNGLE_BUTTON("WOOD_BUTTON"), + JUNGLE_DOOR("JUNGLE_DOOR_ITEM", "JUNGLE_DOOR"), + JUNGLE_FENCE, + JUNGLE_FENCE_GATE, + JUNGLE_LEAVES(3, "LEAVES"), + JUNGLE_LOG(3, "LOG"), + JUNGLE_PLANKS(3, "WOOD"), + JUNGLE_PRESSURE_PLATE("WOOD_PLATE"), + JUNGLE_SAPLING(3, "SAPLING"), + JUNGLE_SIGN("SIGN"), + JUNGLE_SLAB(3, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + JUNGLE_STAIRS("JUNGLE_WOOD_STAIRS"), + JUNGLE_TRAPDOOR("TRAP_DOOR"), + JUNGLE_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + JUNGLE_WOOD(3, "LOG"), + KELP("1.13"), + KELP_PLANT("1.13"), + KNOWLEDGE_BOOK("1.12", "BOOK"), + LADDER, + LANTERN("1.14", "SEA_LANTERN", ""), + LAPIS_BLOCK, + LAPIS_LAZULI(4, "INK_SACK"), + LAPIS_ORE, + LARGE_FERN(3, "DOUBLE_PLANT"), + LAVA("STATIONARY_LAVA"), + LAVA_BUCKET, + LEAD("LEASH"), + LEATHER, + LEATHER_BOOTS, + LEATHER_CHESTPLATE, + LEATHER_HELMET, + LEATHER_HORSE_ARMOR("1.14", "IRON_HORSE_ARMOR", ""), + LEATHER_LEGGINGS, + LECTERN("1.14", "BOOKSHELF", ""), + LEVER, + LIGHT_BLUE_BANNER(12, "BANNER", "STANDING_BANNER"), + LIGHT_BLUE_BED(3, "BED_BLOCK", "BED"), + LIGHT_BLUE_CARPET(3, "CARPET"), + LIGHT_BLUE_CONCRETE(3, "CONCRETE"), + LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"), + LIGHT_BLUE_DYE(12, "INK_SACK"), + LIGHT_BLUE_GLAZED_TERRACOTTA(3, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_BLUE_TERRACOTTA"), + LIGHT_BLUE_SHULKER_BOX, + LIGHT_BLUE_STAINED_GLASS(3, "STAINED_GLASS"), + LIGHT_BLUE_STAINED_GLASS_PANE(3, "THIN_GLASS", "STAINED_GLASS_PANE"), + LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"), + LIGHT_BLUE_WALL_BANNER(12, "WALL_BANNER", "BANNER", "STANDING_BANNER"), + LIGHT_BLUE_WOOL(3, "WOOL"), + LIGHT_GRAY_BANNER(7, "BANNER", "STANDING_BANNER"), + LIGHT_GRAY_BED(8, "BED_BLOCK", "BED"), + LIGHT_GRAY_CARPET(8, "CARPET"), + LIGHT_GRAY_CONCRETE(8, "CONCRETE"), + LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"), + LIGHT_GRAY_DYE(7, "INK_SACK"), + /** + * Renamed to SILVER_GLAZED_TERRACOTTA in 1.12 + * Renamed to LIGHT_GRAY_GLAZED_TERRACOTTA in 1.14 + */ + LIGHT_GRAY_GLAZED_TERRACOTTA("1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_GRAY_TERRACOTTA", "SILVER_GLAZED_TERRACOTTA"), + LIGHT_GRAY_SHULKER_BOX("SILVER_SHULKER_BOX"), + LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"), + LIGHT_GRAY_STAINED_GLASS_PANE(8, "THIN_GLASS", "STAINED_GLASS_PANE"), + LIGHT_GRAY_TERRACOTTA(8, "HARD_CLAY", "STAINED_CLAY"), + LIGHT_GRAY_WALL_BANNER(7, "WALL_BANNER"), + LIGHT_GRAY_WOOL(8, "WOOL"), + LIGHT_WEIGHTED_PRESSURE_PLATE("GOLD_PLATE"), + LILAC(1, "DOUBLE_PLANT"), + LILY_OF_THE_VALLEY(15, "1.14", "WHITE_DYE", ""), + LILY_PAD("WATER_LILY"), + LIME_BANNER(10, "BANNER", "STANDING_BANNER"), + LIME_BED(5, "BED_BLOCK", "BED"), + LIME_CARPET(5, "CARPET"), + LIME_CONCRETE(5, "CONCRETE"), + LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"), + LIME_DYE(10, "INK_SACK"), + LIME_GLAZED_TERRACOTTA(5, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIME_TERRACOTTA"), + LIME_SHULKER_BOX, + LIME_STAINED_GLASS(5, "STAINED_GLASS"), + LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"), + LIME_TERRACOTTA(5, "HARD_CLAY", "STAINED_CLAY"), + LIME_WALL_BANNER(10, "WALL_BANNER"), + LIME_WOOL(5, "WOOL"), + LINGERING_POTION, + LLAMA_SPAWN_EGG(103, "MONSTER_EGG"), + LODESTONE("1.16"), + LOOM("1.14"), + MAGENTA_BANNER(13, "BANNER", "STANDING_BANNER"), + MAGENTA_BED(2, "BED_BLOCK", "BED"), + MAGENTA_CARPET(2, "CARPET"), + MAGENTA_CONCRETE(2, "CONCRETE"), + MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"), + MAGENTA_DYE(13, "INK_SACK"), + MAGENTA_GLAZED_TERRACOTTA(2, "1.12", "HARD_CLAY", "STAINED_CLAY", "MAGENTA_TERRACOTTA"), + MAGENTA_SHULKER_BOX, + MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"), + MAGENTA_STAINED_GLASS_PANE(2, "THIN_GLASS", "STAINED_GLASS_PANE"), + MAGENTA_TERRACOTTA(2, "HARD_CLAY", "STAINED_CLAY"), + MAGENTA_WALL_BANNER(13, "WALL_BANNER"), + MAGENTA_WOOL(2, "WOOL"), + MAGMA_BLOCK("1.10", "MAGMA"), + MAGMA_CREAM, + MAGMA_CUBE_SPAWN_EGG(62, "MONSTER_EGG"), + /** + * Adding this to the duplicated list will give you a filled map + * for 1.13+ versions and removing it from duplicated list will + * still give you a filled map in -1.12 versions. + * Since higher versions are our priority I'll keep 1.13+ support + * until I can come up with something to fix it. + */ + MAP("EMPTY_MAP"), + MELON("MELON_BLOCK"), + MELON_SEEDS, + MELON_SLICE("MELON"), + MELON_STEM, + MILK_BUCKET, + MINECART, + MOJANG_BANNER_PATTERN, + MOOSHROOM_SPAWN_EGG(96, "MONSTER_EGG"), + MOSSY_COBBLESTONE, + MOSSY_COBBLESTONE_SLAB(3, "STEP"), + MOSSY_COBBLESTONE_STAIRS, + MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL", "COBBLESTONE_WALL"), + MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"), + MOSSY_STONE_BRICK_SLAB(5, "STEP"), + MOSSY_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), + MOSSY_STONE_BRICK_WALL, + MOVING_PISTON("PISTON_BASE", "PISTON_MOVING_PIECE"), + MULE_SPAWN_EGG(32, "MONSTER_EGG"), + MUSHROOM_STEM("BROWN_MUSHROOM"), + MUSHROOM_STEW("MUSHROOM_SOUP"), + MUSIC_DISC_11("GOLD_RECORD"), + MUSIC_DISC_13("GREEN_RECORD"), + MUSIC_DISC_BLOCKS("RECORD_3"), + MUSIC_DISC_CAT("RECORD_4"), + MUSIC_DISC_CHIRP("RECORD_5"), + MUSIC_DISC_FAR("RECORD_6"), + MUSIC_DISC_MALL("RECORD_7"), + MUSIC_DISC_MELLOHI("RECORD_8"), + MUSIC_DISC_STAL("RECORD_9"), + MUSIC_DISC_STRAD("RECORD_10"), + MUSIC_DISC_WAIT("RECORD_11"), + MUSIC_DISC_WARD("RECORD_12"), + MUTTON, + MYCELIUM("MYCEL"), + NAME_TAG, + NAUTILUS_SHELL("1.13"), + NETHERITE_AXE("1.16"), + NETHERITE_BLOCK("1.16"), + NETHERITE_BOOTS("1.16"), + NETHERITE_CHESTPLATE("1.16"), + NETHERITE_HELMET("1.16"), + NETHERITE_HOE("1.16"), + NETHERITE_INGOT("1.16"), + NETHERITE_LEGGINGS("1.16"), + NETHERITE_PICKAXE("1.16"), + NETHERITE_SCRAP("1.16"), + NETHERITE_SHOVEL("1.16"), + NETHERITE_SWORD("1.16"), + NETHERRACK, + NETHER_BRICK("NETHER_BRICK_ITEM"), + NETHER_BRICKS("NETHER_BRICK"), + NETHER_BRICK_FENCE("NETHER_FENCE"), + NETHER_BRICK_SLAB(6, "STEP"), + NETHER_BRICK_STAIRS, + NETHER_BRICK_WALL, + NETHER_GOLD_ORE("1.16"), + NETHER_PORTAL("PORTAL"), + NETHER_QUARTZ_ORE("QUARTZ_ORE"), + NETHER_SPROUTS("1.16"), + NETHER_STAR, + /** + * Just like mentioned in https://minecraft.gamepedia.com/Nether_Wart + * Nether wart is also known as nether stalk in the code. + * NETHER_STALK is the planted state of nether warts. + */ + NETHER_WART("NETHER_WARTS", "NETHER_STALK"), + NETHER_WART_BLOCK, + NOTE_BLOCK, + OAK_BOAT("BOAT"), + OAK_BUTTON("WOOD_BUTTON"), + OAK_DOOR("WOOD_DOOR", "WOODEN_DOOR"), + OAK_FENCE("FENCE"), + OAK_FENCE_GATE("FENCE_GATE"), + OAK_LEAVES("LEAVES"), + OAK_LOG("LOG"), + OAK_PLANKS("WOOD"), + OAK_PRESSURE_PLATE("WOOD_PLATE"), + OAK_SAPLING("SAPLING"), + OAK_SIGN("SIGN"), + OAK_SLAB("WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + OAK_STAIRS("WOOD_STAIRS"), + OAK_TRAPDOOR("TRAP_DOOR"), + OAK_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + OAK_WOOD("LOG"), + OBSERVER, + OBSIDIAN, + OCELOT_SPAWN_EGG(98, "MONSTER_EGG"), + ORANGE_BANNER(14, "BANNER", "STANDING_BANNER"), + ORANGE_BED(1, "BED_BLOCK", "BED"), + ORANGE_CARPET(1, "CARPET"), + ORANGE_CONCRETE(1, "CONCRETE"), + ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"), + ORANGE_DYE(14, "INK_SACK"), + ORANGE_GLAZED_TERRACOTTA(1, "1.12", "HARD_CLAY", "STAINED_CLAY", "ORANGE_TERRACOTTA"), + ORANGE_SHULKER_BOX, + ORANGE_STAINED_GLASS(1, "STAINED_GLASS"), + ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"), + ORANGE_TERRACOTTA(1, "HARD_CLAY", "STAINED_CLAY"), + ORANGE_TULIP(5, "RED_ROSE"), + ORANGE_WALL_BANNER(14, "WALL_BANNER"), + ORANGE_WOOL(1, "WOOL"), + OXEYE_DAISY(8, "RED_ROSE"), + PACKED_ICE, + PAINTING, + PANDA_SPAWN_EGG("1.14"), + PAPER, + PARROT_SPAWN_EGG(105, "MONSTER_EGG"), + PEONY(5, "DOUBLE_PLANT"), + PETRIFIED_OAK_SLAB("WOOD_STEP"), + PHANTOM_MEMBRANE("1.13"), + PHANTOM_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + PIG_SPAWN_EGG(90, "MONSTER_EGG"), + PILLAGER_SPAWN_EGG("1.14"), + PINK_BANNER(9, "BANNER", "STANDING_BANNER"), + PINK_BED(6, "BED_BLOCK", "BED"), + PINK_CARPET(6, "CARPET"), + PINK_CONCRETE(6, "CONCRETE"), + PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"), + PINK_DYE(9, "INK_SACK"), + PINK_GLAZED_TERRACOTTA(6, "1.12", "HARD_CLAY", "STAINED_CLAY", "PINK_TERRACOTTA"), + PINK_SHULKER_BOX, + PINK_STAINED_GLASS(6, "STAINED_GLASS"), + PINK_STAINED_GLASS_PANE(6, "THIN_GLASS", "STAINED_GLASS_PANE"), + PINK_TERRACOTTA(6, "HARD_CLAY", "STAINED_CLAY"), + PINK_TULIP(7, "RED_ROSE"), + PINK_WALL_BANNER(9, "WALL_BANNER"), + PINK_WOOL(6, "WOOL"), + PISTON("PISTON_BASE"), + PISTON_HEAD("PISTON_EXTENSION"), + PLAYER_HEAD(3, "SKULL", "SKULL_ITEM"), + PLAYER_WALL_HEAD(3, "SKULL", "SKULL_ITEM"), + PODZOL(2, "DIRT"), + POISONOUS_POTATO, + POLAR_BEAR_SPAWN_EGG(102, "MONSTER_EGG"), + POLISHED_ANDESITE(6, "STONE"), + POLISHED_ANDESITE_SLAB, + POLISHED_ANDESITE_STAIRS, + POLISHED_BASALT("1.16"), + POLISHED_BLACKSTONE("1.16"), + POLISHED_BLACKSTONE_BRICKS("1.16"), + POLISHED_BLACKSTONE_BRICK_SLAB("1.16"), + POLISHED_BLACKSTONE_BRICK_STAIRS("1.16"), + POLISHED_BLACKSTONE_BRICK_WALL("1.16"), + POLISHED_BLACKSTONE_BUTTON("1.16"), + POLISHED_BLACKSTONE_PRESSURE_PLATE("1.16"), + POLISHED_BLACKSTONE_SLAB("1.16"), + POLISHED_BLACKSTONE_STAIRS("1.16"), + POLISHED_BLACKSTONE_WALL("1.16"), + POLISHED_DIORITE(4, "STONE"), + POLISHED_DIORITE_SLAB, + POLISHED_DIORITE_STAIRS, + POLISHED_GRANITE(2, "STONE"), + POLISHED_GRANITE_SLAB, + POLISHED_GRANITE_STAIRS, + POPPED_CHORUS_FRUIT("CHORUS_FRUIT_POPPED"), + POPPY("RED_ROSE"), + PORKCHOP("PORK"), + POTATO("POTATO_ITEM"), + POTATOES("POTATO"), + POTION, + POTTED_ACACIA_SAPLING(4, "SAPLING", "FLOWER_POT"), + POTTED_ALLIUM(2, "RED_ROSE", "FLOWER_POT"), + POTTED_AZURE_BLUET(3, "RED_ROSE", "FLOWER_POT"), + POTTED_BAMBOO, + POTTED_BIRCH_SAPLING(2, "SAPLING", "FLOWER_POT"), + POTTED_BLUE_ORCHID(1, "RED_ROSE", "FLOWER_POT"), + POTTED_BROWN_MUSHROOM("FLOWER_POT"), + POTTED_CACTUS("FLOWER_POT"), + POTTED_CORNFLOWER, + POTTED_DANDELION("YELLOW_FLOWER", "FLOWER_POT"), + POTTED_DARK_OAK_SAPLING(5, "SAPLING", "FLOWER_POT"), + POTTED_DEAD_BUSH("FLOWER_POT"), + POTTED_FERN(2, "LONG_GRASS", "FLOWER_POT"), + POTTED_JUNGLE_SAPLING(3, "SAPLING", "FLOWER_POT"), + POTTED_LILY_OF_THE_VALLEY, + POTTED_OAK_SAPLING("SAPLING", "FLOWER_POT"), + POTTED_ORANGE_TULIP(5, "RED_ROSE", "FLOWER_POT"), + POTTED_OXEYE_DAISY(8, "RED_ROSE", "FLOWER_POT"), + POTTED_PINK_TULIP(7, "RED_ROSE", "FLOWER_POT"), + POTTED_POPPY("RED_ROSE", "FLOWER_POT"), + POTTED_RED_MUSHROOM("FLOWER_POT"), + POTTED_RED_TULIP(4, "RED_ROSE", "FLOWER_POT"), + POTTED_SPRUCE_SAPLING(1, "SAPLING", "FLOWER_POT"), + POTTED_WHITE_TULIP(6, "RED_ROSE", "FLOWER_POT"), + POTTED_WITHER_ROSE, + POWERED_RAIL, + PRISMARINE, + PRISMARINE_BRICKS(2, "PRISMARINE"), + PRISMARINE_BRICK_SLAB(4, "STEP"), + PRISMARINE_BRICK_STAIRS("1.13"), + PRISMARINE_CRYSTALS, + PRISMARINE_SHARD, + PRISMARINE_SLAB("1.13"), + PRISMARINE_STAIRS("1.13"), + PRISMARINE_WALL, + PUFFERFISH(3, "RAW_FISH"), + PUFFERFISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), + PUFFERFISH_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + PUMPKIN, + PUMPKIN_PIE, + PUMPKIN_SEEDS, + PUMPKIN_STEM, + PURPLE_BANNER(5, "BANNER", "STANDING_BANNER"), + PURPLE_BED(10, "BED_BLOCK", "BED"), + PURPLE_CARPET(10, "CARPET"), + PURPLE_CONCRETE(10, "CONCRETE"), + PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"), + PURPLE_DYE(5, "INK_SACK"), + PURPLE_GLAZED_TERRACOTTA(10, "1.12", "HARD_CLAY", "STAINED_CLAY", "PURPLE_TERRACOTTA"), + PURPLE_SHULKER_BOX, + PURPLE_STAINED_GLASS(10, "STAINED_GLASS"), + PURPLE_STAINED_GLASS_PANE(10, "THIN_GLASS", "STAINED_GLASS_PANE"), + PURPLE_TERRACOTTA(10, "HARD_CLAY", "STAINED_CLAY"), + PURPLE_WALL_BANNER(5, "WALL_BANNER"), + PURPLE_WOOL(10, "WOOL"), + PURPUR_BLOCK, + PURPUR_PILLAR, + PURPUR_SLAB("PURPUR_DOUBLE_SLAB"), + PURPUR_STAIRS, + QUARTZ, + QUARTZ_BLOCK, + QUARTZ_PILLAR(2, "QUARTZ_BLOCK"), + QUARTZ_SLAB(7, "STEP"), + QUARTZ_STAIRS, + RABBIT, + RABBIT_FOOT, + RABBIT_HIDE, + RABBIT_SPAWN_EGG(101, "MONSTER_EGG"), + RABBIT_STEW, + RAIL("RAILS"), + RAVAGER_SPAWN_EGG("1.14"), + REDSTONE, + REDSTONE_BLOCK, + /** + * Unlike redstone torch, REDSTONE_LAMP_ON isn't an item. + * The name is just here on the list for matching. + * + * @see #REDSTONE_TORCH + */ + REDSTONE_LAMP("REDSTONE_LAMP_ON", "REDSTONE_LAMP_OFF"), + REDSTONE_ORE("GLOWING_REDSTONE_ORE"), + /** + * REDSTONE_TORCH_OFF isn't an item, but a block. + * But REDSTONE_TORCH_ON is the item. + * The name is just here on the list for matching. + */ + REDSTONE_TORCH("REDSTONE_TORCH_OFF", "REDSTONE_TORCH_ON"), + REDSTONE_WALL_TORCH, + REDSTONE_WIRE, + RED_BANNER(1, "BANNER", "STANDING_BANNER"), + /** + * Data value 14 or 0 + */ + RED_BED(0, "BED_BLOCK", "BED"), + RED_CARPET(14, "CARPET"), + RED_CONCRETE(14, "CONCRETE"), + RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"), + /** + * Data value 0 or 1? + */ + RED_DYE(0, "INK_SACK", "ROSE_RED"), + RED_GLAZED_TERRACOTTA(14, "1.12", "HARD_CLAY", "STAINED_CLAY", "RED_TERRACOTTA"), + RED_MUSHROOM, + RED_MUSHROOM_BLOCK("RED_MUSHROOM", "HUGE_MUSHROOM_2"), + RED_NETHER_BRICKS("RED_NETHER_BRICK"), + RED_NETHER_BRICK_SLAB(4, "STEP"), + RED_NETHER_BRICK_STAIRS, + RED_NETHER_BRICK_WALL, + RED_SAND(1, "SAND"), + RED_SANDSTONE, + RED_SANDSTONE_SLAB("STONE_SLAB2", "DOUBLE_STONE_SLAB2"), + RED_SANDSTONE_STAIRS, + RED_SANDSTONE_WALL, + RED_SHULKER_BOX, + RED_STAINED_GLASS(14, "STAINED_GLASS"), + RED_STAINED_GLASS_PANE(14, "THIN_GLASS", "STAINED_GLASS_PANE"), + RED_TERRACOTTA(14, "HARD_CLAY", "STAINED_CLAY"), + RED_TULIP(4, "RED_ROSE"), + RED_WALL_BANNER(1, "WALL_BANNER"), + RED_WOOL(14, "WOOL"), + REPEATER("DIODE", "DIODE_BLOCK_ON", "DIODE_BLOCK_OFF"), + REPEATING_COMMAND_BLOCK("COMMAND", "COMMAND_REPEATING"), + RESPAWN_ANCHOR("1.16"), + ROSE_BUSH(4, "DOUBLE_PLANT"), + ROTTEN_FLESH, + SADDLE, + SALMON(1, "RAW_FISH"), + SALMON_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), + SALMON_SPAWN_EGG("1.13", "MONSTER_EGG", ""), + SAND, + SANDSTONE, + SANDSTONE_SLAB(1, "STEP", "STONE_SLAB", "DOUBLE_STEP"), + SANDSTONE_STAIRS, + SANDSTONE_WALL, + SCAFFOLDING("1.14", "SLIME_BLOCK", ""), + SCUTE("1.13"), + SEAGRASS("1.13", "GRASS", ""), + SEA_LANTERN, + SEA_PICKLE("1.13"), + SHEARS, + SHEEP_SPAWN_EGG(91, "MONSTER_EGG"), + SHIELD, + SHROOMLIGHT("1.16"), + SHULKER_BOX("PURPLE_SHULKER_BOX"), + SHULKER_SHELL, + SHULKER_SPAWN_EGG(69, "MONSTER_EGG"), + SILVERFISH_SPAWN_EGG(60, "MONSTER_EGG"), + SKELETON_HORSE_SPAWN_EGG(28, "MONSTER_EGG"), + SKELETON_SKULL("SKULL", "SKULL_ITEM"), + SKELETON_SPAWN_EGG(51, "MONSTER_EGG"), + SKELETON_WALL_SKULL("SKULL", "SKULL_ITEM"), + SKULL_BANNER_PATTERN, + SLIME_BALL, + SLIME_BLOCK, + SLIME_SPAWN_EGG(55, "MONSTER_EGG"), + SMITHING_TABLE, + SMOKER("1.14", "FURNACE", ""), + SMOOTH_QUARTZ("1.13", "QUARTZ", ""), + SMOOTH_QUARTZ_SLAB(7, "STEP"), + SMOOTH_QUARTZ_STAIRS, + SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"), + SMOOTH_RED_SANDSTONE_SLAB("STONE_SLAB2"), + SMOOTH_RED_SANDSTONE_STAIRS, + SMOOTH_SANDSTONE(2, "SANDSTONE"), + SMOOTH_SANDSTONE_SLAB("STEP"), + SMOOTH_SANDSTONE_STAIRS, + SMOOTH_STONE("STEP"), + SMOOTH_STONE_SLAB("STEP"), + SNOW, + SNOWBALL("SNOW_BALL"), + SNOW_BLOCK, + SOUL_CAMPFIRE("1.16"), + SOUL_FIRE("1.16"), + SOUL_LANTERN("1.16"), + SOUL_SAND, + SOUL_SOIL("1.16"), + SOUL_TORCH("1.16"), + SOUL_WALL_TORCH("1.16"), + SPAWNER("MOB_SPAWNER"), + SPECTRAL_ARROW("1.9", "ARROW", ""), + SPIDER_EYE, + SPIDER_SPAWN_EGG(52, "MONSTER_EGG"), + SPLASH_POTION, + SPONGE, + SPRUCE_BOAT("BOAT_SPRUCE"), + SPRUCE_BUTTON("WOOD_BUTTON"), + SPRUCE_DOOR("SPRUCE_DOOR_ITEM", "SPRUCE_DOOR"), + SPRUCE_FENCE, + SPRUCE_FENCE_GATE, + SPRUCE_LEAVES(1, "LEAVES"), + SPRUCE_LOG(1, "LOG"), + SPRUCE_PLANKS(1, "WOOD"), + SPRUCE_PRESSURE_PLATE("WOOD_PLATE"), + SPRUCE_SAPLING(1, "SAPLING"), + SPRUCE_SIGN("SIGN"), + SPRUCE_SLAB(1, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + SPRUCE_STAIRS("SPRUCE_WOOD_STAIRS"), + SPRUCE_TRAPDOOR("TRAP_DOOR"), + SPRUCE_WALL_SIGN("SIGN_POST", "WALL_SIGN"), + SPRUCE_WOOD(1, "LOG"), + SQUID_SPAWN_EGG(94, "MONSTER_EGG"), + STICK, + STICKY_PISTON("PISTON_BASE", "PISTON_STICKY_BASE"), + STONE, + STONECUTTER("1.14"), + STONE_AXE, + STONE_BRICKS("SMOOTH_BRICK"), + STONE_BRICK_SLAB(4, "STEP", "STONE_SLAB", "DOUBLE_STEP"), + STONE_BRICK_STAIRS("SMOOTH_STAIRS"), + STONE_BRICK_WALL, + STONE_BUTTON, + STONE_HOE, + STONE_PICKAXE, + STONE_PRESSURE_PLATE("STONE_PLATE"), + STONE_SHOVEL("STONE_SPADE"), + STONE_SLAB("STEP", "DOUBLE_STEP"), + STONE_STAIRS, + STONE_SWORD, + STRAY_SPAWN_EGG(6, "MONSTER_EGG"), + STRING, + STRIPPED_ACACIA_LOG("LOG_2"), + STRIPPED_ACACIA_WOOD("LOG_2"), + STRIPPED_BIRCH_LOG(2, "LOG"), + STRIPPED_BIRCH_WOOD(2, "LOG"), + STRIPPED_CRIMSON_HYPHAE("1.16"), + STRIPPED_CRIMSON_STEM("1.16"), + STRIPPED_DARK_OAK_LOG("LOG"), + STRIPPED_DARK_OAK_WOOD("LOG"), + STRIPPED_JUNGLE_LOG(3, "LOG"), + STRIPPED_JUNGLE_WOOD(3, "LOG"), + STRIPPED_OAK_LOG("LOG"), + STRIPPED_OAK_WOOD("LOG"), + STRIPPED_SPRUCE_LOG(1, "LOG"), + STRIPPED_SPRUCE_WOOD(1, "LOG"), + STRIPPED_WARPED_HYPHAE("1.16"), + STRIPPED_WARPED_STEM("1.16"), + STRUCTURE_BLOCK, + /** + * Originally developers used barrier blocks for its purpose. + * So technically this isn't really considered as a suggested material. + */ + STRUCTURE_VOID("1.10", "", "BARRIER"), + SUGAR, + /** + * Sugar Cane is a known material in pre-1.13 + * Use XBlock when comparing block types. + */ + SUGAR_CANE("SUGAR_CANE_BLOCK"), + SUNFLOWER("DOUBLE_PLANT"), + SUSPICIOUS_STEW("1.14", "MUSHROOM_STEW", ""), + SWEET_BERRIES("1.14"), + SWEET_BERRY_BUSH("1.14", "GRASS", ""), + TALL_GRASS(2, "DOUBLE_PLANT"), + TALL_SEAGRASS(2, "1.13", "TALL_GRASS", ""), + TARGET("1.16"), + TERRACOTTA("HARD_CLAY"), + TIPPED_ARROW("1.9", "ARROW", ""), + TNT, + TNT_MINECART("EXPLOSIVE_MINECART"), + TORCH, + TOTEM_OF_UNDYING("TOTEM"), + TRADER_LLAMA_SPAWN_EGG(103, "1.14", "MONSTER_EGG", ""), + TRAPPED_CHEST, + TRIDENT("1.13"), + TRIPWIRE, + TRIPWIRE_HOOK, + TROPICAL_FISH(2, "RAW_FISH"), + TROPICAL_FISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), + TROPICAL_FISH_SPAWN_EGG("1.13", "MONSTER_EGG"), + TUBE_CORAL("1.13"), + TUBE_CORAL_BLOCK("1.13"), + TUBE_CORAL_FAN("1.13"), + TUBE_CORAL_WALL_FAN, + TURTLE_EGG("1.13", "EGG", ""), + TURTLE_HELMET("1.13", "IRON_HELMET", ""), + TURTLE_SPAWN_EGG("1.13", "CHICKEN_SPAWN_EGG", ""), + TWISTING_VINES("1.16"), + TWISTING_VINES_PLANT("1.16"), + VEX_SPAWN_EGG(35, "MONSTER_EGG"), + VILLAGER_SPAWN_EGG(120, "MONSTER_EGG"), + VINDICATOR_SPAWN_EGG(36, "MONSTER_EGG"), + VINE, + /** + * 1.13 tag is not added because it's the same thing as {@link #AIR} + * + * @see #CAVE_AIR + */ + VOID_AIR("AIR"), + WALL_TORCH("TORCH"), + WANDERING_TRADER_SPAWN_EGG("1.14", "VILLAGER_SPAWN_EGG", ""), + WARPED_BUTTON("1.16"), + WARPED_DOOR("1.16"), + WARPED_FENCE("1.16"), + WARPED_FENCE_GATE("1.16"), + WARPED_FUNGUS("1.16"), + WARPED_FUNGUS_ON_A_STICK("1.16"), + WARPED_HYPHAE("1.16"), + WARPED_NYLIUM("1.16"), + WARPED_PLANKS("1.16"), + WARPED_PRESSURE_PLATE("1.16"), + WARPED_ROOTS("1.16"), + WARPED_SIGN("1.16"), + WARPED_SLAB("1.16"), + WARPED_STAIRS("1.16"), + WARPED_STEM("1.16"), + WARPED_TRAPDOOR("1.16"), + WARPED_WALL_SIGN("1.16"), + WARPED_WART_BLOCK("1.16"), + /** + * This is used for blocks only. + * In 1.13- WATER will turn into STATIONARY_WATER after it finished spreading. + * After 1.13+ this uses + * https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/data/Levelled.html water flowing system. + * Use XBlock for this instead. + */ + WATER("STATIONARY_WATER"), + WATER_BUCKET, + WEEPING_VINES("1.16"), + WEEPING_VINES_PLANT("1.16"), + WET_SPONGE(1, "SPONGE"), + /** + * Wheat is a known material in pre-1.13 + * Use XBlock when comparing block types. + */ + WHEAT("CROPS"), + WHEAT_SEEDS("SEEDS"), + WHITE_BANNER(15, "BANNER", "STANDING_BANNER"), + WHITE_BED("BED_BLOCK", "BED"), + WHITE_CARPET("CARPET"), + WHITE_CONCRETE("CONCRETE"), + WHITE_CONCRETE_POWDER("CONCRETE_POWDER"), + WHITE_DYE(15, "1.14", "INK_SACK", "BONE_MEAL"), + WHITE_GLAZED_TERRACOTTA("1.12", "HARD_CLAY", "STAINED_CLAY"), + WHITE_SHULKER_BOX, + WHITE_STAINED_GLASS("STAINED_GLASS"), + WHITE_STAINED_GLASS_PANE("THIN_GLASS", "STAINED_GLASS_PANE"), + WHITE_TERRACOTTA("HARD_CLAY", "STAINED_CLAY", "TERRACOTTA"), + WHITE_TULIP(6, "RED_ROSE"), + WHITE_WALL_BANNER(15, "WALL_BANNER"), + WHITE_WOOL("WOOL"), + WITCH_SPAWN_EGG(66, "MONSTER_EGG"), + WITHER_ROSE("1.14", "BLACK_DYE", ""), + WITHER_SKELETON_SKULL(1, "SKULL", "SKULL_ITEM"), + WITHER_SKELETON_SPAWN_EGG(5, "MONSTER_EGG"), + WITHER_SKELETON_WALL_SKULL(1, "SKULL", "SKULL_ITEM"), + WOLF_SPAWN_EGG(95, "MONSTER_EGG"), + WOODEN_AXE("WOOD_AXE"), + WOODEN_HOE("WOOD_HOE"), + WOODEN_PICKAXE("WOOD_PICKAXE"), + WOODEN_SHOVEL("WOOD_SPADE"), + WOODEN_SWORD("WOOD_SWORD"), + WRITABLE_BOOK("BOOK_AND_QUILL"), + WRITTEN_BOOK, + YELLOW_BANNER(11, "BANNER", "STANDING_BANNER"), + YELLOW_BED(4, "BED_BLOCK", "BED"), + YELLOW_CARPET(4, "CARPET"), + YELLOW_CONCRETE(4, "CONCRETE"), + YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"), + YELLOW_DYE(11, "INK_SACK", "DANDELION_YELLOW"), + YELLOW_GLAZED_TERRACOTTA(4, "1.12", "HARD_CLAY", "STAINED_CLAY", "YELLOW_TERRACOTTA"), + YELLOW_SHULKER_BOX, + YELLOW_STAINED_GLASS(4, "STAINED_GLASS"), + YELLOW_STAINED_GLASS_PANE(4, "THIN_GLASS", "STAINED_GLASS_PANE"), + YELLOW_TERRACOTTA(4, "HARD_CLAY", "STAINED_CLAY"), + YELLOW_WALL_BANNER(11, "WALL_BANNER"), + YELLOW_WOOL(4, "WOOL"), + ZOMBIE_HEAD(2, "SKULL", "SKULL_ITEM"), + ZOMBIE_HORSE_SPAWN_EGG(29, "MONSTER_EGG"), + ZOMBIE_SPAWN_EGG(54, "MONSTER_EGG"), + ZOMBIE_VILLAGER_SPAWN_EGG(27, "MONSTER_EGG"), + ZOMBIE_WALL_HEAD(2, "SKULL", "SKULL_ITEM"), + PIGLIN_SPAWN_EGG(57, "MONSTER_EGG"), + ZOMBIFIED_PIGLIN_SPAWN_EGG(57, "MONSTER_EGG", "ZOMBIE_PIGMAN_SPAWN_EGG"); + + + /** + * An immutable cached set of {@link XMaterial#values()} to avoid allocating memory for + * calling the method every time. + * + * @since 2.0.0 + */ + public static final EnumSet VALUES = EnumSet.allOf(XMaterial.class); + /** + * A set of material names that can be damaged. + *

+ * Most of the names are not complete as this list is intended to be + * checked with {@link String#contains} for memory usage. + * + * @since 1.0.0 + */ + private static final ImmutableSet DAMAGEABLE = ImmutableSet.of( + "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", + "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", + "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", + "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", + "CARROT_ON_A_STICK", "CARROT_STICK", "SPADE", "SHIELD" + ); + /** + * XMaterial Paradox (Duplication Check) + *

+ * A map of duplicated material names in 1.13 and 1.12 that will conflict with the legacy names. + * Values are the new material names. + *
+ * Duplicates are normally only checked by keys, not values. + * + * @since 3.0.0 + */ + @SuppressWarnings("UnstableApiUsage") + private static final ImmutableMap duplicated = Maps.immutableEnumMap(ImmutableMap.builder() + .put(MELON, MELON_SLICE) + .put(CARROT, CARROTS) + .put(POTATO, POTATOES) + .put(BEETROOT, BEETROOTS) + .put(BROWN_MUSHROOM, BROWN_MUSHROOM_BLOCK) + .put(BRICK, BRICKS) + .put(NETHER_BRICK, NETHER_BRICKS) + + // Illegal Elements + // Since both 1.12 and 1.13 have _DOOR XMaterial will use it + // for 1.12 to parse the material, but it needs _DOOR_ITEM. + // We'll trick XMaterial into thinking this needs to be parsed + // using the old methods. + // These materials have their enum name added to the legacy list as well. + .put(DARK_OAK_DOOR, DARK_OAK_DOOR) + .put(ACACIA_DOOR, ACACIA_DOOR) + .put(BIRCH_DOOR, BIRCH_DOOR) + .put(JUNGLE_DOOR, JUNGLE_DOOR) + .put(SPRUCE_DOOR, SPRUCE_DOOR) + + .build() + ); + /* + * A set of all the legacy names without duplicates. + *

+ * It'll help to free up a lot of memory if it's not used. + * Add it back if you need it. + * + * @see #containsLegacy(String) + * @since 2.2.0 + * + private static final ImmutableSet LEGACY_VALUES = VALUES.stream().map(XMaterial::getLegacy) + .flatMap(Arrays::stream) + .filter(m -> m.charAt(1) == '.') + .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf)); + */ + + /** + * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. + * For strings that match a certain XMaterial. Mostly cached for configs. + * + * @since 1.0.0 + */ + private static final Cache NAME_CACHE = CacheBuilder.newBuilder() + .softValues() + .expireAfterAccess(15, TimeUnit.MINUTES) + .build(); + /** + * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. + * For XMaterials that are already parsed once. + * + * @since 3.0.0 + */ + private static final Cache> PARSED_CACHE = CacheBuilder.newBuilder() + .softValues() + .expireAfterAccess(10, TimeUnit.MINUTES) + .concurrencyLevel(Runtime.getRuntime().availableProcessors()) + .build(); + + /** + * Pre-compiled RegEx pattern. + * Include both replacements to avoid recreating string multiple times with multiple RegEx checks. + * + * @since 3.0.0 + */ + private static final Pattern FORMAT_PATTERN = Pattern.compile("\\W+"); + /** + * The current version of the server in the a form of a major version. + * + * @since 1.0.0 + */ + private static final int VERSION = Integer.parseInt(getMajorVersion(Bukkit.getVersion()).substring(2)); + /** + * Cached result if the server version is after the v1.13 flattening update. + * Please don't mistake this with flat-chested people. It happened. + * + * @since 3.0.0 + */ + private static final boolean ISFLAT = supports(13); + /** + * The data value of this material https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening + * + * @see #getData() + */ + private final byte data; + /** + * A list of material names that was being used for older verions. + * + * @see #getLegacy() + */ + private final String[] legacy; + + XMaterial(int data, String... legacy) { + this.data = (byte) data; + this.legacy = legacy; + } + + XMaterial() { + this(0); + } + + XMaterial(String... legacy) { + this(0, legacy); + } + + /** + * Checks if the version is 1.13 Aquatic Update or higher. + * An invocation of this method yields the cached result from the expression: + *

+ *

+ * {@link #supports(int) 13}} + *
+ * + * @return true if 1.13 or higher. + * @see #getVersion() + * @see #supports(int) + * @since 1.0.0 + */ + public static boolean isNewVersion() { + return ISFLAT; + } + + /** + * This is just an extra method that method that can be used for many cases. + * It can be used in {@link org.bukkit.event.player.PlayerInteractEvent} + * or when accessing {@link org.bukkit.entity.Player#getMainHand()}, + * or other compatibility related methods. + *

+ * An invocation of this method yields exactly the same result as the expression: + *

+ *

+ * {@link #getVersion()} == 1.8 + *
+ * + * @since 2.0.0 + */ + public static boolean isOneEight() { + return !supports(9); + } + + /** + * The current version of the server. + * + * @return the current server version or 0.0 if unknown. + * @see #isNewVersion() + * @since 2.0.0 + */ + public static double getVersion() { + return VERSION; + } + + /** + * When using newer versions of Minecraft ({@link #isNewVersion()}), helps + * to find the old material name with its data value using a cached search for optimization. + * + * @see #matchDefinedXMaterial(String, byte) + * @since 1.0.0 + */ + @Nullable + private static XMaterial requestOldXMaterial(@Nonnull String name, byte data) { + String holder = name + data; + XMaterial cache = NAME_CACHE.getIfPresent(holder); + if (cache != null) return cache; + + for (XMaterial material : VALUES) { + // Not using material.name().equals(name) check is intended. + if ((data == -1 || data == material.data) && material.anyMatchLegacy(name)) { + NAME_CACHE.put(holder, material); + return material; + } + } + + return null; + } + + /** + * Checks if XMaterial enum contains a material with the given name. + *

+ * You should use {@link #matchXMaterial(String)} instead if you're going + * to get the XMaterial object after checking if it's available in the list + * by doing a simple {@link Optional#isPresent()} check. + * This is just to avoid multiple loops for maximum performance. + * + * @param name name of the material. + * @return true if XMaterial enum has this material. + * @since 1.0.0 + */ + public static boolean contains(@Nonnull String name) { + Validate.notEmpty(name, "Cannot check for null or empty material name"); + name = format(name); + + for (XMaterial materials : VALUES) + if (materials.name().equals(name)) return true; + return false; + } + + /** + * Parses the given material name as an XMaterial with unspecified data value. + * + * @see #matchXMaterialWithData(String) + * @since 2.0.0 + */ + @Nonnull + public static Optional matchXMaterial(@Nonnull String name) { + Validate.notEmpty(name, "Cannot match a material with null or empty material name"); + Optional oldMatch = matchXMaterialWithData(name); + if (oldMatch.isPresent()) return oldMatch; + return matchDefinedXMaterial(format(name), (byte) -1); + } + + /** + * Parses material name and data value from the specified string. + * The seperators are: , or : + * Spaces are allowed. Mostly used when getting materials from config for old school minecrafters. + *

+ * Examples + *

+     *     {@code INK_SACK:1 -> RED_DYE}
+     *     {@code WOOL, 14  -> RED_WOOL}
+     * 
+ * + * @param name the material string that consists of the material name, data and separator character. + * @return the parsed XMaterial. + * @see #matchXMaterial(String) + * @since 3.0.0 + */ + private static Optional matchXMaterialWithData(String name) { + for (char separator : new char[]{',', ':'}) { + int index = name.indexOf(separator); + if (index == -1) continue; + + String mat = format(name.substring(0, index)); + byte data = Byte.parseByte(StringUtils.deleteWhitespace(name.substring(index + 1))); + return matchDefinedXMaterial(mat, data); + } + + return Optional.empty(); + } + + /** + * Parses the given material as an XMaterial. + * + * @throws IllegalArgumentException may be thrown as an unexpected exception. + * @see #matchDefinedXMaterial(String, byte) + * @see #matchXMaterial(ItemStack) + * @since 2.0.0 + */ + @Nonnull + public static XMaterial matchXMaterial(@Nonnull Material material) { + Objects.requireNonNull(material, "Cannot match null material"); + return matchDefinedXMaterial(material.name(), (byte) -1) + .orElseThrow(() -> new IllegalArgumentException("Unsupported Material With No Bytes: " + material.name())); + } + + /** + * Parses the given item as an XMaterial using its material and data value (durability). + * + * @param item the ItemStack to match. + * @return an XMaterial if matched any. + * @throws IllegalArgumentException may be thrown as an unexpected exception. + * @see #matchDefinedXMaterial(String, byte) + * @since 2.0.0 + */ + @Nonnull + @SuppressWarnings("deprecation") + public static XMaterial matchXMaterial(@Nonnull ItemStack item) { + Objects.requireNonNull(item, "Cannot match null ItemStack"); + String material = item.getType().name(); + byte data = (byte) (ISFLAT || isDamageable(material) ? 0 : item.getDurability()); + + return matchDefinedXMaterial(material, data) + .orElseThrow(() -> new IllegalArgumentException("Unsupported Material: " + material + " (" + data + ')')); + } + + /** + * Parses the given material name and data value as an XMaterial. + * All the values passed to this method will not be null or empty and are formatted correctly. + * + * @param name the formatted name of the material. + * @param data the data value of the material. + * @return an XMaterial (with the same data value if specified) + * @see #matchXMaterial(Material) + * @see #matchXMaterial(int, byte) + * @see #matchXMaterial(ItemStack) + * @since 3.0.0 + */ + @Nonnull + private static Optional matchDefinedXMaterial(@Nonnull String name, byte data) { + boolean duplicated = isDuplicated(name); + + // Do basic number and boolean checks before accessing more complex enum stuff. + // Maybe we can simplify (ISFLAT || !duplicated) with the (!ISFLAT && duplicated) under it to save a few nanoseconds? + // if (!Boolean.valueOf(Boolean.getBoolean(Boolean.TRUE.toString())).equals(Boolean.FALSE.booleanValue())) return null; + if (data <= 0 && !duplicated) { + // Apparently the transform method is more efficient than toJavaUtil() + // toJavaUtil isn't even supported in older versions. + Optional xMat = Enums.getIfPresent(XMaterial.class, name).transform(Optional::of).or(Optional.empty()); + if (xMat.isPresent()) return xMat; + } + + // XMaterial Paradox (Duplication Check) + // I've concluded that this is just an infinite loop that keeps + // going around the Singular Form and the Plural Form materials. A waste of brain cells and a waste of time. + // This solution works just fine anyway. + XMaterial xMat = requestOldXMaterial(name, data); + if (xMat == null) { + // Special case. Refer to FILLED_MAP for more info. + if (data > 0 && name.endsWith("MAP")) return Optional.of(FILLED_MAP); + return Optional.empty(); + } + + if (!ISFLAT && duplicated && xMat.name().charAt(xMat.name().length() - 1) == 'S') { + // A solution for XMaterial Paradox. + // Manually parses the duplicated materials to find the exact material based on the server version. + // If ends with "S" -> Plural Form Material + return Enums.getIfPresent(XMaterial.class, name).transform(Optional::of).or(Optional.empty()); + } + return Optional.ofNullable(xMat); + } + + /** + * XMaterial Paradox (Duplication Check) + * Checks if the material has any duplicates. + *

+ * Example: + *

{@code MELON, CARROT, POTATO, BEETROOT -> true} + * + * @param name the name of the material to check. + * @return true if there's a duplicated material for this material, otherwise false. + * @see #isDuplicated() + * @since 2.0.0 + */ + private static boolean isDuplicated(@Nonnull String name) { + // Don't use matchXMaterial() since this method is being called from matchXMaterial() itself and will cause a StackOverflowError. + for (Map.Entry duplicated : duplicated.entrySet()) { + XMaterial material = duplicated.getKey(); + if (material.name().equals(name) || material.anyMatchLegacy(name)) return true; + } + return false; + } + + /** + * Gets the XMaterial based on the material's ID (Magic Value) and data value.
+ * You should avoid using this for performance issues. + * + * @param id the ID (Magic value) of the material. + * @param data the data value of the material. + * @return a parsed XMaterial with the same ID and data value. + * @see #matchXMaterial(ItemStack) + * @since 2.0.0 + */ + @Nonnull + public static Optional matchXMaterial(int id, byte data) { + if (id < 0 || data < 0) return Optional.empty(); + + // Looping through Material.values() will take longer. + for (XMaterial materials : VALUES) + if (materials.data == data && materials.getId() == id) return Optional.of(materials); + return Optional.empty(); + } + + /** + * Attempts to build the string like an enum name. + * Removes all the spaces, numbers and extra non-English characters. Also removes some config/in-game based strings. + * + * @param name the material name to modify. + * @return a Material enum name. + * @since 2.0.0 + */ + @Nonnull + private static String format(@Nonnull String name) { + return FORMAT_PATTERN.matcher( + name.trim().replace('-', '_').replace(' ', '_')).replaceAll("").toUpperCase(Locale.ENGLISH); + } + + /** + * Checks if the specified version is the same version or higher than the current server version. + * + * @param version the major version to be checked. "1." is ignored. E.g. 1.12 = 12 | 1.9 = 9 + * @return true of the version is equal or higher than the current version. + * @since 2.0.0 + */ + public static boolean supports(int version) { + return VERSION >= version; + } + + /** + * Converts the enum names to a more friendly and readable string. + * + * @return a formatted string. + * @see #toWord(String) + * @since 2.1.0 + */ + @Nonnull + public static String toWord(@Nonnull Material material) { + Objects.requireNonNull(material, "Cannot translate a null material to a word"); + return toWord(material.name()); + } + + /** + * Parses an enum name to a normal word. + * Normal names have underlines removed and each word capitalized. + *

+ * Examples: + *

+     *     EMERALD                 -> Emerald
+     *     EMERALD_BLOCK           -> Emerald Block
+     *     ENCHANTED_GOLDEN_APPLE  -> Enchanted Golden Apple
+     * 
+ * + * @param name the name of the enum. + * @return a cleaned more readable enum name. + * @since 2.1.0 + */ + @Nonnull + private static String toWord(@Nonnull String name) { + return WordUtils.capitalize(name.replace('_', ' ').toLowerCase(Locale.ENGLISH)); + } + + /** + * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) + * + * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" + * @return the exact major version. + * @since 2.0.0 + */ + @Nonnull + public static String getMajorVersion(@Nonnull String version) { + Validate.notEmpty(version, "Cannot get major Minecraft version from null or empty string"); + + // getVersion() + int index = version.lastIndexOf("MC:"); + if (index != -1) { + version = version.substring(index + 4, version.length() - 1); + } else if (version.endsWith("SNAPSHOT")) { + // getBukkitVersion() + index = version.indexOf('-'); + version = version.substring(0, index); + } + + // 1.13.2, 1.14.4, etc... + int lastDot = version.lastIndexOf('.'); + if (version.indexOf('.') != lastDot) version = version.substring(0, lastDot); + + return version; + } + + /** + * Checks if the material can be damaged by using it. + * Names going through this method are not formatted. + * + * @param name the name of the material. + * @return true of the material can be damaged. + * @see #isDamageable() + * @since 1.0.0 + */ + public static boolean isDamageable(@Nonnull String name) { + Objects.requireNonNull(name, "Material name cannot be null"); + for (String damageable : DAMAGEABLE) + if (name.contains(damageable)) return true; + return false; + } + + /** + * Checks if the list of given material names matches the given base material. + * Mostly used for configs. + *

+ * Supports {@link String#contains} {@code CONTAINS:NAME} and Regular Expression {@code REGEX:PATTERN} formats. + *

+ * Example: + *

+     *     XMaterial material = {@link #matchXMaterial(ItemStack)};
+     *     if (material.isOneOf(plugin.getConfig().getStringList("disabled-items")) return;
+     * 
+ *
+ * {@code CONTAINS} Examples: + *
+     *     {@code "CONTAINS:CHEST" -> CHEST, ENDERCHEST, TRAPPED_CHEST -> true}
+     *     {@code "cOnTaINS:dYe" -> GREEN_DYE, YELLOW_DYE, BLUE_DYE, INK_SACK -> true}
+     * 
+ *

+ * {@code REGEX} Examples + *

+     *     {@code "REGEX:^.+_.+_.+$" -> Every Material with 3 underlines or more: SHULKER_SPAWN_EGG, SILVERFISH_SPAWN_EGG, SKELETON_HORSE_SPAWN_EGG}
+     *     {@code "REGEX:^.{1,3}$" -> Material names that have 3 letters only: BED, MAP, AIR}
+     * 
+ *

+ * The reason that there are tags for {@code CONTAINS} and {@code REGEX} + * is for the performance. + * Please avoid using the {@code REGEX} tag if you can use the {@code CONTAINS} tag. + * It'll have a huge impact on performance. + * Please avoid using {@code (capturing groups)} there's no use for them in this case. + * If you want to use groups, use {@code (?: non-capturing groups)}. It's faster. + *

+ * You can make a cache for pre-compiled RegEx patterns from your config. + * It's better, but not much faster since these patterns are not that complex. + *

+ * Want to learn RegEx? You can mess around in RegExr website. + * + * @param material the base material to match other materials with. + * @param materials the material names to check base material on. + * @return true if one of the given material names is similar to the base material. + * @since 3.1.1 + */ + public static boolean isOneOf(@Nonnull Material material, @Nullable List materials) { + if (materials == null || materials.isEmpty()) return false; + Objects.requireNonNull(material, "Cannot match materials with a null material"); + String name = material.name(); + + for (String comp : materials) { + comp = comp.toUpperCase(); + if (comp.startsWith("CONTAINS:")) { + comp = format(comp.substring(9)); + if (name.contains(comp)) return true; + continue; + } + if (comp.startsWith("REGEX:")) { + comp = comp.substring(6); + if (name.matches(comp)) return true; + continue; + } + + // Direct Object Equals + Optional mat = matchXMaterial(comp); + if (mat.isPresent() && mat.get().parseMaterial() == material) return true; + } + return false; + } + + /** + * Gets the version which this material was added in. + * If the material doesn't have a version it'll return 0; + * + * @return the Minecraft version which tihs material was added in. + * @since 3.0.0 + */ + public int getMaterialVersion() { + if (this.legacy.length == 0) return 0; + String version = this.legacy[0]; + if (version.charAt(1) != '.') return 0; + + return Integer.parseInt(version.substring(2)); + } + + /** + * Sets the {@link Material} (and data value on older versions) of an item. + * Damageable materials will not have their durability changed. + *

+ * Use {@link #parseItem()} instead when creating new ItemStacks. + * + * @param item the item to change its type. + * @see #parseItem() + * @since 3.0.0 + */ + @Nonnull + @SuppressWarnings("deprecation") + public ItemStack setType(@Nonnull ItemStack item) { + Objects.requireNonNull(item, "Cannot set material for null ItemStack"); + + item.setType(this.parseMaterial()); + if (!ISFLAT && !this.isDamageable()) item.setDurability(this.data); + return item; + } + + /** + * Checks if the list of given material names matches the given base material. + * Mostly used for configs. + * + * @param materials the material names to check base material on. + * @return true if one of the given material names is similar to the base material. + * @see #isOneOf(Material, List) + * @since 3.0.0 + */ + public boolean isOneOf(@Nullable List materials) { + Material material = this.parseMaterial(); + if (material == null) return false; + return isOneOf(material, materials); + } + + /** + * Checks if the given string matches any of this material's legacy material names. + * All the values passed to this method will not be null or empty and are formatted correctly. + * + * @param name the name to check + * @return true if it's one of the legacy names. + * @since 2.0.0 + */ + private boolean anyMatchLegacy(@Nonnull String name) { + for (String legacy : this.legacy) { + if (legacy.isEmpty()) break; // Left-side suggestion list + if (name.equals(legacy)) return true; + } + return false; + } + + /** + * User-friendly readable name for this material + * In most cases you should be using {@link #name()} instead. + * + * @return string of this object. + * @see #toWord(String) + * @since 3.0.0 + */ + @Override + public String toString() { + return toWord(this.name()); + } + + /** + * Gets the ID (Magic value) of the material. + * + * @return the ID of the material or -1 if it's a new block or the material is not supported. + * @see #matchXMaterial(int, byte) + * @since 2.2.0 + */ + @SuppressWarnings("deprecation") + public int getId() { + if (this.data != 0 || (this.legacy.length != 0 && Integer.parseInt(this.legacy[0].substring(2)) >= 13)) return -1; + Material material = this.parseMaterial(); + return material == null ? -1 : material.getId(); + } + + /** + * Checks if the material has any duplicates. + * + * @return true if there is a duplicated name for this material, otherwise false. + * @see #isDuplicated(String) + * @since 2.0.0 + */ + public boolean isDuplicated() { + return duplicated.containsKey(this); + } + + /** + * Checks if the material can be damaged by using it. + * Names going through this method are not formatted. + * + * @return true if the item can be damaged (have its durability changed), otherwise false. + * @see #isDamageable(String) + * @since 1.0.0 + */ + public boolean isDamageable() { + return isDamageable(this.name()); + } + + /** + * The data value of this material pre-flattening. + *

+ * Can be accessed with {@link ItemStack#getData()} then {@code MaterialData#getData()} + * or {@link ItemStack#getDurability()} if not damageable. + * + * @return data of this material, or 0 if none. + * @since 1.0.0 + */ + @SuppressWarnings("deprecation") + public byte getData() { + return data; + } + + /** + * Get a list of materials names that was previously used by older versions. + * If the material was added in a new version {@link #isNewVersion()}, + * then the first element will indicate which version the material was added in. + * + * @return a list of legacy material names and the first element as the version the material was added in if new. + * @since 1.0.0 + */ + @Nonnull + public String[] getLegacy() { + return legacy; + } + + /** + * Parses an item from this XMaterial. + * Uses data values on older versions. + * + * @return an ItemStack with the same material (and data value if in older versions.) + * @see #parseItem(boolean) + * @see #setType(ItemStack) + * @since 1.0.0 + */ + @Nullable + public ItemStack parseItem() { + return parseItem(false); + } + + /** + * Parses an item from this XMaterial. + * Uses data values on older versions. + * + * @param suggest if true {@link #parseMaterial(boolean)} true will be used. + * @return an ItemStack with the same material (and data value if in older versions.) + * @see #setType(ItemStack) + * @since 2.0.0 + */ + @Nullable + @SuppressWarnings("deprecation") + public ItemStack parseItem(boolean suggest) { + Material material = this.parseMaterial(suggest); + if (material == null) return null; + return ISFLAT ? new ItemStack(material) : new ItemStack(material, 1, this.data); + } + + /** + * Parses the material of this XMaterial. + * + * @return the material related to this XMaterial based on the server version. + * @see #parseMaterial(boolean) + * @since 1.0.0 + */ + @Nullable + public Material parseMaterial() { + return parseMaterial(false); + } + + /** + * Parses the material of this XMaterial and accepts suggestions. + * + * @param suggest use a suggested material (from older materials) if the material is added in a later version of Minecraft. + * @return the material related to this XMaterial based on the server version. + * @since 2.0.0 + */ + @SuppressWarnings("OptionalAssignedToNull") + @Nullable + public Material parseMaterial(boolean suggest) { + Optional cache = PARSED_CACHE.getIfPresent(this); + if (cache != null) return cache.orElse(null); + Material mat; + + if (!ISFLAT && this.isDuplicated()) mat = requestOldMaterial(suggest); + else { + mat = Material.getMaterial(this.name()); + if (mat == null) mat = requestOldMaterial(suggest); + } + + if (mat != null) PARSED_CACHE.put(this, Optional.ofNullable(mat)); + return mat; + } + + /** + * Parses a material for older versions of Minecraft. + * Accepts suggestions if specified. + * + * @param suggest if true suggested materials will be considered for old versions. + * @return a parsed material suitable for the current Minecraft version. + * @see #parseMaterial(boolean) + * @since 2.0.0 + */ + @Nullable + private Material requestOldMaterial(boolean suggest) { + for (int i = this.legacy.length - 1; i >= 0; i--) { + String legacy = this.legacy[i]; + + // Check if we've reached the end and the last string is our + // material version. + if (i == 0 && legacy.charAt(1) == '.') return null; + + // According to the suggestion list format, all the other names continuing + // from here are considered as a "suggestion" + // The empty string is an indicator for suggestion list on the left side. + if (legacy.isEmpty()) { + if (suggest) continue; + break; + } + + Material material = Material.getMaterial(legacy); + if (material != null) return material; + } + return null; + } + + /** + * Checks if an item has the same material (and data value on older versions). + * + * @param item item to check. + * @return true if the material is the same as the item's material (and data value if on older versions), otherwise false. + * @since 1.0.0 + */ + @SuppressWarnings("deprecation") + public boolean isSimilar(@Nonnull ItemStack item) { + Objects.requireNonNull(item, "Cannot compare with null ItemStack"); + if (item.getType() != this.parseMaterial()) return false; + return ISFLAT || this.isDamageable() || item.getDurability() == this.data; + } + + /** + * Gets the suggested material names that can be used + * if the material is not supported in the current version. + * + * @return a list of suggested material names. + * @see #parseMaterial(boolean) + * @since 2.0.0 + */ + @Nonnull + public List getSuggestions() { + if (this.legacy.length == 0 || this.legacy[0].charAt(1) != '.') return new ArrayList<>(); + List suggestions = new ArrayList<>(); + for (String legacy : this.legacy) { + if (legacy.isEmpty()) break; + suggestions.add(legacy); + } + return suggestions; + } + + /** + * Checks if this material is supported in the current version. + * Suggested materials will be ignored. + *

+ * Note that you should use {@link #parseMaterial()} and check if it's null + * if you're going to parse and use the material later. + * + * @return true if the material exists in {@link Material} list. + * @since 2.0.0 + */ + public boolean isSupported() { + int version = this.getMaterialVersion(); + if (version != 0) return supports(version); + + Material material = Material.getMaterial(this.name()); + if (material != null) return true; + return requestOldMaterial(false) != null; + } + + /** + * Checks if the material is newly added after the 1.13 Aquatic Update. + * + * @return true if the material was newly added, otherwise false. + * @see #getMaterialVersion() + * @since 2.0.0 + */ + public boolean isFromNewSystem() { + return this.legacy.length != 0 && Integer.parseInt(this.legacy[0].substring(2)) > 13; + } +} \ No newline at end of file