9
0
mirror of https://github.com/PSYCHEER/VanillaCustomizer.git synced 2025-12-31 12:56:40 +00:00

Initial commit

This commit is contained in:
LoneDev
2024-05-14 13:52:25 +02:00
commit c9e53353ff
79 changed files with 6145 additions and 0 deletions

View File

@@ -0,0 +1,86 @@
package dev.lone.vanillacustomizer;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.annotations.Nullable;
import dev.lone.vanillacustomizer.customization.rules.RuleVanillaItemMatcher;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
// TODO: find a better name for this
public class ChangeSession
{
public final ItemStack item;
public final ItemStack originalItem;
public ItemMeta meta;
public NBTItem nbt;
public final boolean isVanilla;
@Nullable
private Boolean hasChanged_cached;
public ChangeSession(ItemStack item, boolean trackChanges)
{
this.item = item;
if(trackChanges)
this.originalItem = item.clone();
else
this.originalItem = null;
isVanilla = RuleVanillaItemMatcher.satisfy(item);
}
public ItemMeta refreshMeta()
{
// Meta always needs to be refreshed as Spigot caches it!
meta = item.getItemMeta();
return meta;
}
private void refreshNbt()
{
nbt = new NBTItem(item);
}
public NBTItem nbt()
{
if(nbt != null)
return nbt;
refreshNbt();
return nbt;
}
/**
* Shorthand to call saveMetaChanges and avoid deprecation warning
*/
@SuppressWarnings("deprecation")
public void saveNbt()
{
// nbt.saveMetaChanges(); // TODO: idk if I need to somehow save the data or not, probably new NBT api lib doesn't require it anymore.
}
public void applyMeta()
{
this.item.setItemMeta(this.meta);
refreshNbt();
}
public boolean hasChanged()
{
if(hasChanged_cached != null)
return hasChanged_cached;
if(originalItem == null)
return false;
hasChanged_cached = !originalItem.equals(item);
return hasChanged_cached;
}
public void refreshAll()
{
refreshNbt();
refreshMeta();
}
}

View File

@@ -0,0 +1,513 @@
package dev.lone.vanillacustomizer;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import dev.lone.LoneLibs.annotations.Nullable;
import dev.lone.vanillacustomizer.api.VanillaCustomizerApi;
import dev.lone.vanillacustomizer.commands.registered.MainCommand;
import dev.lone.vanillacustomizer.customization.changes.*;
import dev.lone.vanillacustomizer.customization.Customization;
import dev.lone.vanillacustomizer.customization.matchers.RuleNbtMatcher;
import dev.lone.vanillacustomizer.customization.rules.*;
import dev.lone.vanillacustomizer.nms.items.Rarity;
import dev.lone.vanillacustomizer.utils.*;
import org.apache.commons.io.FileUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.util.*;
public class Customizations
{
public LinkedHashMap<String, Customization> customizations = new LinkedHashMap<>();
public void load()
{
customizations.clear();
for (File file : getAllYmlFiles())
{
ConfigFile config = new ConfigFile(Main.inst(), false, file.toPath().toString(), false, false);
ConfigurationSection cosmeticsSection = config.getConfigurationSection("customizations");
if (cosmeticsSection == null) // File has no rules
continue;
for (String key : cosmeticsSection.getKeys(false))
{
Customization customization = new Customization();
ConfigurationSection section = config.getConfigurationSection("customizations." + key);
assert section != null;
if(!section.getBoolean("enabled", true))
continue;
// TODO: rules_match: ANY | ALL
ConfigurationSection rulesSection = section.getConfigurationSection("rules");
if (rulesSection == null)
{
Main.msg.error("Error: Customization '" + key + "' missing 'rules'. File: " + config.getPartialFilePath());
continue;
}
for (String matcherKey : rulesSection.getKeys(false))
{
try
{
switch (matcherKey)
{
case "material_wildcards" ->
{
List<String> materialWildcards = rulesSection.getStringList(matcherKey);
RuleMaterialWildcards rule = new RuleMaterialWildcards();
for (String noMatch : rule.init(materialWildcards))
{
Main.msg.warn("Warning: 'material_wildcards' -> '" + noMatch + "' of '" + key + "' has matched 0 items. File: " + config.getPartialFilePath());
}
customization.addRule(rule);
}
case "material" ->
{
String matStr = rulesSection.getString(matcherKey);
Material material = EnumUtil.safeGet(matStr, Material.class, null);
if (material == null)
{
throwInvalidPropertyValue("material", matStr);
// Main.msg.error("Error: Customization '" + key + "' has invalid 'material'. File: " + config.getPartialFilePath());
break;
}
customization.addRule(new RuleMaterial(material));
}
case "materials" ->
{
List<String> matStrings = rulesSection.getStringList(matcherKey);
List<Material> materials = new ArrayList<>();
for (String matStr : matStrings)
{
Material material = EnumUtil.safeGet(matStr, Material.class, null);
if (material == null)
{
throwInvalidPropertyValue("material", matStr);
// Main.msg.error("Error: Customization '" + key + "' has invalid 'material'. File: " + config.getPartialFilePath());
}
else
{
materials.add(material);
}
}
customization.addRule(new RuleMaterials(materials));
}
case "material_regex" ->
{
String regexStr = rulesSection.getString(matcherKey);
RuleMaterialRegex ruleMaterialRegex = new RuleMaterialRegex(regexStr);
customization.addRule(ruleMaterialRegex);
}
case "nbt" ->
{
RuleNbtMatcher nbtMatcher = new RuleNbtMatcher(
rulesSection.getString(matcherKey + ".path"),
rulesSection.getString(matcherKey + ".value"),
rulesSection.getString(matcherKey + ".type", "string")
);
customization.addRule(nbtMatcher);
}
// Matches only items which don't have custom lore and colored display name.
case "is_vanilla_item" ->
{
boolean isVanilla = rulesSection.getBoolean(matcherKey);
customization.addRule(new RuleVanillaItemMatcher(isVanilla));
}
case "rarity" ->
{
String rarityString = rulesSection.getString(matcherKey, "").toUpperCase();
Rarity rarity = EnumUtil.safeGet(rarityString,
Rarity.class,
null);
if(rarity == null)
{
throwInvalidPropertyValue("rarity", rarityString);
continue;
}
RuleRarity rule = new RuleRarity(rarity);
customization.addRule(rule);
}
case "placeable" ->
{
boolean is = rulesSection.getBoolean(matcherKey);
customization.addRule(new RulePlaceable(is));
}
case "hardness_greater_than" ->
{
double val = rulesSection.getDouble(matcherKey);
customization.addRule(new RuleHardnessGraterThan(val));
}
case "edible" ->
{
boolean val = rulesSection.getBoolean(matcherKey);
customization.addRule(new RuleEdible(val));
}
case "smelted" ->
{
boolean val = rulesSection.getBoolean(matcherKey);
customization.addRule(new RuleSmelted(val));
}
}
}
catch (Throwable ex)
{
if(ex instanceof InvalidCustomizationPropertyExtension)
{
Main.msg.error("Error loading customization '" + key + "'. File: " + config.getPartialFilePath());
Main.msg.error(ex.getMessage());
}
else
Main.msg.error("Error loading customization '" + key + "'. File: " + config.getPartialFilePath(), ex);
}
}
ConfigurationSection changesSection = section.getConfigurationSection("changes");
if (changesSection == null)
{
Main.msg.error("Error: Customization '" + key + "' missing 'changes'. File: " + config.getPartialFilePath());
continue;
}
for (String changeKey : changesSection.getKeys(false))
{
try
{
switch (changeKey)
{
case "rename" ->
{
String name = changesSection.getString(changeKey);
assert name != null;
customization.addChange(new Renamer(name));
}
case "rename_json" ->
{
String json = changesSection.getString(changeKey);
customization.addChange(new RenamerJson(json));
}
case "replace_word_display_name" ->
{
ConfigurationSection thisSection = changesSection.getConfigurationSection(changeKey);
if (thisSection == null)
throwInvalidConfig();
String from = thisSection.getString("from");
String to = thisSection.getString("to");
customization.addChange(new ReplaceWordDisplayName(from, to));
}
case "lore_set" ->
{
List<String> list = changesSection.getStringList(changeKey);
customization.addChange(new LoreSet(list));
}
case "lore_set_json" ->
{
List<String> list = changesSection.getStringList(changeKey);
customization.addChange(new LoreSetJson(list));
}
case "lore_insert" ->
{
ConfigurationSection thisSection = changesSection.getConfigurationSection(changeKey);
if (thisSection == null)
throwInvalidConfig();
List<String> list = thisSection.getStringList("lines");
int index = thisSection.getInt("index", 0);
customization.addChange(new LoreInsert(list, index));
}
case "lore_insert_json" ->
{
ConfigurationSection thisSection = changesSection.getConfigurationSection(changeKey);
if (thisSection == null)
throwInvalidConfig();
List<String> list = thisSection.getStringList("lines");
int index = thisSection.getInt("index", 0);
customization.addChange(new LoreInsertJson(list, index));
}
case "replace_word_lore" ->
{
ConfigurationSection thisSection = changesSection.getConfigurationSection(changeKey);
if (thisSection == null)
throwInvalidConfig();
String from = thisSection.getString("from");
String to = thisSection.getString("to");
customization.addChange(new ReplaceWordLore(from, to));
}
case "protect_nbt_data" ->
{
customization.addChange(new ProtectNbtData());
}
case "durability" ->
{
short amount = (short) changesSection.getInt(changeKey);
customization.addChange(new ReplaceDurability(amount));
}
case "custom_model_data" ->
{
int id = changesSection.getInt(changeKey);
customization.addChange(new ReplaceCustomModelData(id));
}
case "add_enchants" ->
{
HashMap<Enchantment, Integer> enchants = new HashMap<>();
List<String> enchantsStrings = changesSection.getStringList(changeKey);
for (String enchantStringEntry : enchantsStrings)
{
String[] tmp = enchantStringEntry.split(":");
Enchantment enchant = null;
int enchantLevel = 1;
if (tmp.length == 1)
{
enchant = Enchantment.getByName(tmp[0]);
if (enchant == null)
enchant = Enchantment.getByKey(NamespacedKey.minecraft(tmp[0]));
}
else if (tmp.length == 2)
{
if (Utilz.isNumeric(tmp[1]))
{
enchant = Enchantment.getByName(tmp[0]);
enchantLevel = Utilz.parseInt(tmp[1], 1);
if (enchant == null)
enchant = Enchantment.getByKey(NamespacedKey.minecraft(tmp[0]));
}
else
{
enchant = Enchantment.getByKey(new NamespacedKey(tmp[0], tmp[1]));
}
}
else if (tmp.length == 3)
{
enchant = Enchantment.getByKey(new NamespacedKey(tmp[0], tmp[1]));
enchantLevel = Utilz.parseInt(tmp[2], 1);
}
enchants.put(enchant, enchantLevel);
}
customization.addChange(new EnchantsAdd(enchants));
}
case "remove_enchants" ->
{
List<Enchantment> enchants = new ArrayList<>();
List<String> enchantsStrings = changesSection.getStringList(changeKey);
for (String enchantStringEntry : enchantsStrings)
{
String[] tmp = enchantStringEntry.split(":");
Enchantment enchant = null;
if (tmp.length == 1)
{
enchant = Enchantment.getByName(tmp[0]);
if (enchant == null)
enchant = Enchantment.getByKey(NamespacedKey.minecraft(tmp[0]));
}
else if (tmp.length == 2)
{
if (Utilz.isNumeric(tmp[1]))
{
enchant = Enchantment.getByName(tmp[0]);
if (enchant == null)
enchant = Enchantment.getByKey(NamespacedKey.minecraft(tmp[0]));
}
else
{
enchant = Enchantment.getByKey(new NamespacedKey(tmp[0], tmp[1]));
}
}
else if (tmp.length == 3)
{
enchant = Enchantment.getByKey(new NamespacedKey(tmp[0], tmp[1]));
}
enchants.add(enchant);
}
customization.addChange(new EnchantsRemove(enchants));
}
case "add_attributes" ->
{
Multimap<Attribute, AttributeModifier> modifiers = ArrayListMultimap.create();
ConfigurationSection thisSection = changesSection.getConfigurationSection(changeKey);
if (thisSection == null)
throwInvalidConfig();
Set<String> attributeEntriesKeys = thisSection.getKeys(false);
for (String attributeEntryKey : attributeEntriesKeys)
{
ConfigurationSection attributeSection = thisSection.getConfigurationSection(attributeEntryKey);
if (attributeSection == null)
throwInvalidConfig();
@Nullable String attributeStr = getStringOrThrow(attributeSection, "attribute");
Attribute attribute = Utilz.strToAttributeType(attributeStr);
if (attribute == null)
throwInvalidPropertyValue("attribute");
@Nullable String slotStr = getStringOrThrow(attributeSection, "slot");
EquipmentSlot slot = Utilz.strToVanillaEquipmentSlot(slotStr);
if (slot == null)
throwInvalidPropertyValue("slot");
@Nullable String name = getStringOrThrow(attributeSection, "name");
@Nullable String uuid = attributeSection.getString("uuid");
@Nullable String operation = getStringOrThrow(attributeSection, "operation");
@Nullable double amount = attributeSection.getDouble("amount", 0);
AttributeModifier modifier = AttributesAdd.generateModifier(
uuid,
name,
attribute,
amount,
operation,
slot
);
modifiers.put(attribute, modifier);
}
customization.addChange(new AttributesAdd(modifiers));
}
case "flags" ->
{
List<String> flagsStrings = changesSection.getStringList(changeKey);
if (flagsStrings.size() == 0)
throwInvalidPropertyValue("flags");
List<ItemFlag> flags = new ArrayList<>();
for (String flagsString : flagsStrings)
{
ItemFlag flag = EnumUtil.safeGet(flagsString, ItemFlag.class, null);
if(flag == null)
{
throwInvalidPropertyValue("flags", flagsString);
continue;
}
flags.add(flag);
}
customization.addChange(new FlagsAdd(flags));
}
case "material" ->
{
Material material = EnumUtil.safeGet(changesSection.getString(changeKey, "").toUpperCase(),
Material.class,
null);
if (material == null)
throwInvalidPropertyValue("material");
customization.addChange(new ReplaceMaterial(material));
}
}
}
catch (Throwable ex)
{
if(ex instanceof InvalidCustomizationPropertyExtension)
{
Main.msg.error("Error loading customization '" + key + "'. File: " + config.getPartialFilePath());
Main.msg.error(ex.getMessage());
}
else
Main.msg.error("Error loading customization '" + key + "'. File: " + config.getPartialFilePath(), ex);
}
}
if (!customization.isEmpty())
{
customizations.put(key, customization);
}
}
}
}
private String getStringOrThrow(ConfigurationSection section, String name)
{
@Nullable String value = section.getString(name);
if(value == null)
throwMissingProperty(name);
return value;
}
private void throwInvalidConfig()
{
throw new InvalidCustomizationPropertyExtension("Invalid configuration. Please check the tutorials.");
}
private void throwMissingProperty(String name)
{
throw new InvalidCustomizationPropertyExtension("Missing property '" + name + "'.");
}
private void throwInvalidPropertyValue(String name)
{
throw new InvalidCustomizationPropertyExtension("Invalid value for property '" + name + "'.");
}
private void throwInvalidPropertyValue(String name, String value)
{
throw new InvalidCustomizationPropertyExtension("Invalid value for property '" + name + "' -> '" + value + "'.");
}
public void handle(ItemStack itemStack, Player player)
{
if (itemStack == null || itemStack.getType() == Material.AIR)
return;
boolean trackChanges = MainCommand.hasDebugTag(player);
ChangeSession session = new ChangeSession(itemStack, trackChanges);
for (Map.Entry<String, Customization> entry : customizations.entrySet())
{
Customization customization = entry.getValue();
customization.handle(session);
}
// Warning! This doesn't edit the session data. Do not access use "customization" obj
// after this line since it would result not updated with changes done by the API handlers.
boolean apiExecuted = VanillaCustomizerApi.inst().executeHandlers(session.item, player);
// In case the API executed any code.
if(apiExecuted)
session.refreshAll();
if(trackChanges && session.hasChanged())
{
// TODO make it configurable
LoreInsert.putLine(session, 0, ChatColor.GOLD + SmallCaps.apply("VANILLACUSTOMIZER"));
//noinspection DataFlowIssue
if(session.refreshMeta().getLore().size() > 1)
LoreInsert.putLine(session, 1, " ");
}
}
private static List<File> getAllYmlFiles()
{
File cosmeticsDir = new File(Main.inst().getDataFolder().getAbsolutePath() + "/contents/");
if (!cosmeticsDir.exists())
cosmeticsDir.mkdirs();
return new ArrayList<>(FileUtils.listFiles(
cosmeticsDir,
new String[]{"yml"},
true
));
}
}

View File

@@ -0,0 +1,9 @@
package dev.lone.vanillacustomizer;
public class InvalidCustomizationPropertyExtension extends IllegalArgumentException
{
public InvalidCustomizationPropertyExtension(String text)
{
super(text);
}
}

View File

@@ -0,0 +1,159 @@
package dev.lone.vanillacustomizer;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.Pair;
import dev.lone.LoneLibs.chat.Msg;
import dev.lone.vanillacustomizer.commands.Commands;
import dev.lone.vanillacustomizer.nms.items.ItemsNms;
import dev.lone.vanillacustomizer.utils.Packets;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
public final class Main extends JavaPlugin implements Listener
{
// Useful:
// https://lingojam.com/MinecraftSmallFont
// https://game8.co/games/Minecraft/archives/378457#hl_1
//DO NOT SET AS "final" OR SPIGOT.MC won't replace it.
public static String b = "%%__USER__%%";
public static Msg msg;
private static Main inst;
public static Main inst()
{
return inst;
}
Customizations customizations;
@Override
public void onEnable()
{
inst = this;
msg = new Msg("[VanillaCustomizer] ");
Bukkit.getPluginManager().registerEvents(this, this);
ItemsNms.inst().initialize();
customizations = new Customizations();
// https://nms.screamingsandals.org/1.19/net/minecraft/network/protocol/game/ClientboundContainerSetContentPacket.html
Packets.out(this, PacketType.Play.Server.WINDOW_ITEMS, e -> {
Player player = e.getPlayer();
if(player.getGameMode() == GameMode.CREATIVE)
return;
PacketContainer packet = e.getPacket();
List<ItemStack> items = packet.getItemListModifier().read(0);
ItemStack carriedItem = packet.getItemModifier().read(0);
for (ItemStack item : items)
{
customizations.handle(item, player);
}
customizations.handle(carriedItem, player);
});
// https://nms.screamingsandals.org/1.19/net/minecraft/network/protocol/game/ClientboundSetEquipmentPacket.html
Packets.out(this, PacketType.Play.Server.ENTITY_EQUIPMENT, e -> {
Player player = e.getPlayer();
if(player.getGameMode() == GameMode.CREATIVE)
return;
PacketContainer packet = e.getPacket();
List<Pair<EnumWrappers.ItemSlot, ItemStack>> slotsPairs = packet.getSlotStackPairLists().read(0);
for (Pair<EnumWrappers.ItemSlot, ItemStack> pair : slotsPairs)
{
customizations.handle(pair.getSecond(), player);
}
});
// https://nms.screamingsandals.org/1.19.2/net/minecraft/network/protocol/game/ClientboundContainerSetSlotPacket.html
Packets.out(this, PacketType.Play.Server.SET_SLOT, e -> {
Player player = e.getPlayer();
if(player.getGameMode() == GameMode.CREATIVE)
return;
PacketContainer packet = e.getPacket();
ItemStack itemStack = packet.getItemModifier().read(0);
customizations.handle(itemStack, player);
});
// https://mappings.cephx.dev/1.20.1/net/minecraft/network/protocol/game/ClientboundMerchantOffersPacket.html
Packets.out(this, PacketType.Play.Server.OPEN_WINDOW_MERCHANT, e -> {
Player player = e.getPlayer();
if(player.getGameMode() == GameMode.CREATIVE)
return;
PacketContainer packet = e.getPacket();
List<MerchantRecipe> recipes = packet.getMerchantRecipeLists().read(0);
for (int i = 0, recipesSize = recipes.size(); i < recipesSize; i++)
{
// NOTE: for some reason, I don't know why, if I don't clone the items they actually get edited in-game!
// I'm sure since if I quit the server, remove the plugin and join I still see the edited recipes!
MerchantRecipe recipe = recipes.get(i);
List<ItemStack> ingredients = recipe.getIngredients();
for (int j = 0, ingredientsSize = ingredients.size(); j < ingredientsSize; j++)
{
ItemStack itemStack = ingredients.get(j).clone();
customizations.handle(itemStack, player);
ingredients.set(j, itemStack);
}
ItemStack result = recipe.getResult().clone();
customizations.handle(result, player);
MerchantRecipe newRecipe = new MerchantRecipe(result, recipe.getMaxUses());
newRecipe.setUses(recipe.getUses());
newRecipe.setDemand(recipe.getDemand());
newRecipe.setPriceMultiplier(recipe.getPriceMultiplier());
newRecipe.setExperienceReward(recipe.hasExperienceReward());
newRecipe.setSpecialPrice(recipe.getSpecialPrice());
newRecipe.setIngredients(ingredients);
newRecipe.setVillagerExperience(recipe.getVillagerExperience());
recipes.set(i, newRecipe);
}
packet.getMerchantRecipeLists().write(0, recipes);
});
Commands.register(this);
reload();
}
public void reload()
{
customizations.load();
}
@EventHandler(ignoreCancelled = true)
private void onGamemode(PlayerGameModeChangeEvent e)
{
// This is important to force the player inventory to update ( #updateInventory() triggers WINDOW_ITEMS packet)
// so that the CREATIVE gamemode won't edit the items, as CREATIVE makes the client apply any visual change
// to the items, the game works like that, for example custom clients can create any NBT item while in CREATIVE.
Bukkit.getScheduler().runTaskLater(this, () -> {
e.getPlayer().updateInventory();
}, 5L);
}
}

View File

@@ -0,0 +1,75 @@
package dev.lone.vanillacustomizer.api;
import dev.lone.vanillacustomizer.Main;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unused")
public class VanillaCustomizerApi implements Listener
{
//<editor-fold desc="Exposed API">
public static VanillaCustomizerApi inst()
{
if(inst == null)
inst = new VanillaCustomizerApi(Main.inst());
return inst;
}
public void registerHandler(Plugin plugin, CustomizerHandler handler)
{
handlers.computeIfAbsent(plugin, plugin1 -> new ArrayList<>()).add(handler);
}
@FunctionalInterface
public interface CustomizerHandler
{
void call(Player player, ItemStack itemStack);
}
//</editor-fold>
//<editor-fold desc="Internal methods">
private static final HashMap<Plugin, List<CustomizerHandler>> handlers = new HashMap<>();
private static VanillaCustomizerApi inst;
VanillaCustomizerApi(Plugin plugin)
{
Bukkit.getPluginManager().registerEvents(this, plugin);
}
public boolean executeHandlers(ItemStack itemStack, Player player)
{
if(handlers.size() == 0)
return false;
boolean executedAnything = false;
for (Map.Entry<Plugin, List<CustomizerHandler>> entry : handlers.entrySet())
{
List<CustomizerHandler> handlers = entry.getValue();
for (CustomizerHandler handler : handlers)
{
handler.call(player, itemStack);
executedAnything = true;
}
}
return executedAnything;
}
@EventHandler
private void pluginUnload(PluginDisableEvent e)
{
handlers.remove(e.getPlugin());
}
//</editor-fold>
}

View File

@@ -0,0 +1,38 @@
package dev.lone.vanillacustomizer.commands;
import dev.lone.LoneLibs.annotations.NotNull;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
public abstract class CommandRun implements CommandExecutor, TabCompleter
{
protected CommandRun(JavaPlugin plugin, String name)
{
plugin.getCommand(name).setExecutor(this);
plugin.getCommand(name).setTabCompleter(this);
}
protected abstract void run(Player sender, Command command, String label, String[] args);
protected abstract void run(ConsoleCommandSender sender, Command command, String label, String[] args);
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args)
{
if(sender instanceof Player)
run((Player) sender, command, label, args);
else if(sender instanceof ConsoleCommandSender)
run((ConsoleCommandSender) sender, command, label, args);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, @NotNull String[] args)
{
return List.of();
}
}

View File

@@ -0,0 +1,12 @@
package dev.lone.vanillacustomizer.commands;
import dev.lone.vanillacustomizer.commands.registered.MainCommand;
import org.bukkit.plugin.java.JavaPlugin;
public class Commands
{
public static void register(JavaPlugin plugin)
{
new MainCommand(plugin, "vanillacustomizer");
}
}

View File

@@ -0,0 +1,135 @@
package dev.lone.vanillacustomizer.commands.registered;
import dev.lone.LoneLibs.annotations.NotNull;
import dev.lone.vanillacustomizer.Main;
import dev.lone.vanillacustomizer.commands.CommandRun;
import dev.lone.vanillacustomizer.utils.SmallCaps;
import fr.mrmicky.fastinv.FastInv;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.List;
import java.util.stream.IntStream;
public class MainCommand extends CommandRun
{
HashMap<Player, Integer> playerPage = new HashMap<>();
public MainCommand(JavaPlugin plugin, String name)
{
super(plugin, name);
}
public static boolean hasDebugTag(Player player)
{
return player.hasMetadata("showdebugtag");
}
@Override
public void run(Player player, Command command, String label, String[] args)
{
if(args.length >= 1)
{
switch (args[0])
{
case "showdebugtag":
boolean showdebugtag = hasDebugTag(player);
if (showdebugtag)
Main.msg.send(player, "Disabled debug tag");
else
Main.msg.send(player, "Enabled debug tag");
if (!showdebugtag)
player.setMetadata("showdebugtag", new FixedMetadataValue(Main.inst(), 0));
else
player.removeMetadata("showdebugtag", Main.inst());
// To trigger refresh
player.updateInventory();
break;
case "small":
String text = args[1];
Main.msg.send(player, SmallCaps.apply(text));
break;
case "debugmenu":
FastInv inv = new FastInv(54);
int page = 0;
playerPage.put(player, page);
loadPage(inv, page);
inv.setItem(52, new ItemStack(Material.WHITE_CONCRETE), e -> {
// todo check >= 0
playerPage.put(player, playerPage.get(player) - 1);
loadPage(inv, playerPage.get(player));
});
inv.setItem(53, new ItemStack(Material.RED_CONCRETE), e -> {
playerPage.put(player, playerPage.get(player) + 1);
loadPage(inv, playerPage.get(player));
});
inv.open(player);
break;
case "reload":
Main.inst().reload();
Bukkit.getOnlinePlayers().forEach(Player::updateInventory);
Main.msg.send(player, "Reloaded configs.");
break;
}
}
}
@Override
public void run(ConsoleCommandSender sender, Command command, String label, String[] args)
{
if(args.length >= 1)
{
switch (args[0])
{
case "reload":
Main.inst().reload();
Bukkit.getOnlinePlayers().forEach(Player::updateInventory);
Main.msg.send(sender, "Reloaded configs.");
return;
}
}
sender.sendMessage("This command can be run only by players!");
}
private void loadPage(FastInv inv, int page)
{
inv.removeItems(IntStream.rangeClosed(0, 44).toArray());
Material[] values = Material.values();
int j = 0;
for (int i = page * 45; j < 45 && i < values.length; i++)
{
Material mat = values[i];
if (mat.isItem())
{
inv.addItem(new ItemStack(mat));
j++;
}
}
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, @NotNull String[] args)
{
return List.of("reload", "showdebugtag", "small", "debugmenu");
}
}

View File

@@ -0,0 +1,52 @@
package dev.lone.vanillacustomizer.customization;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.vanillacustomizer.customization.changes.IChange;
import dev.lone.vanillacustomizer.customization.rules.IRule;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class Customization
{
public List<IRule> rules = new ArrayList<>();
public List<IChange> changes = new ArrayList<>();
public boolean isEmpty()
{
return rules.isEmpty() && changes.isEmpty();
}
public void addRule(IRule rule)
{
rules.add(rule);
}
public void addChange(IChange change)
{
changes.add(change);
}
public boolean matchesAll(ChangeSession session)
{
for (IRule rule : rules)
{
if(!rule.matches(session))
return false;
}
return true;
}
//TODO: maybe implement also matchAny?
public void handle(ChangeSession session)
{
if(matchesAll(session))
{
for (IChange change : changes)
{
change.apply(session);
}
}
}
}

View File

@@ -0,0 +1,83 @@
package dev.lone.vanillacustomizer.customization.changes;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.inventory.EquipmentSlot;
import dev.lone.LoneLibs.annotations.NotNull;
import dev.lone.LoneLibs.annotations.Nullable;
import java.util.UUID;
public class AttributesAdd implements IChange
{
Multimap<Attribute, AttributeModifier> modifiers;
public AttributesAdd(Multimap<Attribute, AttributeModifier> modifiers)
{
this.modifiers = modifiers;
}
public static AttributeModifier generateModifier(@Nullable String uuid,
String name,
Attribute attribute,
double value,
@NotNull String operation,
EquipmentSlot slot)
{
AttributeModifier.Operation op;
if (operation.equals("multiply_base"))
op = AttributeModifier.Operation.ADD_SCALAR;
else if (operation.equals("multiply"))
op = AttributeModifier.Operation.MULTIPLY_SCALAR_1;
else
op = AttributeModifier.Operation.ADD_NUMBER;
return new AttributeModifier(
uuid != null ? UUID.fromString(uuid) : UUID.nameUUIDFromBytes((attribute + op.name() + value + slot).getBytes()),
name,
value,
op,
slot
);
}
@Override
public void apply(ChangeSession session)
{
session.refreshMeta();
Multimap<Attribute, AttributeModifier> finalModifiers = ArrayListMultimap.create();
if(session.meta.hasAttributeModifiers())
{
Multimap<Attribute, AttributeModifier> originalAttributes = session.meta.getAttributeModifiers();
assert originalAttributes != null;
originalAttributes.forEach((attribute, attributeModifier) -> {
modifiers.forEach((newAttr, newMod) -> {
// If the item already has the same attribute with same UUID I have to replace it with the
// new attribute provided in the configuration.
if(attributeModifier.getUniqueId().equals(newMod.getUniqueId()))
{
finalModifiers.put(newAttr, newMod);
}
// Otherwise I have to put both as they don't interfere.
else
{
finalModifiers.put(attribute, attributeModifier);
finalModifiers.put(newAttr, newMod);
}
});
});
modifiers.forEach(finalModifiers::put);
session.meta.setAttributeModifiers(finalModifiers);
}
else
{
session.meta.setAttributeModifiers(modifiers);
}
session.applyMeta();
}
}

View File

@@ -0,0 +1,64 @@
package dev.lone.vanillacustomizer.customization.changes;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.inventory.EquipmentSlot;
import dev.lone.LoneLibs.annotations.NotNull;
import dev.lone.LoneLibs.annotations.Nullable;
import java.util.UUID;
@Deprecated //TODO
public class AttributesRemove implements IChange
{
Multimap<Attribute, AttributeModifier> modifiers;
public AttributesRemove(Multimap<Attribute, AttributeModifier> modifiers)
{
this.modifiers = modifiers;
}
@Override
public void apply(ChangeSession session)
{
session.refreshMeta();
if (!session.meta.hasAttributeModifiers())
return;
Multimap<Attribute, AttributeModifier> finalModifiers = ArrayListMultimap.create();
Multimap<Attribute, AttributeModifier> originalAttributes = session.meta.getAttributeModifiers();
assert originalAttributes != null;
// modifiers.forEach((attrRemove, modRemove) -> {
//
// if(originalAttributes.containsKey(attrRemove))
// {
// if()
// }
//
// // If the item already has the same attribute with same UUID I have to replace it with the
// // new attribute provided in the configuration.
// if(attributeModifier.getUniqueId().equals(modRemove.getUniqueId()))
// {
// finalModifiers.put(attrRemove, modRemove);
// }
// // Otherwise I have to put both as they don't interfere.
// else
// {
// finalModifiers.put(attribute, attributeModifier);
// finalModifiers.put(attrRemove, modRemove);
// }
// });
//
// originalAttributes.forEach((attribute, attributeModifier) -> {
//
// });
// modifiers.forEach(finalModifiers::put);
// session.meta.setAttributeModifiers(finalModifiers);
//
// session.applyMeta();
}
}

View File

@@ -0,0 +1,37 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.enchantments.Enchantment;
import java.util.HashMap;
import java.util.Map;
public class EnchantsAdd implements IChange
{
final HashMap<Enchantment, Integer> enchants;
public EnchantsAdd(HashMap<Enchantment, Integer> enchants)
{
this.enchants = enchants;
}
@Override
public void apply(ChangeSession session)
{
if(session.refreshMeta() == null)
return;
for (Map.Entry<Enchantment, Integer> e : enchants.entrySet())
{
Enchantment enchantment = e.getKey();
Integer level = e.getValue();
if(level <= 0)
session.meta.removeEnchant(enchantment);
else
session.meta.addEnchant(enchantment, level, true);
}
session.applyMeta();
}
}

View File

@@ -0,0 +1,30 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.enchantments.Enchantment;
import java.util.List;
public class EnchantsRemove implements IChange
{
final List<Enchantment> enchants;
public EnchantsRemove(List<Enchantment> enchants)
{
this.enchants = enchants;
}
@Override
public void apply(ChangeSession session)
{
if(session.refreshMeta() == null)
return;
for (Enchantment enchant : enchants)
{
session.meta.removeEnchant(enchant);
}
session.applyMeta();
}
}

View File

@@ -0,0 +1,24 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.inventory.ItemFlag;
import java.util.List;
public class FlagsAdd implements IChange
{
final ItemFlag[] flags;
public FlagsAdd(List<ItemFlag> flags)
{
this.flags = flags.toArray(ItemFlag[]::new);
}
@Override
public void apply(ChangeSession session)
{
session.refreshMeta();
session.meta.addItemFlags(flags);
session.applyMeta();
}
}

View File

@@ -0,0 +1,23 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.vanillacustomizer.nms.items.ItemsNms;
public interface IChange
{
void apply(ChangeSession session);
static String replacePlaceholders(ChangeSession session, String str)
{
if(session.item.getType().isEdible())
{
str = str.replace("{food}", String.valueOf(ItemsNms.nms().getNutrition(session.item)));
str = str.replace("{saturation}", String.valueOf(ItemsNms.nms().getSaturation(session.item)));
}
if(session.item.getType().isBlock())
str = str.replace("{hardness}", String.valueOf(ItemsNms.nms().getDestroySpeed(session.item)));
return str;
}
}

View File

@@ -0,0 +1,68 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTList;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.ConfigFile;
import java.util.List;
public class LoreInsert implements IChange
{
private final List<String> lines;
private final int index;
public LoreInsert(List<String> lines, int index)
{
this.lines = ConfigFile.getColored(lines);
this.index = index;
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
if(!display.hasTag("Lore"))
{
NBTList<String> lore = display.getStringList("Lore");
for (String line : lines)
lore.add(Comp.legacyToJson(IChange.replacePlaceholders(session, line)));
}
else
{
NBTList<String> lore = display.getStringList("Lore");
// If the index is correctly inside the already existing lore range I can put the new lines there.
if(index < lore.size())
{
int i = index;
for (String line : lines)
{
lore.add(i, Comp.legacyToJson(IChange.replacePlaceholders(session, line)));
i++;
}
}
else // If it's out of bounds I just append at the end.
{
for (String line : lines)
lore.add(Comp.legacyToJson(IChange.replacePlaceholders(session, line)));
}
}
session.saveNbt();
}
public static void putLine(ChangeSession session, int index, String line)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
NBTList<String> lore = display.getStringList("Lore");
lore.add(index, Comp.legacyToJson(line));
session.saveNbt();
}
}

View File

@@ -0,0 +1,53 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTList;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.vanillacustomizer.utils.Utilz;
import java.util.ArrayList;
import java.util.List;
public class LoreInsertJson implements IChange
{
private final List<String> linesJson;
private final int index;
public LoreInsertJson(List<String> linesJson, int index)
{
this.linesJson = Utilz.fixJsonFormatting(linesJson);
this.index = index;
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
List<String> newLinesJson = new ArrayList<>();
for (String lineJson : linesJson)
newLinesJson.add(IChange.replacePlaceholders(session, lineJson));
if(!display.hasTag("Lore"))
{
NBTList<String> lore = display.getStringList("Lore");
lore.addAll(newLinesJson);
}
else
{
NBTList<String> lore = display.getStringList("Lore");
if(index < lore.size())
{
lore.addAll(index, newLinesJson);
}
else
{
lore.addAll(newLinesJson);
}
}
session.saveNbt();
}
}

View File

@@ -0,0 +1,34 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTList;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.ConfigFile;
import java.util.List;
public class LoreSet implements IChange
{
private final List<String> lines;
public LoreSet(List<String> lines)
{
this.lines = ConfigFile.getColored(lines);
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
display.removeKey("Lore");
NBTList<String> lore = display.getStringList("Lore");
for (String line : lines)
lore.add(Comp.legacyToJson(IChange.replacePlaceholders(session, line)));
session.saveNbt();
}
}

View File

@@ -0,0 +1,39 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTList;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.Utilz;
import java.util.ArrayList;
import java.util.List;
public class LoreSetJson implements IChange
{
private final List<String> linesJson;
public LoreSetJson(List<String> linesJson)
{
this.linesJson = Utilz.fixJsonFormatting(linesJson);
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
display.removeKey("Lore");
NBTList<String> lore = display.getStringList("Lore");
List<String> newLinesJson = new ArrayList<>();
for (String lineJson : linesJson)
newLinesJson.add(IChange.replacePlaceholders(session, lineJson));
lore.addAll(newLinesJson);
session.saveNbt();
}
}

View File

@@ -0,0 +1,17 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.vanillacustomizer.ChangeSession;
public class ProtectNbtData implements IChange
{
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
nbt.removeKey("PublicBukkitValues");
nbt.removeKey("itemsadder");
session.saveNbt();
}
}

View File

@@ -0,0 +1,29 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.ConfigFile;
import org.bukkit.ChatColor;
public class Renamer implements IChange
{
private final String name;
public Renamer(String name)
{
name = ConfigFile.convertColor(name);
this.name = !name.startsWith("&f") ? ChatColor.WHITE + name : name;
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
display.setString("Name", Comp.legacyToJson(IChange.replacePlaceholders(session, name)));
session.saveNbt();
}
}

View File

@@ -0,0 +1,31 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.Utilz;
public class RenamerJson implements IChange
{
private final String json;
public RenamerJson(String json)
{
// This should validate if the json is valid and throw an exception if not.
// NOTE: test if it is actually the case.
Comp.jsonToComponent(json);
this.json = Utilz.fixJsonFormatting(json);
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
display.setString("Name", IChange.replacePlaceholders(session, json));
session.saveNbt();
}
}

View File

@@ -0,0 +1,23 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.vanillacustomizer.ChangeSession;
public class ReplaceCustomModelData implements IChange
{
private final int id;
public ReplaceCustomModelData(int id)
{
this.id = id;
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
nbt.setInteger("CustomModelData", id);
session.saveNbt();
}
}

View File

@@ -0,0 +1,24 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.inventory.meta.Damageable;
public class ReplaceDurability implements IChange
{
private final short amount;
public ReplaceDurability(short amount)
{
this.amount = amount;
}
@Override
public void apply(ChangeSession session)
{
Damageable damageable = (Damageable) session.refreshMeta();
assert damageable != null;
short max = session.item.getType().getMaxDurability();
damageable.setDamage(amount > max ? 0 : (short) (max - amount));
}
}

View File

@@ -0,0 +1,21 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.Material;
public class ReplaceMaterial implements IChange
{
private final Material material;
public ReplaceMaterial(Material material)
{
this.material = material;
}
@Override
public void apply(ChangeSession session)
{
session.item.setType(material);
session.refreshAll(); // Idk if it's needed
}
}

View File

@@ -0,0 +1,36 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.ConfigFile;
public class ReplaceWordDisplayName implements IChange
{
private final String from;
private final String to;
public ReplaceWordDisplayName(String from, String to)
{
this.from = ConfigFile.convertColor(from);
this.to = ConfigFile.convertColor(to);
}
@Override
public void apply(ChangeSession session)
{
if(session.refreshMeta() == null)
return;
if(!session.refreshMeta().hasDisplayName())
return;
String name = session.refreshMeta().getDisplayName().replace(from, to);
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
display.setString("Name", Comp.legacyToJson(name));
session.saveNbt();
}
}

View File

@@ -0,0 +1,46 @@
package dev.lone.vanillacustomizer.customization.changes;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTList;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.LoneLibs.chat.Comp;
import dev.lone.vanillacustomizer.utils.ConfigFile;
import lonelibs.net.kyori.adventure.text.Component;
import lonelibs.net.kyori.adventure.text.TextReplacementConfig;
public class ReplaceWordLore implements IChange
{
TextReplacementConfig textReplacement;
public ReplaceWordLore(String from, String to)
{
from = ConfigFile.convertColor(from);
to = ConfigFile.convertColor(to);
textReplacement = TextReplacementConfig.builder()
.match(from)
.replacement(to)
.build();
}
@Override
public void apply(ChangeSession session)
{
NBTItem nbt = session.nbt();
NBTCompound display = nbt.getOrCreateCompound("display");
if(!display.hasTag("Lore"))
return;
NBTList<String> lore = display.getStringList("Lore");
for (int i = 0; i < lore.size(); i++)
{
String lineJson = lore.get(i);
Component component = Comp.jsonToComponent(lineJson);
component = component.replaceText(textReplacement);
lore.set(i, Comp.componentToJson(component));
}
session.saveNbt();
}
}

View File

@@ -0,0 +1,6 @@
package dev.lone.vanillacustomizer.customization.matchers;
public interface ITextMatcher
{
boolean matches(String text);
}

View File

@@ -0,0 +1,19 @@
package dev.lone.vanillacustomizer.customization.matchers;
import java.util.regex.Pattern;
public class RegexMatcher implements ITextMatcher
{
final Pattern regex;
public RegexMatcher(String regexStr)
{
regex = Pattern.compile(regexStr);
}
@Override
public boolean matches(String text)
{
return regex.matcher(text).matches();
}
}

View File

@@ -0,0 +1,107 @@
package dev.lone.vanillacustomizer.customization.matchers;
import dev.lone.LoneLibs.nbt.nbtapi.NBTCompound;
import dev.lone.LoneLibs.nbt.nbtapi.NBTItem;
import dev.lone.LoneLibs.nbt.nbtapi.NBTType;
import dev.lone.vanillacustomizer.customization.rules.IRule;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
public class RuleNbtMatcher implements IRule
{
final String nbtPath;
Object nbtValue;
String[] nbtPathSplit;
NBTType nbtValueType;
public RuleNbtMatcher(String nbtPath, String nbtValueStr, String nbtValueTypeStr)
{
this.nbtPath = nbtPath;
this.nbtValue = nbtValueStr;
String nbtTypeFixed = "NBTTag" + StringUtils.capitalize(nbtValueTypeStr.toLowerCase());
try
{
nbtValueType = NBTType.valueOf(nbtTypeFixed);
}
catch(IllegalArgumentException exc)
{
throw new IllegalArgumentException("Unknown nbt.type '" + nbtValueTypeStr + "' for nbt path '" + nbtPath + "'." +
ChatColor.GRAY + " Allowed: string, int, float, double, byte, short");
}
switch (nbtValueType)
{
case NBTTagString:
break;
case NBTTagInt:
nbtValue = Integer.parseInt(nbtValueStr);
break;
case NBTTagFloat:
nbtValue = Float.parseFloat(nbtValueStr);
break;
case NBTTagDouble:
nbtValue = Double.parseDouble(nbtValueStr);
break;
case NBTTagByte:
nbtValue = Byte.parseByte(nbtValueStr);
case NBTTagShort:
nbtValue = Short.parseShort(nbtValueStr);
break;
}
this.nbtPathSplit = nbtPath.split("\\.");
}
public String getNbtPath()
{
return nbtPath;
}
public Object getNbtValue()
{
return nbtValue;
}
@Override
public boolean matches(ItemStack item)
{
NBTItem nbt = new NBTItem(item);
if (!nbt.hasTag(nbtPathSplit[0]))
return false;
NBTCompound currentCompound = nbt.getCompound(nbtPathSplit[0]);
for(int i=1; i<nbtPathSplit.length-1; i++)
{
if (!currentCompound.hasTag(nbtPathSplit[i]))
return false;
currentCompound = currentCompound.getCompound(nbtPathSplit[i]);
}
if (!currentCompound.hasTag(nbtPathSplit[nbtPathSplit.length-1]))
return false;
NBTType nbtType = currentCompound.getType(nbtPathSplit[nbtPathSplit.length-1]);
if (nbtType != nbtValueType)
return false;
if (nbtType == NBTType.NBTTagString)
return (currentCompound.getString(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
else if (nbtType == NBTType.NBTTagInt)
return (currentCompound.getInteger(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
else if (nbtType == NBTType.NBTTagDouble)
return (currentCompound.getDouble(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
else if (nbtType == NBTType.NBTTagFloat)
return (currentCompound.getFloat(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
else if (nbtType == NBTType.NBTTagByte)
return (currentCompound.getByte(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
else if (nbtType == NBTType.NBTTagShort)
return (currentCompound.getShort(nbtPathSplit[nbtPathSplit.length-1]).equals(nbtValue));
return false;
}
}

View File

@@ -0,0 +1,83 @@
package dev.lone.vanillacustomizer.customization.matchers;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import java.util.ArrayList;
import java.util.List;
@Deprecated
public class WildcardsMatcher implements ITextMatcher
{
// private List<String> wildcardStart;
// private List<String> wildcardEnd;
// private List<String> wildcardContains;
private List<String> wildcards;
public void addWildcard(String wildcard)
{
// String cleanMatcher = wildcard.replace("*", "");
// if(wildcard.startsWith("*") && wildcard.endsWith("*"))
// {
// if (wildcardContains == null)
// wildcardContains = new ArrayList<>();
// wildcardContains.add(cleanMatcher);
// }
// else
// {
// if (wildcard.startsWith("*"))
// {
// if (wildcardStart == null)
// wildcardStart = new ArrayList<>();
// wildcardStart.add(cleanMatcher);
// }
// else
// {
// if (wildcardEnd == null)
// wildcardEnd = new ArrayList<>();
// wildcardEnd.add(cleanMatcher);
// }
// }
if (wildcards == null)
wildcards = new ArrayList<>();
wildcards.add(wildcard);
}
@Override
public boolean matches(String text)
{
for (String wildcard : wildcards)
{
if(FilenameUtils.wildcardMatch(text, wildcard, IOCase.INSENSITIVE))
return true;
}
// if(wildcardContains != null)
// {
// for (String wildcard : wildcardContains)
// {
// if(text.contains(wildcard))
// return true;
// }
// }
//
// if(wildcardStart != null)
// {
// for (String wildcard : wildcardStart)
// {
// if(text.endsWith(wildcard))
// return true;
// }
// }
//
// if(wildcardEnd != null)
// {
// for (String wildcard : wildcardEnd)
// {
// if(text.startsWith(wildcard))
// return true;
// }
// }
return false;
}
}

View File

@@ -0,0 +1,14 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.ChangeSession;
import org.bukkit.inventory.ItemStack;
public interface IRule
{
boolean matches(ItemStack item);
default boolean matches(ChangeSession session)
{
return matches(session.item);
}
}

View File

@@ -0,0 +1,22 @@
package dev.lone.vanillacustomizer.customization.rules;
import org.bukkit.inventory.ItemStack;
public class RuleEdible implements IRule
{
private final boolean value;
public RuleEdible(boolean value)
{
this.value = value;
}
@Override
public boolean matches(ItemStack item)
{
if(value)
return item.getType().isEdible();
else
return !item.getType().isEdible();
}
}

View File

@@ -0,0 +1,20 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.nms.items.ItemsNms;
import org.bukkit.inventory.ItemStack;
public class RuleHardnessGraterThan implements IRule
{
private final double value;
public RuleHardnessGraterThan(double value)
{
this.value = value;
}
@Override
public boolean matches(ItemStack item)
{
return ItemsNms.nms().getDestroySpeed(item) > value;
}
}

View File

@@ -0,0 +1,20 @@
package dev.lone.vanillacustomizer.customization.rules;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class RuleMaterial implements IRule
{
Material material;
public RuleMaterial(Material material)
{
this.material = material;
}
@Override
public boolean matches(ItemStack item)
{
return item.getType() == material;
}
}

View File

@@ -0,0 +1,22 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.customization.matchers.RegexMatcher;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class RuleMaterialRegex implements IRule
{
RegexMatcher matcher;
public RuleMaterialRegex(String regexStr)
{
matcher = new RegexMatcher(regexStr);
}
@Override
public boolean matches(ItemStack item)
{
return matcher.matches(item.getType().toString());
}
}

View File

@@ -0,0 +1,44 @@
package dev.lone.vanillacustomizer.customization.rules;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class RuleMaterialWildcards implements IRule
{
List<Material> matches = new ArrayList<>();
public List<String> init(List<String> materialWildcards)
{
List<String> noMatches = new ArrayList<>();
for (String entry : materialWildcards)
{
boolean any = false;
for (Material material : Material.values())
{
if(FilenameUtils.wildcardMatch(material.toString(), entry, IOCase.INSENSITIVE))
{
matches.add(material);
any = true;
}
}
if(!any)
{
noMatches.add(entry);
}
}
return noMatches;
}
@Override
public boolean matches(ItemStack item)
{
return matches.contains(item.getType());
}
}

View File

@@ -0,0 +1,29 @@
package dev.lone.vanillacustomizer.customization.rules;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class RuleMaterials implements IRule
{
List<Material> materials;
public RuleMaterials(List<Material> materials)
{
this.materials = materials;
}
@Override
public boolean matches(ItemStack item)
{
Material type = item.getType();
for (Material entry : materials)
{
if(type == entry)
return true;
}
return false;
}
}

View File

@@ -0,0 +1,19 @@
package dev.lone.vanillacustomizer.customization.rules;
import org.bukkit.inventory.ItemStack;
public class RulePlaceable implements IRule
{
final boolean placeable;
public RulePlaceable(boolean placeable)
{
this.placeable = placeable;
}
@Override
public boolean matches(ItemStack item)
{
return item.getType().isBlock();
}
}

View File

@@ -0,0 +1,21 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.nms.items.ItemsNms;
import dev.lone.vanillacustomizer.nms.items.Rarity;
import org.bukkit.inventory.ItemStack;
public class RuleRarity implements IRule
{
private Rarity rarity;
public RuleRarity(Rarity rarity)
{
this.rarity = rarity;
}
@Override
public boolean matches(ItemStack item)
{
return rarity.equals(ItemsNms.nms().getRarity(item));
}
}

View File

@@ -0,0 +1,23 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.nms.items.ItemsNms;
import org.bukkit.inventory.ItemStack;
public class RuleSmelted implements IRule
{
private final boolean value;
public RuleSmelted(boolean value)
{
this.value = value;
}
@Override
public boolean matches(ItemStack item)
{
if(value)
return ItemsNms.inst().SMELTED_MATERIALS.contains(item.getType());
else
return !ItemsNms.inst().SMELTED_MATERIALS.contains(item.getType());
}
}

View File

@@ -0,0 +1,54 @@
package dev.lone.vanillacustomizer.customization.rules;
import dev.lone.vanillacustomizer.ChangeSession;
import dev.lone.vanillacustomizer.utils.Utilz;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class RuleVanillaItemMatcher implements IRule
{
final boolean isVanilla;
public RuleVanillaItemMatcher(boolean isVanilla)
{
this.isVanilla = isVanilla;
}
public static boolean satisfy(ItemStack itemStack)
{
if(itemStack == null)
return false;
if(!itemStack.hasItemMeta())
return true;
ItemMeta meta = itemStack.getItemMeta();
if(meta == null)
return true;
// TODO: warning, items with no lore would still be considered vanilla while they might be custom.
// might need to check NBT
if(meta.hasLore())
{
return false;
}
String displayName = meta.getDisplayName();
displayName = Utilz.backColor(displayName);
// Check if italic, means that might have been renamed using anvil.
return !displayName.startsWith("&o");
}
@Override
public boolean matches(ItemStack item)
{
return false;
}
@Override
public boolean matches(ChangeSession session)
{
return session.isVanilla;
}
}

View File

@@ -0,0 +1,69 @@
package dev.lone.vanillacustomizer.nms;
import dev.lone.LoneLibs.annotations.Nullable;
import dev.lone.LoneLibs.nbt.nbtapi.utils.MinecraftVersion;
import dev.lone.vanillacustomizer.Main;
import org.bukkit.Bukkit;
import java.lang.reflect.InvocationTargetException;
/**
* Utility to initialize NMS wrappers and avoid Maven circular dependency problems.
*/
public class Nms
{
public static boolean is_v18_2_or_greater;
public static boolean is_v19_2_or_greater;
public static boolean is_v17_or_greater;
public static boolean is_v1_16_or_greater;
static
{
is_v19_2_or_greater = MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_19_R1);
is_v18_2_or_greater = MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_18_R1);
is_v17_or_greater = MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1);
is_v1_16_or_greater = MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_16_R1);
}
/**
* Gets a suitable implementaion for the current Minecraft server version.
*
* @param implClazz the interface class which every implementation implements.
* @param nmsHolder the wrapper which holds NMS methods as Singleton utility.
* @param ignoreError If loading errors should be ignored, for example if no implementation exists. This is hacky but can
* be useful in some cases.
* @return the correct implementation.
*/
@Nullable
@SuppressWarnings("unchecked")
public static <T> T findImplementation(Class<T> implClazz, Object nmsHolder, boolean ignoreError)
{
String nmsVersion = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
try
{
Class<?> implClass = Class.forName(nmsHolder.getClass().getPackage().getName() + ".impl." + nmsVersion);
try
{
//To fix a bug: For example implementations of IBlockInfo class have BlockInfo has first param of the constructor.
return (T) implClass.getDeclaredConstructor(nmsHolder.getClass()).newInstance(nmsHolder);
}
catch (NoSuchMethodException e)
{
return (T) implClass.getDeclaredConstructor().newInstance();
}
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e)
{
if (ignoreError)
return null;
Main.msg.error("Error getting implementation for " + nmsHolder.getClass() + " - NMS " + nmsVersion);
e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(Main.inst());
Bukkit.shutdown();
}
return null;
}
}

View File

@@ -0,0 +1,14 @@
package dev.lone.vanillacustomizer.nms.items;
import org.bukkit.inventory.ItemStack;
public interface IItemsNms
{
Rarity getRarity(ItemStack bukkitItem);
float getDestroySpeed(ItemStack bukkitItem);
int getNutrition(ItemStack bukkitItem);
float getSaturation(ItemStack bukkitItem);
}

View File

@@ -0,0 +1,46 @@
package dev.lone.vanillacustomizer.nms.items;
import dev.lone.vanillacustomizer.nms.Nms;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.CookingRecipe;
import java.util.ArrayList;
import java.util.List;
public class ItemsNms
{
public IItemsNms nms;
static ItemsNms instance;
public List<Material> SMELTED_MATERIALS = new ArrayList<>();
ItemsNms()
{
nms = Nms.findImplementation(IItemsNms.class, this, false);
}
public static ItemsNms inst()
{
if(instance == null)
instance = new ItemsNms();
return instance;
}
public static IItemsNms nms()
{
return inst().nms;
}
public void initialize()
{
Bukkit.recipeIterator().forEachRemaining(recipe -> {
if(recipe instanceof CookingRecipe)
{
Material type = recipe.getResult().getType();
if(!type.isEdible())
SMELTED_MATERIALS.add(type);
}
});
}
}

View File

@@ -0,0 +1,18 @@
package dev.lone.vanillacustomizer.nms.items;
import org.bukkit.Color;
public enum Rarity
{
COMMON(Color.WHITE),
UNCOMMON(Color.YELLOW),
RARE(Color.AQUA),
EPIC(Color.PURPLE);
public final Color color;
Rarity(Color var2)
{
this.color = var2;
}
}

View File

@@ -0,0 +1,539 @@
package dev.lone.vanillacustomizer.utils;
import dev.lone.LoneLibs.annotations.NotNull;
import dev.lone.vanillacustomizer.Main;
import dev.lone.vanillacustomizer.nms.Nms;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffectType;
import dev.lone.LoneLibs.annotations.Nullable;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 2020-01-08 LoneDev
*/
public class ConfigFile
{
private static final Pattern hexPattern = Pattern.compile("%#([A-Fa-f0-9]){6}%");
final Plugin plugin;
private FileConfiguration config;
private final String filePath;
private final File configFile;
private boolean hasDefaultFile = true;
private boolean autoAddMissingProperties = false;
private String partialFilePath;
private boolean announceCustomLanguage;
/**
* @param plugin Plugin
* @param filePath Partial path of the file (root = plugins/XXX/)
* @param hasDefaultFile If there is a default file in .jar resources
* @param autoAddMissingProperties Add properties that are missing from user config (useful on plugin updates if you create new properties in the config)
*/
public ConfigFile(Plugin plugin, boolean pluginsFolderRoot, String filePath, boolean hasDefaultFile, boolean autoAddMissingProperties)
{
this(plugin, pluginsFolderRoot, filePath, hasDefaultFile, autoAddMissingProperties, true);
}
public ConfigFile(Plugin plugin, boolean pluginsFolderRoot, String filePath, boolean hasDefaultFile, boolean autoAddMissingProperties, boolean announceCustomLanguage)
{
this.plugin = plugin;
this.announceCustomLanguage = announceCustomLanguage;
if (pluginsFolderRoot)
{
this.partialFilePath = filePath;
this.filePath = plugin.getDataFolder() + File.separator + filePath;
//this.filePath = "plugins/" + plugin.getName() + "/" + filePath;
}
else
{
this.partialFilePath = filePath.replace(plugin.getDataFolder().getAbsolutePath(), "");
this.filePath = filePath;
}
this.partialFilePath = this.partialFilePath.replace("\\", "/");
if (!new File(this.filePath).exists())
new File(this.filePath).getParentFile().mkdirs();
this.hasDefaultFile = hasDefaultFile;
this.autoAddMissingProperties = autoAddMissingProperties;
this.configFile = new File(this.filePath);
try
{
config = loadConfiguration(configFile);//seems to be the cause of lag on /iareload
initFile();
}
catch (IOException | InvalidConfigurationException e)
{
e.printStackTrace();
}
}
public ConfigFile(Plugin plugin, boolean pluginsFolderRoot, String filePath, boolean hasDefaultFile)
{
this(plugin, pluginsFolderRoot, filePath, hasDefaultFile, false);
}
@NotNull
public static YamlConfiguration loadConfiguration(@NotNull File file) throws IOException, InvalidConfigurationException
{
Validate.notNull(file, "File cannot be null");
YamlConfiguration config = new YamlConfiguration();
try
{
config.load(file);
}
catch (FileNotFoundException ignored)
{
// Happens the first time since the file obviously doesn't exist.
}
catch (IOException | InvalidConfigurationException exc)
{
Bukkit.getLogger().log(Level.SEVERE, "Cannot load file: " + file, exc);
throw exc;
}
return config;
}
private ConfigFile(Plugin plugin, String filePath)
{
this.plugin = plugin;
this.filePath = filePath;
this.configFile = new File(this.filePath);
config = YamlConfiguration.loadConfiguration(configFile);
}
public ConfigFile clone()
{
ConfigFile clone = new ConfigFile(plugin, filePath);
clone.partialFilePath = partialFilePath;
clone.hasDefaultFile = hasDefaultFile;
clone.autoAddMissingProperties = autoAddMissingProperties;
return clone;
}
public File getFile()
{
return configFile;
}
/**
* Reloads from file
*/
public void reload()
{
config = YamlConfiguration.loadConfiguration(configFile);
}
/**
* Inits file taking it from original file in .jar if not exists and adding missing attributes if autoAddMissingProperties
*/
public void initFile()
{
if (hasDefaultFile)
{
String resourceFilePath = this.filePath
.replace("plugins/" + plugin.getName() + "/", "")
.replace("plugins\\" + plugin.getName() + "\\", "")
.replace("plugins\\" + plugin.getName() + "/", "");
try
{
if (!configFile.exists())
{
// Load the default file from JAR resources
FileUtils.copyInputStreamToFile(plugin.getResource(resourceFilePath), configFile);
}
else
{
if (autoAddMissingProperties)
{
InputStream defaultFileStream = plugin.getResource(resourceFilePath);
if(defaultFileStream != null)
{
FileConfiguration c = YamlConfiguration
.loadConfiguration((new InputStreamReader(defaultFileStream, StandardCharsets.UTF_8)));
for (String k : c.getKeys(true))
{
if (!config.contains(k))
config.set(k, c.get(k));
}
config.save(configFile);
}
}
}
config.load(configFile);
}
catch (IOException | InvalidConfigurationException | NullPointerException e)
{
//e.printStackTrace();
//Main.msg.sendConsoleError("ERROR LOADING file '" + filePath + "'");
if (announceCustomLanguage)
Main.msg.log(ChatColor.YELLOW + "Using custom language file '" + filePath + "'");
e.printStackTrace();
}
}
}
public FileConfiguration getConfigFile()
{
return config;
}
public String getFilePath()
{
return filePath;
}
public String getPartialFilePath()
{
return partialFilePath;
}
public static String convertColor(String string)
{
return convertColor0(string).replace("\\n", "\n");
}
private static String convertColor0(String message)
{
if (Nms.is_v1_16_or_greater)
{
Matcher matcher = hexPattern.matcher(message);
while (matcher.find())
{
final net.md_5.bungee.api.ChatColor hexColor = net.md_5.bungee.api.ChatColor.of(matcher.group().substring(1, matcher.group().length() - 1));
final String before = message.substring(0, matcher.start());
final String after = message.substring(matcher.end());
message = before + hexColor + after;
matcher = hexPattern.matcher(message);
}
}
return message.replace("&", "\u00A7");
}
protected void notifyMissingProperty(String path)
{
Main.msg.error("MISSING FILE PROPERTY! '" + path + "' in file '" + filePath + "'");
}
public void set(String path, Object value)
{
this.config.set(path, value);
}
public void save()
{
try
{
this.config.save(configFile);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void save(File newLocation)
{
try
{
this.config.save(newLocation);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public boolean hasKey(String path)
{
return config.contains(path);
}
public void remove(String path)
{
config.set(path, null);
}
public List<String> getSectionKeysList(String path)
{
if (!hasKey(path))
return new ArrayList<>();
return new ArrayList<>(config.getConfigurationSection(path).getKeys(false));
}
public static List<String> getSectionKeysListBySection(ConfigurationSection section)
{
return getSectionKeysListBySection(section, "");
}
public static List<String> getSectionKeysListBySection(ConfigurationSection section, String path)
{
if (!section.contains(path))
return new ArrayList<>();
return new ArrayList<>(section.getKeys(false));
}
public Map<String, Object> getSectionKeysAndValues(String path)
{
if (!hasKey(path))
return null;
return config.getConfigurationSection(path).getValues(false);
}
public Object get(String path, Object defaultValue)
{
if (hasKey(path))
return config.get(path);
return defaultValue;
}
public String getString(String path)
{
return config.getString(path);
}
public String getString(String path, String defaultValue)
{
if (!hasKey(path))
return defaultValue;
return config.getString(path);
}
public int getInt(String path)
{
return config.getInt(path);
}
/**
* Riturna interno se trovato, se no ritorna defaultValue
*
* @param path
* @param defaultValue
* @return
*/
public int getInt(String path, int defaultValue)
{
if (hasKey(path))
return config.getInt(path);
return defaultValue;
}
/**
* Ritorna double se trovato, se no ritorna defaultValue
*
* @param path
* @param defaultValue
* @return
*/
public double getDouble(String path, double defaultValue)
{
if (hasKey(path))
return config.getDouble(path);
return defaultValue;
}
public float getFloat(String path, float defaultValue)
{
if (hasKey(path))
return (float) config.getDouble(path);
return defaultValue;
}
public float getFloat(String path)
{
return getFloat(path, 0f);
}
public boolean getBoolean(String path)
{
return config.getBoolean(path);
}
public boolean getBoolean(String path, boolean defaultValue)
{
if (hasKey(path))
return config.getBoolean(path);
return defaultValue;
}
public Material getMaterial(String path, Material defaultValue)
{
if (hasKey(path))
return EnumUtil.safeGet(config.getString(path).toUpperCase(), Material.class, defaultValue);
else
return defaultValue;
}
public static Material getMaterialByString(String value, Material defaultValue)
{
if(value == null)
return null;
return EnumUtil.safeGet(value.toUpperCase(), Material.class, defaultValue);
}
public Material getMaterial(String path)
{
return getMaterial(path, null);
}
public PotionEffectType getPotionEffectType(String path)
{
if (hasKey(path))
return PotionEffectType.getByName(config.getString(path));
else
return null;
}
@Nullable
public static PotionEffectType getPotionEffectTypeByString(String value)
{
return PotionEffectType.getByName(value);
}
public String getColored(String path)
{
return getColored(path, null);
}
public String getColored(String path, String defaultValue)
{
if (hasKey(path))
{
return convertColor(config.getString(path));
}
else
{
//notifyMissingProperty(path);
//return ChatColor.RED + "Error in file " + filePath;
}
return defaultValue;
}
public String getStripped(String name)
{
return ChatColor.stripColor(getColored(name));
}
public String getStrippedColors(String name)
{
return ChatColor.stripColor(getColored(name));
}
/**
* Returns a list of strings with colors already converted to bukkit format
*/
public static List<String> getColored(List<String> list)
{
ArrayList<String> colored = new ArrayList<>();
for (String entry : list)
colored.add(convertColor(entry));
return colored;
}
/**
* Returns a list of strings with colors already converted to bukkit format
*
* @param path
* @param colored
* @return
*/
public List<String> getStringList(String path, boolean colored)
{
if (colored)
{
ArrayList<String> coloredList = new ArrayList<>();
try
{
ArrayList<String> list = (ArrayList<String>) config.getStringList(path);
for (String entry : list)
coloredList.add(convertColor(entry));
}
catch (NullPointerException exc)
{
exc.printStackTrace();
notifyMissingProperty(path);
}
return coloredList;
}
return config.getStringList(path);
}
/**
* Returns a list of strings (without converting colors)
*
* @param path
* @return
*/
public List<String> getStringList(String path)
{
return getStringList(path, false);
}
public List<Material> getMaterialList(String path)
{
ArrayList<Material> coloredList = new ArrayList<>();
ArrayList<String> list = (ArrayList<String>) config.getStringList(path);
for (String material : list)
{
if (Material.valueOf(material.toUpperCase()) != null)//does this even work?
coloredList.add(Material.valueOf(material.toUpperCase()));
else
Main.msg.error("No material found with name " + material + ". Please check config '" + filePath + "'");
}
return coloredList;
}
@Nullable
public ConfigurationSection getConfigurationSection(@NotNull String path)
{
return config.getConfigurationSection(path);
}
@Nullable
public EntityType getEntityType(String key, EntityType armorStand, Consumer<String> failAction)
{
if (hasKey(key))
{
String val = getString(key).toUpperCase();
try
{
return EntityType.valueOf(val);
}
catch (Exception exc)
{
failAction.accept(val);
return null;
}
}
return armorStand;
}
}

View File

@@ -0,0 +1,17 @@
package dev.lone.vanillacustomizer.utils;
public class EnumUtil
{
public static <T extends Enum<T>> T safeGet(String str, Class<T> enumType, T fallback)
{
try
{
return Enum.valueOf(enumType, str);
}
catch (Exception e)
{
return fallback;
}
}
}

View File

@@ -0,0 +1,36 @@
package dev.lone.vanillacustomizer.utils;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import org.bukkit.plugin.Plugin;
import java.util.function.Consumer;
public class Packets
{
/**
* Register Server->Client packet listener
*/
public static void out(Plugin plugin, PacketType packetType, Consumer<PacketEvent> handle)
{
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(
PacketAdapter.params()
.plugin(plugin)
.types(packetType)
.listenerPriority(ListenerPriority.MONITOR)
)
{
@Override
public void onPacketSending(PacketEvent e)
{
if (e.isCancelled() || e.isPlayerTemporary())
return;
handle.accept(e);
}
});
}
}

View File

@@ -0,0 +1,24 @@
package dev.lone.vanillacustomizer.utils;
import dev.lone.LoneLibs.annotations.NotNull;
public class SmallCaps
{
private static final char[] CHARS = "ᴀʙᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴘǫʀsᴛxʏ".toCharArray();
public static String apply(@NotNull String string)
{
final StringBuilder sb = new StringBuilder();
final char[] chars = string.toLowerCase().toCharArray();
for (char c : chars)
{
final int index = c - 'a';
if (index >= 0 && index < CHARS.length)
sb.append(CHARS[index]);
else
sb.append(c);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,599 @@
package dev.lone.vanillacustomizer.utils;
import dev.lone.LoneLibs.chat.Comp;
import lonelibs.net.kyori.adventure.text.Component;
import lonelibs.net.kyori.adventure.text.format.TextColor;
import lonelibs.net.kyori.adventure.text.format.TextDecoration;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.CharacterIterator;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Utilz
{
public static Random random = new Random();
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("##.00");
private static final Pattern PATTERN_HEX = Pattern.compile("%#([A-Fa-f0-9]){6}%");
private static final Pattern PATTERN_IS_NUMERIC = Pattern.compile("-?\\d+(\\.\\d+)?");
public static void removeEnchantments(ItemStack item)
{
item.getEnchantments().keySet().forEach(item::removeEnchantment);
}
public static String addSpace(String s)
{
return s.replace("-", " ");
}
public static float getRandom(String level)
{
if (level.contains("-"))
{
String[] spl = level.split("-");
return round(randomNumber(Float.parseFloat(spl[0]), Float.parseFloat(spl[1])), 2);
}
else return Integer.parseInt(level);
}
public static int getRandomInt(String level)
{
if (level.contains("-"))
{
String[] spl = level.split("-");
return getRandomInt(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]));
}
else return Integer.parseInt(level);
}
public static float round(float d, int decimalPlace)
{
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}
public static String round(double value, int places, boolean showZeroes)
{
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
String result = bd.doubleValue() + "";
if (!showZeroes)
result = result
.replace(".00", "")
.replace(".0", "");
return result;
}
public static float randomNumber(float f, float g)
{
return random.nextFloat() * (g - f) + f;
}
/**
* Returns a 0 to 1 random double.
*
* @return A random double from 0 to 1.
*/
public static double randomNumber()
{
return random.nextDouble();
}
/**
* Supports negative min
*/
public static int getRandomInt(int min, int max)
{
if (max == min)
return max;
return random.nextInt((max - min) + 1) + min;
}
/**
* Supports negative min
*/
public static int getRandomInt(Random random, int min, int max)
{
if (max == min)
return max;
return random.nextInt((max - min) + 1) + min;
}
public static boolean getSuccess(int percent)
{
int i = getRandomInt(1, 100);
return i <= percent;
}
public static boolean hasPermmision(Player p, String perm)
{
if (p.hasPermission(perm)) return true;
return p.isOp();
}
public static String backColor(String name)
{
return name.replace("\u00A7", "&");
}
public static boolean isColored(String str)
{
return str.contains("\u00A7([0-fk-or])") || str.contains("&([0-fk-or])");
}
/**
* @param strNum check if it is numeric
*/
public static boolean isNumeric(String strNum)
{
if (strNum == null)
return false;
return PATTERN_IS_NUMERIC.matcher(strNum).matches();
}
private static java.awt.Color hex2Rgb(String colorStr)
{
try
{
return new java.awt.Color(
Integer.valueOf(colorStr.substring(1, 3), 16),
Integer.valueOf(colorStr.substring(3, 5), 16),
Integer.valueOf(colorStr.substring(5, 7), 16)
);
}
catch (Throwable e)
{
e.printStackTrace();
}
return null;
}
public static Color hexToBukkitColor(String colorStr)
{
if (colorStr == null)
return null;
//fix java.lang.NumberFormatException: For input string: ".0"
if (colorStr.endsWith(".0"))
colorStr = colorStr.replace(".0", "");
colorStr = colorStr.replace(".", "");
//fix java.lang.StringIndexOutOfBoundsException: String index out of range: 7
while (colorStr.length() < 7)
colorStr = colorStr + "0";
if (!colorStr.startsWith("#"))
colorStr = "#" + colorStr;
java.awt.Color javaColor = hex2Rgb(colorStr);
return Color.fromRGB(javaColor.getRed(), javaColor.getGreen(), javaColor.getBlue());
}
public static String colorToHexString(int rgb)
{
java.awt.Color tmp = new java.awt.Color(rgb);
return colorToHexString(tmp.getRed(), tmp.getGreen(), tmp.getBlue());
}
public static String colorToHexString(Color color, boolean hashtagPrefix)
{
java.awt.Color tmp = new java.awt.Color(color.asRGB());
return colorToHexString(tmp.getRed(), tmp.getGreen(), tmp.getBlue(), hashtagPrefix);
}
public static String colorToHexString(int r, int g, int b)
{
return colorToHexString(r, g, b, true);
}
public static String colorToHexString(int r, int g, int b, boolean hashtagPrefix)
{
if (hashtagPrefix)
return String.format("#%02x%02x%02x", r, g, b);
return String.format("%02x%02x%02x", r, g, b);
}
public static Color bukkitColor(int rgb)
{
java.awt.Color tmp = new java.awt.Color(rgb);
return Color.fromRGB(tmp.getRed(), tmp.getGreen(), tmp.getBlue());
}
public static int ceilDivision(float a, float b)
{
return (int) Math.ceil(a / b);
}
public static int parseInt(String number, int defaultValue)
{
try
{
return Integer.parseInt(number);
}
catch (Throwable ignored){}
return defaultValue;
}
public static float parseFloat(String number, float defaultValue)
{
try
{
return Float.parseFloat(number);
}
catch (Throwable ignored){}
return defaultValue;
}
public static Color bukkitColorFromString(String potionColorStr)
{
try
{
return (Color) FieldUtils.readStaticField(Color.class, potionColorStr);
}
catch (Exception e)
{
try
{
if (!Utilz.isNumeric(potionColorStr))
{
if (potionColorStr == null)
return null;
//fix java.lang.NumberFormatException: For input string: ".0"
if (potionColorStr.endsWith(".0"))
potionColorStr = potionColorStr.replace(".0", "");
potionColorStr = potionColorStr.replace(".", "");
//fix java.lang.StringIndexOutOfBoundsException: String index out of range: 7
while (potionColorStr.length() < 7)
potionColorStr = potionColorStr + "0";
if (!potionColorStr.startsWith("#"))
potionColorStr = "#" + potionColorStr;
java.awt.Color javaColor = hex2Rgb(potionColorStr);
return Color.fromRGB(javaColor.getRed(), javaColor.getGreen(), javaColor.getBlue());
}
else
{
Color.fromBGR(Integer.parseInt(potionColorStr));
}
}
catch (Throwable ignored)
{
}
}
return null;
}
public static int bukkitColorFromString_integer(String potionColorStr)
{
try
{
return ((Color) FieldUtils.readStaticField(Color.class, potionColorStr)).asRGB();
}
catch (Exception e)
{
try
{
if (!Utilz.isNumeric(potionColorStr))
{
if (potionColorStr == null)
return -1;
//fix java.lang.NumberFormatException: For input string: ".0"
if (potionColorStr.endsWith(".0"))
potionColorStr = potionColorStr.replace(".0", "");
potionColorStr = potionColorStr.replace(".", "");
//fix java.lang.StringIndexOutOfBoundsException: String index out of range: 7
while (potionColorStr.length() < 7)
potionColorStr = potionColorStr + "0";
if (!potionColorStr.startsWith("#"))
potionColorStr = "#" + potionColorStr;
java.awt.Color javaColor = hex2Rgb(potionColorStr);
return Color.fromRGB(javaColor.getRed(), javaColor.getGreen(), javaColor.getBlue()).asRGB();
}
else
{
return Integer.parseInt(potionColorStr);
}
}
catch (Throwable ignored){}
}
return -1;
}
public static boolean isBetween(int number, int min, int max, boolean equals)
{
if (equals)
return number >= min && number <= max;
return number > min && number < max;
}
public static boolean isBetween(int number, int min, int max)
{
return isBetween(number, min, max, true);
}
public static String getDateNowFormatted()
{
return getDateFormatted(new Date());
}
public static String getDateFormatted(Date date)
{
return new SimpleDateFormat("yyyy-MM-dd_HH-mm").format(date);
}
public static void printFunctionCaller()
{
try
{
StackTraceElement[] stackTrace = new Throwable().fillInStackTrace().getStackTrace();
StringBuilder a = new StringBuilder();
for (int i = 1; i < stackTrace.length; i++)
a.append(stackTrace[i].getMethodName() + ":" + stackTrace[i].getLineNumber()).append("->");
System.out.println(a.toString());
}
catch (Throwable ignored)
{
}
}
public static void showBook(Player player, String json)
{
ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
Bukkit.getUnsafe().modifyItemStack(book, json);
player.openBook(book);
}
public static int rgb(int r, int g, int b)
{
return new java.awt.Color(r, g, b, 255).getRGB();
}
public static boolean mkdirs(String path, boolean printErrors)
{
File file = new File(path);
if (file.exists())
return true;
try
{
Files.createDirectories(file.toPath());
}
catch (Throwable e)
{
if (printErrors)
e.printStackTrace();
return false;
}
return true;
}
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value)
{
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
/** See: {@link Utilz#partialFilePath(String)}. */
public static String partialFilePath(File file)
{
return partialFilePath(file.getAbsolutePath());
}
/**
* Input:
* "C:/Progetti/Minecraft/TestServer/1.19/plugins/ItemsAdder/contents/_iainternal/resourcepack/assets/_iainternal/textures/icons/icon_next_orange.png"
* "C:/Progetti/Minecraft/TestServer/blank_template/1.19.4/plugins/ModelEngine/resource pack/contents/prova/123/asd"
* Output:
* "contents/_iainternal/resourcepack/assets/_iainternal/textures/icons/icon_next_orange.png"
* "resource pack/contents/prova/123/asd"
*/
public static String partialFilePath(String fileAbsolutePath)
{
if (fileAbsolutePath == null)
return null;
String finalPath = fileAbsolutePath.replace("\\", "/");
int indexOfPlugins = finalPath.indexOf("plugins/");
if(indexOfPlugins != -1)
finalPath = finalPath.substring(indexOfPlugins);
// Remove the plugins/XXX/ text
int indexOfSlash = finalPath.indexOf("/");
if(indexOfSlash != -1)
finalPath = finalPath.substring(indexOfSlash + 1);
indexOfSlash = finalPath.indexOf("/");
if(indexOfSlash != -1)
finalPath = finalPath.substring(indexOfSlash + 1);
return finalPath;
}
public static int getFilesCount(File dir)
{
String[] list = dir.list();
if (list == null)
return 0;
return list.length;
}
public static String getPathRelativeToServerRoot(File file)
{
String serveRootPath = Bukkit.getServer().getWorldContainer().getAbsolutePath();
if (serveRootPath.endsWith("."))
serveRootPath = serveRootPath.substring(0, serveRootPath.length() - 2);
File serverRootDir = new File(serveRootPath).getParentFile();
return file.getAbsolutePath().replace(serverRootDir.getAbsolutePath(), "");
}
public static Path path(String path)
{
return new File(path).toPath();
}
/**
* Very important, zip files must use / not \\ or Minecraft won't recognize files..
*/
public static String sanitizePath(String str)
{
str = str.replace("\\", "/");
if (str.startsWith("/"))
str = str.substring(1);
return str;
}
public static String sanitizedPath(File file)
{
return sanitizePath(file.getAbsolutePath());
}
public static String removeStartsWith(String str, String starsWith)
{
if (str.startsWith(starsWith))
return str.substring(starsWith.length());
return str;
}
public static String removeEndsWith(String str, String endsWith)
{
return str.replaceFirst(endsWith + "$", "");
}
public static String getLastNormalizedPathEntry(String str)
{
return str.substring(str.lastIndexOf('/') + 1);
}
public static String cloneString(String str)
{
return new String(str.getBytes(StandardCharsets.UTF_8));
}
public static <T> T[] copy(T[] matrix)
{
return Arrays.copyOf(matrix, matrix.length);
}
public static String fileExtension(File file)
{
return FilenameUtils.getExtension(file.getAbsolutePath());
}
public static String fileName(File file, boolean extension)
{
if(extension)
return file.getName();
return FilenameUtils.getBaseName(file.getAbsolutePath());
}
public static String humanReadableByteCountSI(long bytes)
{
if (-1000 < bytes && bytes < 1000)
{
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950)
{
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
public static int minMax(int value, int min, int max)
{
if(value < min)
return min;
return Math.min(value, max);
}
public static String substringBefore(String string, String before)
{
return string.substring(string.indexOf(before));
}
public static Attribute strToAttributeType(String attributeModifier)
{
attributeModifier = attributeModifier.replace("minecraft:", "");
return switch (attributeModifier)
{
case "generic.max_health" -> Attribute.GENERIC_MAX_HEALTH;
case "generic.follow_range" -> Attribute.GENERIC_FOLLOW_RANGE;
case "generic.knockback_resistance" -> Attribute.GENERIC_KNOCKBACK_RESISTANCE;
case "generic.movement_speed" -> Attribute.GENERIC_MOVEMENT_SPEED;
case "generic.flying_speed" -> Attribute.GENERIC_FLYING_SPEED;
case "generic.attack_damage" -> Attribute.GENERIC_ATTACK_DAMAGE;
case "generic.attack_knockback" -> // 1.16+
Attribute.GENERIC_ATTACK_KNOCKBACK;
case "generic.attack_speed" -> Attribute.GENERIC_ATTACK_SPEED;
case "generic.armor" -> Attribute.GENERIC_ARMOR;
case "generic.armor_toughness" -> Attribute.GENERIC_ARMOR_TOUGHNESS;
case "generic.luck" -> Attribute.GENERIC_LUCK;
case "zombie.spawn_reinforcements" -> Attribute.ZOMBIE_SPAWN_REINFORCEMENTS;
case "horse.jump_strength" -> Attribute.HORSE_JUMP_STRENGTH;
default -> null;
};
}
public static EquipmentSlot strToVanillaEquipmentSlot(String str)
{
return switch (str.toLowerCase())
{
case "head" -> EquipmentSlot.HEAD;
case "chest" -> EquipmentSlot.CHEST;
case "legs" -> EquipmentSlot.LEGS;
case "feet" -> EquipmentSlot.FEET;
case "mainhand" -> EquipmentSlot.HAND;
case "offhand" -> EquipmentSlot.OFF_HAND;
default -> null;
};
}
public static List<String> fixJsonFormatting(List<String> linesJson)
{
for (int i = 0, linesJsonSize = linesJson.size(); i < linesJsonSize; i++)
{
String jsonLine = linesJson.get(i);
linesJson.set(i, fixJsonFormatting(jsonLine));
}
return linesJson;
}
public static String fixJsonFormatting(String jsonString)
{
Component component = Comp.jsonToComponent(jsonString);
component = component.colorIfAbsent(TextColor.color(255, 255, 255));
component = component.decorationIfAbsent(TextDecoration.ITALIC, TextDecoration.State.FALSE);
return Comp.componentToJson(component);
}
}

View File

@@ -0,0 +1,44 @@
customizations:
custom1:
rules:
material_wildcards:
- "*_SWORD"
changes:
rename: "Amogus"
custom2:
rules:
material: STONE
changes:
rename: "CUSTOM RULE 2!!!!"
custom3:
rules:
materials:
- DIAMOND
- EMERALD
changes:
rename: "CUSTOM RULE 3!!!"
custom4:
rules:
materials:
- DIAMOND_CHESTPLATE
- EMERALD
changes:
rename: "CUSTOM RULE 4!!!"
custom5:
rules:
materials:
- IRON_INGOT
changes:
replace_word_display_name:
from: "test"
to: "changed_text!!!"
custom6:
rules:
nbt:
path: "itemsadder.id"
value: ruby
type: string
changes:
replace_word_display_name:
from: "Rub"
to: "FOUND NBT RULE!"

View File

@@ -0,0 +1,9 @@
name: VanillaCustomizer
version: 0.2
main: dev.lone.vanillacustomizer.Main
api-version: 1.13
commands:
vanillacustomizer:
description: Main admin plugin command
usage: /<command>
permission: "vanillacustomizer.admin"