9
0
mirror of https://github.com/Xiao-MoMi/Custom-Fishing.git synced 2025-12-28 19:39:06 +00:00
This commit is contained in:
Xiao-MoMi
2023-03-25 00:40:31 +08:00
parent 27705af333
commit 2f24857c8c
8 changed files with 0 additions and 1252 deletions

View File

@@ -1,226 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import net.momirealms.customfishing.CustomFishing;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AdventureUtil {
public static Component getComponentFromMiniMessage(String text) {
return MiniMessage.miniMessage().deserialize(replaceLegacy(text));
}
/**
* Send a message to a command sender
* @param sender sender
* @param s message
*/
public static void sendMessage(CommandSender sender, String s) {
if (s == null) return;
if (sender instanceof Player player) playerMessage(player, s);
else consoleMessage(s);
}
/**
* Send a message to console
* @param s message
*/
public static void consoleMessage(String s) {
if (s == null) return;
Audience au = CustomFishing.getAdventure().sender(Bukkit.getConsoleSender());
MiniMessage mm = MiniMessage.miniMessage();
Component parsed = mm.deserialize(replaceLegacy(s));
au.sendMessage(parsed);
}
/**
* Send a message to a player
* @param player player
* @param s message
*/
public static void playerMessage(Player player, String s) {
if (s == null) return;
Audience au = CustomFishing.getAdventure().player(player);
MiniMessage mm = MiniMessage.miniMessage();
Component parsed = mm.deserialize(replaceLegacy(s));
au.sendMessage(parsed);
}
/**
* Send a title to a player
* @param player player
* @param s1 title
* @param s2 subtitle
* @param in in (ms)
* @param duration duration (ms)
* @param out out (ms)
*/
public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) {
Audience au = CustomFishing.getAdventure().player(player);
MiniMessage mm = MiniMessage.miniMessage();
Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out));
Title title = Title.title(mm.deserialize(replaceLegacy(s1)), mm.deserialize(replaceLegacy(s2)), times);
au.showTitle(title);
}
/**
* Send a title to a player
* @param player player
* @param s1 title
* @param s2 subtitle
* @param in in (ms)
* @param duration duration (ms)
* @param out out (ms)
*/
public static void playerTitle(Player player, Component s1, Component s2, int in, int duration, int out) {
Audience au = CustomFishing.getAdventure().player(player);
Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out));
Title title = Title.title(s1, s2, times);
au.showTitle(title);
}
/**
* Send an actionbar to a player
* @param player player
* @param s actionbar
*/
public static void playerActionbar(Player player, String s) {
Audience au = CustomFishing.getAdventure().player(player);
MiniMessage mm = MiniMessage.miniMessage();
au.sendActionBar(mm.deserialize(replaceLegacy(s)));
}
/**
* Play a sound to a player
* @param player player
* @param source sound source
* @param key sound key
* @param volume volume
* @param pitch pitch
*/
public static void playerSound(Player player, Sound.Source source, Key key, float volume, float pitch) {
Sound sound = Sound.sound(key, source, volume, pitch);
Audience au = CustomFishing.getAdventure().player(player);
au.playSound(sound);
}
/**
* Replace the legacy codes with MiniMessage Format
* @param str text
* @return MiniMessage format text
*/
public static String replaceLegacy(String str) {
StringBuilder stringBuilder = new StringBuilder();
char[] chars = str.replace("&","§").toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '§') {
if (i + 1 < chars.length) {
switch (chars[i+1]) {
case '0' -> {i++;stringBuilder.append("<black>");}
case '1' -> {i++;stringBuilder.append("<dark_blue>");}
case '2' -> {i++;stringBuilder.append("<dark_green>");}
case '3' -> {i++;stringBuilder.append("<dark_aqua>");}
case '4' -> {i++;stringBuilder.append("<dark_red>");}
case '5' -> {i++;stringBuilder.append("<dark_purple>");}
case '6' -> {i++;stringBuilder.append("<gold>");}
case '7' -> {i++;stringBuilder.append("<gray>");}
case '8' -> {i++;stringBuilder.append("<dark_gray>");}
case '9' -> {i++;stringBuilder.append("<blue>");}
case 'a' -> {i++;stringBuilder.append("<green>");}
case 'b' -> {i++;stringBuilder.append("<aqua>");}
case 'c' -> {i++;stringBuilder.append("<red>");}
case 'd' -> {i++;stringBuilder.append("<light_purple>");}
case 'e' -> {i++;stringBuilder.append("<yellow>");}
case 'f' -> {i++;stringBuilder.append("<white>");}
case 'r' -> {i++;stringBuilder.append("<reset><!italic>");}
case 'l' -> {i++;stringBuilder.append("<bold>");}
case 'm' -> {i++;stringBuilder.append("<strikethrough>");}
case 'o' -> {i++;stringBuilder.append("<italic>");}
case 'n' -> {i++;stringBuilder.append("<underlined>");}
case 'k' -> {i++;stringBuilder.append("<obfuscated>");}
case 'x' -> {stringBuilder.append("<#").append(chars[i+3]).append(chars[i+5]).append(chars[i+7]).append(chars[i+9]).append(chars[i+11]).append(chars[i+13]).append(">");i += 13;}
}
}
}
else {
stringBuilder.append(chars[i]);
}
}
return stringBuilder.toString();
}
public static String replaceMiniMessage(String str) {
String result = str.replace("&","§");
List<String> miniFormat = new ArrayList<>();
Pattern pattern = Pattern.compile("<.*?>");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) miniFormat.add(matcher.group());
for (String mini : miniFormat) {
StringBuilder replacer = new StringBuilder();
switch (mini) {
case "<black>" -> replacer = new StringBuilder("§0");
case "<dark_blue>" -> replacer = new StringBuilder("§1");
case "<dark_green>" -> replacer = new StringBuilder("§2");
case "<dark_aqua>" -> replacer = new StringBuilder("§3");
case "<dark_red>" -> replacer = new StringBuilder("§4");
case "<dark_purple>" -> replacer = new StringBuilder("§5");
case "<gold>" -> replacer = new StringBuilder("§6");
case "<gray>" -> replacer = new StringBuilder("§7");
case "<dark_gray>" -> replacer = new StringBuilder("§8");
case "<blue>" -> replacer = new StringBuilder("§9");
case "<green>" -> replacer = new StringBuilder("§a");
case "<aqua>" -> replacer = new StringBuilder("§b");
case "<red>" -> replacer = new StringBuilder("§c");
case "<light_purple>" -> replacer = new StringBuilder("§d");
case "<yellow>" -> replacer = new StringBuilder("§e");
case "<white>" -> replacer = new StringBuilder("§f");
case "<reset>" -> replacer = new StringBuilder("§r");
case "<bold>" -> replacer = new StringBuilder("§l");
case "<strikethrough>" -> replacer = new StringBuilder("§m");
case "<italic>" -> replacer = new StringBuilder("§o");
case "<underlined>" -> replacer = new StringBuilder("§n");
case "<obfuscated>" -> replacer = new StringBuilder("§k");
default -> {
if (mini.length() == 9 && mini.charAt(1) == '#') {
replacer = new StringBuilder("§x");
for (int i = 2; i < 8; i++) {
replacer.append("§").append(mini.charAt(i));
}
}
}
}
result = result.replace(mini, replacer.toString());
}
return result;
}
}

View File

@@ -1,131 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.*;
import com.google.common.collect.Lists;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.fishing.loot.Item;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class ArmorStandUtil {
public static PacketContainer getDestroyPacket(int id) {
PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
destroyPacket.getIntLists().write(0, List.of(id));
return destroyPacket;
}
public static PacketContainer getSpawnPacket(int id, Location location) {
PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
entityPacket.getModifier().write(0, id);
entityPacket.getModifier().write(1, UUID.randomUUID());
entityPacket.getEntityTypeModifier().write(0, EntityType.ARMOR_STAND);
entityPacket.getDoubles().write(0, location.getX());
entityPacket.getDoubles().write(1, location.getY());
entityPacket.getDoubles().write(2, location.getZ());
return entityPacket;
}
public static PacketContainer getMetaPacket(int id) {
PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
metaPacket.getIntegers().write(0, id);
if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) {
WrappedDataWatcher wrappedDataWatcher = createDataWatcher();
setValueList(metaPacket, wrappedDataWatcher);
} else {
metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher().getWatchableObjects());
}
return metaPacket;
}
static void setValueList(PacketContainer metaPacket, WrappedDataWatcher wrappedDataWatcher) {
List<WrappedDataValue> wrappedDataValueList = Lists.newArrayList();
wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> {
final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject();
wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue()));
});
metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList);
}
public static PacketContainer getMetaPacket(int id, String text) {
PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
metaPacket.getIntegers().write(0, id);
if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) {
WrappedDataWatcher wrappedDataWatcher = createDataWatcher(text);
setValueList(metaPacket, wrappedDataWatcher);
} else {
metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher(text).getWatchableObjects());
}
return metaPacket;
}
public static WrappedDataWatcher createDataWatcher() {
WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher();
WrappedDataWatcher.Serializer serializer1 = WrappedDataWatcher.Registry.get(Boolean.class);
WrappedDataWatcher.Serializer serializer2 = WrappedDataWatcher.Registry.get(Byte.class);
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer1), false);
byte flag = 0x20;
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), flag);
return wrappedDataWatcher;
}
public static WrappedDataWatcher createDataWatcher(String text) {
WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher();
WrappedDataWatcher.Serializer serializer1 = WrappedDataWatcher.Registry.get(Boolean.class);
WrappedDataWatcher.Serializer serializer2 = WrappedDataWatcher.Registry.get(Byte.class);
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), Optional.of(WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(text))).getHandle()));
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer1), true);
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), (byte) 0x01);
byte flag = 0x20;
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), flag);
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer1), true);
return wrappedDataWatcher;
}
public static PacketContainer getEquipPacket(int id, ItemStack itemStack) {
PacketContainer equipPacket = new PacketContainer(PacketType.Play.Server.ENTITY_EQUIPMENT);
equipPacket.getIntegers().write(0, id);
List<Pair<EnumWrappers.ItemSlot, ItemStack>> pairs = new ArrayList<>();
pairs.add(new Pair<>(EnumWrappers.ItemSlot.HEAD, itemStack));
equipPacket.getSlotStackPairLists().write(0, pairs);
return equipPacket;
}
public static void sendAnimationToPlayer(Location location, Player player, String key, int time) {
int id = new Random().nextInt(Integer.MAX_VALUE);
Item item = CustomFishing.getInstance().getEffectManager().getUtilItem(key);
if (item == null) return;
CustomFishing.getProtocolManager().sendServerPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0)));
CustomFishing.getProtocolManager().sendServerPacket(player, getMetaPacket(id));
CustomFishing.getProtocolManager().sendServerPacket(player, getEquipPacket(id, ItemStackUtil.getFromItem(item)));
Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.getInstance(), () -> {
CustomFishing.getProtocolManager().sendServerPacket(player, getDestroyPacket(id));
}, time);
}
}

View File

@@ -1,197 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import dev.dejvokep.boostedyaml.YamlDocument;
import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning;
import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings;
import dev.dejvokep.boostedyaml.settings.general.GeneralSettings;
import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings;
import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.fishing.Effect;
import net.momirealms.customfishing.fishing.action.*;
import net.momirealms.customfishing.fishing.requirements.*;
import net.momirealms.customfishing.helper.Log;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class ConfigUtil {
/**
* Get a config by name
* @param configName config's name
* @return yaml
*/
public static YamlConfiguration getConfig(String configName) {
File file = new File(CustomFishing.getInstance().getDataFolder(), configName);
if (!file.exists()) CustomFishing.getInstance().saveResource(configName, false);
return YamlConfiguration.loadConfiguration(file);
}
/**
* Update config
* @param fileName config
*/
public static void update(String fileName){
try {
YamlDocument.create(new File(CustomFishing.getInstance().getDataFolder(), fileName), Objects.requireNonNull(CustomFishing.getInstance().getResource(fileName)), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build());
} catch (IOException e){
Log.warn(e.getMessage());
}
}
/**
* Create a data file if not exists
* @param file file path
* @return yaml data
*/
public static YamlConfiguration readData(File file) {
if (!file.exists()) {
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
AdventureUtil.consoleMessage("<red>[CustomFishing] Failed to generate data files!</red>");
}
}
return YamlConfiguration.loadConfiguration(file);
}
public static RequirementInterface[] getRequirements(ConfigurationSection section) {
if (section != null) {
List<RequirementInterface> requirements = new ArrayList<>();
for (String type : section.getKeys(false)) {
switch (type) {
case "biome" -> requirements.add(new BiomeImpl(null, section.getStringList(type)));
case "weather" -> requirements.add(new WeatherImpl(null, section.getStringList(type)));
case "ypos" -> requirements.add(new YPosImpl(null, section.getStringList(type)));
case "season" -> requirements.add(new SeasonImpl(null, section.getStringList(type)));
case "world" -> requirements.add(new WorldImpl(null, section.getStringList(type)));
case "permission" -> requirements.add(new PermissionImpl(null, section.getString(type)));
case "time" -> requirements.add(new TimeImpl(null, section.getStringList(type)));
case "skill-level" -> requirements.add(new SkillLevelImpl(null, section.getInt(type)));
case "job-level" -> requirements.add(new JobLevelImpl(null, section.getInt(type)));
case "papi-condition" -> requirements.add(new CustomPapi(null, Objects.requireNonNull(section.getConfigurationSection(type)).getValues(false)));
}
}
return requirements.toArray(new RequirementInterface[0]);
}
return null;
}
public static RequirementInterface[] getRequirementsWithMsg(ConfigurationSection section) {
if (section != null) {
List<RequirementInterface> requirements = new ArrayList<>();
for (String id : section.getKeys(false)) {
ConfigurationSection innerSec = section.getConfigurationSection(id);
if (innerSec == null) continue;
String type = innerSec.getString("type");
if (type == null) continue;
String[] msg = innerSec.getStringList("message").size() == 0 ? (innerSec.getString("message") == null ? null : new String[]{innerSec.getString("message")}) : innerSec.getStringList("message").toArray(new String[0]);
switch (type) {
case "biome" -> requirements.add(new BiomeImpl(msg, innerSec.getStringList("value")));
case "weather" -> requirements.add(new WeatherImpl(msg, innerSec.getStringList("value")));
case "ypos" -> requirements.add(new YPosImpl(msg, innerSec.getStringList("value")));
case "season" -> requirements.add(new SeasonImpl(msg, innerSec.getStringList("value")));
case "world" -> requirements.add(new WorldImpl(msg, innerSec.getStringList("value")));
case "permission" -> requirements.add(new PermissionImpl(msg, innerSec.getString("value")));
case "time" -> requirements.add(new TimeImpl(msg, innerSec.getStringList("value")));
case "skill-level" -> requirements.add(new SkillLevelImpl(msg, innerSec.getInt("value")));
case "job-level" -> requirements.add(new JobLevelImpl(msg, innerSec.getInt("value")));
case "papi-condition" -> requirements.add(new CustomPapi(msg, Objects.requireNonNull(innerSec.getConfigurationSection("value")).getValues(false)));
}
}
return requirements.toArray(new RequirementInterface[0]);
}
return null;
}
public static Action[] getActions(ConfigurationSection section, String nick) {
if (section != null) {
List<Action> actions = new ArrayList<>();
for (String action : section.getKeys(false)) {
switch (action) {
case "message" -> actions.add(new MessageActionImpl(section.getStringList(action).toArray(new String[0]), nick));
case "command" -> actions.add(new CommandActionImpl(section.getStringList(action).toArray(new String[0]), nick));
case "exp" -> actions.add(new VanillaXPImpl(section.getInt(action), false));
case "mending" -> actions.add(new VanillaXPImpl(section.getInt(action), true));
case "skill-xp" -> actions.add(new SkillXPImpl(section.getDouble(action)));
case "job-xp" -> actions.add(new JobXPImpl(section.getDouble(action)));
case "sound" -> actions.add(new SoundActionImpl(
section.getString(action + ".source"),
section.getString(action + ".key"),
(float) section.getDouble(action + ".volume"),
(float) section.getDouble(action + ".pitch")
));
case "potion-effect" -> {
List<PotionEffect> potionEffectList = new ArrayList<>();
for (String key : section.getConfigurationSection(action).getKeys(false)) {
PotionEffectType type = PotionEffectType.getByName(section.getString(action + "." + key + ".type", "BLINDNESS").toUpperCase());
if (type == null) AdventureUtil.consoleMessage("<red>[CustomFishing] Potion effect " + section.getString(action + "." + key + ".type", "BLINDNESS") + " doesn't exists");
potionEffectList.add(new PotionEffect(
type == null ? PotionEffectType.LUCK : type,
section.getInt(action + "." + key + ".duration"),
section.getInt(action + "." + key + ".amplifier")
));
}
actions.add(new PotionEffectImpl(potionEffectList.toArray(new PotionEffect[0])));
}
}
}
return actions.toArray(new Action[0]);
}
return null;
}
public static Effect getEffect(ConfigurationSection section) {
Effect effect = new Effect();
if (section == null) return effect;
for (String modifier : section.getKeys(false)) {
switch (modifier) {
case "weight-add" -> {
HashMap<String, Integer> as = new HashMap<>();
Objects.requireNonNull(section.getConfigurationSection(modifier)).getValues(false).forEach((group, value) -> as.put(group, (Integer) value));
effect.setWeightAS(as);
}
case "weight-multiply" -> {
HashMap<String, Double> md = new HashMap<>();
Objects.requireNonNull(section.getConfigurationSection(modifier)).getValues(false).forEach((group, value) -> md.put(group, Double.parseDouble(String.valueOf(value))-1));
effect.setWeightMD(md);
}
case "time" -> effect.setTimeModifier(section.getDouble(modifier));
case "difficulty" -> effect.setDifficulty(section.getInt(modifier));
case "double-loot" -> effect.setDoubleLootChance(section.getDouble(modifier));
case "score" -> effect.setScoreMultiplier(section.getDouble(modifier));
case "size-multiply" -> effect.setSizeMultiplier(section.getDouble(modifier));
case "lava-fishing" -> effect.setCanLavaFishing(section.getBoolean(modifier, false));
}
}
return effect;
}
}

View File

@@ -1,70 +0,0 @@
package net.momirealms.customfishing.util;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import net.momirealms.customfishing.CustomFishing;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.UUID;
public class FakeItemUtil {
public static PacketContainer getDestroyPacket(int id) {
PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
destroyPacket.getIntLists().write(0, List.of(id));
return destroyPacket;
}
public static PacketContainer getSpawnPacket(int id, Location location) {
PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
entityPacket.getModifier().write(0, id);
entityPacket.getModifier().write(1, UUID.randomUUID());
entityPacket.getEntityTypeModifier().write(0, EntityType.DROPPED_ITEM);
entityPacket.getDoubles().write(0, location.getX());
entityPacket.getDoubles().write(1, location.getY() - 0.5);
entityPacket.getDoubles().write(2, location.getZ());
return entityPacket;
}
public static PacketContainer getMetaPacket(int id, ItemStack itemStack) {
PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
metaPacket.getIntegers().write(0, id);
if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) {
WrappedDataWatcher wrappedDataWatcher = createDataWatcher(itemStack);
ArmorStandUtil.setValueList(metaPacket, wrappedDataWatcher);
} else {
metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher(itemStack).getWatchableObjects());
}
return metaPacket;
}
public static PacketContainer getTpPacket(int id, Location location) {
PacketContainer tpPacket = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT);
tpPacket.getModifier().write(0, id);
tpPacket.getDoubles().write(0, location.getX());
tpPacket.getDoubles().write(1, location.getY() - 0.5);
tpPacket.getDoubles().write(2, location.getZ());
return tpPacket;
}
public static PacketContainer getVelocity(int id, Vector vector) {
PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.ENTITY_VELOCITY);
entityPacket.getModifier().write(0, id);
entityPacket.getIntegers().write(1, (int) (vector.getX() * 8000));
entityPacket.getIntegers().write(2, (int) (vector.getY() * 8000));
entityPacket.getIntegers().write(3, (int) (vector.getZ() * 8000));
return entityPacket;
}
public static WrappedDataWatcher createDataWatcher(ItemStack itemStack) {
WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher();
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(8, WrappedDataWatcher.Registry.getItemStackSerializer(false)), itemStack);
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(5, WrappedDataWatcher.Registry.get(Boolean.class)), true);
return wrappedDataWatcher;
}
}

View File

@@ -1,118 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class InventoryUtil {
/**
* Converts itemStacks to base64
* @param contents items
* @return base64
*/
public static @NotNull String toBase64(ItemStack[] contents) {
boolean convert = false;
for (ItemStack content : contents) {
if (content != null) {
convert = true;
break;
}
}
if (convert) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeInt(contents.length);
for (ItemStack itemStack : contents) {
dataOutput.writeObject(itemStack);
}
dataOutput.close();
byte[] byteArr = outputStream.toByteArray();
outputStream.close();
return Base64Coder.encodeLines(byteArr);
} catch (IOException e) {
throw new RuntimeException("[CustomFishing] Data save error", e);
}
}
return "";
}
/**
* Get itemStacks from base64
* @param base64 base64
* @return itemStacks
*/
@Nullable
public static ItemStack[] getInventoryItems(String base64) {
ItemStack[] itemStacks = null;
try {
itemStacks = stacksFromBase64(base64);
} catch (IllegalArgumentException exception) {
exception.printStackTrace();
}
return itemStacks;
}
private static ItemStack[] stacksFromBase64(String data) {
if (data == null || data.equals("")) return new ItemStack[]{};
ByteArrayInputStream inputStream;
try {
inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
} catch (IllegalArgumentException e) {
return new ItemStack[]{};
}
BukkitObjectInputStream dataInput = null;
ItemStack[] stacks = null;
try {
dataInput = new BukkitObjectInputStream(inputStream);
stacks = new ItemStack[dataInput.readInt()];
} catch (IOException e) {
e.printStackTrace();
}
if (stacks == null) return new ItemStack[]{};
for (int i = 0; i < stacks.length; i++) {
try {
stacks[i] = (ItemStack) dataInput.readObject();
}
catch (IOException | ClassNotFoundException | NullPointerException e) {
try {
dataInput.close();
} catch (IOException exception) {
AdventureUtil.consoleMessage("<red>[CustomFishing] Error! Failed to read fishing bag data");
}
return null;
}
}
try {
dataInput.close();
} catch (IOException ignored) {
}
return stacks;
}
}

View File

@@ -1,292 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import de.tr7zw.changeme.nbtapi.NBTListCompound;
import de.tr7zw.changeme.nbtapi.iface.ReadWriteNBT;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.fishing.loot.DroppedItem;
import net.momirealms.customfishing.fishing.loot.Item;
import net.momirealms.customfishing.fishing.loot.Loot;
import net.momirealms.customfishing.object.LeveledEnchantment;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class ItemStackUtil {
/**
* Build itemStack from item's config
* @param item item
* @return itemStack
*/
public static ItemStack getFromItem(Item item) {
ItemStack itemStack = new ItemStack(item.getMaterial());
itemStack.setAmount(item.getAmount());
ItemMeta itemMeta = itemStack.getItemMeta();
if (item.getCustomModelData() != 0) itemMeta.setCustomModelData(item.getCustomModelData());
if (item.isUnbreakable()) itemMeta.setUnbreakable(true);
if (item.getItemFlags() != null) item.getItemFlags().forEach(itemMeta::addItemFlags);
if (item.getEnchantment() != null) {
if (itemStack.getType() == Material.ENCHANTED_BOOK){
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) itemMeta;
item.getEnchantment().forEach(enchantment -> meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.key())),enchantment.level(),true));
itemStack.setItemMeta(meta);
}
else {
item.getEnchantment().forEach(enchantment -> itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.key())),enchantment.level(),true));
itemStack.setItemMeta(itemMeta);
}
}
else {
itemStack.setItemMeta(itemMeta);
}
NBTItem nbtItem = new NBTItem(itemStack);
if (item.getName() != null) {
NBTCompound display = nbtItem.addCompound("display");
String name = item.getName();
if (name.contains("&") || name.contains("§")){
name = AdventureUtil.replaceLegacy(name);
}
display.setString("Name", GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<!i>" + name)));
}
if (item.getLore() != null) {
NBTCompound display = nbtItem.addCompound("display");
List<String> lore = display.getStringList("Lore");
item.getLore().forEach(line -> {
if (line.contains("&") || line.contains("§")){
line = AdventureUtil.replaceLegacy(line);
}
lore.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<!i>" + line)));
});
}
if (item.getCfTag() != null) {
NBTCompound cfCompound = nbtItem.addCompound("CustomFishing");
cfCompound.setString("type", item.getCfTag()[0]);
cfCompound.setString("id", item.getCfTag()[1]);
}
if (item.getHead64() != null) {
NBTCompound nbtCompound = nbtItem.addCompound("SkullOwner");
nbtCompound.setUUID("Id", item.isHeadStackable() ? UUID.nameUUIDFromBytes(item.getKey().getBytes()) : UUID.randomUUID());
NBTListCompound texture = nbtCompound.addCompound("Properties").getCompoundList("textures").addCompound();
texture.setString("Value", item.getHead64());
}
if (item.getTotem() != null) {
nbtItem.setString("Totem", item.getTotem());
}
if (item.getNbt() != null) NBTUtil.setTags(item.getNbt(), nbtItem);
return nbtItem.getItem();
}
/**
* Get an itemStack with random durability
* @param itemStack itemStack
*/
public static void addRandomDamage(ItemStack itemStack){
if (itemStack.getItemMeta() instanceof Damageable damageable){
damageable.setDamage((int) (itemStack.getType().getMaxDurability() * Math.random()));
itemStack.setItemMeta(damageable);
}
}
/**
* Adds owner tag
* @param itemStack itemStack
* @param name owner
*/
public static void addOwner(ItemStack itemStack, String name){
NBTItem nbtItem = new NBTItem(itemStack);
nbtItem.setString("M_Owner", name);
itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
}
/**
* Add random enchantments
* @param itemStack itemStack
* @param enchantments enchantments
*/
public static void addRandomEnchants(ItemStack itemStack, LeveledEnchantment[] enchantments){
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemStack.getType() == Material.ENCHANTED_BOOK){
EnchantmentStorageMeta meta = (EnchantmentStorageMeta)itemMeta;
for (LeveledEnchantment enchantment : enchantments) {
if (enchantment.chance() > Math.random()) meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.key())),enchantment.level(),true);
}
itemStack.setItemMeta(meta);
}
else {
for (LeveledEnchantment enchantment : enchantments) {
if (enchantment.chance() > Math.random()) itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.key())),enchantment.level(),true);
}
itemStack.setItemMeta(itemMeta);
}
}
/**
* Add customFishing tags
* @param itemStack itemStack
* @param type type
* @param id id
* @return itemStack
*/
public static ItemStack addIdentifier(ItemStack itemStack, String type, String id){
NBTItem nbtItem = new NBTItem(itemStack);
NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing");
nbtCompound.setString("type", type);
nbtCompound.setString("id", id);
itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
return itemStack;
}
public static void givePlayerLoot(Player player, String key, int amount){
Loot loot = CustomFishing.getInstance().getLootManager().getLoot(key);
if (!(loot instanceof DroppedItem droppedItem)) return;
ItemStack itemStack = CustomFishing.getInstance().getFishingManager().getCustomFishingLootItemStack(droppedItem, player);
if (itemStack.getType() == Material.AIR) return;
itemStack.setAmount(amount);
player.getInventory().addItem(itemStack);
}
public static void givePlayerRod(Player player, String rodKey, int amount){
Item item = CustomFishing.getInstance().getEffectManager().getRodItem(rodKey);
if (item == null) return;
ItemStack itemStack = getFromItem(item);
for (int i = 0; i < amount; i++) {
player.getInventory().addItem(itemStack);
}
}
public static void givePlayerBait(Player player, String baitKey, int amount){
Item item = CustomFishing.getInstance().getEffectManager().getBaitItem(baitKey);
if (item == null) return;
ItemStack itemStack = getFromItem(item);
itemStack.setAmount(amount);
player.getInventory().addItem(itemStack);
}
public static void givePlayerUtil(Player player, String utilKey, int amount){
Item item = CustomFishing.getInstance().getEffectManager().getUtilItem(utilKey);
if (item == null) return;
ItemStack itemStack = getFromItem(item);
itemStack.setAmount(amount);
player.getInventory().addItem(itemStack);
}
public static boolean saveToFile(ItemStack itemStack, String key){
if (itemStack == null || itemStack.getType() == Material.AIR || CustomFishing.getInstance().getLootManager().hasLoot(key)) return false;
File file = new File(CustomFishing.getInstance().getDataFolder(), File.separator + "loots" + File.separator + "imported.yml");
YamlConfiguration data = ConfigUtil.readData(file);
data.set(key + ".material", itemStack.getType().toString());
data.set(key + ".amount", itemStack.getAmount());
NBTItem nbtItem = new NBTItem(itemStack);
Map<String, Object> map0 = compoundToMap(nbtItem);
if (map0.size() != 0) {
data.createSection(key + ".nbt", map0);
}
try {
data.save(file);
CustomFishing.getInstance().getLootManager().unload();
CustomFishing.getInstance().getLootManager().load();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static void addExtraMeta(ItemStack itemStack, DroppedItem droppedItem, double sizeMultiplier) {
NBTItem nbtItem = new NBTItem(itemStack);
boolean changed = replaceSizeLore(droppedItem.getSize(), nbtItem, sizeMultiplier);
if (droppedItem.getBasicPrice() != 0) {
NBTCompound fishMetaCompound = nbtItem.addCompound("FishMeta");
fishMetaCompound.setFloat("base", droppedItem.getBasicPrice());
changed = true;
}
if (droppedItem.getSizeBonus() != 0) {
NBTCompound fishMetaCompound = nbtItem.addCompound("FishMeta");
fishMetaCompound.setFloat("bonus", droppedItem.getSizeBonus());
changed = true;
}
if (changed) {
itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
private static boolean replaceSizeLore(String[] sizes, NBTItem nbtItem, double sizeMultiplier) {
if (sizes == null) return false;
float min = Float.parseFloat(sizes[0]);
float max = Float.parseFloat(sizes[1]);
if (max - min < 0) return false;
float size = (float) ((min + Math.random() * (max - min)) * sizeMultiplier);
String sizeText = String.format("%.1f", size);
NBTCompound nbtCompound = nbtItem.getCompound("display");
if (nbtCompound == null || !nbtCompound.hasTag("Lore")) return false;
List<String> lore = nbtCompound.getStringList("Lore");
lore.replaceAll(s -> s.replace("{size}", sizeText));
NBTCompound fishMetaCompound = nbtItem.addCompound("FishMeta");
fishMetaCompound.setFloat("size", size);
return true;
}
public static Map<String, Object> compoundToMap(ReadWriteNBT nbtCompound){
Map<String, Object> map = new HashMap<>();
for (String key : nbtCompound.getKeys()) {
switch (nbtCompound.getType(key)){
case NBTTagByte -> map.put(key, "(Byte) " + nbtCompound.getByte(key));
case NBTTagInt -> map.put(key, "(Int) " + nbtCompound.getInteger(key));
case NBTTagDouble -> map.put(key, "(Double) " + nbtCompound.getDouble(key));
case NBTTagLong -> map.put(key, "(Long) " + nbtCompound.getLong(key));
case NBTTagFloat -> map.put(key, "(Float) " + nbtCompound.getFloat(key));
case NBTTagShort -> map.put(key, "(Short) " + nbtCompound.getShort(key));
case NBTTagString -> map.put(key, "(String) " + nbtCompound.getString(key));
case NBTTagByteArray -> map.put(key, "(ByteArray) " + Arrays.toString(nbtCompound.getByteArray(key)));
case NBTTagIntArray -> map.put(key, "(IntArray) " + Arrays.toString(nbtCompound.getIntArray(key)));
case NBTTagCompound -> {
Map<String, Object> map1 = compoundToMap(nbtCompound.getCompound(key));
if (map1.size() != 0) map.put(key, map1);
}
case NBTTagList -> {
List<Object> list = new ArrayList<>();
switch (nbtCompound.getListType(key)) {
case NBTTagCompound -> nbtCompound.getCompoundList(key).forEach(a -> list.add(compoundToMap(a)));
case NBTTagInt -> nbtCompound.getIntegerList(key).forEach(a -> list.add("(Int) " + a));
case NBTTagDouble -> nbtCompound.getDoubleList(key).forEach(a -> list.add("(Double) " + a));
case NBTTagString -> nbtCompound.getStringList(key).forEach(a -> list.add("(String) " + a));
case NBTTagFloat -> nbtCompound.getFloatList(key).forEach(a -> list.add("(Float) " + a));
case NBTTagLong -> nbtCompound.getLongList(key).forEach(a -> list.add("(Long) " + a));
case NBTTagIntArray -> nbtCompound.getIntArrayList(key).forEach(a -> list.add("(IntArray) " + Arrays.toString(a)));
}
if (list.size() != 0) map.put(key, list);
}
}
}
return map;
}
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import net.momirealms.customfishing.helper.Log;
import org.bukkit.configuration.file.YamlConfiguration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ArrayList;
import java.util.List;
public class JedisUtil {
private static JedisPool jedisPool;
public static Jedis getJedis(){
return jedisPool.getResource();
}
public static void initializeRedis(YamlConfiguration configuration){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setTestWhileIdle(true);
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
jedisPoolConfig.setNumTestsPerEvictionRun(-1);
jedisPoolConfig.setMinEvictableIdleTimeMillis(configuration.getInt("Redis.MinEvictableIdleTimeMillis",1800000));
jedisPoolConfig.setMaxTotal(configuration.getInt("Redis.MaxTotal",8));
jedisPoolConfig.setMaxIdle(configuration.getInt("Redis.MaxIdle",8));
jedisPoolConfig.setMinIdle(configuration.getInt("Redis.MinIdle",1));
jedisPoolConfig.setMaxWaitMillis(configuration.getInt("redis.MaxWaitMillis",30000));
if (configuration.getString("Redis.password") != null) {
jedisPool = new JedisPool(jedisPoolConfig, configuration.getString("Redis.host","localhost"), configuration.getInt("Redis.port",6379), 2000, configuration.getString("Redis.password"));
}
else {
jedisPool = new JedisPool(jedisPoolConfig, configuration.getString("Redis.host","localhost"), configuration.getInt("Redis.port",6379));
}
AdventureUtil.consoleMessage("[CustomFishing] <white>Redis Server Connected!");
List<Jedis> minIdleJedisList = new ArrayList<>(jedisPoolConfig.getMinIdle());
for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
Jedis jedis;
try {
jedis = jedisPool.getResource();
minIdleJedisList.add(jedis);
jedis.ping();
} catch (Exception e) {
Log.warn(e.getMessage());
}
}
for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
Jedis jedis;
try {
jedis = minIdleJedisList.get(i);
jedis.close();
} catch (Exception e) {
Log.warn(e.getMessage());
}
}
}
public static void closePool() {
if (jedisPool != null) {
jedisPool.close();
jedisPool = null;
}
}
public static boolean isPoolEnabled() {
return jedisPool != null && !jedisPool.isClosed();
}
}

View File

@@ -1,129 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.util;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import de.tr7zw.changeme.nbtapi.NBTListCompound;
import org.bukkit.configuration.MemorySection;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class NBTUtil {
public static NBTItem setNBTToItemStack(Map<String, Object> nbt, ItemStack itemStack){
NBTItem nbtItem = new NBTItem(itemStack);
setTags(nbt, nbtItem);
return nbtItem;
}
@SuppressWarnings("unchecked")
public static void setTags(Map<String, Object> map, NBTCompound nbtCompound) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof MemorySection memorySection) {
setTags(memorySection.getValues(false), nbtCompound.addCompound(key));
} else if (value instanceof List<?> list) {
for (Object o : list) {
if (o instanceof String stringValue) {
setListValue(key, stringValue, nbtCompound);
} else if (o instanceof Map<?, ?> mapValue) {
setCompoundList(key, (Map<String, Object>) mapValue, nbtCompound);
}
}
} else if (value instanceof String stringValue) {
setSingleValue(key, stringValue, nbtCompound);
}
}
}
private static void setCompoundList(String key, Map<String, Object> map, NBTCompound nbtCompound) {
NBTListCompound nbtListCompound = nbtCompound.getCompoundList(key).addCompound();
setTags(map, nbtListCompound);
}
private static void setListValue(String key, String value, NBTCompound nbtCompound) {
String[] parts = getTypeAndData(value);
String type = parts[0]; String data = parts[1];
switch (type) {
case "String" -> nbtCompound.getStringList(key).add(data);
case "UUID" -> nbtCompound.getUUIDList(key).add(UUID.fromString(data));
case "Double" -> nbtCompound.getDoubleList(key).add(Double.valueOf(data));
case "Long" -> nbtCompound.getLongList(key).add(Long.valueOf(data));
case "Float" -> nbtCompound.getFloatList(key).add(Float.valueOf(data));
case "Int" -> nbtCompound.getIntegerList(key).add(Integer.valueOf(data));
case "IntArray" -> {
String[] split = data.replace("[", "").replace("]", "").replaceAll("\\s", "").split(",");
int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
nbtCompound.getIntArrayList(key).add(array);
}
default -> throw new IllegalArgumentException("Invalid value type: " + type);
}
}
private static void setSingleValue(String key, String value, NBTCompound nbtCompound) {
String[] parts = getTypeAndData(value);
String type = parts[0]; String data = parts[1];
switch (type) {
case "Int" -> nbtCompound.setInteger(key, Integer.valueOf(data));
case "String" -> nbtCompound.setString(key, data);
case "Long" -> nbtCompound.setLong(key, Long.valueOf(data));
case "Float" -> nbtCompound.setFloat(key, Float.valueOf(data));
case "Double" -> nbtCompound.setDouble(key, Double.valueOf(data));
case "Short" -> nbtCompound.setShort(key, Short.valueOf(data));
case "Boolean" -> nbtCompound.setBoolean(key, Boolean.valueOf(data));
case "UUID" -> nbtCompound.setUUID(key, UUID.nameUUIDFromBytes(data.getBytes()));
case "Byte" -> nbtCompound.setByte(key, Byte.valueOf(data));
case "ByteArray" -> {
String[] split = splitValue(value);
byte[] bytes = new byte[split.length];
for (int i = 0; i < split.length; i++){
bytes[i] = Byte.parseByte(split[i]);
}
nbtCompound.setByteArray(key, bytes);
}
case "IntArray" -> {
String[] split = splitValue(value);
int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
nbtCompound.setIntArray(key, array);
}
default -> throw new IllegalArgumentException("Invalid value type: " + type);
}
}
private static String[] getTypeAndData(String str) {
String[] parts = str.split("\\s+", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid value format: " + str);
}
String type = parts[0].substring(1, parts[0].length() - 1);
String data = parts[1];
return new String[]{type, data};
}
private static String[] splitValue(String value) {
return value.substring(value.indexOf('[') + 1, value.lastIndexOf(']'))
.replaceAll("\\s", "")
.split(",");
}
}