Initial commit
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package net.crankedpvp.crankedutils;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.SneakyThrows;
|
||||
import me.mattstudios.mf.base.CommandManager;
|
||||
import me.mattstudios.mf.base.components.TypeResult;
|
||||
import net.crankedpvp.crankedutils.commands.DebugModifierCommand;
|
||||
import net.crankedpvp.crankedutils.commands.DebugPotionsCommand;
|
||||
import net.crankedpvp.crankedutils.commands.ReloadConfigCommand;
|
||||
import net.crankedpvp.crankedutils.listeners.ArmorListener;
|
||||
import net.crankedpvp.crankedutils.listeners.DamageDebugHelpListener;
|
||||
import net.crankedpvp.crankedutils.listeners.DupePatch;
|
||||
import net.crankedpvp.crankedutils.modifiers.ModifierType;
|
||||
import net.crankedpvp.crankedutils.potion.PotionManager;
|
||||
import net.crankedpvp.crankedutils.utils.DamageHandler;
|
||||
import net.crankedpvp.crankedutils.utils.FactionUtils;
|
||||
import net.crankedpvp.crankedutils.utils.cache.CacheManager;
|
||||
import net.crankedpvp.crankedutils.utils.config.ConfigManager;
|
||||
import net.crankedpvp.crankedutils.utils.cosmicgui.GUIListener;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
@Getter
|
||||
public class CrankedUtils extends JavaPlugin {
|
||||
|
||||
@Getter
|
||||
public static CrankedUtils instance;
|
||||
|
||||
private CacheManager cacheManager;
|
||||
private ConfigManager configManager;
|
||||
private DamageHandler damageHandler;
|
||||
private CommandManager commandManager;
|
||||
private PotionManager potionManager;
|
||||
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
|
||||
this.configManager = new ConfigManager(this);
|
||||
this.configManager.setupFiles();
|
||||
|
||||
this.cacheManager = new CacheManager();
|
||||
|
||||
this.damageHandler = new DamageHandler(this);
|
||||
|
||||
PluginManager pm = Bukkit.getPluginManager();
|
||||
pm.registerEvents(new ArmorListener(), this);
|
||||
pm.registerEvents(new GUIListener(), this);
|
||||
pm.registerEvents(new DupePatch(), this);
|
||||
pm.registerEvents(new DamageDebugHelpListener(), this);
|
||||
|
||||
//pm.registerEvents(new PotionEffectListener(), this);
|
||||
|
||||
this.commandManager = new CommandManager(this);
|
||||
this.registerCommandParameters();
|
||||
this.commandManager.register(new ReloadConfigCommand(this));
|
||||
this.commandManager.register(new DebugPotionsCommand());
|
||||
this.commandManager.register(new DebugModifierCommand());
|
||||
|
||||
this.potionManager = new PotionManager();
|
||||
|
||||
FactionUtils.init();
|
||||
|
||||
}
|
||||
|
||||
private void registerCommandParameters() {
|
||||
this.commandManager.getParameterHandler().register(ModifierType.class, argument -> {
|
||||
ModifierType modifierType = ModifierType.valueOf(String.valueOf(argument).toUpperCase());
|
||||
return new TypeResult(modifierType, argument);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
FactionUtils.destroy();
|
||||
instance = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package net.crankedpvp.crankedutils;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HoverText {
|
||||
String text;
|
||||
List<ChatColor> lastColors = new ArrayList<>();
|
||||
|
||||
|
||||
public List<ChatColor> getLastColors() {
|
||||
return this.lastColors;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return this.text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public static HoverText formatColors(String s) {
|
||||
HoverText text = new HoverText();
|
||||
StringBuilder main = new StringBuilder();
|
||||
if (s.contains(" ")) {
|
||||
ArrayList<ChatColor> letterColors = new ArrayList<ChatColor>();
|
||||
for (String word : s.split(" ")) {
|
||||
boolean foundColorChar = false;
|
||||
boolean lastLetterLegit = true;
|
||||
StringBuilder newWord = new StringBuilder();
|
||||
for (char c : word.toCharArray()) {
|
||||
if (c == '\u00a7') {
|
||||
foundColorChar = true;
|
||||
if (!lastLetterLegit) continue;
|
||||
letterColors.clear();
|
||||
lastLetterLegit = false;
|
||||
continue;
|
||||
}
|
||||
if (foundColorChar) {
|
||||
ChatColor color = ChatColor.getByChar(c);
|
||||
if (color != null) {
|
||||
letterColors.add(color);
|
||||
}
|
||||
foundColorChar = false;
|
||||
continue;
|
||||
}
|
||||
for (ChatColor color : letterColors) {
|
||||
if (color == null) continue;
|
||||
newWord.append(color);
|
||||
}
|
||||
newWord.append(c);
|
||||
lastLetterLegit = true;
|
||||
}
|
||||
newWord.append(" ");
|
||||
main.append(newWord);
|
||||
}
|
||||
} else {
|
||||
main.append(s);
|
||||
}
|
||||
text.setText(main.toString().trim());
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.crankedpvp.crankedutils.commands;
|
||||
|
||||
import me.mattstudios.mf.annotations.Command;
|
||||
import me.mattstudios.mf.annotations.Completion;
|
||||
import me.mattstudios.mf.annotations.Default;
|
||||
import me.mattstudios.mf.annotations.Permission;
|
||||
import me.mattstudios.mf.base.CommandBase;
|
||||
import net.crankedpvp.crankedutils.modifiers.AttributeModifier;
|
||||
import net.crankedpvp.crankedutils.modifiers.ModifierType;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@Command("debugmodifier")
|
||||
public class DebugModifierCommand extends CommandBase {
|
||||
|
||||
@Default
|
||||
@Permission("cranked.admin")
|
||||
public void debugModifier(final Player player, @Completion("#enum") ModifierType modifier) {
|
||||
System.out.println(AttributeModifier.getModificationAmount(player.getItemInHand(), modifier));
|
||||
player.sendMessage("" + AttributeModifier.getModificationAmount(player.getItemInHand(), modifier));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package net.crankedpvp.crankedutils.commands;
|
||||
|
||||
import me.mattstudios.mf.annotations.*;
|
||||
import me.mattstudios.mf.base.CommandBase;
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.potion.CrankedPotionPlayer;
|
||||
import net.crankedpvp.crankedutils.potion.PotionCache;
|
||||
import net.crankedpvp.crankedutils.utils.CC;
|
||||
import net.crankedpvp.crankedutils.utils.PotionEffectUtils;
|
||||
import net.crankedpvp.crankedutils.utils.config.ConfigManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Command("debugpotions")
|
||||
@Alias({"debugpots", "debugpotion"})
|
||||
public class DebugPotionsCommand extends CommandBase {
|
||||
|
||||
|
||||
@Default
|
||||
@Permission("cranked.admin")
|
||||
@WrongUsage("&c/debugpots [player]")
|
||||
public void mainCommand(Player sender, @Optional Player player) {
|
||||
|
||||
CrankedPotionPlayer crankedPotionPlayer = null;
|
||||
|
||||
if (player != null) {
|
||||
crankedPotionPlayer = CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(player.getUniqueId());
|
||||
|
||||
} else {
|
||||
crankedPotionPlayer = CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(sender.getUniqueId());
|
||||
}
|
||||
|
||||
if (crankedPotionPlayer == null) {
|
||||
sender.sendMessage(CC.translate("&cNo potion effects"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (crankedPotionPlayer.hasPotionEffect(PotionEffectType.SPEED)) {
|
||||
sender.sendMessage(CC.translate("&7"));
|
||||
sender.sendMessage(CC.translate("&b&lPotions Debug"));
|
||||
sender.sendMessage(CC.translate("&5Highest Level Speed: &f" + crankedPotionPlayer.getHighestLevel(PotionEffectType.SPEED)));
|
||||
sender.sendMessage(CC.translate("&5Highest Level Speed Cache: &f" + crankedPotionPlayer.getPotionCacheOfHighestLevel(PotionEffectType.SPEED).getId()));
|
||||
}
|
||||
|
||||
for (Map.Entry<String, PotionCache> entry : crankedPotionPlayer.getPotionCacheMap().entrySet()) {
|
||||
String id = entry.getKey();
|
||||
PotionCache cache = entry.getValue();
|
||||
sender.sendMessage(CC.translate("&bID: &f" + id));
|
||||
sender.sendMessage(CC.translate("&dDetails:"));
|
||||
sender.sendMessage(CC.translate("&f * &6 Effect: &7" + cache.getType().getName()));
|
||||
sender.sendMessage(CC.translate("&f * &6 Duration: &7" + cache.getDuration()));
|
||||
sender.sendMessage(CC.translate("&f * &6 Level: &7" + cache.getLevel()));
|
||||
}
|
||||
sender.sendMessage(CC.translate("&7"));
|
||||
|
||||
}
|
||||
|
||||
@SubCommand("clear")
|
||||
@Permission("cranked.admin")
|
||||
@WrongUsage("&c/debugpots clear <player>")
|
||||
public void mainCommand(CommandSender sender, Player player) {
|
||||
PotionEffectUtils.clearPlayerEffects(player);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package net.crankedpvp.crankedutils.commands;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.utils.config.ConfigManager;
|
||||
import me.mattstudios.mf.annotations.Alias;
|
||||
import me.mattstudios.mf.annotations.Command;
|
||||
import me.mattstudios.mf.annotations.Default;
|
||||
import me.mattstudios.mf.base.CommandBase;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@Command("creload")
|
||||
@Alias("crankedreload")
|
||||
public class ReloadConfigCommand extends CommandBase {
|
||||
|
||||
private final ConfigManager configManager;
|
||||
|
||||
public ReloadConfigCommand(CrankedUtils plugin) {
|
||||
this.configManager = plugin.getConfigManager();
|
||||
}
|
||||
|
||||
@Default
|
||||
public void mainCommand(Player sender) {
|
||||
this.configManager.reloadFiles();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.crankedpvp.crankedutils.compat;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class ParamBuilder {
|
||||
private final List<RParam> parameters = new LinkedList<RParam>();
|
||||
private int validObjectCount = 0;
|
||||
|
||||
public ParamBuilder() {
|
||||
}
|
||||
|
||||
public ParamBuilder(Class<?> clazz, Object obj) {
|
||||
this.add(clazz, obj);
|
||||
}
|
||||
|
||||
public ParamBuilder add(RParam param) {
|
||||
this.parameters.add(param);
|
||||
if (param != null) {
|
||||
++this.validObjectCount;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ParamBuilder add(Class<?> clazz, Object param) {
|
||||
this.add(new RParam(clazz, param));
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<RParam> getParameters() {
|
||||
return this.parameters;
|
||||
}
|
||||
|
||||
public int getValidObjectCount() {
|
||||
return this.validObjectCount;
|
||||
}
|
||||
|
||||
public void setValidObjectCount(int validObjectCount) {
|
||||
this.validObjectCount = validObjectCount;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.crankedpvp.crankedutils.compat;
|
||||
|
||||
public class RParam {
|
||||
private final Class<?> methodClass;
|
||||
private Object instance;
|
||||
|
||||
public RParam(Class<?> clazz) {
|
||||
this.methodClass = clazz;
|
||||
}
|
||||
|
||||
public RParam(Class<?> methodClass, Object instance) {
|
||||
this.methodClass = methodClass;
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public Class<?> getMethodClass() {
|
||||
return this.methodClass;
|
||||
}
|
||||
|
||||
public Object getInstance() {
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package net.crankedpvp.crankedutils.enums;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import static net.crankedpvp.crankedutils.utils.items.ItemUtils.isAirOrNull;
|
||||
|
||||
/**
|
||||
* @author Arnah
|
||||
* @since Jul 30, 2015
|
||||
*/
|
||||
public enum ArmorType {
|
||||
HELMET(5), CHESTPLATE(6), LEGGINGS(7), BOOTS(8);
|
||||
|
||||
private final int slot;
|
||||
|
||||
ArmorType(int slot){
|
||||
this.slot = slot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to match the ArmorType for the specified ItemStack.
|
||||
*
|
||||
* @param itemStack The ItemStack to parse the type of.
|
||||
* @return The parsed ArmorType, or null if not found.
|
||||
*/
|
||||
public static ArmorType matchType(final ItemStack itemStack){
|
||||
if(isAirOrNull(itemStack)) return null;
|
||||
String type = itemStack.getType().name();
|
||||
if(type.endsWith("_HELMET") || type.endsWith("SKULL")) return HELMET;
|
||||
else if(type.endsWith("_CHESTPLATE")) return CHESTPLATE;
|
||||
else if(type.endsWith("_LEGGINGS")) return LEGGINGS;
|
||||
else if(type.endsWith("_BOOTS")) return BOOTS;
|
||||
else return null;
|
||||
}
|
||||
|
||||
public int getSlot(){
|
||||
return this.slot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package net.crankedpvp.crankedutils.events;
|
||||
|
||||
import net.crankedpvp.crankedutils.enums.ArmorType;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.player.PlayerEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public final class ArmorEquipEvent extends PlayerEvent implements Cancellable {
|
||||
private static final HandlerList handlers;
|
||||
private boolean cancel;
|
||||
private final EquipMethod equipType;
|
||||
private final ArmorType type;
|
||||
private ItemStack oldArmorPiece;
|
||||
private ItemStack newArmorPiece;
|
||||
|
||||
public ArmorEquipEvent(final Player player, final EquipMethod equipType, final ArmorType type, final ItemStack oldArmorPiece, final ItemStack newArmorPiece) {
|
||||
super(player);
|
||||
this.cancel = false;
|
||||
this.equipType = equipType;
|
||||
this.type = type;
|
||||
this.oldArmorPiece = oldArmorPiece;
|
||||
this.newArmorPiece = newArmorPiece;
|
||||
}
|
||||
|
||||
public static final HandlerList getHandlerList() {
|
||||
return ArmorEquipEvent.handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final HandlerList getHandlers() {
|
||||
return ArmorEquipEvent.handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setCancelled(final boolean cancel) {
|
||||
this.cancel = cancel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean isCancelled() {
|
||||
return this.cancel;
|
||||
}
|
||||
|
||||
public final ArmorType getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public final ItemStack getOldArmorPiece() {
|
||||
return this.oldArmorPiece;
|
||||
}
|
||||
|
||||
public final void setOldArmorPiece(final ItemStack oldArmorPiece) {
|
||||
this.oldArmorPiece = oldArmorPiece;
|
||||
}
|
||||
|
||||
public final ItemStack getNewArmorPiece() {
|
||||
return this.newArmorPiece;
|
||||
}
|
||||
|
||||
public final void setNewArmorPiece(final ItemStack newArmorPiece) {
|
||||
this.newArmorPiece = newArmorPiece;
|
||||
}
|
||||
|
||||
public EquipMethod getMethod() {
|
||||
return this.equipType;
|
||||
}
|
||||
|
||||
static {
|
||||
handlers = new HandlerList();
|
||||
}
|
||||
|
||||
public enum EquipMethod {
|
||||
SHIFT_CLICK,
|
||||
DRAG,
|
||||
PICK_DROP,
|
||||
HOTBAR,
|
||||
HOTBAR_SWAP,
|
||||
DISPENSER,
|
||||
BROKE,
|
||||
DEATH,
|
||||
DOUBLE_PICK_DROP,
|
||||
HOTBAR_ARMOR_SWITCH,
|
||||
QUIT_SERVER
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.crankedpvp.crankedutils.events;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.player.PlayerEvent;
|
||||
|
||||
public class EnderPearlThrowEvent extends PlayerEvent implements Cancellable {
|
||||
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private int cooldownInSeconds;
|
||||
private boolean cancel;
|
||||
|
||||
public EnderPearlThrowEvent(Player player, int cooldownInSeconds) {
|
||||
super(player);
|
||||
this.cooldownInSeconds = cooldownInSeconds;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return EnderPearlThrowEvent.handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final HandlerList getHandlers() {
|
||||
return EnderPearlThrowEvent.handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setCancelled(final boolean cancel) {
|
||||
this.cancel = cancel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean isCancelled() {
|
||||
return this.cancel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package net.crankedpvp.crankedutils.events;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
@Getter
|
||||
public class PlayerCombatEnterEvent extends Event implements Cancellable {
|
||||
|
||||
private final Player player;
|
||||
private boolean cancelled;
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
public PlayerCombatEnterEvent(Player player) {
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean b) {
|
||||
this.cancelled = b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package net.crankedpvp.crankedutils.interfaces;
|
||||
|
||||
public interface Weighable {
|
||||
int getWeight();
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package net.crankedpvp.crankedutils.listeners;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.enums.ArmorType;
|
||||
import net.crankedpvp.crankedutils.events.ArmorEquipEvent;
|
||||
import net.minecraft.server.v1_8_R3.MinecraftServer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event.Result;
|
||||
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.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.inventory.*;
|
||||
import org.bukkit.event.inventory.InventoryType.SlotType;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerItemBreakEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.metadata.FixedMetadataValue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ArmorListener implements Listener {
|
||||
|
||||
private final List<String> blockedMaterials;
|
||||
|
||||
public ArmorListener() {
|
||||
this.blockedMaterials = Arrays.asList(
|
||||
"FURNACE",
|
||||
"CHEST",
|
||||
"TRAPPED_CHEST",
|
||||
"BEACON",
|
||||
"DISPENSER",
|
||||
"DROPPER",
|
||||
"HOPPER",
|
||||
"WORKBENCH",
|
||||
"ENCHANTMENT_TABLE",
|
||||
"ENDER_CHEST",
|
||||
"ANVIL",
|
||||
"BED_BLOCK",
|
||||
"FENCE_GATE",
|
||||
"SPRUCE_FENCE_GATE",
|
||||
"BIRCH_FENCE_GATE",
|
||||
"ACACIA_FENCE_GATE",
|
||||
"JUNGLE_FENCE_GATE",
|
||||
"DARK_OAK_FENCE_GATE",
|
||||
"IRON_DOOR_BLOCK",
|
||||
"WOODEN_DOOR",
|
||||
"SPRUCE_DOOR",
|
||||
"BIRCH_DOOR",
|
||||
"JUNGLE_DOOR",
|
||||
"ACACIA_DOOR",
|
||||
"DARK_OAK_DOOR",
|
||||
"WOOD_BUTTON",
|
||||
"STONE_BUTTON",
|
||||
"TRAP_DOOR",
|
||||
"IRON_TRAPDOOR",
|
||||
"DIODE_BLOCK_OFF",
|
||||
"DIODE_BLOCK_ON",
|
||||
"REDSTONE_COMPARATOR_OFF",
|
||||
"REDSTONE_COMPARATOR_ON",
|
||||
"FENCE",
|
||||
"SPRUCE_FENCE",
|
||||
"BIRCH_FENCE",
|
||||
"JUNGLE_FENCE",
|
||||
"DARK_OAK_FENCE",
|
||||
"ACACIA_FENCE",
|
||||
"NETHER_FENCE",
|
||||
"BREWING_STAND",
|
||||
"CAULDRON",
|
||||
"LEGACY_SIGN_POST",
|
||||
"LEGACY_WALL_SIGN",
|
||||
"LEGACY_SIGN",
|
||||
"ACACIA_SIGN",
|
||||
"ACACIA_WALL_SIGN",
|
||||
"BIRCH_SIGN",
|
||||
"BIRCH_WALL_SIGN",
|
||||
"DARK_OAK_SIGN",
|
||||
"DARK_OAK_WALL_SIGN",
|
||||
"JUNGLE_SIGN",
|
||||
"JUNGLE_WALL_SIGN",
|
||||
"OAK_SIGN",
|
||||
"OAK_WALL_SIGN",
|
||||
"SPRUCE_SIGN",
|
||||
"SPRUCE_WALL_SIGN",
|
||||
"LEVER",
|
||||
"DAYLIGHT_DETECTOR_INVERTED",
|
||||
"DAYLIGHT_DETECTOR"
|
||||
);
|
||||
}
|
||||
//Event Priority is highest because other plugins might cancel the events before we check.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public final void inventoryClick(final InventoryClickEvent event) {
|
||||
boolean shift = false, numberkey = false;
|
||||
if (event.isCancelled()) return;
|
||||
if (event.getAction() == InventoryAction.NOTHING) return;// Why does this get called if nothing happens??
|
||||
if (event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT) {
|
||||
shift = true;
|
||||
}
|
||||
if (event.getClick().equals(ClickType.NUMBER_KEY)) {
|
||||
numberkey = true;
|
||||
}
|
||||
if (event.getSlotType() != SlotType.ARMOR && event.getSlotType() != SlotType.QUICKBAR && event.getSlotType() != SlotType.CONTAINER)
|
||||
return;
|
||||
if (event.getClickedInventory() != null && !event.getClickedInventory().getType().equals(InventoryType.PLAYER))
|
||||
return;
|
||||
if (!event.getInventory().getType().equals(InventoryType.CRAFTING) && !event.getInventory().getType().equals(InventoryType.PLAYER))
|
||||
return;
|
||||
if (!(event.getWhoClicked() instanceof Player)) return;
|
||||
ArmorType newArmorType = ArmorType.matchType(shift ? event.getCurrentItem() : event.getCursor());
|
||||
if (!shift && newArmorType != null && event.getRawSlot() != newArmorType.getSlot()) {
|
||||
// Used for drag and drop checking to make sure you aren't trying to place a helmet in the boots slot.
|
||||
return;
|
||||
}
|
||||
if (shift) {
|
||||
newArmorType = ArmorType.matchType(event.getCurrentItem());
|
||||
if (newArmorType != null) {
|
||||
boolean equipping = event.getRawSlot() != newArmorType.getSlot();
|
||||
if (newArmorType.equals(ArmorType.HELMET) && (equipping == isAirOrNull(event.getWhoClicked().getInventory().getHelmet())) || newArmorType.equals(ArmorType.CHESTPLATE) && (equipping == isAirOrNull(event.getWhoClicked().getInventory().getChestplate())) || newArmorType.equals(ArmorType.LEGGINGS) && (equipping == isAirOrNull(event.getWhoClicked().getInventory().getLeggings())) || newArmorType.equals(ArmorType.BOOTS) && (equipping == isAirOrNull(event.getWhoClicked().getInventory().getBoots()))) {
|
||||
if (hasAvailableSlot((Player) event.getWhoClicked())) {
|
||||
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent((Player) event.getWhoClicked(), ArmorEquipEvent.EquipMethod.SHIFT_CLICK, newArmorType, equipping ? null : event.getCurrentItem(), equipping ? event.getCurrentItem() : null);
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ItemStack newArmorPiece = event.getCursor();
|
||||
ItemStack oldArmorPiece = event.getCurrentItem();
|
||||
if (numberkey) {
|
||||
if (event.getClickedInventory().getType().equals(InventoryType.PLAYER)) {// Prevents shit in the 2by2 crafting
|
||||
// e.getClickedInventory() == The players inventory
|
||||
// e.getHotBarButton() == key people are pressing to equip or unequip the item to or from.
|
||||
// e.getRawSlot() == The slot the item is going to.
|
||||
// e.getSlot() == Armor slot, can't use e.getRawSlot() as that gives a hotbar slot ;-;
|
||||
ItemStack hotbarItem = event.getClickedInventory().getItem(event.getHotbarButton());
|
||||
if (!isAirOrNull(hotbarItem) && event.getAction() != InventoryAction.HOTBAR_MOVE_AND_READD){// Equipping
|
||||
newArmorType = ArmorType.matchType(hotbarItem);
|
||||
newArmorPiece = hotbarItem;
|
||||
oldArmorPiece = event.getClickedInventory().getItem(event.getSlot());
|
||||
} else { // Unequipping
|
||||
newArmorType = ArmorType.matchType(!isAirOrNull(event.getCurrentItem()) ? event.getCurrentItem() : event.getCursor());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (isAirOrNull(event.getCursor()) && !isAirOrNull(event.getCurrentItem())) {// unequip with no new item going into the slot.
|
||||
newArmorType = ArmorType.matchType(event.getCurrentItem());
|
||||
}
|
||||
// e.getCurrentItem() == Unequip
|
||||
// e.getCursor() == Equip
|
||||
// newArmorType = ArmorType.matchType(!isAirOrNull(e.getCurrentItem()) ? e.getCurrentItem() : e.getCursor());
|
||||
}
|
||||
if (newArmorType != null && event.getRawSlot() == newArmorType.getSlot()) {
|
||||
ArmorEquipEvent.EquipMethod method = ArmorEquipEvent.EquipMethod.PICK_DROP;
|
||||
|
||||
if (event.getAction() == InventoryAction.HOTBAR_SWAP || numberkey) {
|
||||
method = ArmorEquipEvent.EquipMethod.HOTBAR_SWAP;
|
||||
}
|
||||
|
||||
|
||||
/* System.out.println("---------------------------------");
|
||||
System.out.println(event.getClick().name());
|
||||
System.out.println(event.getAction().name());
|
||||
System.out.println(event.getRawSlot());
|
||||
System.out.println(event.getSlotType());
|
||||
System.out.println("---------------------------------");*/
|
||||
|
||||
|
||||
ArmorEquipEvent armorEquipEvent;
|
||||
|
||||
if (event.getClick() == ClickType.DOUBLE_CLICK) {
|
||||
method = ArmorEquipEvent.EquipMethod.DOUBLE_PICK_DROP;
|
||||
armorEquipEvent = new ArmorEquipEvent((Player) event.getWhoClicked(), method, newArmorType, newArmorPiece, oldArmorPiece);
|
||||
} else {
|
||||
armorEquipEvent = new ArmorEquipEvent((Player) event.getWhoClicked(), method, newArmorType, oldArmorPiece, newArmorPiece);
|
||||
}
|
||||
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void playerInteractEvent(PlayerInteractEvent e) {
|
||||
if (e.useItemInHand().equals(Result.DENY)) return;
|
||||
if (e.getAction() == Action.PHYSICAL) return;
|
||||
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
|
||||
Player player = e.getPlayer();
|
||||
if (!e.useInteractedBlock().equals(Result.DENY)) {
|
||||
if (e.getClickedBlock() != null && e.getAction() == Action.RIGHT_CLICK_BLOCK && !player.isSneaking()) {// Having both of these checks is useless, might as well do it though.
|
||||
// Some blocks have actions when you right click them which stops the client from equipping the armor in hand.
|
||||
Material mat = e.getClickedBlock().getType();
|
||||
for (String s : this.blockedMaterials) {
|
||||
if (mat.name().equalsIgnoreCase(s)) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
ArmorType newArmorType = ArmorType.matchType(e.getItem());
|
||||
if (newArmorType != null) {
|
||||
if (newArmorType.equals(ArmorType.HELMET) && isAirOrNull(e.getPlayer().getInventory().getHelmet()) || newArmorType.equals(ArmorType.CHESTPLATE) && isAirOrNull(e.getPlayer().getInventory().getChestplate()) || newArmorType.equals(ArmorType.LEGGINGS) && isAirOrNull(e.getPlayer().getInventory().getLeggings()) || newArmorType.equals(ArmorType.BOOTS) && isAirOrNull(e.getPlayer().getInventory().getBoots())) {
|
||||
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(e.getPlayer(), ArmorEquipEvent.EquipMethod.HOTBAR, ArmorType.matchType(e.getItem()), null, e.getItem());
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
e.setCancelled(true);
|
||||
player.updateInventory();
|
||||
}
|
||||
} else if (newArmorType.equals(ArmorType.HELMET) && !isAirOrNull(e.getPlayer().getInventory().getHelmet()) || newArmorType.equals(ArmorType.CHESTPLATE) && !isAirOrNull(e.getPlayer().getInventory().getChestplate()) || newArmorType.equals(ArmorType.LEGGINGS) && !isAirOrNull(e.getPlayer().getInventory().getLeggings()) || newArmorType.equals(ArmorType.BOOTS) && !isAirOrNull(e.getPlayer().getInventory().getBoots())) {
|
||||
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(e.getPlayer(), ArmorEquipEvent.EquipMethod.HOTBAR_ARMOR_SWITCH, ArmorType.matchType(e.getItem()),getOldArmorPiece(player,e.getItem()) , e.getItem());
|
||||
|
||||
if (player.hasMetadata("lastArmorSwap") && (long) MinecraftServer.currentTick - player.getMetadata("lastArmorSwap").get(0).asLong() <= 12L) {
|
||||
return;
|
||||
}
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
player.setMetadata("lastArmorSwap", new FixedMetadataValue(CrankedUtils.getInstance(), MinecraftServer.currentTick));
|
||||
this.equipArmor(player, e.getPlayer().getItemInHand());
|
||||
player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 10.0f, 0.95f);
|
||||
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
e.setCancelled(true);
|
||||
player.updateInventory();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ItemStack getOldArmorPiece(Player p, ItemStack itemStack) {
|
||||
ArmorType newArmorType = ArmorType.matchType(itemStack);
|
||||
|
||||
switch (newArmorType) {
|
||||
case BOOTS:
|
||||
return p.getInventory().getBoots();
|
||||
case HELMET:
|
||||
return p.getInventory().getHelmet();
|
||||
case LEGGINGS:
|
||||
return p.getInventory().getLeggings();
|
||||
case CHESTPLATE:
|
||||
return p.getInventory().getChestplate();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void equipArmor(Player player, ItemStack is) {
|
||||
if (is == null || is.getType() == Material.AIR) {
|
||||
return;
|
||||
}
|
||||
String n = is.getType().toString().toLowerCase();
|
||||
PlayerInventory inv = player.getInventory();
|
||||
if (n.contains("helmet")) {
|
||||
ItemStack old = inv.getHelmet();
|
||||
inv.setHelmet(is);
|
||||
player.setItemInHand(null);
|
||||
if (old != null && old.getType() != Material.AIR) {
|
||||
inv.setItemInHand(old);
|
||||
}
|
||||
} else if (n.contains("chestplate")) {
|
||||
ItemStack old = inv.getChestplate();
|
||||
inv.setChestplate(is);
|
||||
player.setItemInHand(null);
|
||||
if (old != null && old.getType() != Material.AIR) {
|
||||
inv.setItemInHand(old);
|
||||
}
|
||||
} else if (n.contains("leggings")) {
|
||||
ItemStack old = inv.getLeggings();
|
||||
inv.setLeggings(is);
|
||||
player.setItemInHand(null);
|
||||
if (old != null && old.getType() != Material.AIR) {
|
||||
inv.setItemInHand(old);
|
||||
}
|
||||
} else if (n.contains("boots")) {
|
||||
ItemStack old = inv.getBoots();
|
||||
inv.setBoots(is);
|
||||
player.setItemInHand(null);
|
||||
if (old != null && old.getType() != Material.AIR) {
|
||||
inv.setItemInHand(old);
|
||||
}
|
||||
}
|
||||
player.updateInventory();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void inventoryDrag(InventoryDragEvent event) {
|
||||
// getType() seems to always be even.
|
||||
// Old Cursor gives the item you are equipping
|
||||
// Raw slot is the ArmorType slot
|
||||
// Can't replace armor using this method making getCursor() useless.
|
||||
ArmorType type = ArmorType.matchType(event.getOldCursor());
|
||||
if (event.getRawSlots().isEmpty()) return; // Idk if this will ever happen
|
||||
if (type != null && type.getSlot() == event.getRawSlots().stream().findFirst().orElse(0)) {
|
||||
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent((Player) event.getWhoClicked(), ArmorEquipEvent.EquipMethod.DRAG, type, null, event.getOldCursor());
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
event.setResult(Result.DENY);
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void itemBreakEvent(PlayerItemBreakEvent e) {
|
||||
ArmorType type = ArmorType.matchType(e.getBrokenItem());
|
||||
if (type != null) {
|
||||
Player p = e.getPlayer();
|
||||
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(p, ArmorEquipEvent.EquipMethod.BROKE, type, e.getBrokenItem(), null);
|
||||
Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
|
||||
if (armorEquipEvent.isCancelled()) {
|
||||
ItemStack i = e.getBrokenItem().clone();
|
||||
i.setAmount(1);
|
||||
i.setDurability((short) (i.getDurability() - 1));
|
||||
if (type.equals(ArmorType.HELMET)) {
|
||||
p.getInventory().setHelmet(i);
|
||||
} else if (type.equals(ArmorType.CHESTPLATE)) {
|
||||
p.getInventory().setChestplate(i);
|
||||
} else if (type.equals(ArmorType.LEGGINGS)) {
|
||||
p.getInventory().setLeggings(i);
|
||||
} else if (type.equals(ArmorType.BOOTS)) {
|
||||
p.getInventory().setBoots(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void playerDeathEvent(PlayerDeathEvent e) {
|
||||
Player p = e.getEntity();
|
||||
if (e.getKeepInventory()) return;
|
||||
for (ItemStack i : p.getInventory().getArmorContents()) {
|
||||
if (!isAirOrNull(i)) {
|
||||
Bukkit.getServer().getPluginManager().callEvent(new ArmorEquipEvent(p, ArmorEquipEvent.EquipMethod.DEATH, ArmorType.matchType(i), i, null));
|
||||
// No way to cancel a death event.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isAirOrNull(ItemStack item) {
|
||||
return item == null || item.getType().equals(Material.AIR);
|
||||
}
|
||||
|
||||
public static boolean hasAvailableSlot(Player player) {
|
||||
Inventory inv = player.getInventory();
|
||||
boolean check = false;
|
||||
for (ItemStack item : inv.getContents()) {
|
||||
if (item == null) {
|
||||
check = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return check;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package net.crankedpvp.crankedutils.listeners;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.utils.CC;
|
||||
import net.crankedpvp.crankedutils.utils.DamageHandler;
|
||||
import net.crankedpvp.crankedutils.utils.config.ConfigManager;
|
||||
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.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class DamageDebugHelpListener implements Listener {
|
||||
|
||||
private static final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onDamage(EntityDamageByEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player)) return;
|
||||
if (!(event.getDamager() instanceof Player)) return;
|
||||
if (!CrankedUtils.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled")) return;
|
||||
if (event.getEntity().hasPermission(DamageHandler.DAMAGE_DEBUG_PERMISSION))
|
||||
event.getEntity().sendMessage(CC.translate("&e&lHIT&7 " + event.getDamager().getName() + " &8-> &7" + event.getEntity().getName() + " &8(&eTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
if (event.getDamager().hasPermission(DamageHandler.DAMAGE_DEBUG_PERMISSION))
|
||||
event.getDamager().sendMessage(CC.translate("&d&lHIT&7 " + event.getDamager().getName() + " &8-> &7" + event.getEntity().getName() + " &8(&dTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&e&lHIT&7 " + event.getDamager().getName() + " &8-> &7" + event.getEntity().getName() + " &8(&eDamage " + DamageHandler.formatDamageAmount(event.getDamage()) + "&8)" + " &8(&eTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onDamageEnd(EntityDamageByEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player)) return;
|
||||
if (!(event.getDamager() instanceof Player)) return;
|
||||
if (!CrankedUtils.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled")) return;
|
||||
if (event.getEntity().hasPermission(DamageHandler.DAMAGE_DEBUG_PERMISSION))
|
||||
event.getEntity().sendMessage(CC.translate("&e&lHIT&7 &8(&eFinal Damage: &7" + DamageHandler.formatDamageAmount(event.getFinalDamage()) + "&8) &8(&eDamage: &7" + DamageHandler.formatDamageAmount(event.getDamage()) + "&8)"+ " &8(&eTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
if (event.getDamager().hasPermission(DamageHandler.DAMAGE_DEBUG_PERMISSION))
|
||||
event.getDamager().sendMessage(CC.translate("&d&lHIT&7 &8(&dFinal Damage: &7" + DamageHandler.formatDamageAmount(event.getFinalDamage()) + "&8) &8(&dDamage: &7" + DamageHandler.formatDamageAmount(event.getDamage()) + "&8)"+ " &8(&dTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&e&lHIT&7 &8(&eFinal Damage: &7" + DamageHandler.formatDamageAmount(event.getFinalDamage()) + "&8) &8(&eDamage: &7" + DamageHandler.formatDamageAmount(event.getDamage()) + "&8)"+ " &8(&eTime: &7" + formatter.format(new Date()) + "&8)" ));
|
||||
|
||||
if (!CrankedUtils.getInstance().getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("extra-debug-enabled")) return;
|
||||
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c&lORIGINAL DAMAGE"));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Base Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.BASE)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Absorption Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.ABSORPTION)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Armor Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.ARMOR)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Magic Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.MAGIC)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Resistance Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.RESISTANCE)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Blocking Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.BLOCKING)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Hard Hit Damage: " + event.getOriginalDamage(EntityDamageEvent.DamageModifier.HARD_HAT)));
|
||||
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c&lUPDATED DAMAGE"));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Base Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.BASE)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Absorption Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.ABSORPTION)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Armor Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.ARMOR)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Magic Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.MAGIC)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Resistance Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.RESISTANCE)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Blocking Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.BLOCKING)));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate("&c* &7Hard Hit Damage: " + event.getDamage(EntityDamageEvent.DamageModifier.HARD_HAT)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package net.crankedpvp.crankedutils.listeners;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.CC;
|
||||
import net.crankedpvp.crankedutils.utils.items.ItemUtils;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryOpenEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.inventory.CraftingInventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class DupePatch implements Listener {
|
||||
@EventHandler
|
||||
public void removeItemWhenOpen(InventoryOpenEvent event) {
|
||||
if(event.getPlayer() == null) return;
|
||||
if(event.getView().getTopInventory() instanceof CraftingInventory || event.getPlayer().getOpenInventory().getTopInventory() == null) return;
|
||||
ItemStack itemStack = event.getPlayer().getItemOnCursor();
|
||||
if(ItemUtils.isAirOrNull(itemStack)) return;
|
||||
event.getPlayer().setItemOnCursor(null);
|
||||
event.getPlayer().getInventory().addItem(itemStack);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void preprocessCommand(PlayerCommandPreprocessEvent event) {
|
||||
if(event.getPlayer() == null) return;
|
||||
if(event.getMessage() == null) return;
|
||||
|
||||
if(event.getMessage().startsWith("/")) {
|
||||
if(event.getPlayer().getOpenInventory().getTopInventory() instanceof CraftingInventory || event.getPlayer().getOpenInventory().getTopInventory() == null) return;
|
||||
event.setCancelled(true);
|
||||
if (event.getPlayer().isOp()) {
|
||||
event.getPlayer().sendMessage(CC.translate("&cYou cannot execute commands while inside of a GUI"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package net.crankedpvp.crankedutils.listeners;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.potion.CrankedPotionPlayer;
|
||||
import net.crankedpvp.crankedutils.potion.PotionCache;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.PotionEffectExpireEvent;
|
||||
import org.bukkit.event.player.PlayerKickEvent;
|
||||
import org.bukkit.event.player.PlayerPickupItemEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerPickup(PlayerPickupItemEvent event) {
|
||||
long time;
|
||||
if (event.getItem().hasMetadata("protectedItem") && ((time = event.getItem().getMetadata("protectedItem").get(0).asLong()) == -1L || time > System.currentTimeMillis()) && !event.getItem().getMetadata("protectedOwner").get(0).asString().equals(event.getPlayer().getUniqueId().toString())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onExpire(PotionEffectExpireEvent event) {
|
||||
if (!(event.getEntity() instanceof Player)) return;
|
||||
CrankedPotionPlayer crankedPotionPlayer =CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(event.getEntity().getUniqueId());
|
||||
PotionCache potionCache = crankedPotionPlayer.getPotionCacheOfHighestLevel(event.getEffect().getType());
|
||||
if (potionCache != null) {
|
||||
((Player) event).getPlayer().addPotionEffect(new PotionEffect(potionCache.getType(), potionCache.getDuration(), potionCache.getLevel()));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onLogout(PlayerQuitEvent event) {
|
||||
CrankedPotionPlayer crankedPotionPlayer =CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(event.getPlayer().getUniqueId());
|
||||
crankedPotionPlayer.clearEffects();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onKick(PlayerKickEvent event) {
|
||||
CrankedPotionPlayer crankedPotionPlayer =CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(event.getPlayer().getUniqueId());
|
||||
crankedPotionPlayer.clearEffects();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package net.crankedpvp.crankedutils.modifiers;
|
||||
|
||||
import de.tr7zw.nbtapi.NBTCompound;
|
||||
import de.tr7zw.nbtapi.NBTItem;
|
||||
import net.crankedpvp.crankedutils.utils.Pair;
|
||||
import net.minecraft.server.v1_8_R3.*;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AttributeModifier {
|
||||
|
||||
public static ItemStack applyModifications(ItemStack itemStack, List<Pair<ModifierType, Double>> modifierTypePairs) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
|
||||
NBTTagCompound compound = nmsStack.getTag();
|
||||
if (compound == null) {
|
||||
compound = new NBTTagCompound();
|
||||
nmsStack.setTag(compound);
|
||||
compound = nmsStack.getTag();
|
||||
}
|
||||
|
||||
NBTTagList modifiers = new NBTTagList();
|
||||
|
||||
for(Pair<ModifierType, Double> modifierTypePair : modifierTypePairs) {
|
||||
ModifierType modifierType = modifierTypePair.getLeft();
|
||||
Double amount = modifierTypePair.getRight();
|
||||
|
||||
NBTTagCompound nbtTagCompound = new NBTTagCompound();
|
||||
nbtTagCompound.set("AttributeName", new NBTTagString(modifierType.getModifier()));
|
||||
nbtTagCompound.set("Name", new NBTTagString(modifierType.getModifier()));
|
||||
nbtTagCompound.set("Amount", new NBTTagDouble(amount));
|
||||
nbtTagCompound.set("Operation", new NBTTagInt(0));
|
||||
nbtTagCompound.set("UUIDLeast", new NBTTagInt(894654));
|
||||
nbtTagCompound.set("UUIDMost", new NBTTagInt(2872));
|
||||
|
||||
modifiers.add(nbtTagCompound);
|
||||
}
|
||||
compound.set("AttributeModifiers", modifiers);
|
||||
nmsStack.setTag(compound);
|
||||
return CraftItemStack.asBukkitCopy(nmsStack);
|
||||
}
|
||||
|
||||
public static double getModificationAmount(ItemStack itemStack, ModifierType modifierType) {
|
||||
NBTItem nbtItem = new NBTItem(itemStack);
|
||||
NBTCompound nbtCompound = nbtItem.getCompound("AttributeModifiers");
|
||||
return nbtCompound.getDouble("Amount");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.crankedpvp.crankedutils.modifiers;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public enum ModifierType {
|
||||
|
||||
MAX_HEALTH("generic.maxHealth"),
|
||||
FOLLOW_RANGE("generic.followRange"),
|
||||
KNOCKBACK_RESISTANCE("generic.knockbackResistance"),
|
||||
MOVEMENT_SPEED("generic.movementSpeed"),
|
||||
ATTACK_DAMAGE("generic.attackDamage"),
|
||||
ARMOR("generic.armor"),
|
||||
ARMOR_TOUGHNESS("generic.armorToughness"),
|
||||
ATTACK_SPEED("generic.attackSpeed"),
|
||||
LUCK("generic.luck"),
|
||||
JUMP_STRENGTH("horse.jumpStrength"),
|
||||
SPAWN_REINFORCEMENTS("zombie.spawnReinforcements");
|
||||
|
||||
@Getter
|
||||
private final String modifier;
|
||||
|
||||
ModifierType(String modifier) {
|
||||
this.modifier = modifier;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package net.crankedpvp.crankedutils.potion;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Getter
|
||||
public class CrankedPotionPlayer {
|
||||
private final Map<String, PotionCache> potionCacheMap;
|
||||
private final UUID uuid;
|
||||
public CrankedPotionPlayer(UUID uuid) {
|
||||
this.potionCacheMap = new HashMap<>();
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public boolean hasPotionEffect(PotionEffectType type) {
|
||||
for (PotionCache potionCache : potionCacheMap.values()) {
|
||||
if (potionCache.getType() == type) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public int getHighestLevel(PotionEffectType type) {
|
||||
int highest = -1;
|
||||
|
||||
for (PotionCache potionCache : potionCacheMap.values()) {
|
||||
if (potionCache.getType() == type) {
|
||||
if (highest < potionCache.getLevel()) {
|
||||
highest = potionCache.getLevel();
|
||||
}
|
||||
}
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
|
||||
public boolean isInCache(PotionEffectType potionEffectType) {
|
||||
for(PotionCache value : potionCacheMap.values()) {
|
||||
if(value.getType().equals(potionEffectType)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public PotionCache getPotionCacheOfHighestLevel(PotionEffectType type) {
|
||||
PotionCache highest = null;
|
||||
for (PotionCache potionCache : potionCacheMap.values()) {
|
||||
if (potionCache.getType() == type) {
|
||||
if (highest == null) {
|
||||
highest = potionCache;
|
||||
}
|
||||
if (highest.getLevel() < potionCache.getLevel()) {
|
||||
highest = potionCache;
|
||||
}
|
||||
}
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
|
||||
/*
|
||||
BRYS METHOD
|
||||
public void addPotionEffect(PotionEffectType type, int level, int duration, String id) {
|
||||
potionCacheMap.put(id, new PotionCache(level, duration, type, id));
|
||||
if (getHighestLevel(type) >= level) {
|
||||
if(isPlayerOnline()) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
player.removePotionEffect(type);
|
||||
player.addPotionEffect(new PotionEffect(type, duration, level-1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
public void addPotionEffect(PotionEffectType type, int level, int duration, String id) {
|
||||
//if(id.equals("LeviathanExtraHealth") && potionCacheMap.containsKey(id)) return;
|
||||
//if (getHighestLevel(type) >= level) {
|
||||
if (getHighestLevel(type) < level) {
|
||||
if(isPlayerOnline()) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
player.removePotionEffect(type);
|
||||
player.addPotionEffect(new PotionEffect(type, duration, level-1));
|
||||
}
|
||||
}
|
||||
|
||||
potionCacheMap.put(id, new PotionCache(level, duration, type, id));
|
||||
}
|
||||
|
||||
public void addPotionEffect(PotionEffectType type, int level, String id) {
|
||||
//if (getHighestLevel(type) >= level) {
|
||||
if (getHighestLevel(type) < level) {
|
||||
if(isPlayerOnline()) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
player.removePotionEffect(type);
|
||||
player.addPotionEffect(new PotionEffect(type, Integer.MAX_VALUE, level-1));
|
||||
}
|
||||
}
|
||||
potionCacheMap.put(id, new PotionCache(level, Integer.MAX_VALUE, type, id));
|
||||
}
|
||||
|
||||
//This means, if player already has enchant x, it will add y to the level
|
||||
public void addExtraPotionEffect(PotionEffectType type, int level, int duration, String id) {
|
||||
if (!hasPotionEffect(type)) {
|
||||
addPotionEffect(type, level, duration, id);
|
||||
} else {
|
||||
int newLevel = getHighestLevel(type) + level;
|
||||
addPotionEffect(type, newLevel, duration, id);
|
||||
}
|
||||
}
|
||||
|
||||
//This means, if player already has enchant x, it will add y to the level
|
||||
public void addExtraPotionEffect(PotionEffectType type, int level, String id) {
|
||||
if (!hasPotionEffect(type)) {
|
||||
addPotionEffect(type, level, id);
|
||||
} else {
|
||||
int newLevel = getHighestLevel(type) + level;
|
||||
addPotionEffect(type, newLevel, id);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePotionEffect(String id) {
|
||||
PotionCache potionCache = potionCacheMap.get(id);
|
||||
if(!isPlayerOnline()) return;
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
potionCacheMap.remove(id);
|
||||
if (potionCache == null) return;
|
||||
if (player == null) return;
|
||||
if (player.hasPotionEffect(potionCache.getType())) {
|
||||
player.removePotionEffect(potionCache.getType());
|
||||
}
|
||||
PotionCache newCache = getPotionCacheOfHighestLevel(potionCache.getType());
|
||||
if (newCache != null) {
|
||||
player.addPotionEffect(new PotionEffect(newCache.getType(), newCache.getDuration(), newCache.getLevel()-1));
|
||||
}
|
||||
}
|
||||
|
||||
public void clearEffects() {
|
||||
this.getPotionCacheMap().clear();
|
||||
}
|
||||
|
||||
private boolean isPlayerOnline() {
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
|
||||
return offlinePlayer.isOnline();
|
||||
}
|
||||
|
||||
private Player getPlayerFromUUIDIfOnline() {
|
||||
if(isPlayerOnline()) return Bukkit.getPlayer(uuid);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.crankedpvp.crankedutils.potion;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
@Getter
|
||||
public class PotionCache {
|
||||
private final int level;
|
||||
private final int duration;
|
||||
private final PotionEffectType type;
|
||||
private final String id;
|
||||
|
||||
public PotionCache(int level, int duration, PotionEffectType type, String id) {
|
||||
this.level = level;
|
||||
this.duration = duration;
|
||||
this.type = type;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public boolean isPermanent() {
|
||||
return this.duration == Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package net.crankedpvp.crankedutils.potion;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Getter
|
||||
public class PotionManager {
|
||||
private final Map<UUID, CrankedPotionPlayer> potionPlayerMap;
|
||||
|
||||
public PotionManager() {
|
||||
this.potionPlayerMap = new HashMap<>();
|
||||
}
|
||||
|
||||
public CrankedPotionPlayer getCrankedPotionPlayer(UUID uuid) {
|
||||
if (!potionPlayerMap.containsKey(uuid)) {
|
||||
CrankedPotionPlayer crankedPotionPlayer = new CrankedPotionPlayer(uuid);
|
||||
potionPlayerMap.put(uuid, crankedPotionPlayer);
|
||||
}
|
||||
return potionPlayerMap.get(uuid);
|
||||
}
|
||||
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package net.crankedpvp.crankedutils.struct.factions;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.massivecraft.factions.*;
|
||||
import com.massivecraft.factions.integration.Econ;
|
||||
import com.massivecraft.factions.perms.Relation;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class CrankedFactionHandler extends FactionHandler {
|
||||
@Override
|
||||
public void initHandler() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInOwnFaction(Player player) {
|
||||
Faction at = Board.getInstance().getFactionAt(new FLocation(player.getLocation()));
|
||||
FPlayer fpla = this.getFPlayer(player);
|
||||
return at != null && fpla != null && at.getFPlayers().contains(fpla);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inSameFaction(Player player, Player other) {
|
||||
if (player != null && other != null && other.equals(player)) {
|
||||
return true;
|
||||
}
|
||||
FPlayer pl = this.getFPlayer(player);
|
||||
FPlayer otherFPlayer = this.getFPlayer(other);
|
||||
return pl != null && otherFPlayer != null && pl.hasFaction() && pl.getFaction().getFPlayers().contains(otherFPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inInEnemyFaction(Player player, Player other) {
|
||||
return this.getRelation(player, other) == Relation.ENEMY;
|
||||
}
|
||||
|
||||
private Relation getRelation(Player player, Player other) {
|
||||
if (player == other) {
|
||||
return Relation.MEMBER;
|
||||
}
|
||||
FPlayer fPlayer = this.getFPlayer(player);
|
||||
FPlayer otherfPlayer = this.getFPlayer(other);
|
||||
if (fPlayer == null || otherfPlayer == null) {
|
||||
return Relation.NEUTRAL;
|
||||
}
|
||||
return fPlayer.getRelationTo(otherfPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inInAllyFaction(Player player, Player other) {
|
||||
return this.getRelation(player, other) == Relation.ALLY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFactionTag(Player seeingMsg, Player checking) {
|
||||
FPlayer fplayer = this.getFPlayer(seeingMsg);
|
||||
FPlayer other = this.getFPlayer(checking);
|
||||
return other.getChatTag(fplayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFactionTag(Player seeingMsg) {
|
||||
FPlayer fplayer = this.getFPlayer(seeingMsg);
|
||||
if (!fplayer.hasFaction()) {
|
||||
return null;
|
||||
}
|
||||
return fplayer.getFaction().getTag();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFactionId(Player seeingMsg) {
|
||||
FPlayer fplayer = this.getFPlayer(seeingMsg);
|
||||
if (!fplayer.hasFaction()) {
|
||||
return null;
|
||||
}
|
||||
return fplayer.getFaction().getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFPlayerName(FPlayer fplayer) {
|
||||
return fplayer.getName();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Collection<FPlayer> getAllFPlayers(boolean online) {
|
||||
return online ? FPlayers.getInstance().getOnlinePlayers() : FPlayers.getInstance().getAllFPlayers();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Faction> getAllFactions() {
|
||||
return Factions.getInstance().getAllFactions();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isFocusedPlayer(Faction var1, String var2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFactionAt(Location location) {
|
||||
return Board.getInstance().getFactionAt(new FLocation(location));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFactionAt(FLocation location) {
|
||||
return Board.getInstance().getFactionAt(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFPlayerIdsByTag(String tag) {
|
||||
Faction faction = this.getFactionByTag(tag);
|
||||
if (faction == null) {
|
||||
return null;
|
||||
}
|
||||
ArrayList<String> retr = Lists.newArrayList();
|
||||
faction.getFPlayers().forEach(mem -> retr.add(mem.getId()));
|
||||
return retr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFactionIdByTag(String tag) {
|
||||
Faction faction = this.getFactionByTag(tag);
|
||||
if (faction == null) {
|
||||
return null;
|
||||
}
|
||||
return faction.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FPlayer getFPlayerByName(String name) {
|
||||
return FPlayers.getInstance().getById(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Player getPlayer(FPlayer player) {
|
||||
return player.getPlayer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFaction(FPlayer player, boolean includeWilderness) {
|
||||
Faction faction = player.getFaction();
|
||||
if (!includeWilderness && faction.isNone()) {
|
||||
return null;
|
||||
}
|
||||
return faction;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(FPlayer fplayer, String msg) {
|
||||
fplayer.getPlayer().sendMessage(msg);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean attemptClaim(FPlayer fplayer, Faction faction, Location location, boolean notifyFailure) {
|
||||
return fplayer.attemptClaim(faction, location, notifyFailure);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getMainFactionClass() {
|
||||
return Faction.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getMainFPlayerClass() {
|
||||
return FPlayer.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFPlayerIdsById(String id) {
|
||||
Faction faction = this.getFactionById(id);
|
||||
if (faction == null) {
|
||||
return null;
|
||||
}
|
||||
ArrayList<String> retr = Lists.newArrayList();
|
||||
faction.getFPlayers().forEach(mem -> retr.add(mem.getId()));
|
||||
return retr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFaction(Player player, boolean includeWilderness) {
|
||||
FPlayer fplayer = this.getFPlayer(player);
|
||||
if (fplayer == null) {
|
||||
if (includeWilderness) {
|
||||
return Factions.getInstance().getWilderness();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Faction fac = fplayer.getFaction();
|
||||
if (!includeWilderness && fac.isNone()) {
|
||||
return null;
|
||||
}
|
||||
return fac;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFactionByTag(String tag) {
|
||||
return Factions.getInstance().getBestTagMatch(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Faction getFactionById(String id) {
|
||||
return Factions.getInstance().getFactionById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FPlayer getFPlayer(Player player) {
|
||||
try {
|
||||
return FPlayers.getInstance().getByPlayer(player);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFactionId(Faction faction) {
|
||||
return faction.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFPlayerId(FPlayer fplayer) {
|
||||
return fplayer.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLand(Faction faction) {
|
||||
return faction.getLandRounded();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLandMax(Faction faction) {
|
||||
return (int) Math.round(this.getPowerMax(faction));
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getPower(Faction faction) {
|
||||
return faction.getPower();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getPowerMax(Faction faction) {
|
||||
return faction.getPowerMax();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getFactionBalance(Faction faction) {
|
||||
return Econ.getBalance(faction);
|
||||
}
|
||||
|
||||
private FPlayers getFPlayers() {
|
||||
return FPlayers.getInstance();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package net.crankedpvp.crankedutils.struct.factions;
|
||||
|
||||
import com.massivecraft.factions.FLocation;
|
||||
import com.massivecraft.factions.FPlayer;
|
||||
import com.massivecraft.factions.Faction;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class FactionHandler {
|
||||
public abstract void initHandler() throws NoSuchMethodException;
|
||||
|
||||
public abstract boolean isInOwnFaction(Player var1);
|
||||
|
||||
public abstract boolean inSameFaction(Player var1, Player var2);
|
||||
|
||||
public abstract boolean inInEnemyFaction(Player var1, Player var2);
|
||||
|
||||
public abstract boolean inInAllyFaction(Player var1, Player var2);
|
||||
|
||||
public abstract String getFactionTag(Player var1, Player var2);
|
||||
|
||||
public abstract String getFactionTag(Player var1);
|
||||
|
||||
public abstract String getFactionId(Player var1);
|
||||
|
||||
public abstract String getFPlayerName(FPlayer var1);
|
||||
|
||||
public abstract Collection<FPlayer> getAllFPlayers(boolean var1);
|
||||
|
||||
public abstract Collection<Faction> getAllFactions();
|
||||
|
||||
public abstract boolean isFocusedPlayer(Faction var1, String var2);
|
||||
|
||||
public abstract Faction getFactionAt(Location var1);
|
||||
|
||||
public abstract Faction getFactionAt(FLocation var1);
|
||||
|
||||
public abstract Faction getFaction(Player var1, boolean var2);
|
||||
|
||||
public abstract Faction getFaction(FPlayer var1, boolean var2);
|
||||
|
||||
public abstract void sendMessage(FPlayer var1, String var2);
|
||||
|
||||
public abstract Faction getFactionByTag(String var1);
|
||||
|
||||
public abstract Faction getFactionById(String var1);
|
||||
|
||||
public abstract List<String> getFPlayerIdsByTag(String var1);
|
||||
|
||||
public abstract String getFactionIdByTag(String var1);
|
||||
|
||||
public abstract FPlayer getFPlayerByName(String var1);
|
||||
|
||||
public abstract Player getPlayer(FPlayer var1);
|
||||
|
||||
public abstract boolean attemptClaim(FPlayer var1, Faction var2, Location var3, boolean var4);
|
||||
|
||||
public abstract Class<?> getMainFactionClass();
|
||||
|
||||
public abstract Class<?> getMainFPlayerClass();
|
||||
|
||||
public abstract List<String> getFPlayerIdsById(String var1);
|
||||
|
||||
public abstract FPlayer getFPlayer(Player var1);
|
||||
|
||||
public abstract String getFactionId(Faction var1);
|
||||
|
||||
public abstract String getFPlayerId(FPlayer var1);
|
||||
|
||||
public abstract int getLand(Faction var1);
|
||||
|
||||
public abstract int getLandMax(Faction var1);
|
||||
|
||||
public abstract double getPower(Faction var1);
|
||||
|
||||
public abstract double getPowerMax(Faction var1);
|
||||
|
||||
public abstract double getFactionBalance(Faction var1) throws NoSuchFieldException, IllegalAccessException;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.minecraft.server.v1_8_R3.IChatBaseComponent;
|
||||
import net.minecraft.server.v1_8_R3.PacketPlayOutChat;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class ActionBarUtils {
|
||||
private final PacketPlayOutChat packet;
|
||||
|
||||
public ActionBarUtils(String text) {
|
||||
this.packet = new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a("{\"text\":\"" + text + "\"}"), (byte)2);
|
||||
}
|
||||
|
||||
public void sendToPlayer(Player p) {
|
||||
(((CraftPlayer)p).getHandle()).playerConnection.sendPacket(this.packet);
|
||||
}
|
||||
|
||||
public void sendToAll() {
|
||||
for (Player p : Bukkit.getServer().getOnlinePlayers())
|
||||
(((CraftPlayer)p).getHandle()).playerConnection.sendPacket(this.packet);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.minecraft.server.v1_8_R3.*;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class AnimationUtils {
|
||||
public static void sendDeathEffect(Player died) throws NoSuchFieldException, IllegalAccessException {
|
||||
EntityPlayer player = ((CraftPlayer)died).getHandle();
|
||||
|
||||
EntityPlayer fake = new EntityPlayer(player.server, (WorldServer)player.world, player.getProfile(), new PlayerInteractManager(player.world));
|
||||
fake.playerConnection = new PlayerConnection(player.server, new NetworkManager(EnumProtocolDirection.CLIENTBOUND), fake) {
|
||||
public void sendPacket(Packet packet) {}
|
||||
|
||||
public void c() {}
|
||||
|
||||
public void chat(String s, boolean async) {}
|
||||
};
|
||||
fake.setPositionRotation(player.locX, player.locY, player.locZ, player.yaw, player.pitch);
|
||||
for (int i = 0; i < (fake.getEquipment()).length; i++)
|
||||
fake.setEquipment(i, null);
|
||||
int entityId = fake.getId();
|
||||
PacketPlayOutNamedEntitySpawn fakePlayer = new PacketPlayOutNamedEntitySpawn(fake);
|
||||
PacketPlayOutEntityStatus status = new PacketPlayOutEntityStatus(fake, (byte)3);
|
||||
Set<EntityPlayer> whoReceived = new HashSet<>();
|
||||
EntityTrackerEntry entry = (((WorldServer)player.world).getTracker()).trackedEntities.get(player.getId());
|
||||
if (entry != null) {
|
||||
Set<EntityPlayer> trackedPlayers = (Set<EntityPlayer>) ReflectionUtils.getObject(EntityTrackerEntry.class, entry, "trackedPlayers");
|
||||
for (EntityPlayer tracked : trackedPlayers) {
|
||||
if (tracked instanceof EntityPlayer) {
|
||||
EntityPlayer pl = tracked;
|
||||
if (pl.playerConnection == null || pl.playerConnection.isDisconnected())
|
||||
continue;
|
||||
pl.playerConnection.sendPacket(fakePlayer);
|
||||
pl.playerConnection.sendPacket(status);
|
||||
whoReceived.add(pl);
|
||||
}
|
||||
}
|
||||
}
|
||||
player.playerConnection.sendPacket(fakePlayer);
|
||||
player.playerConnection.sendPacket(status);
|
||||
whoReceived.add(player);
|
||||
Bukkit.getScheduler().scheduleSyncDelayedTask(CrankedUtils.getInstance(), () -> {
|
||||
PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(entityId);
|
||||
for (EntityPlayer pl : whoReceived) {
|
||||
if (pl.playerConnection == null)
|
||||
continue;
|
||||
pl.playerConnection.sendPacket(destroy);
|
||||
}
|
||||
},30L);
|
||||
}
|
||||
|
||||
public static void sendLightning(Player p, Location l){
|
||||
Class<?> light = getNMSClass("EntityLightning");
|
||||
try {
|
||||
Constructor<?> constu =
|
||||
light
|
||||
.getConstructor(getNMSClass("World"),
|
||||
double.class, double.class,
|
||||
double.class, boolean.class, boolean.class);
|
||||
Object wh = p.getWorld().getClass().getMethod("getHandle").invoke(p.getWorld());
|
||||
Object lighobj = constu.newInstance(wh, l.getX(), l.getY(), l.getZ(), false, false);
|
||||
|
||||
Object obj =
|
||||
getNMSClass("PacketPlayOutSpawnEntityWeather")
|
||||
.getConstructor(getNMSClass("Entity")).newInstance(lighobj);
|
||||
|
||||
sendPacket(p, obj);
|
||||
p.playSound(p.getLocation(), Sound.AMBIENCE_THUNDER, 100, 1);
|
||||
} catch (NoSuchMethodException | SecurityException |
|
||||
IllegalAccessException | IllegalArgumentException |
|
||||
InvocationTargetException | InstantiationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> getNMSClass(String name) {
|
||||
String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
|
||||
try {
|
||||
return Class.forName("net.minecraft.server." + version + "." + name);
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendPacket(Player player, Object packet) {
|
||||
try {
|
||||
Object handle = player.getClass().getMethod("getHandle").invoke(player);
|
||||
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
|
||||
playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet"))
|
||||
.invoke(playerConnection, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
public class Arrow {
|
||||
|
||||
public static String arrow() {
|
||||
return "➥";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.minecraft.server.v1_8_R3.BlockPosition;
|
||||
import net.minecraft.server.v1_8_R3.Blocks;
|
||||
import net.minecraft.server.v1_8_R3.IBlockData;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
|
||||
|
||||
public final class BlockUtil {
|
||||
|
||||
private final static IBlockData AIR = Blocks.AIR.getBlockData();
|
||||
|
||||
public static void setBlockFast(Block b, int blockId, byte data, boolean physics) {
|
||||
setBlockFast(b.getWorld(), b.getX(), b.getY(), b.getZ(), blockId, data, physics);
|
||||
}
|
||||
|
||||
public static void setBlockFast(org.bukkit.World world, int x, int y, int z, int blockId, byte data, boolean physics) {
|
||||
net.minecraft.server.v1_8_R3.World w = ((CraftWorld) world).getHandle();
|
||||
BlockPosition bp = new BlockPosition(x, y, z);
|
||||
IBlockData ibd = net.minecraft.server.v1_8_R3.Block.getByCombinedId(blockId + (data << 12));
|
||||
w.setTypeAndData(bp, ibd, physics ? 3 : 2);
|
||||
(w.getChunkAt(x >> 4, z >> 4)).a(bp, ibd);
|
||||
}
|
||||
|
||||
public static void setAir(Block b, boolean physics) {
|
||||
setAir(b.getWorld(), b.getX(), b.getY(), b.getZ(), physics);
|
||||
}
|
||||
|
||||
public static void setAir(org.bukkit.World world, int x, int y, int z, boolean physics) {
|
||||
BlockPosition position = new BlockPosition(x, y, z);
|
||||
((CraftWorld) world).getHandle().setTypeAndData(position, AIR, physics ? 3 : 2);
|
||||
}
|
||||
|
||||
public static void updatePhysics(org.bukkit.World world, int x, int y, int z) {
|
||||
net.minecraft.server.v1_8_R3.World w = ((CraftWorld) world).getHandle();
|
||||
BlockPosition bp = new BlockPosition(x, y, z);
|
||||
w.applyPhysics(bp, w.getType(bp).getBlock());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.150.
|
||||
*/
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class CC {
|
||||
public static final String Black = ChatColor.BLACK.toString();
|
||||
public static final String BlackB = ChatColor.BLACK + ChatColor.BOLD.toString();
|
||||
public static final String BlackI = ChatColor.BLACK + ChatColor.ITALIC.toString();
|
||||
public static final String BlackU = ChatColor.BLACK + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkBlue = ChatColor.DARK_BLUE.toString();
|
||||
public static final String DarkBlueB = ChatColor.DARK_BLUE + ChatColor.BOLD.toString();
|
||||
public static final String DarkBlueI = ChatColor.DARK_BLUE + ChatColor.ITALIC.toString();
|
||||
public static final String DarkBlueU = ChatColor.DARK_BLUE + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkGreen = ChatColor.DARK_GREEN.toString();
|
||||
public static final String DarkGreenB = ChatColor.DARK_GREEN + ChatColor.BOLD.toString();
|
||||
public static final String DarkGreenI = ChatColor.DARK_GREEN + ChatColor.ITALIC.toString();
|
||||
public static final String DarkGreenU = ChatColor.DARK_GREEN + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkAqua = ChatColor.DARK_AQUA.toString();
|
||||
public static final String DarkAquaB = ChatColor.DARK_AQUA + ChatColor.BOLD.toString();
|
||||
public static final String DarkAquaI = ChatColor.DARK_AQUA + ChatColor.ITALIC.toString();
|
||||
public static final String DarkAquaU = ChatColor.DARK_AQUA + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkRed = ChatColor.DARK_RED.toString();
|
||||
public static final String DarkRedB = ChatColor.DARK_RED + ChatColor.BOLD.toString();
|
||||
public static final String DarkRedI = ChatColor.DARK_RED + ChatColor.ITALIC.toString();
|
||||
public static final String DarkRedU = ChatColor.DARK_RED + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkPurple = ChatColor.DARK_PURPLE.toString();
|
||||
public static final String DarkPurpleB = ChatColor.DARK_PURPLE + ChatColor.BOLD.toString();
|
||||
public static final String DarkPurpleI = ChatColor.DARK_PURPLE + ChatColor.ITALIC.toString();
|
||||
public static final String DarkPurpleU = ChatColor.DARK_PURPLE + ChatColor.UNDERLINE.toString();
|
||||
public static final String Gold = ChatColor.GOLD.toString();
|
||||
public static final String GoldB = ChatColor.GOLD + ChatColor.BOLD.toString();
|
||||
public static final String GoldI = ChatColor.GOLD + ChatColor.ITALIC.toString();
|
||||
public static final String GoldU = ChatColor.GOLD + ChatColor.UNDERLINE.toString();
|
||||
public static final String Gray = ChatColor.GRAY.toString();
|
||||
public static final String GrayB = ChatColor.GRAY + ChatColor.BOLD.toString();
|
||||
public static final String GrayI = ChatColor.GRAY + ChatColor.ITALIC.toString();
|
||||
public static final String GrayU = ChatColor.GRAY + ChatColor.UNDERLINE.toString();
|
||||
public static final String DarkGray = ChatColor.DARK_GRAY.toString();
|
||||
public static final String DarkGrayB = ChatColor.DARK_GRAY + ChatColor.BOLD.toString();
|
||||
public static final String DarkGrayI = ChatColor.DARK_GRAY + ChatColor.ITALIC.toString();
|
||||
public static final String DarkGrayU = ChatColor.DARK_GRAY + ChatColor.UNDERLINE.toString();
|
||||
public static final String Blue = ChatColor.BLUE.toString();
|
||||
public static final String BlueB = ChatColor.BLUE + ChatColor.BOLD.toString();
|
||||
public static final String BlueI = ChatColor.BLUE + ChatColor.ITALIC.toString();
|
||||
public static final String BlueU = ChatColor.BLUE + ChatColor.UNDERLINE.toString();
|
||||
public static final String Green = ChatColor.GREEN.toString();
|
||||
public static final String GreenB = ChatColor.GREEN + ChatColor.BOLD.toString();
|
||||
public static final String GreenI = ChatColor.GREEN + ChatColor.ITALIC.toString();
|
||||
public static final String GreenU = ChatColor.GREEN + ChatColor.UNDERLINE.toString();
|
||||
public static final String Aqua = ChatColor.AQUA.toString();
|
||||
public static final String AquaB = ChatColor.AQUA + ChatColor.BOLD.toString();
|
||||
public static final String AquaI = ChatColor.AQUA + ChatColor.ITALIC.toString();
|
||||
public static final String AquaU = ChatColor.AQUA + ChatColor.UNDERLINE.toString();
|
||||
public static final String Red = ChatColor.RED.toString();
|
||||
public static final String RedB = ChatColor.RED + ChatColor.BOLD.toString();
|
||||
public static final String RedI = ChatColor.RED + ChatColor.ITALIC.toString();
|
||||
public static final String RedU = ChatColor.RED + ChatColor.UNDERLINE.toString();
|
||||
public static final String LightPurple = ChatColor.LIGHT_PURPLE.toString();
|
||||
public static final String LightPurpleB = ChatColor.LIGHT_PURPLE + ChatColor.BOLD.toString();
|
||||
public static final String LightPurpleI = ChatColor.LIGHT_PURPLE + ChatColor.ITALIC.toString();
|
||||
public static final String LightPurpleU = ChatColor.LIGHT_PURPLE + ChatColor.UNDERLINE.toString();
|
||||
public static final String Yellow = ChatColor.YELLOW.toString();
|
||||
public static final String YellowB = ChatColor.YELLOW + ChatColor.BOLD.toString();
|
||||
public static final String YellowI = ChatColor.YELLOW + ChatColor.ITALIC.toString();
|
||||
public static final String YellowU = ChatColor.YELLOW + ChatColor.UNDERLINE.toString();
|
||||
public static final String White = ChatColor.WHITE.toString();
|
||||
public static final String WhiteB = ChatColor.WHITE + ChatColor.BOLD.toString();
|
||||
public static final String WhiteI = ChatColor.WHITE + ChatColor.ITALIC.toString();
|
||||
public static final String WhiteU = ChatColor.WHITE + ChatColor.UNDERLINE.toString();
|
||||
public static final String Bold = ChatColor.BOLD.toString();
|
||||
public static final String Strike = ChatColor.STRIKETHROUGH.toString();
|
||||
public static final String Underline = ChatColor.UNDERLINE.toString();
|
||||
public static final String Magic = ChatColor.MAGIC.toString();
|
||||
public static final String Italic = ChatColor.ITALIC.toString();
|
||||
public static final String Reset = ChatColor.RESET.toString();
|
||||
public static final String Go = GreenB + "<!> " + Green;
|
||||
public static final String Wait = YellowB + "<!> " + Yellow;
|
||||
public static final String Stop = RedB + "<!> " + Red;
|
||||
|
||||
public static String prefix(char color) {
|
||||
return CC.translate("&" + color + "&l<!> &" + color);
|
||||
}
|
||||
|
||||
public static String translateAlternating(String string, String colorWayOne, String colourWayTwo) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
|
||||
boolean color = true;
|
||||
for(String letter : string.split("")) {
|
||||
if(Objects.equals(letter, " ")) {
|
||||
stringBuilder.append(" ");
|
||||
continue;
|
||||
}
|
||||
String toAppend = color ? colorWayOne : colourWayTwo;
|
||||
color = !color;
|
||||
stringBuilder.append(toAppend).append(letter);
|
||||
}
|
||||
return CC.translate(stringBuilder.toString());
|
||||
}
|
||||
|
||||
public static String translate(String string) {
|
||||
char[] b = string.toCharArray();
|
||||
|
||||
for (int i = 0; i < b.length - 1; ++i) {
|
||||
if (b[i] == '&' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) {
|
||||
b[i] = 167;
|
||||
b[i + 1] = Character.toLowerCase(b[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
return new String(b);
|
||||
}
|
||||
|
||||
public static List<String> translate(List<String> stringList) {
|
||||
stringList.replaceAll(CC::translate);
|
||||
return stringList;
|
||||
}
|
||||
|
||||
public static List<String> translate(String... string) {
|
||||
return CC.translate(Arrays.asList(string));
|
||||
}
|
||||
|
||||
public static String strip(String string) {
|
||||
return ChatColor.stripColor(string);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.CraftChunk;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ChunkUtils {
|
||||
public static boolean isLocationAInSameChunkAsLocationB(Location aLocation, Location bLocation) {
|
||||
double aX = Math.floor(aLocation.getBlockX() >> 4);
|
||||
double aZ = Math.floor(aLocation.getBlockZ() >> 4);
|
||||
double bX = Math.floor(bLocation.getBlockX() >> 4);
|
||||
double bZ = Math.floor(bLocation.getBlockZ() >> 4);
|
||||
|
||||
return aX == bX && aZ == bZ;
|
||||
|
||||
}
|
||||
|
||||
public static Chunk getChunkIfLoaded(int chunkX, int chunkZ, World bWorld) {
|
||||
net.minecraft.server.v1_8_R3.World world = ((CraftWorld) bWorld).getHandle();
|
||||
net.minecraft.server.v1_8_R3.Chunk theChunk = world.getChunkIfLoaded(chunkX, chunkZ);
|
||||
return (theChunk == null) ? null : theChunk.bukkitChunk;
|
||||
}
|
||||
|
||||
public static List<CraftEntity> getEntitiesInChunk(Chunk chunk) {
|
||||
net.minecraft.server.v1_8_R3.Chunk nmsChunk = ((CraftChunk) chunk).getHandle();
|
||||
List<CraftEntity> toReturn = new ArrayList<>();
|
||||
if (nmsChunk == null) return toReturn;
|
||||
for (List<net.minecraft.server.v1_8_R3.Entity> entities : nmsChunk.entitySlices) {
|
||||
for (net.minecraft.server.v1_8_R3.Entity entity : entities) {
|
||||
if (entity.getBukkitEntity() == null) continue;
|
||||
toReturn.add(entity.getBukkitEntity());
|
||||
}
|
||||
}
|
||||
return toReturn;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.md_5.bungee.api.chat.*;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Clickable {
|
||||
private final List<TextComponent> components = new ArrayList<>();
|
||||
private static final Class<?> CraftItemStackClass = NmsUtils.getCraftClass("inventory.CraftItemStack");
|
||||
private static final Class<?> ItemStackClass = NmsUtils.getNMSClass("ItemStack");
|
||||
private static final Class<?> NBTTagCompoundClass = NmsUtils.getNMSClass("NBTTagCompound");
|
||||
|
||||
public Clickable(String msg) {
|
||||
TextComponent message = new TextComponent(msg);
|
||||
this.components.add(message);
|
||||
}
|
||||
|
||||
public Clickable(String msg, String hoverMsg) {
|
||||
this(msg, hoverMsg, "");
|
||||
}
|
||||
|
||||
public Clickable(String msg, String hoverMsg, String clickString) {
|
||||
add(msg, hoverMsg, clickString);
|
||||
}
|
||||
|
||||
public TextComponent add(String msg, String hoverMsg) {
|
||||
return add(msg, hoverMsg, "");
|
||||
}
|
||||
|
||||
public TextComponent add(String msg, String hoverMsg, String clickString) {
|
||||
TextComponent message = new TextComponent(CC.translate(msg));
|
||||
if (hoverMsg != null && !hoverMsg.isEmpty())
|
||||
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder(CC.translate(hoverMsg)).create())));
|
||||
if (clickString != null && !clickString.isEmpty())
|
||||
message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, clickString));
|
||||
this.components.add(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
public void addItem(String msg, ItemStack itemStack) {
|
||||
TextComponent message = new TextComponent(CC.translate((msg)));
|
||||
if (itemStack != null && itemStack.getType() != Material.AIR)
|
||||
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new BaseComponent[]{new TextComponent(convertItemStackToJson(itemStack))}));
|
||||
this.components.add(message);
|
||||
}
|
||||
|
||||
public void add(String message) {
|
||||
this.components.add(new TextComponent(CC.translate(message)));
|
||||
}
|
||||
|
||||
public void sendToPlayer(Player player) {
|
||||
player.spigot().sendMessage(this.asComponents());
|
||||
}
|
||||
|
||||
public TextComponent[] asComponents() {
|
||||
return this.components.toArray(new TextComponent[0]);
|
||||
}
|
||||
|
||||
public static String convertItemStackToJson(ItemStack itemStack){
|
||||
try {
|
||||
assert CraftItemStackClass != null;
|
||||
Method asNMSCopyMethod = CraftItemStackClass.getMethod("asNMSCopy", ItemStack.class);
|
||||
Method saveMethod = ItemStackClass.getMethod("save", NBTTagCompoundClass);
|
||||
assert NBTTagCompoundClass != null;
|
||||
Object NBTTagCompound = NBTTagCompoundClass.newInstance();
|
||||
Object NMSItemStack = asNMSCopyMethod.invoke(null, itemStack);
|
||||
Object Json = saveMethod.invoke(NMSItemStack, NBTTagCompound);
|
||||
return Json.toString();
|
||||
} catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | SecurityException | InstantiationException e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.utils.cache.CachedPlayer;
|
||||
import net.crankedpvp.crankedutils.utils.cache.cooldown.CurrentCooldown;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class CooldownUtils {
|
||||
|
||||
public static void registerCooldown(Player player, CurrentCooldown cache) {
|
||||
CachedPlayer cachedPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(player);
|
||||
cachedPlayer.registerCache(cache);
|
||||
}
|
||||
|
||||
public static void removeCooldown(Player player, String cacheName) {
|
||||
CachedPlayer cachedPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(player);
|
||||
cachedPlayer.removeCache(cacheName);
|
||||
}
|
||||
|
||||
public static String getFormattedCooldown(Player player, String cache) {
|
||||
CachedPlayer cachedPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(player);
|
||||
return ((CurrentCooldown)cachedPlayer.getCache(cache)).getFormattedTime();
|
||||
}
|
||||
|
||||
public static boolean isCooldownActive(Player player, String cache) {
|
||||
CachedPlayer cachedPlayer = CrankedUtils.getInstance().getCacheManager().getCachedPlayer(player);
|
||||
return cachedPlayer.hasCache(cache) && ((CurrentCooldown)cachedPlayer.getCache(cache)).isActive();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import de.tr7zw.nbtapi.NBTItem;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public class CustomItemUtils {
|
||||
|
||||
public static boolean isCrankedCustomItem(ItemStack itemStack) {
|
||||
if(itemStack == null) return false;
|
||||
if (itemStack.getType() == Material.AIR) return false;
|
||||
|
||||
NBTItem nbtItem = new NBTItem(itemStack);
|
||||
if(!nbtItem.hasNBTData()) return false;
|
||||
return nbtItem.hasKey("crankedCustomItem");
|
||||
}
|
||||
|
||||
public static String getCrankedCustomItem(ItemStack itemStack) {
|
||||
if(itemStack == null) return "";
|
||||
if (itemStack.getType() == Material.AIR) return "";
|
||||
NBTItem nbtItem = new NBTItem(itemStack);
|
||||
return nbtItem.getString("crankedCustomItem");
|
||||
}
|
||||
|
||||
|
||||
public static ItemStack setCrankedCustomItem(ItemStack itemStack, String string) {
|
||||
if(itemStack == null) return itemStack;
|
||||
if (itemStack.getType() == Material.AIR) return itemStack;
|
||||
|
||||
NBTItem nbtItem = new NBTItem(itemStack);
|
||||
nbtItem.setString("crankedCustomItem", string);
|
||||
return nbtItem.getItem();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.utils.config.ConfigManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
public class DamageHandler {
|
||||
private final CrankedUtils plugin;
|
||||
private static final DecimalFormat df = new DecimalFormat("#.##");
|
||||
public static final String DAMAGE_DEBUG_PERMISSION = "cranked.damage.debug";
|
||||
|
||||
public DamageHandler(CrankedUtils plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void cancelDamage(EntityDamageEvent event, String reason) {
|
||||
event.setDamage(0);
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && event.getEntity() instanceof LivingEntity && event.getEntity().hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(event.getEntity(), "&c&lDMG Canceled &7(Reason: " + reason + "&7)");
|
||||
}
|
||||
}
|
||||
|
||||
public void setDamage(EntityDamageEvent event, double amount, String reason) {
|
||||
event.setDamage(amount);
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && event.getEntity() instanceof LivingEntity && event.getEntity().hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(event.getEntity(), "&c&lDMG &7(&b=" + formatDamageAmount(amount) + " DMG&7) &7(Reason: " + reason + "&7)");
|
||||
}
|
||||
}
|
||||
|
||||
public void damage(LivingEntity victim, double amount, String reason) {
|
||||
victim.damage(amount);
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && victim.hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(victim, "&c&l " + formatDamageAmount(amount) + " DMG &7(Reason: " + reason + "&7)");
|
||||
}
|
||||
}
|
||||
|
||||
public void increaseDamage(double amountInPercentage, EntityDamageByEntityEvent event, String damageCause) {
|
||||
double increaseAmount = this.getCorrectIncreasePercentage(amountInPercentage);
|
||||
this.increaseDamage(amountInPercentage, event, damageCause, increaseAmount);
|
||||
}
|
||||
|
||||
|
||||
public void reduceDamage(double amountInPercentage, EntityDamageEvent event, String damageCause) {
|
||||
double decreaseAmount = this.getCorrectDecreasePercentage(amountInPercentage);
|
||||
this.reduceDamage(amountInPercentage, event, damageCause, decreaseAmount);
|
||||
}
|
||||
|
||||
public void removeHealth(LivingEntity to, double amount, String damageCause) {
|
||||
if (!WorldGuardUtils.canPvPInRegion(to.getLocation())) return;
|
||||
|
||||
double getNewHealth = Math.max(to.getHealth() - amount, 0);
|
||||
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && to instanceof Player && to.hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(to, "&c&l- " + formatDamageAmount(amount) + " Health &7(Damage Cause: " + damageCause + "&7)");
|
||||
}
|
||||
|
||||
to.setHealth(getNewHealth);
|
||||
}
|
||||
|
||||
public void healEntity(LivingEntity entity, double amount, String healReason) {
|
||||
if (entity == null) return;
|
||||
if (entity.isDead()) return;
|
||||
|
||||
double finalHealth = Math.min(entity.getHealth() + amount, entity.getMaxHealth());
|
||||
|
||||
entity.setHealth(finalHealth);
|
||||
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && entity.hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(entity, "&a&l+ " + formatDamageAmount(amount) + " HP &7(Heal Reason: " + healReason + "&7)");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void increaseDamage(double amountInPercentage, EntityDamageByEntityEvent event, String damageCause, double increaseAmount) {
|
||||
if (!(event.getEntity() instanceof LivingEntity)) return;
|
||||
if (!(event.getDamager() instanceof LivingEntity)) return;
|
||||
|
||||
if (event.getDamage() <= 0) return;
|
||||
double oldDamage = event.getDamage();
|
||||
double newDamage = oldDamage * increaseAmount;
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && event.getDamager().hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
LivingEntity entity = (LivingEntity) event.getEntity();
|
||||
double oldHealth = entity.getHealth();
|
||||
double healthDifference = this.getHealthDifference(entity.getHealth(), oldHealth);
|
||||
String color = healthDifference > 9.0D ? "&4&l" : "&c&l";
|
||||
this.sendDebugMessage(event.getDamager(), "&a&l\u2B06 Damage &7(&a+" + Math.round(amountInPercentage) + "%&7) &7(&c" + formatDamageAmount(oldDamage) + " &7-> &a" + formatDamageAmount(newDamage) + " &7[&f" + entity.getName() + ": " + color + "-" + (int) healthDifference + "HP&7]) &7(Damage Cause: &f" + damageCause + "&7)");
|
||||
}
|
||||
event.setDamage(newDamage);
|
||||
}
|
||||
|
||||
private void reduceDamage(double amountInPercentage, EntityDamageEvent event, String damageCause, double decreaseAmount) {
|
||||
if (event.getDamage() <= 0) return;
|
||||
|
||||
double oldDamage = event.getDamage();
|
||||
double newDamage = event.getDamage() * decreaseAmount;
|
||||
|
||||
if(damageCause.equals("HeadlessAbilityNerf")) {
|
||||
System.out.println("&c&l\u2B07 Damage &7(&c-" + Math.round(amountInPercentage) + "%&7) &7(&a" + formatDamageAmount(oldDamage) + " &7-> &c" + formatDamageAmount(newDamage) + "&7) (Damage Cause: &f" + damageCause + "&7)");
|
||||
}
|
||||
if (this.plugin.getConfigManager().getAbstractConfig(ConfigManager.ConfigFile.PRIMARY).getConfig().getBoolean("debug-enabled") && event.getEntity().hasPermission(DAMAGE_DEBUG_PERMISSION)) {
|
||||
this.sendDebugMessage(event.getEntity(), "&c&l\u2B07 Damage &7(&c-" + Math.round(amountInPercentage) + "%&7) &7(&a" + formatDamageAmount(oldDamage) + " &7-> &c" + formatDamageAmount(newDamage) + "&7) (Damage Cause: &f" + damageCause + "&7)");
|
||||
}
|
||||
|
||||
event.setDamage(newDamage);
|
||||
}
|
||||
|
||||
private void sendDebugMessage(Entity entity, String message) {
|
||||
entity.sendMessage(CC.translate(message));
|
||||
Bukkit.getConsoleSender().sendMessage(CC.translate(CC.Aqua + message));
|
||||
}
|
||||
|
||||
private Double getCorrectIncreasePercentage(double value) {
|
||||
return 0.01D * value + 1.0D;
|
||||
}
|
||||
|
||||
private Double getCorrectDecreasePercentage(double value) {
|
||||
value = 0.01D * value;
|
||||
value = 1.0D - value;
|
||||
return value;
|
||||
}
|
||||
|
||||
private Double getHealthDifference(double healthBeforeModified, double healthAfterModified) {
|
||||
double health = healthBeforeModified - healthAfterModified;
|
||||
health = Math.abs(health);
|
||||
return health;
|
||||
}
|
||||
|
||||
public static String formatDamageAmount(double damage) {
|
||||
return df.format(damage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.minecraft.server.v1_8_R3.EntityArmorStand;
|
||||
import net.minecraft.server.v1_8_R3.EntityLiving;
|
||||
import net.minecraft.server.v1_8_R3.Packet;
|
||||
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy;
|
||||
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
public class DamageIndicatorsUtil {
|
||||
|
||||
public static void showToNearbyPlayers(Entity target, double radius, String text) {
|
||||
List<Player> nearby = target.getNearbyEntities(radius, radius, radius).stream().filter(e -> e.getType() == EntityType.PLAYER).map(e -> (Player)e).filter(e -> e.getUniqueId() != target.getUniqueId()).collect(Collectors.toList());
|
||||
if (!nearby.isEmpty()) {
|
||||
DamageIndicatorsUtil.showToPlayers(target, nearby, text);
|
||||
}
|
||||
}
|
||||
|
||||
public static void showToNearbyPlayers(Entity target, String text) {
|
||||
DamageIndicatorsUtil.showToNearbyPlayers(target, 35.0, text);
|
||||
}
|
||||
|
||||
public static void showToPlayer(Entity target, Player toShow, String text) {
|
||||
DamageIndicatorsUtil.showToPlayers(target, new ArrayList<Player>(Collections.singletonList(toShow)), text);
|
||||
}
|
||||
|
||||
public static void showToPlayers(final Entity target, List<Player> toShow, String text) {
|
||||
for (final Player p : toShow) {
|
||||
//if (!WorldGuardUtils.canPvPInRegion(target.getLocation()) || !WorldGuardUtils.canPvPInRegion(p.getLocation())) continue;
|
||||
double xOffset = Math.random() * (Math.random() > 0.5 ? 0.5 : -0.5);
|
||||
double yOffset = 1.0 + Math.random() * (Math.random() > 0.5 ? 0.5 : -0.5);
|
||||
double zOffset = Math.random() * (Math.random() > 0.5 ? 0.2 : -0.2);
|
||||
final EntityArmorStand armorStand = new EntityArmorStand(((CraftEntity)target).getHandle().world, target.getLocation().getX() + xOffset, target.getLocation().getY() - yOffset, target.getLocation().getZ() + zOffset);
|
||||
armorStand.setGravity(false);
|
||||
armorStand.setCustomName(CC.translate(text));
|
||||
armorStand.setCustomNameVisible(true);
|
||||
armorStand.setInvisible(true);
|
||||
PacketPlayOutSpawnEntityLiving spawnPacket = new PacketPlayOutSpawnEntityLiving(armorStand);
|
||||
((CraftPlayer)p).getHandle().playerConnection.sendPacket(spawnPacket);
|
||||
final int secondsToStay = 3;
|
||||
new BukkitRunnable(){
|
||||
int counter = 0;
|
||||
|
||||
public void run() {
|
||||
block5: {
|
||||
block4: {
|
||||
if (!p.isOnline()) {
|
||||
this.cancel();
|
||||
return;
|
||||
}
|
||||
if (this.counter >= secondsToStay) break block4;
|
||||
Location location = new Location(target.getLocation().getWorld(), armorStand.locX, armorStand.locY, armorStand.locZ);
|
||||
if (!(target.getLocation().distance(location) > 2.0)) break block5;
|
||||
}
|
||||
PacketPlayOutEntityDestroy destroyPacket = new PacketPlayOutEntityDestroy(armorStand.getId());
|
||||
((CraftPlayer)p).getHandle().playerConnection.sendPacket(destroyPacket);
|
||||
this.cancel();
|
||||
}
|
||||
++this.counter;
|
||||
}
|
||||
}.runTaskTimer(CrankedUtils.getInstance(), 0L, 30L);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
|
||||
public class EconomyUtils {
|
||||
private static Economy economy;
|
||||
|
||||
public static Economy getEconomy() {
|
||||
if (economy == null && (economy = Bukkit.getServer().getServicesManager().getRegistration(Economy.class).getProvider()) == null) {
|
||||
Bukkit.getLogger().info("Unable to get economy!!");
|
||||
return null;
|
||||
}
|
||||
return economy;
|
||||
}
|
||||
|
||||
public static boolean hasBalance(OfflinePlayer player, double balance) {
|
||||
return EconomyUtils.getEconomy().has(player, balance);
|
||||
}
|
||||
|
||||
public static double depositBalanceAndGet(OfflinePlayer player, double balance) {
|
||||
EconomyUtils.getEconomy().depositPlayer(player, balance);
|
||||
return EconomyUtils.getEconomy().getBalance(player);
|
||||
}
|
||||
|
||||
public static void depositBalance(OfflinePlayer player, double balance) {
|
||||
EconomyUtils.getEconomy().depositPlayer(player, balance);
|
||||
}
|
||||
|
||||
public static double withdrawBalanceAndGet(OfflinePlayer player, double balance) {
|
||||
EconomyUtils.getEconomy().withdrawPlayer(player, balance);
|
||||
return EconomyUtils.getEconomy().getBalance(player);
|
||||
}
|
||||
|
||||
public static void withdrawBalance(OfflinePlayer player, double balance) {
|
||||
EconomyUtils.getEconomy().withdrawPlayer(player, balance);
|
||||
}
|
||||
|
||||
public static double getBalance(OfflinePlayer player) {
|
||||
return EconomyUtils.getEconomy().getBalance(player);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
|
||||
|
||||
public class EntityUtils {
|
||||
|
||||
public static String getHealthString(LivingEntity entity) {
|
||||
int intHealth = (int) entity.getHealth();
|
||||
int intMaxHealth = (int) entity.getMaxHealth();
|
||||
int amountOfTimes = intMaxHealth - (intMaxHealth - intHealth);
|
||||
amountOfTimes = (int) Math.ceil((double) amountOfTimes / intMaxHealth * 8);
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (int i = 1; i <= 8; i++) {
|
||||
if (amountOfTimes >= i) {
|
||||
builder.append(CC.translate(CC.RedB + "❤"));
|
||||
} else {
|
||||
builder.append(CC.translate(CC.WhiteB + "❤"));
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String getEntityName(EntityType type) {
|
||||
if (type == EntityType.IRON_GOLEM) {
|
||||
return "Iron Golem";
|
||||
}
|
||||
if (type == EntityType.MUSHROOM_COW) {
|
||||
return "Mushroom Cow";
|
||||
}
|
||||
return type.getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import com.earth2me.essentials.IEssentials;
|
||||
import com.earth2me.essentials.User;
|
||||
import lombok.Getter;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class EssentialsUtils {
|
||||
@Getter
|
||||
public static Essentials essentials = (Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
|
||||
@Getter
|
||||
public static IEssentials iEssentials = (IEssentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
|
||||
|
||||
public static void clearTeleportRequests(Player p) {
|
||||
if (essentials != null) {
|
||||
try {
|
||||
User u = essentials.getUser(p);
|
||||
if (u.getTeleport() != null) {
|
||||
u.requestTeleport(u, true);
|
||||
Bukkit.getLogger().info("[Arkkit (Trade)] Cleared Teleport Request for " + p.getName());
|
||||
}
|
||||
} catch (Exception var3) {
|
||||
var3.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static boolean isVanished(Player player) {
|
||||
if (essentials != null) {
|
||||
try {
|
||||
User u = essentials.getUser(player);
|
||||
return u.isVanished();
|
||||
} catch (Exception var3) {
|
||||
var3.printStackTrace();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.massivecraft.factions.FLocation;
|
||||
import com.massivecraft.factions.FPlayer;
|
||||
import com.massivecraft.factions.FPlayers;
|
||||
import com.massivecraft.factions.Faction;
|
||||
import com.massivecraft.factions.iface.RelationParticipator;
|
||||
import com.massivecraft.factions.perms.Relation;
|
||||
import net.crankedpvp.crankedutils.compat.ParamBuilder;
|
||||
import net.crankedpvp.crankedutils.struct.factions.CrankedFactionHandler;
|
||||
import net.crankedpvp.crankedutils.struct.factions.FactionHandler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class FactionUtils {
|
||||
|
||||
private static FactionHandler factionHandler;
|
||||
private static Method getFactionTag;
|
||||
|
||||
public static void destroy() {
|
||||
factionHandler = null;
|
||||
}
|
||||
|
||||
public static void init() throws NoSuchMethodException {
|
||||
try {
|
||||
Class.forName("com.massivecraft.factions.Faction");
|
||||
getFactionTag = ReflectionUtils.getMethod(Faction.class, "getTag");
|
||||
} catch (ClassNotFoundException | NoClassDefFoundError ex) {
|
||||
Bukkit.getLogger().info("NO FACTIONS CLASS FOUND, NOT ENABLED???");
|
||||
return;
|
||||
} catch (Exception ex) {
|
||||
// empty catch block
|
||||
}
|
||||
|
||||
factionHandler = new CrankedFactionHandler();
|
||||
factionHandler.initHandler();
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static int getLand(Faction faction) {
|
||||
return factionHandler.getLand(faction);
|
||||
}
|
||||
|
||||
public static int getLandMax(Faction faction) {
|
||||
return factionHandler.getLandMax(faction);
|
||||
}
|
||||
|
||||
public static double getPower(Faction faction) {
|
||||
return factionHandler.getPower(faction);
|
||||
}
|
||||
|
||||
public static double getPowerMax(Faction faction) {
|
||||
return factionHandler.getPowerMax(faction);
|
||||
}
|
||||
|
||||
public static double getFactionBalance(Faction faction) throws NoSuchFieldException, IllegalAccessException {
|
||||
return factionHandler.getFactionBalance(faction);
|
||||
}
|
||||
|
||||
public static boolean isFocusedPlayer(Faction faction, String playerName) {
|
||||
return factionHandler.isFocusedPlayer(faction, playerName);
|
||||
}
|
||||
|
||||
|
||||
public static String getPlayerName(FPlayer fplayer) {
|
||||
return factionHandler.getFPlayerName(fplayer);
|
||||
}
|
||||
|
||||
|
||||
public static boolean attemptClaim(FPlayer fplayer, Faction faction, Location location, boolean notifyFailure) {
|
||||
return factionHandler.attemptClaim(fplayer, faction, location, notifyFailure);
|
||||
}
|
||||
|
||||
public static boolean isNormal(Faction faction) {
|
||||
return faction != null && (Boolean) ReflectionUtils.callReflectionMethod(faction, Faction.class, "isNormal", null);
|
||||
}
|
||||
|
||||
public static boolean isWarZone(Faction faction) {
|
||||
return faction != null && (Boolean) ReflectionUtils.callReflectionMethod(faction, Faction.class, "isWarZone", null) != false;
|
||||
}
|
||||
|
||||
public static boolean isWilderness(Faction faction) {
|
||||
return (Boolean) ReflectionUtils.callReflectionMethod(faction, Faction.class, "isNone", null);
|
||||
}
|
||||
|
||||
public static boolean isSafeZone(Faction faction) {
|
||||
return faction != null && (Boolean) ReflectionUtils.callReflectionMethod(faction, Faction.class, "isSafeZone", null) != false;
|
||||
}
|
||||
|
||||
public static boolean isWarZone(Location location) {
|
||||
return FactionUtils.isWarZone(FactionUtils.getFactionAt(location));
|
||||
}
|
||||
|
||||
public static boolean isSafeZone(Location location) {
|
||||
return FactionUtils.isSafeZone(FactionUtils.getFactionAt(location));
|
||||
}
|
||||
|
||||
public static Player getPlayer(FPlayer fplayer) {
|
||||
return factionHandler.getPlayer(fplayer);
|
||||
}
|
||||
|
||||
public static Faction getNone() {
|
||||
return FactionUtils.getFactionById("0");
|
||||
}
|
||||
|
||||
public static Faction getWarzone() {
|
||||
return FactionUtils.getFactionById("-2");
|
||||
}
|
||||
|
||||
public static Faction getSafeZone() {
|
||||
return FactionUtils.getFactionById("-1");
|
||||
}
|
||||
|
||||
public static Collection<FPlayer> getFPlayers(boolean onlineOnly) {
|
||||
return factionHandler.getAllFPlayers(onlineOnly);
|
||||
}
|
||||
|
||||
public static Collection<Faction> getAllFactions() {
|
||||
return factionHandler.getAllFactions();
|
||||
}
|
||||
|
||||
public static boolean isWilderness(Location location) {
|
||||
Faction at = FactionUtils.getFactionAt(location);
|
||||
return at == null || FactionUtils.isWilderness(at);
|
||||
}
|
||||
|
||||
public static boolean isFactionMember(Faction faction, FPlayer player) {
|
||||
return faction != null && player != null && ReflectionUtils.callReflectionMethod(faction, RelationParticipator.class, "getRelationTo", new ParamBuilder(RelationParticipator.class, player)) == Relation.MEMBER;
|
||||
}
|
||||
|
||||
public static Relation getRelationTo(RelationParticipator first, RelationParticipator second) {
|
||||
return (Relation) ReflectionUtils.callReflectionMethod(first, RelationParticipator.class, "getRelationTo", new ParamBuilder(RelationParticipator.class, second));
|
||||
}
|
||||
|
||||
public static boolean isInsideOwnFaction(Player player) {
|
||||
return factionHandler.isInOwnFaction(player);
|
||||
}
|
||||
|
||||
public static boolean inSameFaction(Player player, Player other) {
|
||||
return factionHandler.inSameFaction(player, other);
|
||||
}
|
||||
|
||||
public static boolean isInEnemyFaction(Player player, Player other) {
|
||||
return factionHandler.inInEnemyFaction(player, other);
|
||||
}
|
||||
|
||||
public static boolean isInAllyFaction(Player player, Player other) {
|
||||
return factionHandler.inInAllyFaction(player, other);
|
||||
}
|
||||
|
||||
public static String getFactionTag(Player seeingMsg, Player checking) {
|
||||
return factionHandler.getFactionTag(seeingMsg, checking);
|
||||
}
|
||||
|
||||
public static String getFactionTag(Player seeingMsg) {
|
||||
return factionHandler.getFactionTag(seeingMsg);
|
||||
}
|
||||
|
||||
public static String getFactionTag(Faction faction) {
|
||||
if (faction == null) {
|
||||
return "";
|
||||
}
|
||||
if (getFactionTag == null) {
|
||||
Bukkit.getLogger().info("getTag null!");
|
||||
}
|
||||
return (String) ReflectionUtils.invokeMethod(getFactionTag, faction);
|
||||
}
|
||||
|
||||
public static String getFactionId(Player player) {
|
||||
return factionHandler.getFactionId(player);
|
||||
}
|
||||
|
||||
public static String getFactionId(Faction faction) {
|
||||
return factionHandler.getFactionId(faction);
|
||||
}
|
||||
|
||||
public static String getFPlayerId(FPlayer fplayer) {
|
||||
return factionHandler.getFPlayerId(fplayer);
|
||||
}
|
||||
|
||||
public static Faction getFactionAt(Location location) {
|
||||
return factionHandler.getFactionAt(location);
|
||||
}
|
||||
|
||||
public static Faction getFactionAt(FLocation location) {
|
||||
return factionHandler.getFactionAt(location);
|
||||
}
|
||||
|
||||
public static Faction getFaction(Player player) {
|
||||
return factionHandler.getFaction(player, true);
|
||||
}
|
||||
|
||||
public static Faction getFaction(Player player, boolean includeWilderness) {
|
||||
return factionHandler.getFaction(player, includeWilderness);
|
||||
}
|
||||
|
||||
public static Faction getFaction(FPlayer player) {
|
||||
return factionHandler.getFaction(player, true);
|
||||
}
|
||||
|
||||
public static Faction getFaction(FPlayer player, boolean includeWilderness) {
|
||||
return factionHandler.getFaction(player, includeWilderness);
|
||||
}
|
||||
|
||||
public static void sendMessage(FPlayer fplayer, String msg) {
|
||||
factionHandler.sendMessage(fplayer, msg);
|
||||
}
|
||||
|
||||
public static Faction getFactionByTag(String tag) {
|
||||
return factionHandler.getFactionByTag(tag);
|
||||
}
|
||||
|
||||
public static FPlayer getFPlayer(Player player) {
|
||||
return factionHandler.getFPlayer(player);
|
||||
}
|
||||
|
||||
public static Faction getFactionById(String id) {
|
||||
return factionHandler.getFactionById(id);
|
||||
}
|
||||
|
||||
public static String getFactionIdByTag(String tag) {
|
||||
return factionHandler.getFactionIdByTag(tag);
|
||||
}
|
||||
|
||||
public static List<String> getFPlayerIdsByTag(String tag) {
|
||||
return factionHandler.getFPlayerIdsByTag(tag);
|
||||
}
|
||||
|
||||
public static FPlayer getFPlayerByName(String name) {
|
||||
return factionHandler.getFPlayerByName(name);
|
||||
}
|
||||
|
||||
public static List<String> getFPlayerIdsById(String factionName) {
|
||||
return factionHandler.getFPlayerIdsById(factionName);
|
||||
}
|
||||
|
||||
public static Object callFPlayerMethod(FPlayer fplayer, String method) {
|
||||
return ReflectionUtils.callReflectionMethod(fplayer, factionHandler.getMainFPlayerClass(), method, null);
|
||||
}
|
||||
|
||||
public static Object callFPlayerMethod(FPlayer fplayer, String method, ParamBuilder builder) {
|
||||
return ReflectionUtils.callReflectionMethod(fplayer, factionHandler.getMainFPlayerClass(), method, builder);
|
||||
}
|
||||
|
||||
public static Object callFactionMethod(String id, String method, ParamBuilder builder) {
|
||||
Faction fac = FactionUtils.getFactionByTag(id);
|
||||
return ReflectionUtils.callReflectionMethod(fac, factionHandler.getMainFactionClass(), method, builder);
|
||||
}
|
||||
|
||||
public static Object callFactionMethod(Faction faction, String method, ParamBuilder builder) {
|
||||
return ReflectionUtils.callReflectionMethod(faction, factionHandler.getMainFactionClass(), method, builder);
|
||||
}
|
||||
|
||||
public static Map getRelationWishes(Faction faction) throws NoSuchFieldException, IllegalAccessException {
|
||||
return (Map) ReflectionUtils.getObject(factionHandler.getMainFactionClass(), faction, "relationWish");
|
||||
}
|
||||
|
||||
public static Object callFactionMethodByTag(String tag, String method, ParamBuilder builder) {
|
||||
Faction fac = FactionUtils.getFactionByTag(tag);
|
||||
return ReflectionUtils.callReflectionMethod(fac, factionHandler.getMainFactionClass(), method, builder);
|
||||
}
|
||||
|
||||
public static boolean canPvP(Player victim, Player attacker) {
|
||||
FPlayer VictimPlayer = FPlayers.getInstance().getByPlayer(victim);
|
||||
Faction VictimFac = VictimPlayer.getFaction();
|
||||
FPlayer AttackerPlayer = FPlayers.getInstance().getByPlayer(attacker);
|
||||
Faction AttackerFac = AttackerPlayer.getFaction();
|
||||
Relation relationBetween = VictimFac.getRelationTo(AttackerFac);
|
||||
return relationBetween == Relation.ENEMY || relationBetween == Relation.NEUTRAL;
|
||||
}
|
||||
|
||||
public static boolean cantPvPFaction(Player victim, Player attacker) {
|
||||
FPlayer VictimPlayer = FPlayers.getInstance().getByPlayer(victim);
|
||||
Faction VictimFac = VictimPlayer.getFaction();
|
||||
FPlayer AttackerPlayer = FPlayers.getInstance().getByPlayer(attacker);
|
||||
Faction AttackerFac = AttackerPlayer.getFaction();
|
||||
Relation relationBetween = VictimFac.getRelationTo(AttackerFac);
|
||||
return relationBetween != Relation.ENEMY && relationBetween != Relation.NEUTRAL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import com.comphenix.protocol.ProtocolManager;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.events.PacketListener;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.MapMaker;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.comphenix.protocol.PacketType.Play.Server.ENTITY_EQUIPMENT;
|
||||
import static com.comphenix.protocol.PacketType.Play.Server.NAMED_ENTITY_SPAWN;
|
||||
|
||||
/**
|
||||
* Modify player equipment.
|
||||
* @author Kristian
|
||||
*/
|
||||
public abstract class FakeEquipment {
|
||||
/**
|
||||
* Represents an equipment slot.
|
||||
* @author Kristian
|
||||
*/
|
||||
public enum EquipmentSlot {
|
||||
// http://wiki.vg/Protocol#Entity_Equipment_.280x05.29
|
||||
HELD(0),
|
||||
BOOTS(1),
|
||||
LEGGINGS(2),
|
||||
CHESTPLATE(3),
|
||||
HELMET(4);
|
||||
|
||||
private final int id;
|
||||
|
||||
EquipmentSlot(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the entity's equipment in the current slot.
|
||||
* @param entity - the entity.
|
||||
* @return The equipment.
|
||||
*/
|
||||
public ItemStack getEquipment(LivingEntity entity) {
|
||||
switch (this) {
|
||||
case HELD: return entity.getEquipment().getItemInHand();
|
||||
case BOOTS: return entity.getEquipment().getBoots();
|
||||
case LEGGINGS: return entity.getEquipment().getLeggings();
|
||||
case CHESTPLATE: return entity.getEquipment().getChestplate();
|
||||
case HELMET: return entity.getEquipment().getHelmet();
|
||||
default: throw new IllegalArgumentException("Unknown slot: " + this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the entity has an equipment in the current slot.
|
||||
* @param entity - the entity.
|
||||
* @return TRUE if it is empty, FALSE otherwise.
|
||||
*/
|
||||
public boolean isEmpty(LivingEntity entity) {
|
||||
ItemStack stack = getEquipment(entity);
|
||||
return stack != null && stack.getType() == Material.AIR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the underlying equipment slot ID.
|
||||
* @return The ID.
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the corresponding equipment slot.
|
||||
* @param id - the slot ID.
|
||||
* @return The equipment slot.
|
||||
*/
|
||||
public static EquipmentSlot fromId(int id) {
|
||||
for (EquipmentSlot slot : values()) {
|
||||
if (slot.getId() == id) {
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Cannot find slot id: " + id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents an equipment event.
|
||||
* @author Kristian
|
||||
*/
|
||||
public static class EquipmentSendingEvent {
|
||||
private final Player client;
|
||||
private final LivingEntity visibleEntity;
|
||||
private EquipmentSlot slot;
|
||||
private ItemStack equipment;
|
||||
|
||||
private EquipmentSendingEvent(Player client, LivingEntity visibleEntity, EquipmentSlot slot, ItemStack equipment) {
|
||||
this.client = client;
|
||||
this.visibleEntity = visibleEntity;
|
||||
this.slot = slot;
|
||||
this.equipment = equipment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the client that is observing the entity.
|
||||
* @return The observing client.
|
||||
*/
|
||||
public Player getClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the entity whose armor or held item we are updating.
|
||||
* @return The visible entity.
|
||||
*/
|
||||
public LivingEntity getVisibleEntity() {
|
||||
return visibleEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the equipment that we are
|
||||
* @return
|
||||
*/
|
||||
public ItemStack getEquipment() {
|
||||
return equipment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the equipment we will send to the player.
|
||||
* @param equipment - the equipment, or NULL to sent air.
|
||||
*/
|
||||
public void setEquipment(ItemStack equipment) {
|
||||
this.equipment = equipment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the slot of this equipment.
|
||||
* @return The slot.
|
||||
*/
|
||||
public EquipmentSlot getSlot() {
|
||||
return slot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the slot of this equipment.
|
||||
* @param slot - the slot.
|
||||
*/
|
||||
public void setSlot(EquipmentSlot slot) {
|
||||
this.slot = Preconditions.checkNotNull(slot, "slot cannot be NULL");
|
||||
}
|
||||
}
|
||||
|
||||
// Necessary to detect duplicate
|
||||
private final Map<Object, EquipmentSlot> processedPackets = new MapMaker().weakKeys().makeMap();
|
||||
|
||||
private final Plugin plugin;
|
||||
private final ProtocolManager manager;
|
||||
|
||||
// Current listener
|
||||
private PacketListener listener;
|
||||
|
||||
public FakeEquipment(Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.manager = ProtocolLibrary.getProtocolManager();
|
||||
|
||||
manager.addPacketListener(
|
||||
listener = new PacketAdapter(plugin, ENTITY_EQUIPMENT, NAMED_ENTITY_SPAWN) {
|
||||
@Override
|
||||
public void onPacketSending(PacketEvent event) {
|
||||
PacketContainer packet = event.getPacket();
|
||||
PacketType type = event.getPacketType();
|
||||
|
||||
// The entity that is being displayed on the player's screen
|
||||
LivingEntity visibleEntity = (LivingEntity) packet.getEntityModifier(event).read(0);
|
||||
Player observingPlayer = event.getPlayer();
|
||||
|
||||
if (ENTITY_EQUIPMENT.equals(type)) {
|
||||
EquipmentSlot slot = EquipmentSlot.fromId(packet.getIntegers().read(1));
|
||||
ItemStack equipment = packet.getItemModifier().read(0);
|
||||
EquipmentSendingEvent sendingEvent = new EquipmentSendingEvent(
|
||||
observingPlayer, visibleEntity, slot, equipment);
|
||||
|
||||
// Assume we process all packets - the overhead isn't that bad
|
||||
EquipmentSlot previous = processedPackets.get(packet.getHandle());
|
||||
|
||||
// See if this packet instance has already been processed
|
||||
if (previous != null) {
|
||||
// Clone it - otherwise, we'll loose the old modification
|
||||
packet = event.getPacket().deepClone();
|
||||
sendingEvent.setSlot(previous);
|
||||
sendingEvent.setEquipment(previous.getEquipment(visibleEntity).clone());
|
||||
}
|
||||
|
||||
if (onEquipmentSending(sendingEvent)) {
|
||||
processedPackets.put(packet.getHandle(), previous != null ? previous : slot);
|
||||
}
|
||||
|
||||
// Save changes
|
||||
if (slot != sendingEvent.getSlot()) {
|
||||
packet.getIntegers().write(1, slot.getId());
|
||||
}
|
||||
if (equipment != sendingEvent.getEquipment()) {
|
||||
packet.getItemModifier().write(0, sendingEvent.getEquipment());
|
||||
}
|
||||
|
||||
} else if (NAMED_ENTITY_SPAWN.equals(type)) {
|
||||
// Trigger updates?
|
||||
onEntitySpawn(observingPlayer, visibleEntity);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unknown packet type:" + type);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked when a living entity has been spawned on the given client.
|
||||
* @param client - the client.
|
||||
* @param visibleEntity - the visibleEntity.
|
||||
*/
|
||||
protected void onEntitySpawn(Player client, LivingEntity visibleEntity) {
|
||||
// Update all the slots?
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked when the equipment or held item of an living entity is sent to a client.
|
||||
* <p>
|
||||
* This can be fully modified. Please return TRUE if you do, though.
|
||||
* @param equipmentEvent - the equipment event.
|
||||
* @return TRUE if the equipment was modified, FALSE otherwise.
|
||||
*/
|
||||
protected abstract boolean onEquipmentSending(EquipmentSendingEvent equipmentEvent);
|
||||
|
||||
/**
|
||||
* Update the given slot.
|
||||
* @param observer - the observing client.
|
||||
* @param entity - the visible entity that will be updated.
|
||||
* @param slot - the equipment slot to update.
|
||||
*/
|
||||
public void updateSlot(final Player client, LivingEntity visibleEntity, EquipmentSlot slot) {
|
||||
if (listener == null)
|
||||
throw new IllegalStateException("FakeEquipment has closed.");
|
||||
|
||||
final PacketContainer equipmentPacket = new PacketContainer(ENTITY_EQUIPMENT);
|
||||
equipmentPacket.getIntegers().
|
||||
write(0, visibleEntity.getEntityId()).
|
||||
write(1, slot.getId());
|
||||
equipmentPacket.getItemModifier().
|
||||
write(0, slot.getEquipment(visibleEntity));
|
||||
|
||||
// We have to send the packet AFTER named entity spawn has been sent
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
|
||||
try {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(client, equipmentPacket);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new RuntimeException("Unable to update slot.", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the current equipment modifier.
|
||||
*/
|
||||
public void close() {
|
||||
if (listener != null) {
|
||||
manager.removePacketListener(listener);
|
||||
listener = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class GodsetUtils {
|
||||
|
||||
public final static Map<String, List<String>> enchantments = new HashMap<>();
|
||||
|
||||
static {
|
||||
|
||||
enchantments.put("boots", Arrays.asList(
|
||||
"enlighted",
|
||||
"rocketescape",
|
||||
"valor",
|
||||
"angelic",
|
||||
"tank",
|
||||
"armored",
|
||||
"poisoned",
|
||||
"metaphysical",
|
||||
"gears"
|
||||
));
|
||||
|
||||
enchantments.put("leggings", Arrays.asList(
|
||||
"enlighted",
|
||||
"valor",
|
||||
"angelic",
|
||||
"tank",
|
||||
"armored",
|
||||
"cactus",
|
||||
"voodoo",
|
||||
"obsidianshield",
|
||||
"lucky"
|
||||
));
|
||||
|
||||
enchantments.put("chestplate", Arrays.asList(
|
||||
"enlighted",
|
||||
"valor",
|
||||
"angelic",
|
||||
"tank",
|
||||
"armored",
|
||||
"overload",
|
||||
"deathbringer",
|
||||
"leadership",
|
||||
"wither"
|
||||
));
|
||||
|
||||
enchantments.put("helmet", Arrays.asList(
|
||||
"enlighted",
|
||||
"valor",
|
||||
"angelic",
|
||||
"tank",
|
||||
"armored",
|
||||
"drunk",
|
||||
"deathgod",
|
||||
"implants",
|
||||
"endershift"
|
||||
));
|
||||
|
||||
enchantments.put("sword", Arrays.asList(
|
||||
"rage",
|
||||
"doublestrike",
|
||||
"divineimmolation",
|
||||
"enrage",
|
||||
"execute",
|
||||
"silence",
|
||||
"solitude",
|
||||
"lifesteal",
|
||||
"assassin"
|
||||
));
|
||||
|
||||
enchantments.put("axe", Arrays.asList(
|
||||
"rage",
|
||||
"bleed",
|
||||
"cleave",
|
||||
"barbarian",
|
||||
"devour",
|
||||
"insanity",
|
||||
"antigank",
|
||||
"silence",
|
||||
"solitude"
|
||||
));
|
||||
|
||||
enchantments.put("hoe", Arrays.asList(
|
||||
"rage",
|
||||
"bleed",
|
||||
"devour",
|
||||
"solitude",
|
||||
"execute",
|
||||
"enrage",
|
||||
"divineimmolation",
|
||||
"doublestrike",
|
||||
"silence"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
static {
|
||||
|
||||
enchantments.put("boots", Arrays.asList(
|
||||
"abyss",
|
||||
"armored",
|
||||
"lifeessence",
|
||||
"angelic",
|
||||
"dodge",
|
||||
"metaphysical",
|
||||
"tank",
|
||||
"fearless",
|
||||
"reinforced",
|
||||
"speed"
|
||||
));
|
||||
|
||||
enchantments.put("leggings", Arrays.asList(
|
||||
"mirror",
|
||||
"rotanddecay",
|
||||
"armored",
|
||||
"deathbringer",
|
||||
"lifeessence",
|
||||
"dodge",
|
||||
"angelic",
|
||||
"tank",
|
||||
"platemail",
|
||||
"spiked"
|
||||
));
|
||||
|
||||
enchantments.put("chestplate", Arrays.asList(
|
||||
"fat",
|
||||
"armored",
|
||||
"diminish",
|
||||
"enlighted",
|
||||
"judgement",
|
||||
"lifeessence",
|
||||
"angelic",
|
||||
"backbone",
|
||||
"tank",
|
||||
"reinforced"
|
||||
));
|
||||
|
||||
enchantments.put("helmet", Arrays.asList(
|
||||
"cursedmark",
|
||||
"lucky",
|
||||
"armored",
|
||||
"drunk",
|
||||
"enlighted",
|
||||
"healthboost",
|
||||
"lifeessence",
|
||||
"angelic",
|
||||
"dodge",
|
||||
"tank"
|
||||
));
|
||||
|
||||
enchantments.put("sword", Arrays.asList(
|
||||
"rage",
|
||||
"crushing",
|
||||
"divineimmolation",
|
||||
"lifesteal",
|
||||
"silence",
|
||||
"eradicate",
|
||||
"petrify",
|
||||
"purge",
|
||||
"deathcurse",
|
||||
"iceaspect"
|
||||
));
|
||||
|
||||
enchantments.put("axe", Arrays.asList(
|
||||
"enforcer",
|
||||
"enrage",
|
||||
"dualwield",
|
||||
"assassin",
|
||||
"rage",
|
||||
"insanity",
|
||||
"execute",
|
||||
"crushing",
|
||||
"eradicate",
|
||||
"petrify"
|
||||
));
|
||||
|
||||
enchantments.put("hoe", Arrays.asList(
|
||||
"enforcer",
|
||||
"divineimmolation",
|
||||
"rage",
|
||||
"execute",
|
||||
"crushing",
|
||||
"silence",
|
||||
"assassin",
|
||||
"dualwield",
|
||||
"doublestrike",
|
||||
"cleave"
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,62 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import dev.triumphteam.gui.guis.Gui;
|
||||
import dev.triumphteam.gui.guis.GuiItem;
|
||||
import dev.triumphteam.gui.guis.PaginatedGui;
|
||||
import net.crankedpvp.crankedutils.utils.items.ItemBuilder;
|
||||
import org.bukkit.DyeColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
public class GuiUtil {
|
||||
|
||||
public static Gui setupGui(String title, boolean exitButton) {
|
||||
Gui gui = new Gui(6, title);
|
||||
gui.getFiller().fillBorder(new GuiItem(createFillerItem()));
|
||||
if (exitButton)
|
||||
gui.setItem(6, 5, new GuiItem(createExitItem()));
|
||||
return gui;
|
||||
}
|
||||
|
||||
public static Gui setupGui(String title) {
|
||||
return setupGui(title, true);
|
||||
}
|
||||
|
||||
public static PaginatedGui setupGui(PaginatedGui gui) {
|
||||
if(gui.getRows() != 6) return gui;
|
||||
gui.getFiller().fillBorder(new GuiItem(createFillerItem()));
|
||||
gui.setItem(6, 5, new GuiItem(createExitItem(), event -> gui.close(event.getWhoClicked())));
|
||||
gui.setItem(6, 1, new GuiItem(createPreviousItem(), event -> gui.previous()));
|
||||
gui.setItem(6, 9, new GuiItem(createNextItem(), event -> gui.next()));
|
||||
return gui;
|
||||
}
|
||||
|
||||
public static ItemStack createFillerItem() {
|
||||
ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData());
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(CC.translate(" "));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
public static GuiItem createFillerGuiItem() {
|
||||
ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData());
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.setDisplayName(CC.translate(" "));
|
||||
item.setItemMeta(meta);
|
||||
return new GuiItem(item);
|
||||
}
|
||||
|
||||
public static ItemStack createExitItem() {
|
||||
return (new ItemBuilder(Material.REDSTONE, "&cExit Menu")).colorize().build();
|
||||
}
|
||||
|
||||
public static ItemStack createPreviousItem() {
|
||||
return new ItemBuilder(Material.ARROW, "&c<- Previous Page", "&7Right-Click&7 to go to the previous page.").colorize().build();
|
||||
}
|
||||
|
||||
public static ItemStack createNextItem() {
|
||||
return new ItemBuilder(Material.ARROW, "&aNext Page ->", "&7Right-Click&7 to go to the next page.").colorize().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import de.tr7zw.nbtapi.NBTItem;
|
||||
import net.crankedpvp.crankedutils.modifiers.AttributeModifier;
|
||||
import net.crankedpvp.crankedutils.modifiers.ModifierType;
|
||||
import net.crankedpvp.crankedutils.utils.items.ItemBuilder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
public class HookUtils {
|
||||
public static String NBT_STRING = "hookItem";
|
||||
public static String NBT_KEY = "hookItem";
|
||||
|
||||
public static ItemStack applyHookData(ItemStack itemStack) {
|
||||
if(!itemStack.getType().name().endsWith("_HOE")) return null;
|
||||
ItemBuilder itemBuilder = new ItemBuilder(itemStack);
|
||||
itemBuilder.addLore(Arrays.asList("", "&7A powerful hoe that has the ability", "&7to harness Axe & Sword enchants."));
|
||||
NBTItem wrapper = new NBTItem(itemBuilder.colorize().build());
|
||||
wrapper.setString(NBT_KEY, NBT_STRING);
|
||||
ItemStack finalItem = wrapper.getItem();
|
||||
Pair<ModifierType, Double> modifierTypePair = new Pair<>(ModifierType.ATTACK_DAMAGE, 7D);
|
||||
finalItem = AttributeModifier.applyModifications(finalItem, Collections.singletonList(modifierTypePair));
|
||||
return finalItem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
|
||||
public class InventoryClickUtils {
|
||||
|
||||
public static boolean canClickItem(InventoryClickEvent event) {
|
||||
//if (event.getClickedInventory() == null) return false;
|
||||
//if (event.getClickedInventory() == event.get)
|
||||
//return event.getClickedInventory().getType() == InventoryType.PLAYER;
|
||||
//if (event.getClickedInventory() != event.getWhoClicked().getOpenInventory().getBottomInventory()) return false;
|
||||
//return event.getWhoClicked().getOpenInventory().getTopInventory() == null;
|
||||
//return (event.getClickedInventory() == event.getView().getBottomInventory()) || (event.getView().getTopInventory() instanceof CraftingInventory && event.getWhoClicked().getOpenInventory().getTopInventory() == null);
|
||||
return (event.getClickedInventory() == event.getView().getBottomInventory());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.enums.ArmorType;
|
||||
import net.crankedpvp.crankedutils.events.ArmorEquipEvent;
|
||||
import net.crankedpvp.crankedutils.utils.items.ItemUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class InventoryUtils {
|
||||
|
||||
private InventoryUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static boolean hasAvailableSlot(Player player) {
|
||||
return player.getInventory().firstEmpty() != -1;
|
||||
}
|
||||
|
||||
public static boolean hasAvaliableSlot(Player player, int amount) {
|
||||
int amountOpen = 0;
|
||||
Inventory inv = player.getInventory();
|
||||
for (ItemStack item : inv.getContents()) {
|
||||
if(item == null) {
|
||||
amountOpen += 1;
|
||||
}
|
||||
}
|
||||
return amountOpen >= amount;
|
||||
}
|
||||
|
||||
public static boolean canPutItemsInInventory(Player player, List<ItemStack> items) {
|
||||
if(hasAvaliableSlot(player, 1)) return true;
|
||||
int amountOpen = 0;
|
||||
Inventory inv = player.getInventory();
|
||||
for (ItemStack item : inv.getContents()) {
|
||||
if(item == null) {
|
||||
amountOpen += 1;
|
||||
}
|
||||
|
||||
ItemStack itemInInventoryClone = item.clone();
|
||||
|
||||
for(ItemStack itemStack : items) {
|
||||
ItemStack itemToSearchClone = itemStack.clone();
|
||||
itemToSearchClone.setAmount(1);
|
||||
if(itemInInventoryClone == itemToSearchClone && ((item.getAmount() + itemStack.getAmount()) <= 64)) {
|
||||
amountOpen++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return amountOpen >= items.size();
|
||||
|
||||
}
|
||||
|
||||
public static void giveItemToPlayer(Player player, ItemStack itemStack) {
|
||||
if (!InventoryUtils.hasAvailableSlot(player)) {
|
||||
player.getWorld().dropItemNaturally(player.getLocation(), itemStack);
|
||||
} else {
|
||||
player.getInventory().addItem(itemStack);
|
||||
}
|
||||
}
|
||||
|
||||
public static int fitSize(int size) {
|
||||
return size <= 9 ? 9 : (size <= 18 ? 18 : (size <= 27 ? 27 : (size <= 36 ? 36 : (size <= 45 ? 45 : (54)))));
|
||||
}
|
||||
|
||||
public static void giveItemToPlayer(Player player, List<ItemStack> itemStacks) {
|
||||
for (ItemStack itemStack : itemStacks) {
|
||||
giveItemToPlayer(player, itemStack);
|
||||
}
|
||||
}
|
||||
|
||||
public static void giveItemToPlayer(Player player, ItemStack[] itemStacks) {
|
||||
for (ItemStack itemStack : itemStacks) {
|
||||
giveItemToPlayer(player, itemStack);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isEmptyInventory(Player player) {
|
||||
if(isWearingArmor(player)) return false;
|
||||
|
||||
Inventory inv = player.getInventory();
|
||||
for (ItemStack item : inv.getContents()) {
|
||||
if(!ItemUtils.isAirOrNull(item)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isWearingArmor(Player player) {
|
||||
PlayerInventory playerInventory = player.getInventory();
|
||||
if(playerInventory.getHelmet() != null) return true;
|
||||
if(playerInventory.getChestplate() != null) return true;
|
||||
if(playerInventory.getLeggings() != null) return true;
|
||||
return playerInventory.getBoots() != null;
|
||||
}
|
||||
|
||||
public static void clearInventory(Player player) {
|
||||
|
||||
if (!ItemUtils.isAirOrNull(player.getInventory().getBoots())) {
|
||||
ArmorEquipEvent bootsArmorUnEquipEvent = new ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.SHIFT_CLICK, ArmorType.BOOTS, player.getInventory().getBoots(), new ItemStack(Material.AIR));
|
||||
Bukkit.getServer().getPluginManager().callEvent(bootsArmorUnEquipEvent);
|
||||
}
|
||||
|
||||
if (!ItemUtils.isAirOrNull(player.getInventory().getLeggings())) {
|
||||
ArmorEquipEvent leggingsArmorUnEquipEvent = new ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.SHIFT_CLICK, ArmorType.LEGGINGS, player.getInventory().getLeggings(), new ItemStack(Material.AIR));
|
||||
Bukkit.getServer().getPluginManager().callEvent(leggingsArmorUnEquipEvent);
|
||||
}
|
||||
|
||||
if (!ItemUtils.isAirOrNull(player.getInventory().getChestplate())) {
|
||||
ArmorEquipEvent chestplateArmorUnEquipEvent = new ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.SHIFT_CLICK, ArmorType.CHESTPLATE, player.getInventory().getChestplate(), new ItemStack(Material.AIR));
|
||||
Bukkit.getServer().getPluginManager().callEvent(chestplateArmorUnEquipEvent);
|
||||
}
|
||||
|
||||
if (!ItemUtils.isAirOrNull(player.getInventory().getHelmet())) {
|
||||
ArmorEquipEvent helmetArmorUnEquipEvent = new ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.SHIFT_CLICK, ArmorType.HELMET, player.getInventory().getHelmet(), new ItemStack(Material.AIR));
|
||||
Bukkit.getServer().getPluginManager().callEvent(helmetArmorUnEquipEvent);
|
||||
}
|
||||
|
||||
player.getInventory().clear();
|
||||
player.getInventory().setArmorContents(new ItemStack[4]);
|
||||
|
||||
PotionEffectUtils.clearPlayerEffects(player);
|
||||
CrankedUtils.getInstance().getPotionManager().getCrankedPotionPlayer(player.getUniqueId()).getPotionCacheMap().clear();
|
||||
player.getActivePotionEffects().clear();
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
|
||||
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import net.minecraft.server.v1_8_R3.IChatBaseComponent;
|
||||
import net.minecraft.server.v1_8_R3.PacketPlayOutChat;
|
||||
import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.json.simple.JSONArray;
|
||||
|
||||
public class JSONMessage {
|
||||
private JsonObject json;
|
||||
private final JsonParser parser = new JsonParser();
|
||||
|
||||
public JSONMessage() {
|
||||
this.initiateData();
|
||||
}
|
||||
|
||||
public JSONMessage(String text) {
|
||||
this.initiateData();
|
||||
this.json.addProperty("text", text);
|
||||
}
|
||||
|
||||
public JSONMessage(String text, ChatColor color) {
|
||||
this.initiateData();
|
||||
this.json.addProperty("text", text);
|
||||
this.json.addProperty("color", color.name().toLowerCase());
|
||||
}
|
||||
|
||||
public static String getDisplayEnchantName(String name) {
|
||||
switch (name.toLowerCase()) {
|
||||
case "protection_environmental": {
|
||||
return "Protection";
|
||||
}
|
||||
case "protection_explosions": {
|
||||
return "Blast Protection";
|
||||
}
|
||||
case "protection_fall": {
|
||||
return "Feathing Falling";
|
||||
}
|
||||
case "protection_fire": {
|
||||
return "Fire Protection";
|
||||
}
|
||||
case "fire_aspect": {
|
||||
return "Fire Aspect";
|
||||
}
|
||||
case "durability": {
|
||||
return "Unbreaking";
|
||||
}
|
||||
case "dig_speed": {
|
||||
return "Efficiency";
|
||||
}
|
||||
case "arrow_infinite": {
|
||||
return "Infinity";
|
||||
}
|
||||
case "arrow_damage": {
|
||||
return "Power";
|
||||
}
|
||||
case "arrow_fire": {
|
||||
return "Flame";
|
||||
}
|
||||
case "arrow_knockback": {
|
||||
return "Punch";
|
||||
}
|
||||
case "loot_bonus_blocks": {
|
||||
return "Fortune";
|
||||
}
|
||||
case "silk_touch": {
|
||||
return "Silk Touch";
|
||||
}
|
||||
case "knockback": {
|
||||
return "Knockback";
|
||||
}
|
||||
case "damage_all": {
|
||||
return "Sharpness";
|
||||
}
|
||||
case "damage_undead": {
|
||||
return "Smite";
|
||||
}
|
||||
case "damage_arthropods": {
|
||||
return "Bane of Arthropods";
|
||||
}
|
||||
case "protection_projectile": {
|
||||
return "Projectile Protection";
|
||||
}
|
||||
case "oxygen": {
|
||||
return "Resperation";
|
||||
}
|
||||
case "water_worker": {
|
||||
return "Aqua Affinity";
|
||||
}
|
||||
case "thorns": {
|
||||
return "Thorns";
|
||||
}
|
||||
case "loot_bonus_mobs": {
|
||||
return "Looting";
|
||||
}
|
||||
case "depth_strider": {
|
||||
return "Depth Strider";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String getNumber(int i) {
|
||||
if (i > 10) {
|
||||
return i + "";
|
||||
}
|
||||
if (i == 1) {
|
||||
return "I";
|
||||
}
|
||||
if (i == 2) {
|
||||
return "II";
|
||||
}
|
||||
if (i == 3) {
|
||||
return "III";
|
||||
}
|
||||
if (i == 4) {
|
||||
return "IV";
|
||||
}
|
||||
if (i == 5) {
|
||||
return "V";
|
||||
}
|
||||
if (i == 6) {
|
||||
return "VI";
|
||||
}
|
||||
if (i == 7) {
|
||||
return "VII";
|
||||
}
|
||||
if (i == 8) {
|
||||
return "VIII";
|
||||
}
|
||||
if (i == 9) {
|
||||
return "IX";
|
||||
}
|
||||
if (i == 10) {
|
||||
return "X";
|
||||
}
|
||||
return i + "";
|
||||
}
|
||||
|
||||
private void initiateData() {
|
||||
this.json = new JsonObject();
|
||||
this.json.add("extra", new JsonArray());
|
||||
}
|
||||
|
||||
private JsonArray getExtra() {
|
||||
if (!this.json.has("extra")) {
|
||||
this.json.add("extra", new JsonArray());
|
||||
}
|
||||
return (JsonArray) this.json.get("extra");
|
||||
}
|
||||
|
||||
public void addText(String text) {
|
||||
this.addText(null, text, ChatColor.WHITE);
|
||||
}
|
||||
|
||||
public void addText(Player pl, String text, ChatColor color) {
|
||||
JsonObject data = new JsonObject();
|
||||
data.addProperty("text", text);
|
||||
data.addProperty("color", color.name().toLowerCase());
|
||||
if (pl != null && pl.hasPermission("arkhamnetwork.joker_perks")) {
|
||||
data.addProperty("bold", Boolean.valueOf(true));
|
||||
}
|
||||
this.getExtra().add(data);
|
||||
}
|
||||
|
||||
public void addInsertionText(String text, ChatColor color, String insertion) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
o.addProperty("insertion", insertion);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addURL(String text, ChatColor color, String url) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject u = new JsonObject();
|
||||
u.addProperty("action", "open_url");
|
||||
u.addProperty("value", url);
|
||||
o.add("clickEvent", u);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addItem(ItemStack item, String text) {
|
||||
this.addItem(item, text, ChatColor.WHITE);
|
||||
}
|
||||
|
||||
public void addHoverData(String text, String data) {
|
||||
this.addHoverData(text, data, ChatColor.RESET);
|
||||
}
|
||||
|
||||
public void addHoverData(String text, String data, ChatColor color) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject a = new JsonObject();
|
||||
a.addProperty("action", "show_text");
|
||||
a.addProperty("value", data);
|
||||
o.add("hoverEvent", a);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addHoverData(String text, String data, String URL2, ChatColor color) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject a = new JsonObject();
|
||||
a.addProperty("action", "show_text");
|
||||
a.addProperty("value", data);
|
||||
o.add("hoverEvent", a);
|
||||
JsonObject u = new JsonObject();
|
||||
u.addProperty("action", "open_url");
|
||||
u.addProperty("value", URL2);
|
||||
o.add("clickEvent", u);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addRunCommand(String text, ChatColor color, String cmd, String hoverData) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject u = new JsonObject();
|
||||
u.addProperty("action", "run_command");
|
||||
u.addProperty("value", cmd);
|
||||
o.add("clickEvent", u);
|
||||
JsonObject a = new JsonObject();
|
||||
a.addProperty("action", "show_text");
|
||||
a.addProperty("value", hoverData);
|
||||
o.add("hoverEvent", a);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addItem(ItemStack item, String text, ChatColor color) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsItem;
|
||||
if (item == null || item.getType() == Material.AIR) {
|
||||
return;
|
||||
}
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject a = new JsonObject();
|
||||
a.addProperty("action", "show_item");
|
||||
JsonObject i = new JsonObject();
|
||||
i.addProperty("id", item.getTypeId());
|
||||
i.addProperty("Damage", item.getDurability());
|
||||
JsonObject x = new JsonObject();
|
||||
boolean added = false;
|
||||
if (item.getType() == Material.POTION && (nmsItem = CraftItemStack.asNMSCopy(item)).getTag() != null && nmsItem.getTag().hasKey("CustomPotionEffects")) {
|
||||
x.addProperty("CustomPotionEffects", nmsItem.getTag().get("CustomPotionEffects").toString());
|
||||
added = true;
|
||||
}
|
||||
if (item.getItemMeta() != null && (item.getItemMeta().getDisplayName() != null || item.getItemMeta().getLore() != null && item.getItemMeta().getLore().size() > 0 || item.getEnchantments() != null)) {
|
||||
JsonObject v = new JsonObject();
|
||||
ItemMeta m = item.getItemMeta();
|
||||
if (m.hasEnchants()) {
|
||||
// empty if block
|
||||
}
|
||||
if (m.getDisplayName() != null) {
|
||||
v.addProperty("Name", m.getDisplayName().replace(",", " the"));
|
||||
}
|
||||
if (m.getLore() != null || item.getEnchantments() != null) {
|
||||
v.addProperty("Lore", "%LORE%");
|
||||
}
|
||||
x.add("display", v);
|
||||
i.add("tag", x);
|
||||
} else if (added) {
|
||||
i.add("tag", x);
|
||||
}
|
||||
String is = i.toString();
|
||||
is = is.replace("\"", "");
|
||||
if (is.contains("%LORE%")) {
|
||||
ArrayList<String> lor = new ArrayList<String>();
|
||||
if (item.getItemMeta().hasEnchants()) {
|
||||
lor.addAll(this.getEnchantsAsList(item.getEnchantments()));
|
||||
}
|
||||
if (item.getItemMeta().getLore() != null) {
|
||||
for (String lore : item.getItemMeta().getLore()) {
|
||||
if (lore.isEmpty()) {
|
||||
lore = " ";
|
||||
}
|
||||
lor.add(lore.replace(",", ""));
|
||||
}
|
||||
}
|
||||
String lore = JSONArray.toJSONString(lor);
|
||||
lore = lore.replace(":", "|");
|
||||
lore = lore.replace("\"", "");
|
||||
lore = lore.replace("\\", "");
|
||||
lore = lore.replace(",0", "0").replace(",1", "1").replace(",2", "2").replace(",3", "3").replace(",4", "4").replace(",5", "5").replace(",6", "6").replace(",7", "7").replace(",8", "8").replace(",9", "9");
|
||||
is = is.replace("%LORE%", lore);
|
||||
}
|
||||
a.addProperty("value", is);
|
||||
o.add("hoverEvent", a);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public List<String> getEnchantsAsList(Map<Enchantment, Integer> map) {
|
||||
ArrayList<String> lore = new ArrayList<String>();
|
||||
for (Map.Entry<Enchantment, Integer> entry : map.entrySet()) {
|
||||
lore.add(ChatColor.GRAY + org.apache.commons.lang3.StringUtils.capitalize(JSONMessage.getDisplayEnchantName(entry.getKey().getName())) + " " + JSONMessage.getNumber(entry.getValue()));
|
||||
}
|
||||
return lore;
|
||||
}
|
||||
|
||||
public void addSuggestCommand(String text, ChatColor color, String cmd) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject u = new JsonObject();
|
||||
u.addProperty("action", "suggest_command");
|
||||
u.addProperty("value", cmd);
|
||||
o.add("clickEvent", u);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public void addRunCommand(String text, ChatColor color, String cmd) {
|
||||
JsonObject o = new JsonObject();
|
||||
o.addProperty("text", text);
|
||||
o.addProperty("color", color.name().toLowerCase());
|
||||
JsonObject u = new JsonObject();
|
||||
u.addProperty("action", "run_command");
|
||||
u.addProperty("value", cmd);
|
||||
o.add("clickEvent", u);
|
||||
this.getExtra().add(o);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.json.toString();
|
||||
}
|
||||
|
||||
public void sendToPlayer(Player p) {
|
||||
((CraftPlayer) p).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a(this.json.toString()), (byte) 0));
|
||||
}
|
||||
|
||||
public void setColor(ChatColor color) {
|
||||
this.json.addProperty("color", color.name().toLowerCase());
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.json.addProperty("text", text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class JSONUtils {
|
||||
public static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
|
||||
|
||||
public static File getOrCreateFile(File parent, String string) throws IOException {
|
||||
File f;
|
||||
if (!parent.exists()) {
|
||||
parent.mkdir();
|
||||
Bukkit.getLogger().info("Creating directory " + parent.getName());
|
||||
}
|
||||
if (!(f = new File(parent, string)).exists()) {
|
||||
Bukkit.getLogger().info("Creating new file " + string + " due to it not existing!");
|
||||
f.createNewFile();
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
public static File getOrCreateFile(String fileName) throws IOException {
|
||||
File f = new File(fileName);
|
||||
if (!f.exists()) {
|
||||
Bukkit.getLogger().info("Creating new file " + fileName + " due to it not existing!");
|
||||
f.createNewFile();
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
public static Object fromJson(String fileName, Object token) throws IOException {
|
||||
File f = JSONUtils.getOrCreateFile(fileName);
|
||||
return JSONUtils.fromJson(f, token);
|
||||
}
|
||||
|
||||
public static Object fromJson(File f, Object clazz) throws FileNotFoundException {
|
||||
return gson.fromJson(new FileReader(f), JSONUtils.getTypeFromObject(clazz));
|
||||
}
|
||||
|
||||
public static Object fromJson(File f, Object clazz, Object defaultObj) throws FileNotFoundException {
|
||||
Object retr = gson.fromJson(new FileReader(f), JSONUtils.getTypeFromObject(clazz));
|
||||
if (retr == null) {
|
||||
return defaultObj;
|
||||
}
|
||||
return retr;
|
||||
}
|
||||
|
||||
public static Object fromJson(File f, Type token) throws FileNotFoundException {
|
||||
return JSONUtils.fromJson(f, token, gson);
|
||||
}
|
||||
|
||||
public static Object fromJson(File f, Type token, Gson gson) throws FileNotFoundException {
|
||||
return gson.fromJson(new FileReader(f), token);
|
||||
}
|
||||
|
||||
public static String toJSON(Object object, Object token) {
|
||||
return JSONUtils.toJSON(object, token, gson);
|
||||
}
|
||||
|
||||
public static String toJSON(Object object, Object token, Gson gson) {
|
||||
return gson.toJson(object, JSONUtils.getTypeFromObject(token));
|
||||
}
|
||||
|
||||
public static boolean saveJSONToFile(String fileName, Object toSave, Object token) throws IOException {
|
||||
return JSONUtils.saveJSONToFile(JSONUtils.getOrCreateFile(fileName), toSave, token);
|
||||
}
|
||||
|
||||
public static boolean saveJSONToFile(File f, Object toSave, Object token, Gson gson) throws IOException {
|
||||
String str = JSONUtils.toJSON(toSave, token, gson);
|
||||
FileWriter writer = new FileWriter(f);
|
||||
writer.write(str);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean saveJSONToFile(File f, Object toSave, Object token) throws IOException {
|
||||
return JSONUtils.saveJSONToFile(f, toSave, token, gson);
|
||||
}
|
||||
|
||||
private static Type getTypeFromObject(Object object) {
|
||||
return object instanceof Type ? (Type) object : JSONUtils.getTypeFromClass(object.getClass());
|
||||
}
|
||||
|
||||
private static Type getTypeFromClass(Class<?> clazz) {
|
||||
return TypeToken.of(clazz).getType();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class LocationUtils {
|
||||
public static Location getNearbyLocation(Location l, int radius, int minDistance, int yBoost) {
|
||||
Random rand = new Random();
|
||||
Location rand_loc = l.clone();
|
||||
rand_loc.add((rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + minDistance), 0.0, (rand.nextBoolean() ? 1 : -1) * (rand.nextInt(radius) + minDistance));
|
||||
rand_loc.add(0.5, yBoost, 0.5);
|
||||
Block b = rand_loc.getWorld().getHighestBlockAt(rand_loc).getLocation().getBlock();
|
||||
return (double) b.getY() < rand_loc.getY() ? b.getLocation() : rand_loc;
|
||||
}
|
||||
|
||||
public static String locationToFancy(Location location) {
|
||||
return "[" + location.getWorld().getName() + "," + Math.round(location.getX()) + "," + Math.round(location.getY()) + "," + Math.round(location.getZ()) + "]";
|
||||
}
|
||||
|
||||
public static String locationToFancySav(Location location) {
|
||||
return "X: " + Math.round(location.getX()) + " Y: " + Math.round(location.getY()) + " Z: " + Math.round(location.getZ());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.LuckPermsProvider;
|
||||
import net.luckperms.api.model.data.NodeMap;
|
||||
import net.luckperms.api.model.group.Group;
|
||||
import net.luckperms.api.model.user.User;
|
||||
import net.luckperms.api.model.user.UserManager;
|
||||
import net.luckperms.api.node.Node;
|
||||
import net.luckperms.api.node.NodeType;
|
||||
import net.luckperms.api.node.types.InheritanceNode;
|
||||
import net.luckperms.api.track.Track;
|
||||
import net.luckperms.api.track.TrackManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LuckpermUtils {
|
||||
public static RegisteredServiceProvider<LuckPerms> provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class);
|
||||
public static LuckPerms luckPerms = provider.getProvider();
|
||||
public static UserManager lpUserManager = LuckPermsProvider.get().getUserManager();
|
||||
public static TrackManager lpTrackManager = LuckPermsProvider.get().getTrackManager();
|
||||
|
||||
|
||||
|
||||
public static boolean playerHasRank(Player player, String rank) {
|
||||
List<String> ranks = LuckpermUtils.getRanks(player);
|
||||
if(ranks.isEmpty()) return false;
|
||||
return ranks.contains(rank);
|
||||
}
|
||||
|
||||
public static User getLpUser(Player player) {
|
||||
return lpUserManager.getUser(player.getUniqueId());
|
||||
}
|
||||
|
||||
|
||||
public static String getDisplayName(Player player) {
|
||||
return CC.translate(Objects.requireNonNull(lpUserManager.getUser(player.getUniqueId())).getCachedData().getMetaData().getPrefix() + " " + player.getName());
|
||||
}
|
||||
|
||||
public static String getRankPrefix(Player player) {
|
||||
return Objects.requireNonNull(lpUserManager.getUser(player.getUniqueId())).getCachedData().getMetaData().getPrefix();
|
||||
}
|
||||
|
||||
public static String getDisplayName(Group group) {
|
||||
return group.getDisplayName();
|
||||
}
|
||||
|
||||
public static boolean hasPermissions(Player player, String ...permissions) {
|
||||
return hasPermissions(player, Arrays.asList(permissions));
|
||||
}
|
||||
|
||||
public static boolean hasPermissions(Player player, List<String> permissions) {
|
||||
return permissions.stream().allMatch(player::hasPermission);
|
||||
}
|
||||
|
||||
public static void addPermissions(Player player, long expiryTime, String ...permissions) {
|
||||
addPermissions(player, Arrays.asList(permissions), expiryTime);
|
||||
}
|
||||
|
||||
public static void addPermissions(Player player, String ...permissions) {
|
||||
addPermissions(player, Arrays.asList(permissions));
|
||||
}
|
||||
|
||||
public static void addPermissions(Player player, List<String> permissions) {
|
||||
User user = getLpUser(player);
|
||||
if (user == null) return;
|
||||
|
||||
NodeMap userData = user.data();
|
||||
permissions.forEach(perm -> userData.add(Node.builder(perm).build()));
|
||||
lpUserManager.saveUser(user);
|
||||
}
|
||||
|
||||
public static void addPermissions(Player player, List<String> permissions, long expiryTime) {
|
||||
User user = getLpUser(player);
|
||||
if (user == null) return;
|
||||
|
||||
NodeMap userData = user.data();
|
||||
permissions.forEach(perm -> userData.add(Node.builder(perm)
|
||||
.expiry(Duration.ofSeconds(expiryTime))
|
||||
.build()));
|
||||
lpUserManager.saveUser(user);
|
||||
}
|
||||
|
||||
public static boolean hasRanks(Player player, String ...ranks) {
|
||||
return hasRanks(player, Arrays.asList(ranks));
|
||||
}
|
||||
|
||||
public static boolean hasRanks(Player player, List<String> ranks) {
|
||||
List<String> currentRanks = getRanks(player).stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||
ranks = ranks.stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||
return currentRanks.containsAll(ranks);
|
||||
}
|
||||
|
||||
public static List<String> getRanks(Player player) {
|
||||
User user = getLpUser(player);
|
||||
if (user == null) return new ArrayList<>();
|
||||
|
||||
return user.getNodes(NodeType.INHERITANCE).stream()
|
||||
.map(InheritanceNode::getGroupName)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static void addRanks(Player player, long expiryTime, String ...ranks) {
|
||||
addRanks(player, Arrays.asList(ranks), expiryTime);
|
||||
}
|
||||
|
||||
public static void addRanks(Player player, String ...ranks) {
|
||||
addRanks(player, Arrays.asList(ranks));
|
||||
}
|
||||
|
||||
public static void addRanks(Player player, List<String> ranks) {
|
||||
User user = getLpUser(player);
|
||||
if (user == null) return;
|
||||
|
||||
NodeMap userData = user.data();
|
||||
ranks.forEach(rank -> userData.add(InheritanceNode.builder(rank).build()));
|
||||
lpUserManager.saveUser(user);
|
||||
}
|
||||
|
||||
public static void addRanks(Player player, List<String> ranks, long expiryTime) {
|
||||
User user = getLpUser(player);
|
||||
if (user == null) return;
|
||||
|
||||
NodeMap userData = user.data();
|
||||
ranks.forEach(rank -> userData.add(InheritanceNode.builder(rank)
|
||||
.expiry(Duration.ofSeconds(expiryTime))
|
||||
.build()));
|
||||
lpUserManager.saveUser(user);
|
||||
}
|
||||
|
||||
public static Group getGroup(String rankName) {
|
||||
return luckPerms.getGroupManager().getGroup(rankName);
|
||||
}
|
||||
|
||||
public static Track getTrackFromGroup(Group group) {
|
||||
for (Track track : lpTrackManager.getLoadedTracks()) {
|
||||
if (track.containsGroup(group)) return track;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean hasHigherRank(Player player, String rank) {
|
||||
Group targetGroup = getGroup(rank);
|
||||
if (!targetGroup.getWeight().isPresent()) return true;
|
||||
|
||||
int targetWeight = targetGroup.getWeight().getAsInt();
|
||||
Track targetTrack = getTrackFromGroup(targetGroup);
|
||||
|
||||
for (String rankName : getRanks(player)) {
|
||||
Group group = getGroup(rankName);
|
||||
if (targetTrack != getTrackFromGroup(group) || !group.getWeight().isPresent()) continue;
|
||||
if (group.getWeight().getAsInt() > targetWeight) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class MessageUtils {
|
||||
|
||||
public static void sendSuccessMessage(Player player, String message) {
|
||||
sendSuccessMessage(player, message, true);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(Player player, String message, boolean sound) {
|
||||
player.sendMessage(CC.translate("&a&l(!) " + message));
|
||||
if(sound) player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F);
|
||||
}
|
||||
|
||||
public static void sendErrorMessage(Player player, String message) {
|
||||
sendErrorMessage(player, message, true);
|
||||
}
|
||||
|
||||
public static void sendErrorMessage(Player player, String message, boolean sound) {
|
||||
player.sendMessage(CC.translate("&c&l(!) " + message));
|
||||
if(sound) player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MiscUtils {
|
||||
|
||||
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
|
||||
Preconditions.checkNotNull(enumClass);
|
||||
Preconditions.checkNotNull(value);
|
||||
|
||||
try {
|
||||
return Optional.of(Enum.valueOf(enumClass, value));
|
||||
} catch (IllegalArgumentException var3) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T defaultIfNull(T val, T def) {
|
||||
return val != null ? val : def;
|
||||
}
|
||||
|
||||
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
|
||||
return first != null ? first : Preconditions.checkNotNull(second);
|
||||
}
|
||||
|
||||
public static String toNiceString(String string) {
|
||||
string = ChatColor.stripColor(string).replace('_', ' ').toLowerCase();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < string.toCharArray().length; ++i) {
|
||||
char c = string.toCharArray()[i];
|
||||
if (i > 0) {
|
||||
char prev = string.toCharArray()[i - 1];
|
||||
if ((prev == ' ' || prev == '[' || prev == '(') && (i == string.toCharArray().length - 1 || c != 'x' || !Character.isDigit(string.toCharArray()[i + 1]))) {
|
||||
c = Character.toUpperCase(c);
|
||||
}
|
||||
} else if (c != 'x' || !Character.isDigit(string.toCharArray()[i + 1])) {
|
||||
c = Character.toUpperCase(c);
|
||||
}
|
||||
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import net.minecraft.server.v1_8_R3.NBTTagCompound;
|
||||
import net.minecraft.server.v1_8_R3.NBTTagString;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class NbtWrapper {
|
||||
|
||||
public static boolean hasNBTTag(ItemStack item, String key) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = nmsStack.getTag();
|
||||
if (tagCompound == null) return false;
|
||||
if (tagCompound.getString(key).equalsIgnoreCase("")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return tagCompound.getString(key) != null;
|
||||
}
|
||||
|
||||
public static ItemStack setNBTTag(ItemStack item, String tagName, String value) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
|
||||
tagCompound.set(tagName, new NBTTagString(value));
|
||||
item = CraftItemStack.asBukkitCopy(nmsStack);
|
||||
return item;
|
||||
}
|
||||
|
||||
public static String getNBTTag(ItemStack item, String key) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = nmsStack.getTag();
|
||||
if (tagCompound == null) return null;
|
||||
return tagCompound.getString(key);
|
||||
}
|
||||
|
||||
public static boolean hasCompound(ItemStack item, String compound) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
if (!nmsStack.hasTag()) return false;
|
||||
NBTTagCompound tagCompound = nmsStack.getTag().getCompound(compound);
|
||||
return tagCompound != null;
|
||||
}
|
||||
|
||||
public static Set<String> getKeysFromCompound(ItemStack item, String compound) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = nmsStack.getTag().getCompound(compound);
|
||||
return tagCompound.c();
|
||||
}
|
||||
|
||||
public static boolean hasKeyInCompound(ItemStack item, String compound, String key) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
if (!nmsStack.hasTag()) return false;
|
||||
NBTTagCompound tagCompound = nmsStack.getTag().getCompound(compound);
|
||||
if (tagCompound == null) return false;
|
||||
return tagCompound.hasKey(key);
|
||||
}
|
||||
|
||||
public static String getStringFromCompound(ItemStack item, String compound, String key) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = nmsStack.getTag().getCompound(compound);
|
||||
return tagCompound.getString(key);
|
||||
}
|
||||
|
||||
public static Integer getIntegerFromCompound(ItemStack item, String compound, String key) {
|
||||
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
|
||||
NBTTagCompound tagCompound = nmsStack.getTag().getCompound(compound);
|
||||
return tagCompound.getInt(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
public final class NmsUtils {
|
||||
|
||||
private NmsUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static Object getPrivateField(String fieldName, Class<?> clazz, Object object) {
|
||||
Field field;
|
||||
Object o = null;
|
||||
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldName);
|
||||
|
||||
field.setAccessible(true);
|
||||
|
||||
o = field.get(object);
|
||||
}
|
||||
catch(NoSuchFieldException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return o;
|
||||
}
|
||||
|
||||
public static Class<?> getNMSClass(String className){
|
||||
try {
|
||||
String fullName = "net.minecraft.server." + getVersion() + className;
|
||||
Class<?> clazz = Class.forName(fullName);
|
||||
return clazz;
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getVersion(){
|
||||
String name = Bukkit.getServer().getClass().getPackage().getName();
|
||||
return name.substring(name.lastIndexOf('.') + 1) + ".";
|
||||
}
|
||||
|
||||
public static Class<?> getCraftClass(String className){
|
||||
try {
|
||||
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
|
||||
Class<?> clazz = Class.forName(fullName);
|
||||
return clazz;
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static int getVersionNumber(){
|
||||
String name = getVersion().substring(3);
|
||||
return Integer.parseInt(name.substring(0, name.length() - 4));
|
||||
}
|
||||
|
||||
public static int getVersionReleaseNumber(){
|
||||
String NMSVersion = getVersion();
|
||||
return Integer.parseInt(NMSVersion.substring(NMSVersion.length() - 2).replace(".", ""));
|
||||
}
|
||||
|
||||
public static Field getField(Class<?> clazz, String name, boolean declared){
|
||||
try {
|
||||
Field field;
|
||||
if(declared) {
|
||||
field = clazz.getDeclaredField(name);
|
||||
} else{
|
||||
field = clazz.getField(name);
|
||||
}
|
||||
field.setAccessible(true);
|
||||
return field;
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object getFieldObject(Object object, Field field){
|
||||
try {
|
||||
return field.get(object);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setField(Object object, String fieldName, Object fieldValue, boolean declared){
|
||||
try {
|
||||
Field field;
|
||||
if(declared) {
|
||||
field = object.getClass().getDeclaredField(fieldName);
|
||||
} else{
|
||||
field = object.getClass().getField(fieldName);
|
||||
}
|
||||
field.setAccessible(true);
|
||||
field.set(object, fieldValue);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendPacket(Player player, Object packet){
|
||||
try {
|
||||
Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player);
|
||||
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
|
||||
playerConnection.getClass().getMethod("sendPacket", new Class[]{getNMSClass("Packet")}).invoke(playerConnection, packet);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.NumberFormat;
|
||||
|
||||
public class NumberUtils {
|
||||
|
||||
private static final NumberFormat nf = NumberFormat.getIntegerInstance();
|
||||
|
||||
public static String formatMoney(double amount) {
|
||||
return new DecimalFormat("#,##0").format(new BigDecimal(amount));
|
||||
}
|
||||
|
||||
public static String formatNum(int number) {
|
||||
return nf.format(number);
|
||||
}
|
||||
|
||||
public static String formatNum(long number) {
|
||||
return nf.format(number);
|
||||
}
|
||||
|
||||
public static String formatNum(double number) {
|
||||
return nf.format(number);
|
||||
}
|
||||
|
||||
public static String formatNum(float number) {
|
||||
return nf.format(number);
|
||||
}
|
||||
|
||||
public static double round (double value, int precision) {
|
||||
int scale = (int) Math.pow(10, precision);
|
||||
return (double) Math.round(value * scale) / scale;
|
||||
}
|
||||
|
||||
private static final String[] suffix = new String[]{"","k", "m", "b", "t"};
|
||||
private static final int MAX_LENGTH = 4;
|
||||
|
||||
public static String coolFormat(double number) {
|
||||
String r = new DecimalFormat("##0E0").format(number);
|
||||
r = r.replaceAll("E[0-9]", suffix[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]);
|
||||
while(r.length() > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]")){
|
||||
r = r.substring(0, r.length()-2) + r.substring(r.length() - 1);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
public static double getValueFromFormat(String formatted_value) {
|
||||
String numb_val = ChatColor.stripColor(formatted_value.replaceAll(",", "").replace("$", "")).toLowerCase();
|
||||
numb_val = numb_val.replace("k", "000");
|
||||
numb_val = numb_val.replace("million", "000000");
|
||||
numb_val = numb_val.replace("billion", "000000000");
|
||||
numb_val = numb_val.replace("trillion", "000000000000");
|
||||
numb_val = numb_val.replace("mil", "000000");
|
||||
numb_val = numb_val.replace("bil", "000000000");
|
||||
numb_val = numb_val.replace("tril", "000000000000");
|
||||
numb_val = numb_val.replace("m", "000000");
|
||||
numb_val = numb_val.replace("b", "000000000");
|
||||
numb_val = numb_val.replace("t", "000000000000");
|
||||
try {
|
||||
return Long.parseLong(numb_val);
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class PVPUtils {
|
||||
|
||||
private PVPUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static boolean canPVP(Player firstPlayer, LivingEntity secondEntity) {
|
||||
if (!(secondEntity instanceof Player)) return true;
|
||||
Player secondPlayer = (Player) secondEntity;
|
||||
if (!WorldGuardUtils.canPvPInRegion(firstPlayer.getLocation())) return false;
|
||||
if (!WorldGuardUtils.canPvPInRegion(secondEntity.getLocation())) return false;
|
||||
if (firstPlayer.getWorld().getName().equals("tournament_world") && secondPlayer.getWorld().getName().equals("tournament_world") ) return true;
|
||||
return FactionUtils.canPvP(firstPlayer, secondPlayer);
|
||||
}
|
||||
|
||||
public static boolean canPvPInRegion(Player player) {
|
||||
return WorldGuardUtils.canPvPInRegion(player.getLocation());
|
||||
}
|
||||
|
||||
public static boolean isCritical(Player p) {
|
||||
boolean isCritical = p.getFallDistance() > 0.0F && !p.isOnGround() && p.getVehicle() == null;
|
||||
//(p.getVelocity().getY() + 0.0784000015258789) <= 0
|
||||
return isCritical;
|
||||
}
|
||||
|
||||
public static boolean canPvPInRegion(Location location) {
|
||||
return WorldGuardUtils.canPvPInRegion(location);
|
||||
}
|
||||
|
||||
public static List<Player> getNearbyPlayers(Player player, int radius) {
|
||||
List<Player> nearbyPlayers = new ArrayList<>();
|
||||
nearbyPlayers.add(player);
|
||||
for (Entity nearbyEntity : player.getNearbyEntities(radius, radius, radius)) {
|
||||
if (nearbyEntity instanceof Player)
|
||||
nearbyPlayers.add((Player) nearbyEntity);
|
||||
}
|
||||
|
||||
return nearbyPlayers;
|
||||
}
|
||||
|
||||
public static List<Player> getNearbyPlayers(Location location, int radius) {
|
||||
List<Player> nearbyPlayers = new ArrayList<>();
|
||||
for (Entity nearbyEntity : location.getWorld().getNearbyEntities(location, radius, radius, radius)) {
|
||||
if (nearbyEntity instanceof Player)
|
||||
nearbyPlayers.add((Player) nearbyEntity);
|
||||
}
|
||||
return nearbyPlayers;
|
||||
}
|
||||
|
||||
|
||||
public static List<Player> getNearbyPlayersExceptPlayer(Player player, int radius) {
|
||||
List<Player> nearbyPlayers = new ArrayList<>();
|
||||
for (Entity nearbyEntity : player.getNearbyEntities(radius, radius, radius)) {
|
||||
if (nearbyEntity instanceof Player)
|
||||
nearbyPlayers.add((Player) nearbyEntity);
|
||||
}
|
||||
return nearbyPlayers;
|
||||
}
|
||||
|
||||
public static List<Player> getNearbyEnemyPlayers(Player player, int radius) {
|
||||
List<Player> nearbyPlayers = new ArrayList<>();
|
||||
nearbyPlayers.add(player);
|
||||
for (Entity nearbyEntity : player.getNearbyEntities(radius, radius, radius)) {
|
||||
if (nearbyEntity instanceof Player)
|
||||
nearbyPlayers.add((Player) nearbyEntity);
|
||||
}
|
||||
return nearbyPlayers;
|
||||
}
|
||||
|
||||
public static List<Player> getNearbyEnemyPlayersExceptPlayer(Player player, int radius) {
|
||||
List<Player> nearbyPlayers = new ArrayList<>();
|
||||
for (Entity nearbyEntity : player.getNearbyEntities(radius, radius, radius)) {
|
||||
if (nearbyEntity instanceof Player) {
|
||||
if (canPVP(player, (LivingEntity) nearbyEntity)) {
|
||||
nearbyPlayers.add((Player) nearbyEntity);
|
||||
}
|
||||
}
|
||||
}
|
||||
return nearbyPlayers;
|
||||
}
|
||||
|
||||
public static void strikeLightningCircle(Location location) {
|
||||
int circleRadius = 7; // Set the radius of the circle here
|
||||
int numStrikes = 10; // Number of lightning strikes around the player
|
||||
|
||||
double increment = 360.0 / numStrikes;
|
||||
|
||||
// Strike lightning in a circle around the player
|
||||
for (int i = 0; i < numStrikes; i++) {
|
||||
double angle = i * increment;
|
||||
double x = location.getX() + circleRadius * Math.cos(Math.toRadians(angle));
|
||||
double z = location.getZ() + circleRadius * Math.sin(Math.toRadians(angle));
|
||||
Location strikeLocation = new Location(location.getWorld(), x, location.getY(), z);
|
||||
location.getWorld().strikeLightning(strikeLocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class Pair<L, R> {
|
||||
|
||||
private L left;
|
||||
private R right;
|
||||
|
||||
public boolean contains(L value) {
|
||||
if (left == null && right == null) return false;
|
||||
return (left != null && left.equals(value)) || (right != null && right.equals(value));
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return left == null && right == null;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.setLeft(null);
|
||||
this.setRight(null);
|
||||
}
|
||||
|
||||
public static <A,B> Pair<A,B> with(final A value0, final B value1) {
|
||||
return new Pair<A,B>(value0,value1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class PlayerInventoryContents {
|
||||
|
||||
public ItemStack[] inventoryContents;
|
||||
public ItemStack[] armorContents;
|
||||
|
||||
public PlayerInventoryContents(ItemStack[] inventoryContents, ItemStack[] armorContents) {
|
||||
this.inventoryContents = inventoryContents.clone();
|
||||
this.armorContents = armorContents.clone();
|
||||
}
|
||||
|
||||
public void restoreInventory(Player player) {
|
||||
player.getInventory().setContents(this.inventoryContents);
|
||||
}
|
||||
|
||||
public void restoreArmor(Player player) {
|
||||
player.getInventory().setArmorContents(this.armorContents);
|
||||
}
|
||||
|
||||
public void restore(Player player) {
|
||||
restoreInventory(player);
|
||||
restoreArmor(player);
|
||||
player.updateInventory();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
|
||||
import io.netty.util.internal.ThreadLocalRandom;
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Item;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.metadata.FixedMetadataValue;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PlayerUtils {
|
||||
|
||||
public static void giveOrDropProtectedItem(Player player, ItemStack item, int protectionTimer) {
|
||||
if (player.getInventory().firstEmpty() != -1) {
|
||||
player.getInventory().addItem(item);
|
||||
return;
|
||||
}
|
||||
dropProtectedItem(player, player.getLocation(), item, protectionTimer);
|
||||
|
||||
}
|
||||
|
||||
public static int getSpoofedPing(Player player) {
|
||||
/*int ping = ((CraftPlayer) player).getHandle().ping;
|
||||
if (ping == 0) {
|
||||
ping = ThreadLocalRandom.current().nextInt(90, 150);
|
||||
} else if (ping > 80 && ping < 210) {
|
||||
ping = ThreadLocalRandom.current().nextInt(40, 80);
|
||||
|
||||
} else if
|
||||
(ping > 210) {
|
||||
ping = ThreadLocalRandom.current().nextInt(100, 140);
|
||||
}
|
||||
return ping;*/
|
||||
int ping = ((CraftPlayer) player).getHandle().ping;
|
||||
return ping < 45 ? ping : ping - 30;
|
||||
}
|
||||
|
||||
public static void dropProtectedItem(Player player, Location location, ItemStack itemStack, int protectionTimer) {
|
||||
Item itemEntity = location.getWorld().dropItem(location, itemStack);
|
||||
itemEntity.setMetadata("protectedItem", new FixedMetadataValue(CrankedUtils.getInstance(), protectionTimer == -1 ? (long) protectionTimer : System.currentTimeMillis() + (protectionTimer * 1000L)));
|
||||
itemEntity.setMetadata("protectedOwner", new FixedMetadataValue(CrankedUtils.getInstance(), player.getUniqueId().toString()));
|
||||
}
|
||||
|
||||
public static boolean isPlayerBehind(final Player player, final Entity theEntity) {
|
||||
Location playerLoc = player.getLocation();
|
||||
Location targetLoc = theEntity.getLocation();
|
||||
double pvecy = -Math.sin(Math.toRadians(playerLoc.getPitch()));
|
||||
double pvecx = -Math.cos(Math.toRadians(playerLoc.getPitch())) * Math.sin(Math.toRadians(playerLoc.getYaw()));
|
||||
double pvecz = Math.cos(Math.toRadians(playerLoc.getPitch())) * Math.cos(Math.toRadians(playerLoc.getYaw()));
|
||||
double tvecy = -Math.sin(Math.toRadians(targetLoc.getPitch()));
|
||||
double tvecx = -Math.cos(Math.toRadians(targetLoc.getPitch())) * Math.sin(Math.toRadians(targetLoc.getYaw()));
|
||||
double tvecz = Math.cos(Math.toRadians(targetLoc.getPitch())) * Math.cos(Math.toRadians(targetLoc.getYaw()));
|
||||
double dot = tvecx * pvecx + tvecy * pvecy + tvecz * pvecz;
|
||||
return dot > 0.6;
|
||||
}
|
||||
|
||||
public static List<Player> getNearbyPlayers(Player player, double radius) {
|
||||
return player.getNearbyEntities(radius, radius, radius).stream()
|
||||
.filter(entity -> entity instanceof Player)
|
||||
.map(entity -> (Player) entity)
|
||||
.filter(player::canSee)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static void teleportPlayerToClosestLocation(Player player) {
|
||||
Location location = player.getLocation().getBlock().getLocation();
|
||||
location.setX(location.getX() + 0.5);
|
||||
location.setZ(location.getZ() + 0.5);
|
||||
player.teleport(location);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public class PluginUtils {
|
||||
public static void registerListeners(JavaPlugin plugin, Listener... listeners) {
|
||||
for(Listener listener : listeners)
|
||||
Bukkit.getPluginManager().registerEvents(listener, plugin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import lombok.Getter;
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import net.crankedpvp.crankedutils.potion.PotionCache;
|
||||
import net.crankedpvp.crankedutils.potion.PotionManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class PotionEffectUtils implements Listener {
|
||||
|
||||
private static final PotionManager potionManager = CrankedUtils.getInstance().getPotionManager();
|
||||
|
||||
private PotionEffectUtils() {
|
||||
}
|
||||
|
||||
@Getter
|
||||
private static final Set<PotionEffectType> debuffsList = new HashSet<>(Arrays.asList(
|
||||
PotionEffectType.BLINDNESS,
|
||||
PotionEffectType.CONFUSION,
|
||||
PotionEffectType.HARM,
|
||||
PotionEffectType.SLOW,
|
||||
PotionEffectType.SLOW_DIGGING,
|
||||
PotionEffectType.WEAKNESS,
|
||||
PotionEffectType.WITHER,
|
||||
PotionEffectType.POISON
|
||||
));
|
||||
|
||||
public static void bless(Player player) {
|
||||
List<String> idsToRemove = new ArrayList<>();
|
||||
for (PotionCache potionCache : potionManager.getCrankedPotionPlayer(player.getUniqueId()).getPotionCacheMap().values()) {
|
||||
if (getDebuffsList().contains(potionCache.getType())) {
|
||||
idsToRemove.add(potionCache.getId());
|
||||
}
|
||||
}
|
||||
|
||||
for (String id : idsToRemove) {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).removePotionEffect(id);
|
||||
}
|
||||
|
||||
//Just to make sure we didn't miss one
|
||||
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
|
||||
if (getDebuffsList().contains(potionEffect.getType())) {
|
||||
player.removePotionEffect(potionEffect.getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void addPotionEffect(Player player, PotionEffectType type, int level, String id, int durationInSeconds) {
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), () -> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).addPotionEffect(type, level, durationInSeconds * 20, id);
|
||||
}, 1L);
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), ()-> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).removePotionEffect(id);
|
||||
}, (durationInSeconds* 20L) + 1);
|
||||
}
|
||||
|
||||
//This means, if player already has enchant x, it will add y to the level
|
||||
public static void addExtraPotionEffect(Player player, PotionEffectType type, int level, String id, int durationInSeconds) {
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), () -> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).addExtraPotionEffect(type, level, durationInSeconds * 20, id);
|
||||
}, 1L);
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), ()-> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).removePotionEffect(id);
|
||||
}, (durationInSeconds* 20L) + 1);
|
||||
}
|
||||
|
||||
//This means, if player already has enchant x, it will add y to the level
|
||||
public static void addExtraPotionEffect(Player player, PotionEffectType type, int level, String id) {
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), () -> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).addExtraPotionEffect(type, level, Integer.MAX_VALUE, id);
|
||||
}, 1L);
|
||||
|
||||
}
|
||||
|
||||
public static void addPotionEffect(Player player, PotionEffectType type, int level, String id) {
|
||||
Bukkit.getScheduler().runTaskLater(CrankedUtils.getInstance(), () -> {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).addPotionEffect(type, level, id);
|
||||
}, 1L);
|
||||
}
|
||||
|
||||
public static int getPlayerEffectLevel(Player player, PotionEffectType type) {
|
||||
for (PotionCache potionCache : potionManager.getCrankedPotionPlayer(player.getUniqueId()).getPotionCacheMap().values()) {
|
||||
if (potionCache.getType() == type) {
|
||||
return potionCache.getLevel();
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static boolean hasPotionEffect(Player player, String string) {
|
||||
for(PotionCache value : potionManager.getCrankedPotionPlayer(player.getUniqueId()).getPotionCacheMap().values()) {
|
||||
if(value.getId().equals(string)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void removePotionEffect(Player player, String id) {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).removePotionEffect(id);
|
||||
}
|
||||
|
||||
|
||||
public static void clearPlayerEffects(Player player) {
|
||||
potionManager.getCrankedPotionPlayer(player.getUniqueId()).clearEffects();
|
||||
player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class Queue<E> {
|
||||
|
||||
private final LinkedList<E> list = new LinkedList<E>();
|
||||
|
||||
public void enqueue(E item) {
|
||||
list.addLast(item);
|
||||
}
|
||||
|
||||
public E dequeue() {
|
||||
return list.poll();
|
||||
}
|
||||
|
||||
public boolean hasItems() {
|
||||
return !list.isEmpty();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return list.size();
|
||||
}
|
||||
|
||||
public void addItems(Queue<? extends E> q) {
|
||||
while (q.hasItems()) list.addLast(q.dequeue());
|
||||
}
|
||||
|
||||
public void removeFromQueue(E item) {
|
||||
list.remove(item);
|
||||
}
|
||||
|
||||
public boolean contains(E item) {
|
||||
return list.contains(item);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
list.clear();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomUtils {
|
||||
public static ItemStack getRandomItem(Map<ItemStack, Double> itemsMap) {
|
||||
|
||||
double maxValue = 0;
|
||||
for(Double value : itemsMap.values()) {
|
||||
maxValue = maxValue+value;
|
||||
}
|
||||
|
||||
double currentValue = 0;
|
||||
double randomDouble = ThreadLocalRandom.current().nextDouble(maxValue);
|
||||
|
||||
for(Map.Entry<ItemStack, Double> entry : SortUtils.sort(itemsMap).entrySet()) {
|
||||
if(randomDouble > currentValue && randomDouble < currentValue + entry.getValue()) {
|
||||
return entry.getKey();
|
||||
}
|
||||
currentValue = currentValue + entry.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <E> E getRandomSetElement(Set<E> set) {
|
||||
return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public static <E> E getRandomCollectionElement(Collection<E> set) {
|
||||
return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import lombok.NonNull;
|
||||
import net.crankedpvp.crankedutils.compat.ParamBuilder;
|
||||
import net.crankedpvp.crankedutils.compat.RParam;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ReflectionUtils {
|
||||
private static final Map<String, Field> cachedFields = new HashMap<String, Field>();
|
||||
private static final Map<String, Method> cachedMethods = new HashMap<String, Method>();
|
||||
private static final String nmsVersion;
|
||||
private static final Class<?> entityLivingClass;
|
||||
private static final Class<?> genericAttributesClass;
|
||||
private static final Class<?> iattributeInstanceClass;
|
||||
private static final Class<?> attributeInstanceClass;
|
||||
|
||||
static {
|
||||
String name = Bukkit.getServer().getClass().getPackage().getName();
|
||||
nmsVersion = name.substring(name.lastIndexOf(46) + 1) + ".";
|
||||
Bukkit.getLogger().info("[CosmicUtils] Registered NMS version: " + nmsVersion);
|
||||
entityLivingClass = ReflectionUtils.getNMSClass("EntityLiving");
|
||||
attributeInstanceClass = ReflectionUtils.getNMSClass("AttributeInstance");
|
||||
genericAttributesClass = ReflectionUtils.getNMSClass("GenericAttributes");
|
||||
iattributeInstanceClass = ReflectionUtils.getNMSClass("IAttribute");
|
||||
}
|
||||
|
||||
public static Field getField(Class<?> clazz, String field) throws NoSuchFieldException {
|
||||
Field cached = cachedFields.get(clazz.getName() + ":" + field);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Field f = clazz.getDeclaredField(field);
|
||||
f.setAccessible(true);
|
||||
cachedFields.put(clazz.getName() + ":" + field, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
public static Method getMethod(Class<?> clazz, String field) throws NoSuchMethodException {
|
||||
Method cached = cachedMethods.get(clazz.getName() + ":" + field);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Method f = clazz.getDeclaredMethod(field);
|
||||
f.setAccessible(true);
|
||||
cachedMethods.put(clazz.getName() + ":" + field, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
public static Object invokeMethod(Method method, Object instance, Object... args) {
|
||||
try {
|
||||
return method.invoke(instance, args);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object invokeMethod(Method method, Object instance) {
|
||||
try {
|
||||
return method.invoke(instance);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Method getMethod(Class<?> clazz, String field, Class<?>... paramaters) throws NoSuchMethodException {
|
||||
Method cached = cachedMethods.get(clazz.getName() + ":" + field);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Method f = clazz.getDeclaredMethod(field, paramaters);
|
||||
f.setAccessible(true);
|
||||
cachedMethods.put(clazz.getName() + ":" + field, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
public static void setObject(Object object, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
|
||||
Field field = ReflectionUtils.getField(object.getClass(), fieldName);
|
||||
ReflectionUtils.setObject(object, field, value);
|
||||
}
|
||||
|
||||
public static void setObject(Object object, Field field, Object value) throws IllegalAccessException {
|
||||
if (field != null) {
|
||||
field.set(object, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static Object getObject(Class<?> clazz, Object instance, String fieldName) throws NoSuchFieldException, IllegalAccessException {
|
||||
Field f = ReflectionUtils.getField(clazz, fieldName);
|
||||
return f.get(instance);
|
||||
}
|
||||
|
||||
public static Object callReflectionMethod(Object instance, Class<?> clazz, String method) {
|
||||
return ReflectionUtils.callReflectionMethod(instance, clazz, method, null);
|
||||
}
|
||||
|
||||
public static Object callReflectionMethod(@NonNull Object instance, String method) {
|
||||
if (instance == null) {
|
||||
throw new NullPointerException("instance");
|
||||
}
|
||||
return ReflectionUtils.callReflectionMethod(instance, instance.getClass(), method, null);
|
||||
}
|
||||
|
||||
public static Object callReflectionMethod(@NonNull Object instance, String method, ParamBuilder builder) {
|
||||
if (instance == null) {
|
||||
throw new NullPointerException("instance");
|
||||
}
|
||||
return ReflectionUtils.callReflectionMethod(instance, instance.getClass(), method, builder);
|
||||
}
|
||||
|
||||
public static Object callReflectionMethod(Object instance, Class<?> clazz, String method, ParamBuilder builder) {
|
||||
try {
|
||||
if (builder != null) {
|
||||
Class[] params = new Class[builder.getParameters().size()];
|
||||
Object[] objcs = new Object[builder.getValidObjectCount()];
|
||||
int index = 0;
|
||||
for (RParam param : builder.getParameters()) {
|
||||
int i = index++;
|
||||
params[i] = param.getMethodClass();
|
||||
objcs[i] = param.getInstance();
|
||||
}
|
||||
Method m = ReflectionUtils.getMethod(clazz, method, params);
|
||||
return m.invoke(instance, objcs);
|
||||
}
|
||||
Method m = ReflectionUtils.getMethod(clazz, method);
|
||||
return m.invoke(instance);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNMSVersion() {
|
||||
return nmsVersion;
|
||||
}
|
||||
|
||||
public static Class<?> getNMSClass(String className) {
|
||||
String fullName = "net.minecraft.server." + ReflectionUtils.getNMSVersion() + className;
|
||||
Class<?> clazz = null;
|
||||
try {
|
||||
clazz = Class.forName(fullName);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public static Class<?> getOBCClass(String className) {
|
||||
String fullName = "org.bukkit.craftbukkit." + ReflectionUtils.getNMSVersion() + className;
|
||||
Class<?> clazz = null;
|
||||
try {
|
||||
clazz = Class.forName(fullName);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public static Object getNMSHandle(Object obj) {
|
||||
try {
|
||||
return ReflectionUtils.getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> getEntityLivingClass() {
|
||||
return entityLivingClass;
|
||||
}
|
||||
|
||||
public static Class<?> getGenericAttributesClass() {
|
||||
return genericAttributesClass;
|
||||
}
|
||||
|
||||
public static Class<?> getIattributeInstanceClass() {
|
||||
return iattributeInstanceClass;
|
||||
}
|
||||
|
||||
public static Class<?> getAttributeInstanceClass() {
|
||||
return attributeInstanceClass;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
public class RomanNumeral {
|
||||
private static final char[] symbol = new char[] { 'M', 'D', 'C', 'L', 'X', 'V', 'I' };
|
||||
|
||||
private static final int[] value = new int[] { 1000, 500, 100, 50, 10, 5, 1 };
|
||||
|
||||
private static final int[] numbers = new int[] {
|
||||
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,
|
||||
5, 4, 1 };
|
||||
|
||||
private static final String[] letters = new String[] {
|
||||
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
|
||||
"V", "IV", "I" };
|
||||
|
||||
public static int valueOf(String roman) {
|
||||
roman = roman.toUpperCase();
|
||||
if (roman.length() == 0)
|
||||
return 0;
|
||||
for (int i = 0; i < symbol.length; i++) {
|
||||
int pos = roman.indexOf(symbol[i]);
|
||||
if (pos >= 0)
|
||||
return value[i] - valueOf(roman.substring(0, pos)) +
|
||||
valueOf(roman.substring(pos + 1));
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid Roman Symbol.");
|
||||
}
|
||||
|
||||
public static String convertToRoman(int N) {
|
||||
if (N == 0) return "0";
|
||||
String roman = "";
|
||||
for (int i = 0; i < numbers.length; i++) {
|
||||
while (N >= numbers[i]) {
|
||||
roman = roman + letters[i];
|
||||
N -= numbers[i];
|
||||
}
|
||||
}
|
||||
return roman;
|
||||
}
|
||||
|
||||
public static Integer isInt(String args) {
|
||||
try {
|
||||
return Integer.parseInt(args);
|
||||
} catch (Exception ignore) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Double isDouble(String args) {
|
||||
try {
|
||||
return Double.parseDouble(args);
|
||||
} catch (Exception ignore) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.150.
|
||||
*/
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
public class SlotUtils {
|
||||
public static int fitSlots(int size) {
|
||||
return size <= 9 ? 9 : (size <= 18 ? 18 : (size <= 27 ? 27 : (size <= 36 ? 36 : (size <= 45 ? 45 : (54)))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SortUtils {
|
||||
public static <K, V extends Comparable<? super V>> Map<K, V> sort(Map<K, V> map) {
|
||||
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
|
||||
list.sort(Map.Entry.comparingByValue());
|
||||
Map<K, V> result = new LinkedHashMap<>();
|
||||
for (int i = list.size() - 1; i >= 0; i--) {
|
||||
Map.Entry<K, V> entry = list.get(i);
|
||||
result.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class SoundUtils {
|
||||
|
||||
public static void playSoundIfPlayer(CommandSender commandSender, Sound sound) {
|
||||
if(commandSender instanceof Player) {
|
||||
Player player = ((Player)commandSender);
|
||||
player.playSound(player.getLocation(), sound, 2.0F, 2.0F);
|
||||
}
|
||||
}
|
||||
|
||||
public static void tryPlaySuccessSound(CommandSender commandSender) {
|
||||
playSoundIfPlayer(commandSender, Sound.SUCCESSFUL_HIT);
|
||||
}
|
||||
|
||||
public static void tryPlayErrorSound(CommandSender commandSender) {
|
||||
playSoundIfPlayer(commandSender, Sound.ANVIL_LAND);
|
||||
}
|
||||
|
||||
public static void playSuccessSound(Player player) {
|
||||
player.playSound(player.getLocation(), Sound.SUCCESSFUL_HIT, 2.0F, 2.0F);
|
||||
}
|
||||
|
||||
public static void playErrorSound(Player player) {
|
||||
player.playSound(player.getLocation(), Sound.ANVIL_LAND, 2.0F, 2.0F);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StringUtils {
|
||||
|
||||
public static String rainbowify(String string) {
|
||||
return rainbowify(string, true);
|
||||
}
|
||||
|
||||
public static String rainbowify(String string, boolean bold) {
|
||||
List<String> strings = Arrays.asList("&c&l", "&6&l", "&e&l", "&a&l", "&b&l", "&d&l", "&5&l");
|
||||
List<String> finalStrings = bold ? strings : strings.stream().map(color -> color.replace("&l", "")).collect(Collectors.toList());
|
||||
int index = 0;
|
||||
StringBuilder finalString = new StringBuilder();
|
||||
for(String character : string.split("")) {
|
||||
finalString.append(finalStrings.get(index)).append(character);
|
||||
if(!Objects.equals(character, " ")) index++;
|
||||
if(index >= finalStrings.size()-1) index = 0;
|
||||
}
|
||||
return finalString.toString();
|
||||
}
|
||||
|
||||
public static String toNiceString(String string) {
|
||||
string = ChatColor.stripColor(string).replace('_', ' ').toLowerCase();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < string.toCharArray().length; ++i) {
|
||||
char c = string.toCharArray()[i];
|
||||
if (i > 0) {
|
||||
char prev = string.toCharArray()[i - 1];
|
||||
if ((prev == ' ' || prev == '[' || prev == '(') && (i == string.toCharArray().length - 1 || c != 'x' || !Character.isDigit(string.toCharArray()[i + 1]))) {
|
||||
c = Character.toUpperCase(c);
|
||||
}
|
||||
} else if (c != 'x' || !Character.isDigit(string.toCharArray()[i + 1])) {
|
||||
c = Character.toUpperCase(c);
|
||||
}
|
||||
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getProperCase(String text) {
|
||||
StringBuilder sb = new StringBuilder(text.length());
|
||||
char[] charArray = text.toLowerCase().toCharArray();
|
||||
charArray[0] = Character.toUpperCase(charArray[0]);
|
||||
sb.append(new String(charArray));
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
public static String fixName(String string) {
|
||||
StringBuilder fixedString = new StringBuilder();
|
||||
for(String string2 : string.split("_")) {
|
||||
fixedString.append(getProperCase(string2)).append(" ");
|
||||
}
|
||||
return fixedString.substring(0, fixedString.length() -1);
|
||||
}
|
||||
|
||||
public static String getCenteredMessage(String message) {
|
||||
message = ChatColor.translateAlternateColorCodes('&', message);
|
||||
int messagePxSize = 0;
|
||||
boolean previousCode = false;
|
||||
boolean isBold = false;
|
||||
for (char c : message.toCharArray()) {
|
||||
if (c == '\u00a7') {
|
||||
previousCode = true;
|
||||
continue;
|
||||
}
|
||||
if (previousCode) {
|
||||
previousCode = false;
|
||||
if (c == 'l' || c == 'L') {
|
||||
isBold = true;
|
||||
continue;
|
||||
}
|
||||
isBold = false;
|
||||
continue;
|
||||
}
|
||||
StringUtils.DefaultFontInfo dFI = StringUtils.DefaultFontInfo.getDefaultFontInfo(c);
|
||||
messagePxSize += isBold ? dFI.getBoldLength() : dFI.getLength();
|
||||
++messagePxSize;
|
||||
}
|
||||
int halvedMessageSize = messagePxSize / 2;
|
||||
int toCompensate = 154 - halvedMessageSize;
|
||||
int spaceLength = StringUtils.DefaultFontInfo.SPACE.getLength() + 1;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int compensated = 0; compensated < toCompensate; compensated += spaceLength) {
|
||||
sb.append(" ");
|
||||
}
|
||||
return sb + message;
|
||||
}
|
||||
|
||||
public static String flipString(String string) {
|
||||
StringBuilder input = new StringBuilder();
|
||||
input.append(string);
|
||||
input.reverse();
|
||||
return input.toString();
|
||||
}
|
||||
|
||||
public enum DefaultFontInfo {
|
||||
A('A', 5),
|
||||
a('a', 5),
|
||||
B('B', 5),
|
||||
b('b', 5),
|
||||
C('C', 5),
|
||||
c('c', 5),
|
||||
D('D', 5),
|
||||
d('d', 5),
|
||||
E('E', 5),
|
||||
e('e', 5),
|
||||
F('F', 5),
|
||||
f('f', 4),
|
||||
G('G', 5),
|
||||
g('g', 5),
|
||||
H('H', 5),
|
||||
h('h', 5),
|
||||
I('I', 3),
|
||||
i('i', 1),
|
||||
J('J', 5),
|
||||
j('j', 5),
|
||||
K('K', 5),
|
||||
k('k', 4),
|
||||
L('L', 5),
|
||||
l('l', 1),
|
||||
M('M', 5),
|
||||
m('m', 5),
|
||||
N('N', 5),
|
||||
n('n', 5),
|
||||
O('O', 5),
|
||||
o('o', 5),
|
||||
P('P', 5),
|
||||
p('p', 5),
|
||||
Q('Q', 5),
|
||||
q('q', 5),
|
||||
R('R', 5),
|
||||
r('r', 5),
|
||||
S('S', 5),
|
||||
s('s', 5),
|
||||
T('T', 5),
|
||||
t('t', 4),
|
||||
U('U', 5),
|
||||
u('u', 5),
|
||||
V('V', 5),
|
||||
v('v', 5),
|
||||
W('W', 5),
|
||||
w('w', 5),
|
||||
X('X', 5),
|
||||
x('x', 5),
|
||||
Y('Y', 5),
|
||||
y('y', 5),
|
||||
Z('Z', 5),
|
||||
z('z', 5),
|
||||
NUM_1('1', 5),
|
||||
NUM_2('2', 5),
|
||||
NUM_3('3', 5),
|
||||
NUM_4('4', 5),
|
||||
NUM_5('5', 5),
|
||||
NUM_6('6', 5),
|
||||
NUM_7('7', 5),
|
||||
NUM_8('8', 5),
|
||||
NUM_9('9', 5),
|
||||
NUM_0('0', 5),
|
||||
EXCLAMATION_POINT('!', 1),
|
||||
AT_SYMBOL('@', 6),
|
||||
NUM_SIGN('#', 5),
|
||||
DOLLAR_SIGN('$', 5),
|
||||
PERCENT('%', 5),
|
||||
UP_ARROW('^', 5),
|
||||
AMPERSAND('&', 5),
|
||||
ASTERISK('*', 5),
|
||||
LEFT_PARENTHESIS('(', 4),
|
||||
RIGHT_PERENTHESIS(')', 4),
|
||||
MINUS('-', 5),
|
||||
UNDERSCORE('_', 5),
|
||||
PLUS_SIGN('+', 5),
|
||||
EQUALS_SIGN('=', 5),
|
||||
LEFT_CURL_BRACE('{', 4),
|
||||
RIGHT_CURL_BRACE('}', 4),
|
||||
LEFT_BRACKET('[', 3),
|
||||
RIGHT_BRACKET(']', 3),
|
||||
COLON(':', 1),
|
||||
SEMI_COLON(';', 1),
|
||||
DOUBLE_QUOTE('"', 3),
|
||||
SINGLE_QUOTE('\'', 1),
|
||||
LEFT_ARROW('<', 4),
|
||||
RIGHT_ARROW('>', 4),
|
||||
QUESTION_MARK('?', 5),
|
||||
SLASH('/', 5),
|
||||
BACK_SLASH('\\', 5),
|
||||
LINE('|', 1),
|
||||
TILDE('~', 5),
|
||||
TICK('`', 2),
|
||||
PERIOD('.', 1),
|
||||
COMMA(',', 1),
|
||||
SPACE(' ', 3),
|
||||
DEFAULT('a', 4);
|
||||
|
||||
private final char character;
|
||||
private final int length;
|
||||
|
||||
DefaultFontInfo(char character, int length) {
|
||||
this.character = character;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
public static StringUtils.DefaultFontInfo getDefaultFontInfo(char c) {
|
||||
StringUtils.DefaultFontInfo[] var1 = values();
|
||||
int var2 = var1.length;
|
||||
|
||||
for(DefaultFontInfo dFI : var1) {
|
||||
if(dFI.getCharacter() == c) {
|
||||
return dFI;
|
||||
}
|
||||
}
|
||||
|
||||
return DEFAULT;
|
||||
}
|
||||
|
||||
public char getCharacter() {
|
||||
return this.character;
|
||||
}
|
||||
|
||||
public int getLength() {
|
||||
return this.length;
|
||||
}
|
||||
|
||||
public int getBoldLength() {
|
||||
return this == SPACE ? this.getLength() : this.length + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class TimeUtils {
|
||||
public static String formatSeconds(long seconds) {
|
||||
if (seconds == 0L)
|
||||
return "0s";
|
||||
long day = TimeUnit.SECONDS.toDays(seconds);
|
||||
long hours = TimeUnit.SECONDS.toHours(seconds) - day * 24L;
|
||||
long minutes = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toHours(seconds) * 60L;
|
||||
long secs = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toMinutes(seconds) * 60L;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (day > 0L)
|
||||
sb.append(day).append("d").append(" ");
|
||||
if (hours > 0L)
|
||||
sb.append(hours).append("h").append(" ");
|
||||
if (minutes > 0L)
|
||||
sb.append(minutes).append("m").append(" ");
|
||||
if (secs > 0L)
|
||||
sb.append(secs).append("s");
|
||||
String diff = sb.toString();
|
||||
return diff.isEmpty() ? "Now" : diff.trim();
|
||||
}
|
||||
|
||||
public static String formatSecondsInFull(long seconds) {
|
||||
if (seconds == 0L)
|
||||
return "0s";
|
||||
long day = TimeUnit.SECONDS.toDays(seconds);
|
||||
long hours = TimeUnit.SECONDS.toHours(seconds) - day * 24L;
|
||||
long minutes = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toHours(seconds) * 60L;
|
||||
long secs = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toMinutes(seconds) * 60L;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String plural;
|
||||
if (day > 0L) {
|
||||
plural = day == 1 ? " day" : " days";
|
||||
sb.append(day).append(plural).append(" ");
|
||||
}
|
||||
if (hours > 0L) {
|
||||
plural = hours == 1 ? " hour" : " hours";
|
||||
sb.append(hours).append(plural).append(" ");
|
||||
}
|
||||
if (minutes > 0L) {
|
||||
plural = minutes == 1 ? " minute" : " minutes";
|
||||
sb.append(minutes).append(plural).append(" ");
|
||||
}
|
||||
if (secs > 0L) {
|
||||
plural = seconds == 1 ? " second" : " seconds";
|
||||
sb.append(secs).append(plural);
|
||||
}
|
||||
String diff = sb.toString();
|
||||
return diff.isEmpty() ? "Now" : diff.trim();
|
||||
}
|
||||
|
||||
public static String formatMilliseconds(long milliseconds) {
|
||||
long seconds = milliseconds / 1000;
|
||||
return formatSeconds(seconds);
|
||||
}
|
||||
|
||||
public static String formatMillisecondsInFull(long milliseconds) {
|
||||
long seconds = milliseconds / 1000;
|
||||
return formatSecondsInFull(seconds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.Objects;
|
||||
|
||||
public class TitleUtils {
|
||||
|
||||
public static void sendTitle(Player player, String title, String subtitle, int fadeInTime, int showTime, int fadeOutTime) {
|
||||
try {
|
||||
Object chatTitle = Objects.requireNonNull(getNMSClass("IChatBaseComponent")).getDeclaredClasses()[0].getMethod("a", new Class[] { String.class }).invoke(null, "{\"text\": \"" + title + "\"}");
|
||||
Constructor<?> titleConstructor = Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getConstructor(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"),
|
||||
int.class, int.class, int.class);
|
||||
Object packet = titleConstructor.newInstance(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0].getField("TITLE").get(null), chatTitle,
|
||||
fadeInTime, showTime, fadeOutTime);
|
||||
Object chatsTitle = Objects.requireNonNull(getNMSClass("IChatBaseComponent")).getDeclaredClasses()[0].getMethod("a", new Class[] { String.class }).invoke(null, "{\"text\": \"" + subtitle + "\"}");
|
||||
Constructor<?> timingTitleConstructor = Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getConstructor(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"),
|
||||
int.class, int.class, int.class);
|
||||
Object timingPacket = timingTitleConstructor.newInstance(Objects.requireNonNull(getNMSClass("PacketPlayOutTitle")).getDeclaredClasses()[0].getField("SUBTITLE").get(null), chatsTitle,
|
||||
fadeInTime, showTime, fadeOutTime);
|
||||
sendPacket(player, packet);
|
||||
sendPacket(player, timingPacket);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static void sendPacket(Player player, Object packet) {
|
||||
try {
|
||||
Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player);
|
||||
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
|
||||
playerConnection.getClass().getMethod("sendPacket", new Class[] { getNMSClass("Packet") }).invoke(playerConnection, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> getNMSClass(String name) {
|
||||
try {
|
||||
return Class.forName("net.minecraft.server." +
|
||||
Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "." + name);
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import com.sk89q.worldedit.Vector;
|
||||
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
|
||||
import com.sk89q.worldguard.protection.ApplicableRegionSet;
|
||||
import com.sk89q.worldguard.protection.flags.DefaultFlag;
|
||||
import com.sk89q.worldguard.protection.flags.StateFlag;
|
||||
import com.sk89q.worldguard.protection.managers.RegionManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class WorldGuardUtils {
|
||||
|
||||
private static final WorldGuardPlugin worldGuard = getWorldGuard();
|
||||
private static Class<?> bukkitUtil;
|
||||
|
||||
static {
|
||||
try {
|
||||
bukkitUtil = worldGuard.getClass().getClassLoader().loadClass("com.sk89q.worldguard.bukkit.BukkitUtil");
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static Method toVector;
|
||||
|
||||
static {
|
||||
try {
|
||||
toVector = bukkitUtil.getMethod("toVector", Block.class);
|
||||
} catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static boolean canPvPInRegion(Player player) {
|
||||
return canPvPInRegion(player.getLocation());
|
||||
}
|
||||
|
||||
public static boolean canPvPInRegion(LivingEntity entity) {
|
||||
return canPvPInRegion(entity.getLocation());
|
||||
}
|
||||
|
||||
public static boolean canPvPInRegion(Location location) {
|
||||
RegionManager regionManager = worldGuard.getRegionManager(location.getWorld());
|
||||
ApplicableRegionSet set = regionManager.getApplicableRegions(location);
|
||||
return set.queryState(null, DefaultFlag.PVP) != StateFlag.State.DENY;
|
||||
}
|
||||
|
||||
public static WorldGuardPlugin getWorldGuard() {
|
||||
Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
|
||||
if (!(plugin instanceof WorldGuardPlugin)) return null;
|
||||
return (WorldGuardPlugin) plugin;
|
||||
}
|
||||
|
||||
public static String getRegionName(Location l) {
|
||||
try {
|
||||
Vector blockVector = (Vector)toVector.invoke(null, l.getBlock());
|
||||
List<String> regionSet = worldGuard.getGlobalRegionManager().get(l.getWorld()).getApplicableRegionsIDs(blockVector);
|
||||
if (regionSet.size() < 1) {
|
||||
return "";
|
||||
} else {
|
||||
String return_region = "";
|
||||
int return_priority = -1;
|
||||
|
||||
for (String region : regionSet) {
|
||||
int region_priority = worldGuard.getGlobalRegionManager().get(l.getWorld()).getRegion(region).getPriority();
|
||||
if (return_region.equalsIgnoreCase("")) {
|
||||
return_region = worldGuard.getGlobalRegionManager().get(l.getWorld()).getRegion(region).getId();
|
||||
return_priority = region_priority;
|
||||
}
|
||||
|
||||
if (region_priority > return_priority) {
|
||||
return_region = worldGuard.getGlobalRegionManager().get(l.getWorld()).getRegion(region).getId();
|
||||
return_priority = region_priority;
|
||||
}
|
||||
}
|
||||
|
||||
if (return_region.contains("global")) {
|
||||
return_region = "";
|
||||
}
|
||||
|
||||
return return_region;
|
||||
}
|
||||
} catch (Exception var8) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package net.crankedpvp.crankedutils.utils;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class XPUtils {
|
||||
//This method is used to update both the recorded total experience and displayed total experience.
|
||||
//We reset both types to prevent issues.
|
||||
public static void setTotalExperience(final Player player, final int exp) {
|
||||
if (exp < 0) {
|
||||
throw new IllegalArgumentException("Experience is negative!");
|
||||
}
|
||||
player.setExp(0);
|
||||
player.setLevel(0);
|
||||
player.setTotalExperience(0);
|
||||
|
||||
//This following code is technically redundant now, as bukkit now calulcates levels more or less correctly
|
||||
//At larger numbers however... player.getExp(3000), only seems to give 2999, putting the below calculations off.
|
||||
int amount = exp;
|
||||
while (amount > 0) {
|
||||
final int expToLevel = getExpAtLevel(player);
|
||||
amount -= expToLevel;
|
||||
if (amount >= 0) {
|
||||
// give until next level
|
||||
player.giveExp(expToLevel);
|
||||
} else {
|
||||
// give the rest
|
||||
amount += expToLevel;
|
||||
player.giveExp(amount);
|
||||
amount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int getExpAtLevel(final Player player) {
|
||||
return getExpAtLevel(player.getLevel());
|
||||
}
|
||||
|
||||
//new Exp Math from 1.8
|
||||
private static int getExpAtLevel(final int level) {
|
||||
if (level <= 15) {
|
||||
return (2 * level) + 7;
|
||||
}
|
||||
if (level <= 30) {
|
||||
return (5 * level) - 38;
|
||||
}
|
||||
return (9 * level) - 158;
|
||||
|
||||
}
|
||||
|
||||
private static int getExpToLevel(final int level) {
|
||||
int currentLevel = 0;
|
||||
int exp = 0;
|
||||
|
||||
while (currentLevel < level) {
|
||||
exp += getExpAtLevel(currentLevel);
|
||||
currentLevel++;
|
||||
}
|
||||
if (exp < 0) {
|
||||
exp = Integer.MAX_VALUE;
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
//This method is required because the bukkit player.getTotalExperience() method, shows exp that has been 'spent'.
|
||||
//Without this people would be able to use exp and then still sell it.
|
||||
public static int getTotalExperience(final Player player) {
|
||||
int exp = Math.round(getExpAtLevel(player) * player.getExp());
|
||||
int currentLevel = player.getLevel();
|
||||
|
||||
while (currentLevel > 0) {
|
||||
currentLevel--;
|
||||
exp += getExpAtLevel(currentLevel);
|
||||
}
|
||||
if (exp < 0) {
|
||||
exp = Integer.MAX_VALUE;
|
||||
}
|
||||
return exp;
|
||||
}
|
||||
|
||||
private static int getExpUntilNextLevel(final Player player) {
|
||||
int exp = Math.round(getExpAtLevel(player) * player.getExp());
|
||||
int nextLevel = player.getLevel();
|
||||
return getExpAtLevel(nextLevel) - exp;
|
||||
}
|
||||
|
||||
public static boolean hasEnoughExperience(final Player player, final int amount) {
|
||||
return getTotalExperience(player) >= amount;
|
||||
}
|
||||
|
||||
public static void removeExperience(final Player player, final int amount) {
|
||||
setTotalExperience(player, getTotalExperience(player) - amount);
|
||||
}
|
||||
|
||||
public static void addExperience(final Player player, final int amount) {
|
||||
if (amount <= 0) return;
|
||||
setTotalExperience(player, getTotalExperience(player) + amount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package net.crankedpvp.crankedutils.utils.cache;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public abstract class Cache {
|
||||
|
||||
private final String name;
|
||||
|
||||
public Cache(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package net.crankedpvp.crankedutils.utils.cache;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
|
||||
@Getter
|
||||
public class CacheManager {
|
||||
|
||||
@Getter
|
||||
private static CacheManager instance;
|
||||
private final HashMap<UUID, CachedPlayer> playerCaches;
|
||||
|
||||
public CacheManager() {
|
||||
instance = this;
|
||||
this.playerCaches = new HashMap<>();
|
||||
}
|
||||
|
||||
public CachedPlayer getCachedPlayer(Player player) {
|
||||
if(!this.playerCaches.containsKey(player.getUniqueId()))
|
||||
this.playerCaches.put(player.getUniqueId(), new CachedPlayer(player, this));
|
||||
return this.playerCaches.get(player.getUniqueId());
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package net.crankedpvp.crankedutils.utils.cache;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
public class CachedPlayer {
|
||||
|
||||
private final Map<String, Cache> caches;
|
||||
private final Player player;
|
||||
private final CacheManager manager;
|
||||
|
||||
public CachedPlayer(Player player, CacheManager manager) {
|
||||
this.player = player;
|
||||
this.manager = manager;
|
||||
this.caches = new HashMap<>();
|
||||
}
|
||||
|
||||
public boolean hasCache(String name) {
|
||||
return this.caches.containsKey(name);
|
||||
}
|
||||
|
||||
public Cache getCache(String name) {
|
||||
return this.caches.get(name);
|
||||
}
|
||||
|
||||
public Cache registerCache(Cache cache) {
|
||||
this.caches.put(cache.getName(), cache);
|
||||
return cache;
|
||||
}
|
||||
|
||||
public void removeCache(String cacheName) {
|
||||
this.caches.remove(cacheName);
|
||||
}
|
||||
|
||||
//test
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package net.crankedpvp.crankedutils.utils.cache.cooldown;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.TimeUtils;
|
||||
import net.crankedpvp.crankedutils.utils.cache.Cache;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public abstract class CurrentCooldown extends Cache {
|
||||
|
||||
private final long started;
|
||||
private final long duration;
|
||||
|
||||
public CurrentCooldown(String name, int durationInSeconds) {
|
||||
super(name);
|
||||
this.started = System.currentTimeMillis();
|
||||
this.duration = durationInSeconds * 1000L;
|
||||
}
|
||||
|
||||
public CurrentCooldown(String name, long durationInMs) {
|
||||
super(name);
|
||||
this.started = System.currentTimeMillis();
|
||||
this.duration = durationInMs;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return this.started + this.duration > System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public String getFormattedTime() {
|
||||
return TimeUtils.formatSeconds((this.started + this.duration - System.currentTimeMillis())/1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package net.crankedpvp.crankedutils.utils.config;
|
||||
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class AbstractConfig {
|
||||
|
||||
private final JavaPlugin plugin;
|
||||
private final String path;
|
||||
private FileConfiguration config;
|
||||
private final File configFile;
|
||||
|
||||
public AbstractConfig(JavaPlugin plugin, String path) {
|
||||
this.plugin = plugin;
|
||||
this.path = path;
|
||||
this.configFile = new File(plugin.getDataFolder(), path);
|
||||
}
|
||||
|
||||
public boolean setupConfigFile() {
|
||||
boolean copyDefaults = !configFile.exists();
|
||||
|
||||
this.saveDefaultConfig();
|
||||
config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
if (copyDefaults) this.copyDefaults();
|
||||
|
||||
boolean result = this.saveConfig();
|
||||
if (result) this.loadConfigFromDisk();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean saveConfig() {
|
||||
try {
|
||||
config.save(configFile);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().severe("Could not save config file for " + path + "!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void saveDefaultConfig() {
|
||||
if (!configFile.exists()) {
|
||||
InputStream defConfig = plugin.getResource(path);
|
||||
if (defConfig != null) {
|
||||
plugin.saveResource(path,false);
|
||||
} else {
|
||||
try {
|
||||
configFile.getParentFile().mkdirs();
|
||||
configFile.createNewFile();
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().severe("Could not create config file for " + path + "!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public boolean reloadConfig() {
|
||||
boolean copyDefaults = !configFile.exists();
|
||||
|
||||
this.saveDefaultConfig();
|
||||
config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
if (copyDefaults) this.copyDefaults();
|
||||
|
||||
this.saveConfig();
|
||||
return this.loadConfigFromDisk();
|
||||
}
|
||||
|
||||
public boolean loadConfigFromDisk() {
|
||||
try {
|
||||
config.load(configFile);
|
||||
return true;
|
||||
} catch (IOException | InvalidConfigurationException e) {
|
||||
plugin.getLogger().severe("Could not load config for " + path + "!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void copyDefaults() {
|
||||
InputStream defConfig = plugin.getResource(path);
|
||||
if (defConfig != null) {
|
||||
config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfig)));
|
||||
}
|
||||
config.options().copyDefaults(true);
|
||||
}
|
||||
|
||||
public FileConfiguration getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package net.crankedpvp.crankedutils.utils.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ConfigManager {
|
||||
|
||||
private final JavaPlugin plugin;
|
||||
|
||||
@Getter
|
||||
private final Map<ConfigFile, AbstractConfig> configs = new HashMap<>();
|
||||
|
||||
public ConfigManager(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
for (ConfigFile configFile : ConfigFile.values()) {
|
||||
AbstractConfig abstractConfig = new AbstractConfig(plugin, configFile.getFileName());
|
||||
configs.put(configFile, abstractConfig);
|
||||
}
|
||||
}
|
||||
|
||||
public void setupFiles() {
|
||||
configs.values().forEach(AbstractConfig::setupConfigFile);
|
||||
}
|
||||
|
||||
public void reloadFiles() {
|
||||
configs.values().forEach(AbstractConfig::reloadConfig);
|
||||
}
|
||||
|
||||
public AbstractConfig getAbstractConfig(ConfigFile configFile) {
|
||||
return configs.get(configFile);
|
||||
}
|
||||
|
||||
public FileConfiguration getConfig(ConfigFile configFile) {
|
||||
return getAbstractConfig(configFile).getConfig();
|
||||
}
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum ConfigFile {
|
||||
|
||||
PRIMARY("config.yml"),
|
||||
ARMOR_EQUIP("misc/armor-equip-event.yml"),
|
||||
;
|
||||
|
||||
private final String fileName;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package net.crankedpvp.crankedutils.utils.cosmicgui;
|
||||
|
||||
import net.crankedpvp.crankedutils.CrankedUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class CosmicGUI {
|
||||
public static Set<String> allGUINames = new HashSet();
|
||||
public static Map<UUID, CosmicGUI> activeGUIs = new ConcurrentHashMap();
|
||||
public CosmicGUI parentGUI;
|
||||
protected String title;
|
||||
protected int size;
|
||||
protected Player player;
|
||||
protected Inventory inventory;
|
||||
private final Map<Integer, InventoryItem> inventoryItems;
|
||||
private String owningPluginName;
|
||||
private Runnable closeRunnable;
|
||||
|
||||
public CosmicGUI(Player player, String title, int size) {
|
||||
this(player, title, size, InventoryType.CHEST);
|
||||
}
|
||||
|
||||
public CosmicGUI(Player player, String title, int size, InventoryType type) {
|
||||
this.inventoryItems = new HashMap();
|
||||
this.inventory = type == InventoryType.CHEST ? Bukkit.createInventory(null, size, title) : Bukkit.createInventory(null, type);
|
||||
this.player = player;
|
||||
this.size = size;
|
||||
this.title = title;
|
||||
allGUINames.add(this.title);
|
||||
}
|
||||
|
||||
public static CosmicGUI getActiveGUI(UUID uuid) {
|
||||
return activeGUIs.get(uuid);
|
||||
}
|
||||
|
||||
public static void removeGUI(UUID uuid) {
|
||||
activeGUIs.remove(uuid);
|
||||
}
|
||||
|
||||
public void onUnknownItemClick(InventoryClickEvent event) {
|
||||
}
|
||||
|
||||
public abstract void redraw();
|
||||
|
||||
public void openGUI(JavaPlugin owning) {
|
||||
this.owningPluginName = owning.getName();
|
||||
CosmicGUI currentlyActive = activeGUIs.get(this.player.getUniqueId());
|
||||
if (currentlyActive != null) {
|
||||
Bukkit.getLogger().info("Closing already open menu first!");
|
||||
Bukkit.getScheduler().scheduleSyncDelayedTask(owning, () -> {
|
||||
currentlyActive.close();
|
||||
activeGUIs.put(this.player.getUniqueId(), this);
|
||||
this.redraw();
|
||||
this.player.openInventory(this.inventory);
|
||||
});
|
||||
} else {
|
||||
activeGUIs.put(this.player.getUniqueId(), this);
|
||||
this.redraw();
|
||||
this.player.openInventory(this.inventory);
|
||||
}
|
||||
}
|
||||
|
||||
public void setItem(int slot, InventoryItem inventoryItem) {
|
||||
if (inventoryItem != null && inventoryItem.getItem() != null) {
|
||||
this.inventoryItems.put(slot, inventoryItem);
|
||||
this.inventory.setItem(slot, inventoryItem.getItem());
|
||||
} else {
|
||||
this.removeItem(slot);
|
||||
}
|
||||
}
|
||||
|
||||
public void closeWithDelay() {
|
||||
this.closeWithDelay(null);
|
||||
}
|
||||
|
||||
public void closeWithDelay(Consumer<Player> afterClose) {
|
||||
Bukkit.getScheduler().scheduleSyncDelayedTask(CrankedUtils.getInstance(), () -> {
|
||||
this.player.closeInventory();
|
||||
if (afterClose != null) {
|
||||
afterClose.accept(this.player);
|
||||
}
|
||||
|
||||
}, 1L);
|
||||
}
|
||||
|
||||
public void setItem(int slot, ItemStack item, Runnable runnable) {
|
||||
this.setItem(slot, (new InventoryItem(item)).click(runnable));
|
||||
}
|
||||
|
||||
public void onInventoryClose() {
|
||||
if (this.closeRunnable != null) {
|
||||
this.closeRunnable.run();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void close() {
|
||||
this.onInventoryClose();
|
||||
this.player.closeInventory();
|
||||
}
|
||||
|
||||
public void removeItem(int slot) {
|
||||
this.inventory.setItem(slot, null);
|
||||
this.inventoryItems.remove(slot);
|
||||
}
|
||||
|
||||
public CosmicGUI setOnClose(Runnable runnable) {
|
||||
this.closeRunnable = runnable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isInventory(Inventory inventory) {
|
||||
return this.inventory.equals(inventory);
|
||||
}
|
||||
|
||||
public CosmicGUI getParentGUI() {
|
||||
return this.parentGUI;
|
||||
}
|
||||
|
||||
public CosmicGUI setParentGUI(CosmicGUI parent) {
|
||||
this.parentGUI = parent;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<Integer, InventoryItem> getInventoryItems() {
|
||||
return this.inventoryItems;
|
||||
}
|
||||
|
||||
public String getOwningPluginName() {
|
||||
return this.owningPluginName;
|
||||
}
|
||||
|
||||
public void setOwningPluginName(String owningPluginName) {
|
||||
this.owningPluginName = owningPluginName;
|
||||
}
|
||||
|
||||
public Runnable getCloseRunnable() {
|
||||
return this.closeRunnable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.150.
|
||||
*/
|
||||
package net.crankedpvp.crankedutils.utils.cosmicgui;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
|
||||
public class GUIListener
|
||||
implements Listener {
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
CosmicGUI active = CosmicGUI.getActiveGUI(event.getWhoClicked().getUniqueId());
|
||||
if (active != null) {
|
||||
event.setCancelled(true);
|
||||
if (event.getRawSlot() < event.getInventory().getSize()) {
|
||||
int slot = event.getSlot();
|
||||
InventoryItem item = active.getInventoryItems().get(slot);
|
||||
if (item != null) {
|
||||
item.handleClick(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
active.onUnknownItemClick(event);
|
||||
} else if (CosmicGUI.allGUINames.contains(event.getInventory().getName())) {
|
||||
event.setCancelled(true);
|
||||
Bukkit.getLogger().info("Cancelling Inventory CLICKED: " + event.getInventory().getName() + " DUE TO IT NOT BEING TRACKED FOR " + event.getWhoClicked().getName() + ", MASSIVE LAG??");
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClose(InventoryCloseEvent event) {
|
||||
CosmicGUI active = CosmicGUI.getActiveGUI(event.getPlayer().getUniqueId());
|
||||
if (active != null) {
|
||||
active.onInventoryClose();
|
||||
CosmicGUI.removeGUI(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
CosmicGUI active = CosmicGUI.getActiveGUI(event.getPlayer().getUniqueId());
|
||||
if (active != null) {
|
||||
active.close();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPluginDisable(PluginDisableEvent event) {
|
||||
for (CosmicGUI active : CosmicGUI.activeGUIs.values()) {
|
||||
if (!active.getOwningPluginName().equals(event.getPlugin().getName())) continue;
|
||||
Bukkit.getLogger().info("Closing GUI due to " + event.getPlugin().getName() + " disabling!");
|
||||
try {
|
||||
active.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package net.crankedpvp.crankedutils.utils.cosmicgui;
|
||||
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class InventoryItem {
|
||||
private final ItemStack item;
|
||||
private final Map<ClickType, Runnable> clickMap = new HashMap<ClickType, Runnable>();
|
||||
private Runnable runnable;
|
||||
|
||||
public InventoryItem(ItemStack original) {
|
||||
this.item = original;
|
||||
}
|
||||
|
||||
|
||||
public InventoryItem click(ClickType type, Runnable runnable) {
|
||||
this.clickMap.put(type, runnable);
|
||||
return this;
|
||||
}
|
||||
|
||||
public InventoryItem click(Runnable runnable) {
|
||||
this.runnable = runnable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void handleClick(InventoryClickEvent event) {
|
||||
if (this.clickMap.isEmpty() && this.runnable != null) {
|
||||
this.runnable.run();
|
||||
} else {
|
||||
Runnable found = this.clickMap.get(event.getClick());
|
||||
if (found != null) {
|
||||
found.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ItemStack getItem() {
|
||||
return this.item;
|
||||
}
|
||||
|
||||
public Map<ClickType, Runnable> getClickMap() {
|
||||
return this.clickMap;
|
||||
}
|
||||
|
||||
public Runnable getRunnable() {
|
||||
return this.runnable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
package net.crankedpvp.crankedutils.utils.items;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.CC;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.DyeColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
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.util.*;
|
||||
|
||||
public class ItemBuilder {
|
||||
|
||||
private ItemMeta itemMeta;
|
||||
private final ItemStack itemStack;
|
||||
|
||||
public ItemBuilder(String material) {
|
||||
this(Material.valueOf(material));
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material) {
|
||||
this(material,1);
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material, int amount) {
|
||||
this(new ItemStack(material, amount));
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material, String name, String... lore) {
|
||||
this(material, 1, (short) 0, name, lore);
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material, String name, List<String> lore) {
|
||||
this(material, 1, (short) 0, name);
|
||||
setLore(lore);
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material, int amount, short durability) {
|
||||
this(new ItemStack(material, amount, durability));
|
||||
}
|
||||
|
||||
public ItemBuilder(Material material, int amount, short durability, String name, String... lore) {
|
||||
this(new ItemStack(material, amount, durability));
|
||||
setName(name);
|
||||
setLore(lore);
|
||||
}
|
||||
|
||||
public ItemBuilder(ItemBuilder itemBuilder) {
|
||||
this.itemStack = itemBuilder.itemStack;
|
||||
this.itemMeta = itemBuilder.itemMeta;
|
||||
}
|
||||
|
||||
public ItemBuilder(ConfigurationSection section) {
|
||||
this(new ItemBuilder(section.getString("name"))
|
||||
.setLore(section.getStringList("lore"))
|
||||
.setDurability((short) section.getInt("damage"))
|
||||
.setUnbreakable(section.getBoolean("unbreakable"))
|
||||
);
|
||||
}
|
||||
|
||||
public ItemBuilder(ItemStack itemStack) {
|
||||
this.itemStack = itemStack;
|
||||
this.itemMeta = itemStack.getItemMeta();
|
||||
}
|
||||
|
||||
public ItemBuilder clone() {
|
||||
return new ItemBuilder(build());
|
||||
}
|
||||
|
||||
public ItemBuilder setMaterial(String material) {
|
||||
itemStack.setType(Material.valueOf(material));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setMaterial(Material material) {
|
||||
itemStack.setType(material);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setDurability(short durability) {
|
||||
itemStack.setDurability(durability);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setName(String name) {
|
||||
itemMeta.setDisplayName(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addUnsafeEnchantment(Enchantment enchantment, int level) {
|
||||
itemMeta.addEnchant(enchantment, level, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addUnsafeEnchantments(Map<Enchantment, Integer> enchantments) {
|
||||
enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addEnchantment(Enchantment enchantment, int level) {
|
||||
itemMeta.addEnchant(enchantment, level,false);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addEnchantments(Map<Enchantment, Integer> enchantments) {
|
||||
enchantments.forEach((enchantment, level) -> itemMeta.addEnchant(enchantment, level, false));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder removeEnchantment(Enchantment enchantment) {
|
||||
itemMeta.removeEnchant(enchantment);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder removeEnchantments(Collection<Enchantment> enchantments) {
|
||||
enchantments.forEach(itemMeta::removeEnchant);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setGlowing() {
|
||||
if (!itemMeta.hasEnchants()) {
|
||||
itemMeta.addEnchant(Enchantment.DURABILITY,1,true);
|
||||
}
|
||||
return addItemFlag(ItemFlag.HIDE_ENCHANTS);
|
||||
}
|
||||
|
||||
public ItemBuilder removeGlow() {
|
||||
if (!itemMeta.hasEnchants() && !itemMeta.hasItemFlag(ItemFlag.HIDE_ENCHANTS)) {
|
||||
return this;
|
||||
}
|
||||
itemMeta.getEnchants().forEach((enchantment, integer) -> itemMeta.removeEnchant(enchantment));
|
||||
itemMeta.removeItemFlags(ItemFlag.HIDE_ENCHANTS);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder colorize() {
|
||||
colorizeName();
|
||||
return colorizeLore();
|
||||
}
|
||||
|
||||
public ItemBuilder colorizeLore() {
|
||||
if (itemMeta.hasLore()) {
|
||||
List<String> lore = getItemMeta().getLore();
|
||||
lore.replaceAll(CC::translate);
|
||||
return setLore(lore);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder colorizeName() {
|
||||
if (itemMeta.hasDisplayName()) setName(CC.translate(getItemMeta().getDisplayName()));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setUnbreakable(boolean unbreakable) {
|
||||
itemMeta.spigot().setUnbreakable(unbreakable);
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<String> getLore() {
|
||||
return itemMeta.getLore();
|
||||
}
|
||||
|
||||
public ItemBuilder setLore(String... lore) {
|
||||
return setLore(Arrays.asList(lore));
|
||||
}
|
||||
|
||||
public ItemBuilder setLore(List<String> lore) {
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder removeLoreLine(String line) {
|
||||
List<String> lore = new ArrayList<>(itemMeta.getLore());
|
||||
lore.remove(line);
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder removeLoreLine(int index) {
|
||||
if (index < 0) return this;
|
||||
List<String> lore = new ArrayList<>(itemMeta.getLore());
|
||||
if (index > lore.size()) return this;
|
||||
lore.remove(index);
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addLore(String ...lore) {
|
||||
return addLore(Arrays.asList(lore));
|
||||
}
|
||||
|
||||
public ItemBuilder addLore(List<String> lore) {
|
||||
lore.forEach(this::addLoreLine);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addLoreLine(String line) {
|
||||
List<String> lore = itemMeta.hasLore() ? new ArrayList<>(itemMeta.getLore()) : new ArrayList<>();
|
||||
lore.add(line);
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setLoreLine(String line, int pos) {
|
||||
List<String> lore = new ArrayList<>(itemMeta.getLore());
|
||||
if (pos >= lore.size()) return this;
|
||||
lore.set(pos, line);
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addLoreLine(String line, int pos) {
|
||||
List<String> lore = new ArrayList<>(itemMeta.getLore());
|
||||
if (pos >= lore.size()) return this;
|
||||
lore.add(pos, line);
|
||||
itemMeta.setLore(lore);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addItemFlags(List<String> itemFlags) {
|
||||
for (String itemFlagStr : itemFlags) {
|
||||
try {
|
||||
ItemFlag itemFlag = ItemFlag.valueOf(itemFlagStr);
|
||||
addItemFlag(itemFlag);
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setItemFlags(List<ItemFlag> itemFlags) {
|
||||
itemMeta.addItemFlags(itemFlags.toArray(new ItemFlag[0]));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setAmount(int amount) {
|
||||
itemStack.setAmount(amount);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setType(Material type) {
|
||||
itemStack.setType(type);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addItemFlag(ItemFlag itemFlag) {
|
||||
itemMeta.addItemFlags(itemFlag);
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public ItemBuilder setColor(DyeColor color) {
|
||||
itemStack.setDurability(color.getData());
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setLeatherArmorColor(Color color) {
|
||||
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta;
|
||||
if (Bukkit.getItemFactory().isApplicable(leatherArmorMeta, itemStack)) {
|
||||
leatherArmorMeta.setColor(color);
|
||||
itemMeta = leatherArmorMeta;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder setSkullOwner(String owner) {
|
||||
SkullMeta skullMeta = (SkullMeta) itemMeta;
|
||||
if (Bukkit.getItemFactory().isApplicable(skullMeta, itemStack)) {
|
||||
skullMeta.setOwner(owner);
|
||||
itemMeta = skullMeta;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemMeta getItemMeta() {
|
||||
return itemMeta;
|
||||
}
|
||||
|
||||
public ItemStack build() {
|
||||
itemStack.setItemMeta(itemMeta);
|
||||
return itemStack;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package net.crankedpvp.crankedutils.utils.items;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public final class ItemUtils {
|
||||
|
||||
public static Material[] swords;
|
||||
public static Material[] swords_and_bow;
|
||||
public static Material[] armor;
|
||||
public static Material[] helmets;
|
||||
public static Material[] helmets_and_boots;
|
||||
public static Material[] chestplates;
|
||||
public static Material[] leggings;
|
||||
public static Material[] boots;
|
||||
public static Material[] pickaxe;
|
||||
public static Material[] tools;
|
||||
public static Material[] axe;
|
||||
public static Material[] weapons;
|
||||
public static Material[] weapons_and_tools;
|
||||
|
||||
static {
|
||||
swords = new Material[]{Material.WOOD_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLD_SWORD, Material.DIAMOND_SWORD};
|
||||
swords_and_bow = new Material[]{Material.WOOD_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLD_SWORD, Material.DIAMOND_SWORD, Material.BOW};
|
||||
armor = new Material[]{Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS, Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS};
|
||||
helmets = new Material[]{Material.LEATHER_HELMET, Material.GOLD_HELMET, Material.IRON_HELMET, Material.CHAINMAIL_HELMET, Material.DIAMOND_HELMET};
|
||||
helmets_and_boots = new Material[]{Material.LEATHER_HELMET, Material.GOLD_HELMET, Material.IRON_HELMET, Material.CHAINMAIL_HELMET, Material.DIAMOND_HELMET, Material.LEATHER_BOOTS, Material.GOLD_BOOTS, Material.CHAINMAIL_BOOTS, Material.IRON_BOOTS, Material.DIAMOND_BOOTS};
|
||||
chestplates = new Material[]{Material.LEATHER_CHESTPLATE, Material.GOLD_CHESTPLATE, Material.IRON_CHESTPLATE, Material.CHAINMAIL_CHESTPLATE, Material.DIAMOND_CHESTPLATE};
|
||||
leggings = new Material[]{Material.LEATHER_LEGGINGS, Material.GOLD_LEGGINGS, Material.IRON_LEGGINGS, Material.CHAINMAIL_LEGGINGS, Material.DIAMOND_LEGGINGS};
|
||||
boots = new Material[]{Material.LEATHER_BOOTS, Material.GOLD_BOOTS, Material.CHAINMAIL_BOOTS, Material.IRON_BOOTS, Material.DIAMOND_BOOTS};
|
||||
pickaxe = new Material[]{Material.WOOD_PICKAXE, Material.STONE_PICKAXE, Material.IRON_PICKAXE, Material.GOLD_PICKAXE, Material.DIAMOND_PICKAXE};
|
||||
tools = new Material[]{Material.WOOD_PICKAXE, Material.STONE_PICKAXE, Material.IRON_PICKAXE, Material.GOLD_PICKAXE, Material.DIAMOND_PICKAXE, Material.WOOD_HOE, Material.STONE_HOE, Material.IRON_HOE, Material.GOLD_HOE, Material.DIAMOND_HOE, Material.WOOD_SPADE, Material.STONE_SPADE, Material.IRON_SPADE, Material.GOLD_SPADE, Material.DIAMOND_SPADE, Material.WOOD_AXE, Material.STONE_AXE, Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE, Material.FISHING_ROD};
|
||||
axe = new Material[]{Material.WOOD_AXE, Material.STONE_AXE, Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE};
|
||||
weapons = new Material[]{Material.WOOD_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLD_SWORD, Material.DIAMOND_SWORD, Material.WOOD_AXE, Material.STONE_AXE, Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE, Material.BOW};
|
||||
weapons_and_tools = new Material[]{Material.WOOD_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLD_SWORD, Material.DIAMOND_SWORD, Material.WOOD_AXE, Material.STONE_AXE, Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE, Material.BOW, Material.WOOD_PICKAXE, Material.STONE_PICKAXE, Material.IRON_PICKAXE, Material.GOLD_PICKAXE, Material.DIAMOND_PICKAXE, Material.WOOD_HOE, Material.STONE_HOE, Material.IRON_HOE, Material.GOLD_HOE, Material.DIAMOND_HOE, Material.WOOD_SPADE, Material.STONE_SPADE, Material.IRON_SPADE, Material.GOLD_SPADE, Material.DIAMOND_SPADE, Material.WOOD_AXE, Material.STONE_AXE, Material.IRON_AXE, Material.GOLD_AXE, Material.DIAMOND_AXE};
|
||||
}
|
||||
|
||||
private ItemUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static String getDisplayName(ItemStack is) {
|
||||
return is.hasItemMeta() && is.getItemMeta().hasDisplayName() ? is.getItemMeta().getDisplayName() : StringUtils.capitaliseAllWords(is.getType().name().toLowerCase().replace("_", " "));
|
||||
}
|
||||
public static boolean isBoots(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack.getType().name().contains("_BOOTS")));
|
||||
}
|
||||
|
||||
public static boolean isLeggings(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack.getType().name().contains("_LEGGINGS")));
|
||||
}
|
||||
|
||||
public static boolean isChestplate(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack.getType().name().contains("_CHESTPLATE")));
|
||||
}
|
||||
|
||||
public static boolean isHelmet(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack.getType().name().contains("_HELMET")));
|
||||
}
|
||||
|
||||
public static boolean isArmor(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack
|
||||
.getType().name().contains("_HELMET") || itemStack
|
||||
.getType().name().contains("_CHESTPLATE") || itemStack
|
||||
.getType().name().contains("_LEGGINGS") || itemStack
|
||||
.getType().name().contains("_BOOTS")));
|
||||
}
|
||||
|
||||
public static boolean isTool(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack
|
||||
.getType().name().contains("_SHOVEL") || itemStack
|
||||
.getType().name().contains("_HOE") || itemStack
|
||||
.getType().name().contains("_PICKAXE")));
|
||||
}
|
||||
|
||||
public static boolean isWeapon(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && (itemStack
|
||||
.getType().name().endsWith("_SWORD") || itemStack
|
||||
.getType().name().endsWith("_AXE") || itemStack
|
||||
.getType().name().endsWith("_HOE")
|
||||
));
|
||||
}
|
||||
|
||||
public static boolean isSword(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && itemStack
|
||||
.getType().name().contains("_SWORD") || itemStack.getType().name().endsWith("_HOE"));
|
||||
}
|
||||
|
||||
public static boolean isAxe(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && itemStack
|
||||
.getType().name().contains("_AXE") || itemStack.getType().name().endsWith("_HOE"));
|
||||
}
|
||||
|
||||
public static boolean isEnchantable(ItemStack itemStack) {
|
||||
if (isAirOrNull(itemStack)) return false;
|
||||
return (isTool(itemStack) ||
|
||||
isArmor(itemStack) ||
|
||||
isWeapon(itemStack) ||
|
||||
itemStack.getType() == Material.BOW);
|
||||
}
|
||||
|
||||
public static boolean isSkull(ItemStack itemStack) {
|
||||
return (!isAirOrNull(itemStack) && itemStack.getType() == Material.SKULL_ITEM);
|
||||
}
|
||||
|
||||
public static boolean isAirOrNull(ItemStack item){
|
||||
return item == null || item.getType().equals(Material.AIR);
|
||||
}
|
||||
|
||||
public static ItemStack decreaseItemStackAmountByOne(ItemStack itemStack) {
|
||||
if (itemStack.getAmount() == 1) return null;
|
||||
|
||||
itemStack.setAmount(itemStack.getAmount() - 1);
|
||||
return itemStack;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package net.crankedpvp.crankedutils.utils.items;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.Property;
|
||||
import de.tr7zw.nbtapi.NBTCompound;
|
||||
import de.tr7zw.nbtapi.NBTItem;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.UUID;
|
||||
|
||||
public class SkullUtils {
|
||||
|
||||
private final static ItemStack DEFAULT_SKULL = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
|
||||
|
||||
public static ItemStack getSkullFromSkin(String skinURL) {
|
||||
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)3);
|
||||
if (skinURL == null || skinURL.isEmpty())
|
||||
return skull;
|
||||
SkullMeta skullMeta = (SkullMeta)skull.getItemMeta();
|
||||
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
|
||||
profile.getProperties().put("textures", new Property("textures", Base64Coder.encodeString("{textures:{SKIN:{\"url\":\"http://textures.minecraft.net/texture/" + skinURL + "\"}}}")));
|
||||
Field profileField;
|
||||
try {
|
||||
profileField = skullMeta.getClass().getDeclaredField("profile");
|
||||
} catch (NoSuchFieldException|SecurityException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
profileField.setAccessible(true);
|
||||
try {
|
||||
profileField.set(skullMeta, profile);
|
||||
} catch (IllegalArgumentException|IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
skull.setItemMeta(skullMeta);
|
||||
return skull;
|
||||
}
|
||||
|
||||
public static ItemStack getSkull(ItemStack item, String skullTexture) {
|
||||
if (skullTexture == null) throw new IllegalStateException("Skull Texture cannot be null!");
|
||||
|
||||
NBTItem nbtItem = new NBTItem(item);
|
||||
|
||||
NBTCompound skullOwnerCompound = nbtItem.addCompound("SkullOwner");
|
||||
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
skullOwnerCompound.setString("Id", uuid);
|
||||
|
||||
skullOwnerCompound.addCompound("Properties").getCompoundList("textures").addCompound().setString("Value", skullTexture);
|
||||
|
||||
return nbtItem.getItem();
|
||||
}
|
||||
|
||||
public static ItemStack editSkullTexture(ItemStack itemStack, String skullTexture) {
|
||||
if(itemStack == null || itemStack.getType() != Material.SKULL_ITEM) return null;
|
||||
if (skullTexture == null) throw new IllegalStateException("Skull Texture cannot be null!");
|
||||
|
||||
NBTItem nbtItem = new NBTItem(itemStack);
|
||||
NBTCompound skullOwnerCompound = nbtItem.getCompound("SkullOwner");
|
||||
if(skullOwnerCompound == null) return null;
|
||||
if(skullOwnerCompound.hasKey("Id")) return null;
|
||||
if(skullOwnerCompound.getCompound("Properties") == null) return null;
|
||||
NBTCompound propertiesCompound = skullOwnerCompound.getCompound("Properties");
|
||||
if(propertiesCompound == null) return null;
|
||||
if(propertiesCompound.getCompoundList("textures") == null) return null;
|
||||
propertiesCompound.getCompoundList("textures").stream().filter(nbtListCompound -> nbtListCompound.hasTag("Value")).forEach(nbtListCompound -> nbtListCompound.getString("Value"));
|
||||
return nbtItem.getItem();
|
||||
}
|
||||
|
||||
public static ItemStack getSkull(String skullTexture) {
|
||||
if (skullTexture == null) throw new IllegalStateException("Skull Texture cannot be null!");
|
||||
return getSkull(DEFAULT_SKULL, skullTexture);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static ItemStack getSkullFromPlayer(OfflinePlayer player) {
|
||||
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
|
||||
SkullMeta skull = (SkullMeta) item.getItemMeta();
|
||||
skull.setDisplayName(player.getName());
|
||||
skull.setOwner(player.getName());
|
||||
item.setItemMeta(skull);
|
||||
return item;
|
||||
}
|
||||
|
||||
public static ItemStack getSkullFromPlayer(Player player) {
|
||||
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
|
||||
SkullMeta skull = (SkullMeta) item.getItemMeta();
|
||||
skull.setDisplayName(player.getName());
|
||||
skull.setOwner(player.getName());
|
||||
item.setItemMeta(skull);
|
||||
return item;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer;
|
||||
|
||||
public interface VariableSerializer<T> {
|
||||
|
||||
String serialize(T obj);
|
||||
|
||||
T deserialize(String s);
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.item;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.serializer.VariableSerializer;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.io.BukkitObjectInputStream;
|
||||
import org.bukkit.util.io.BukkitObjectOutputStream;
|
||||
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
public class ItemStackArraySerializer {
|
||||
|
||||
public static String serialize(ItemStack[] obj) {
|
||||
try {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
|
||||
|
||||
dataOutput.writeInt(obj.length);
|
||||
|
||||
for (ItemStack itemStack : obj) {
|
||||
dataOutput.writeObject(itemStack);
|
||||
}
|
||||
|
||||
dataOutput.close();
|
||||
return Base64Coder.encodeLines(outputStream.toByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Unable to save item stacks.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static ItemStack[] deserialize(String s) {
|
||||
try {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(s));
|
||||
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
|
||||
ItemStack[] items = new ItemStack[dataInput.readInt()];
|
||||
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
items[i] = (ItemStack) dataInput.readObject();
|
||||
}
|
||||
|
||||
dataInput.close();
|
||||
return items;
|
||||
} catch (Exception e) {
|
||||
return new ItemStack[0];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.item;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.serializer.VariableSerializer;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.io.BukkitObjectInputStream;
|
||||
import org.bukkit.util.io.BukkitObjectOutputStream;
|
||||
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ItemStackListSerializer {
|
||||
|
||||
public static String serialize(List<ItemStack> obj) {
|
||||
try {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
|
||||
dataOutput.writeInt(obj.size());
|
||||
|
||||
for (ItemStack itemStack : obj) {
|
||||
dataOutput.writeObject(itemStack);
|
||||
}
|
||||
|
||||
dataOutput.close();
|
||||
return Base64Coder.encodeLines(outputStream.toByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Unable to save item stacks.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<ItemStack> deserialize(String s) {
|
||||
try {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(s));
|
||||
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
|
||||
List<ItemStack> list = new ArrayList<>();
|
||||
|
||||
for(int i = 0; i < dataInput.readInt(); i++) {
|
||||
list.add((ItemStack) dataInput.readObject());
|
||||
}
|
||||
|
||||
dataInput.close();
|
||||
return list;
|
||||
} catch (Exception e) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.item;
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.serializer.VariableSerializer;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.io.BukkitObjectInputStream;
|
||||
import org.bukkit.util.io.BukkitObjectOutputStream;
|
||||
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
public class ItemStackSerializer {
|
||||
|
||||
public static String serialize(ItemStack obj) {
|
||||
try {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
|
||||
|
||||
dataOutput.writeObject(obj);
|
||||
|
||||
dataOutput.close();
|
||||
return Base64Coder.encodeLines(outputStream.toByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Unable to save item stacks.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static ItemStack deserialize(String s) {
|
||||
try {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(s));
|
||||
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
|
||||
|
||||
return (ItemStack) dataInput.readObject();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Unable to load item stack.", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.location;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LocationSerializerDeserializer {
|
||||
|
||||
public static String serialize(Location obj) {
|
||||
if (obj == null) {
|
||||
return "";
|
||||
}
|
||||
return obj.getWorld().getName() + ":" + obj.getBlockX() + ":" + obj.getBlockY() + ":" + obj.getBlockZ();
|
||||
}
|
||||
|
||||
public static Location deserialize(String s) {
|
||||
if (s == null || s.trim().equals("")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final String[] parts = s.split(":");
|
||||
|
||||
if (parts.length == 4) {
|
||||
final World w = Bukkit.getServer().getWorld(parts[0]);
|
||||
final int x = Integer.parseInt(parts[1]);
|
||||
final int y = Integer.parseInt(parts[2]);
|
||||
final int z = Integer.parseInt(parts[3]);
|
||||
return new Location(w, x, y, z);
|
||||
}
|
||||
|
||||
if (parts.length == 6) {
|
||||
final World w = Bukkit.getServer().getWorld(parts[0]);
|
||||
final double x = Double.parseDouble(parts[1]);
|
||||
final double y = Double.parseDouble(parts[2]);
|
||||
final double z = Double.parseDouble(parts[3]);
|
||||
final float yaw = Float.parseFloat(parts[4]);
|
||||
final float pitch = Float.parseFloat(parts[5]);
|
||||
return new Location(w, x, y, z, yaw, pitch);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static List<Location> deserializeArray(List<String> strings) {
|
||||
return strings.stream()
|
||||
.map(LocationSerializerDeserializer::deserialize)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.uuid;
|
||||
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.serializer.VariableSerializer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDListSerializer {
|
||||
|
||||
|
||||
public static String serialize(List<UUID> l) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
if(l == null) return "";
|
||||
for(UUID u : l)
|
||||
b.append(u.toString()).append(",");
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
public static List<UUID> deserialize(String s) {
|
||||
if(s==null || s.isEmpty()) return null;
|
||||
String[] array = s.split(",");
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
for(String str : array) {
|
||||
str = str.replace(",", "");
|
||||
if(str.isEmpty()) continue;
|
||||
uuids.add(UUID.fromString(str));
|
||||
}
|
||||
return uuids;
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package net.crankedpvp.crankedutils.utils.serializer.uuid;
|
||||
|
||||
|
||||
import net.crankedpvp.crankedutils.utils.serializer.VariableSerializer;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDSerializer {
|
||||
|
||||
public static String serialize(UUID obj) {
|
||||
if(obj == null) return "";
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public static UUID deserialize(String s) {
|
||||
try {
|
||||
return UUID.fromString(s);
|
||||
}catch(Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user