From dfcaa8de09f232ed009b91670009c0b82247726f Mon Sep 17 00:00:00 2001 From: Xiao-MoMi <70987828+Xiao-MoMi@users.noreply.github.com> Date: Tue, 6 Sep 2022 22:25:47 +0800 Subject: [PATCH] 2.0-PRE-1 --- build.gradle | 9 +- .../customnameplates/ConfigManager.java | 266 +++++++----- .../customnameplates/CustomNameplates.java | 155 ++++--- .../actionbar/ActionbarSender.java | 6 +- .../bossbar/protocollib/BossBarSenderP.java | 13 +- .../bossbar/protocollib/TimerTaskP.java | 1 - .../customnameplates/commands/Execute.java | 406 +++++++----------- .../commands/TabComplete.java | 4 +- .../customnameplates/data/DataManager.java | 57 +-- .../customnameplates/data/SqlHandler.java | 21 +- .../customnameplates/font/FontCache.java | 103 ----- .../customnameplates/font/FontChar.java | 14 +- .../customnameplates/font/FontNegative.java | 10 +- .../customnameplates/font/FontUtil.java | 27 ++ .../{FontWidth.java => FontWidthNormal.java} | 48 +-- .../customnameplates/font/FontWidthThin.java | 38 +- .../customnameplates/hook/Placeholders.java | 91 ++-- .../listener/EntityDestroyListener.java | 42 ++ .../listener/MountPacketListener.java | 36 ++ .../listener/PacketsListener.java | 80 ---- .../customnameplates/listener/PapiReload.java | 3 +- .../listener/PlayerListener.java | 127 ++++-- .../listener/PlayerPacketsListener.java | 57 +++ .../nameplates/NameplateConfig.java | 34 +- .../nameplates/NameplateInstance.java | 66 +++ .../nameplates/NameplateUtil.java | 44 +- .../customnameplates/objects/ASInfo.java | 34 ++ .../{utils => objects}/BGInfo.java | 2 +- .../{background => objects}/BackGround.java | 49 +-- .../{utils => objects}/NPInfo.java | 2 +- .../resource/ResourceManager.java | 270 ++++++------ .../scoreboard/NameplatesTeam.java | 148 ++++--- .../scoreboard/ScoreBoardManager.java | 21 +- .../customnameplates/scoreboard/TeamInfo.java | 27 ++ .../AdventureUtil.java} | 5 +- .../utils/ArmorStandPacketUtil.java | 232 ++++++++++ .../{UpdateConfig.java => ConfigUtil.java} | 2 +- .../customnameplates/utils/HoloUtil.java | 121 ++++++ .../customnameplates/utils/SqlConnection.java | 11 +- .../utils/TeamPacketUtil.java | 125 ++++++ .../resources/{module.yml => MODULES.yml} | 2 +- .../minecraft/shaders/core/note.txt | 0 .../shaders/core/rendertype_text.fsh | 3 + .../shaders/core/rendertype_text.json | 117 +++++ .../shaders/core/rendertype_text.vsh | 87 ++++ .../core/rendertype_text_see_through.fsh | 20 + .../core/rendertype_text_see_through.json | 22 + .../core/rendertype_text_see_through.vsh | 18 + src/main/resources/background.yml | 18 +- src/main/resources/bossbar.yml | 21 +- src/main/resources/char-width.yml | 5 +- src/main/resources/config.yml | 43 +- src/main/resources/custom-papi.yml | 6 + src/main/resources/messages/messages_cn.yml | 3 +- src/main/resources/messages/messages_en.yml | 3 +- src/main/resources/messages/messages_es.yml | 3 +- src/main/resources/nameplate.yml | 75 ++++ src/main/resources/nameplates/cat.png | Bin 0 -> 812 bytes src/main/resources/nameplates/cheems.png | Bin 0 -> 820 bytes src/main/resources/nameplates/egg.png | Bin 0 -> 769 bytes src/main/resources/nameplates/halloween.png | Bin 0 -> 525 bytes src/main/resources/nameplates/hutao.png | Bin 0 -> 985 bytes src/main/resources/nameplates/rabbit.png | Bin 0 -> 268 bytes src/main/resources/nameplates/starsky.png | Bin 0 -> 502 bytes .../{resources => nameplates}/trident.png | Bin src/main/resources/nameplates/wither.png | Bin 0 -> 636 bytes src/main/resources/nameplates/xmas.png | Bin 0 -> 479 bytes 67 files changed, 2076 insertions(+), 1177 deletions(-) delete mode 100644 src/main/java/net/momirealms/customnameplates/font/FontCache.java create mode 100644 src/main/java/net/momirealms/customnameplates/font/FontUtil.java rename src/main/java/net/momirealms/customnameplates/font/{FontWidth.java => FontWidthNormal.java} (64%) create mode 100644 src/main/java/net/momirealms/customnameplates/listener/EntityDestroyListener.java create mode 100644 src/main/java/net/momirealms/customnameplates/listener/MountPacketListener.java delete mode 100644 src/main/java/net/momirealms/customnameplates/listener/PacketsListener.java create mode 100644 src/main/java/net/momirealms/customnameplates/listener/PlayerPacketsListener.java create mode 100644 src/main/java/net/momirealms/customnameplates/nameplates/NameplateInstance.java create mode 100644 src/main/java/net/momirealms/customnameplates/objects/ASInfo.java rename src/main/java/net/momirealms/customnameplates/{utils => objects}/BGInfo.java (94%) rename src/main/java/net/momirealms/customnameplates/{background => objects}/BackGround.java (73%) rename src/main/java/net/momirealms/customnameplates/{utils => objects}/NPInfo.java (94%) create mode 100644 src/main/java/net/momirealms/customnameplates/scoreboard/TeamInfo.java rename src/main/java/net/momirealms/customnameplates/{AdventureManager.java => utils/AdventureUtil.java} (94%) create mode 100644 src/main/java/net/momirealms/customnameplates/utils/ArmorStandPacketUtil.java rename src/main/java/net/momirealms/customnameplates/utils/{UpdateConfig.java => ConfigUtil.java} (97%) create mode 100644 src/main/java/net/momirealms/customnameplates/utils/HoloUtil.java create mode 100644 src/main/java/net/momirealms/customnameplates/utils/TeamPacketUtil.java rename src/main/resources/{module.yml => MODULES.yml} (82%) create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/note.txt create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.fsh create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.json create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.vsh create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.fsh create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.json create mode 100644 src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.vsh create mode 100644 src/main/resources/nameplate.yml create mode 100644 src/main/resources/nameplates/cat.png create mode 100644 src/main/resources/nameplates/cheems.png create mode 100644 src/main/resources/nameplates/egg.png create mode 100644 src/main/resources/nameplates/halloween.png create mode 100644 src/main/resources/nameplates/hutao.png create mode 100644 src/main/resources/nameplates/rabbit.png create mode 100644 src/main/resources/nameplates/starsky.png rename src/main/resources/{resources => nameplates}/trident.png (100%) create mode 100644 src/main/resources/nameplates/wither.png create mode 100644 src/main/resources/nameplates/xmas.png diff --git a/build.gradle b/build.gradle index 4184d9e..a5cf2fd 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } group = 'net.momirealms' -version = '1.8.7' +version = '2.0-PRE-1' repositories { mavenCentral() @@ -43,7 +43,7 @@ dependencies { compileOnly 'commons-io:commons-io:2.11.0' compileOnly 'dev.dejvokep:boosted-yaml:1.3' implementation('net.kyori:adventure-api:4.11.0') - implementation('net.kyori:adventure-platform-bukkit:4.1.1') + implementation('net.kyori:adventure-platform-bukkit:4.1.2') implementation('net.kyori:adventure-text-minimessage:4.11.0') implementation('net.kyori:adventure-text-serializer-gson:4.11.0') } @@ -78,9 +78,10 @@ tasks.withType(JavaCompile) { } shadowJar { - relocate ('net.kyori', 'libs.kyori') + relocate ('net.kyori', 'net.momirealms.customnameplates.libs') } + tasks.register("delete", Delete).get().delete("build/libs/"+project.name+"-"+project.version+".jar") tasks.named("build").get().dependsOn("shadowJar").finalizedBy("delete").doLast { println("Deleting: "+ "build/libs/"+project.name+"-"+project.version+".jar") -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/ConfigManager.java b/src/main/java/net/momirealms/customnameplates/ConfigManager.java index d9239b7..6c01d29 100644 --- a/src/main/java/net/momirealms/customnameplates/ConfigManager.java +++ b/src/main/java/net/momirealms/customnameplates/ConfigManager.java @@ -19,13 +19,15 @@ package net.momirealms.customnameplates; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.key.Key; -import net.momirealms.customnameplates.background.BackGround; +import net.momirealms.customnameplates.objects.BackGround; import net.momirealms.customnameplates.bossbar.adventure.BossBarConfigA; import net.momirealms.customnameplates.bossbar.protocollib.BossBarConfigP; import net.momirealms.customnameplates.bossbar.protocollib.Overlay; -import net.momirealms.customnameplates.hook.Placeholders; -import net.momirealms.customnameplates.utils.BGInfo; -import net.momirealms.customnameplates.utils.NPInfo; +import net.momirealms.customnameplates.font.FontWidthNormal; +import net.momirealms.customnameplates.font.FontWidthThin; +import net.momirealms.customnameplates.utils.AdventureUtil; +import net.momirealms.customnameplates.objects.BGInfo; +import net.momirealms.customnameplates.objects.NPInfo; import org.bukkit.Bukkit; import org.bukkit.boss.BarColor; import org.bukkit.configuration.file.FileConfiguration; @@ -33,6 +35,7 @@ import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.util.HashMap; +import java.util.List; import java.util.TreeMap; public class ConfigManager { @@ -44,6 +47,11 @@ public class ConfigManager { public static HashMap papiNP = new HashMap<>(); public static HashMap fontWidth = new HashMap<>(); + /** + * 获取配置文件 + * @param configName 文件名 + * @return YAML配置 + */ public static YamlConfiguration getConfig(String configName) { File file = new File(CustomNameplates.instance.getDataFolder(), configName); if (!file.exists()) { @@ -52,32 +60,25 @@ public class ConfigManager { return YamlConfiguration.loadConfiguration(file); } + /** + * 载入模块 + */ public static boolean nameplate; public static boolean background; public static boolean bossbar; public static boolean actionbar; public static boolean useAdventure; public static void loadModule(){ - YamlConfiguration module = getConfig("module.yml"); - nameplate = module.getBoolean("nameplate"); - background = module.getBoolean("background"); - bossbar = module.getBoolean("bossbar"); - actionbar = module.getBoolean("actionbar"); - YamlConfiguration bossbarmode = getConfig("bossbar.yml"); - useAdventure = bossbarmode.getString("mode").equalsIgnoreCase("Adventure"); - } - - - public static void loadWidth(){ - - fontWidth.clear(); - YamlConfiguration config = getConfig("char-width.yml"); - config.getConfigurationSection("").getKeys(false).forEach(key -> { - fontWidth.put(key.charAt(0), config.getInt(key)); - }); - AdventureManager.consoleMessage("[CustomNameplates] Loaded " + fontWidth.size() + " custom char width"); + YamlConfiguration module = getConfig("MODULES.yml"); + nameplate = module.getBoolean("nameplate", true); + background = module.getBoolean("background", true); + bossbar = module.getBoolean("bossbar", true); + actionbar = module.getBoolean("actionbar", true); } + /** + * 载入主配置 + */ public static class MainConfig{ public static String namespace; public static String fontName; @@ -87,27 +88,22 @@ public class ConfigManager { public static String bg_folder_path; public static String ss_folder_path; public static String font; - public static String default_nameplate; - public static String player_prefix; - public static String player_suffix; + public static List offsets; public static Key key; public static boolean itemsAdder; public static boolean placeholderAPI; - public static boolean show_after; public static String lang; - public static Long preview; public static boolean thin_font; - public static boolean hidePrefix; - public static boolean hideSuffix; - public static boolean anotherFont; public static boolean tab; public static boolean oraxen; - public static int fontOffset; - public static int version; - public static void ReloadConfig(){ + public static boolean extract; + public static String version; + + public static void reload(){ CustomNameplates.instance.saveDefaultConfig(); CustomNameplates.instance.reloadConfig(); + FileConfiguration config = CustomNameplates.instance.getConfig(); lang = config.getString("config.lang"); namespace = config.getString("config.namespace"); @@ -118,56 +114,86 @@ public class ConfigManager { folder_path = config.getString("config.nameplate-folder-path","font\\nameplates\\"); bg_folder_path = config.getString("config.background-folder-path","font\\backgrounds\\"); ss_folder_path = config.getString("config.space-split-folder-path","font\\"); - default_nameplate = config.getString("config.default-nameplate"); - player_prefix = config.getString("config.prefix"); - player_suffix = config.getString("config.suffix"); - anotherFont = config.getBoolean("config.another-ascii-font.enable",true); - if(config.getBoolean("config.extract-shader",true)){ - CustomNameplates.instance.saveResource("shaders.zip", true); - } - itemsAdder = config.getBoolean("config.integrations.ItemsAdder",false); - fontOffset = config.getInt("config.another-ascii-font.y-offset",3); - version = config.getInt("config-version",1); - if (itemsAdder){ - if(CustomNameplates.instance.getServer().getPluginManager().getPlugin("ItemsAdder") == null){ - CustomNameplates.instance.getLogger().warning("Failed to initialize ItemsAdder!"); - itemsAdder = false; - } - } - placeholderAPI = config.getBoolean("config.integrations.PlaceholderAPI",false); - if (placeholderAPI){ - if(CustomNameplates.instance.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null){ - loadPapi(); - - }else { - CustomNameplates.instance.getLogger().warning("Failed to initialize PlaceholderAPI!"); - placeholderAPI = false; - } - } - tab = config.getBoolean("config.integrations.TAB",false); - if (tab){ - if(CustomNameplates.instance.getServer().getPluginManager().getPlugin("TAB") == null){ - tab = false; - } - } - oraxen = config.getBoolean("config.integrations.Oraxen",false); - if (oraxen){ - if(CustomNameplates.instance.getServer().getPluginManager().getPlugin("Oraxen") == null){ - oraxen = false; - } - } - - show_after = config.getBoolean("config.show-after-load-resourcepack"); key = Key.key(fontName); - preview = config.getLong("config.preview-duration"); thin_font = config.getBoolean("config.use-thin-font",false); - hidePrefix = config.getBoolean("config.hide-prefix-when-equipped",false); - hideSuffix = config.getBoolean("config.hide-suffix-when-equipped",false); + itemsAdder = config.getBoolean("config.integrations.ItemsAdder",false); + version = config.getString("config-version"); + placeholderAPI = config.getBoolean("config.integrations.PlaceholderAPI",false); + tab = config.getBoolean("config.integrations.TAB",false); + oraxen = config.getBoolean("config.integrations.Oraxen",false); + offsets = config.getIntegerList("config.ascii-y-offset.offset"); + + if(config.getBoolean("config.extract-shader",true)) { + extract = true; + } + if (itemsAdder && CustomNameplates.instance.getServer().getPluginManager().getPlugin("ItemsAdder") == null){ + CustomNameplates.instance.getLogger().warning("Failed to initialize ItemsAdder!"); + itemsAdder = false; + } + if (placeholderAPI && CustomNameplates.instance.getServer().getPluginManager().getPlugin("PlaceholderAPI") == null){ + CustomNameplates.instance.getLogger().warning("Failed to initialize PlaceholderAPI!"); + placeholderAPI = false; + } + if (tab && CustomNameplates.instance.getServer().getPluginManager().getPlugin("TAB") == null){ + CustomNameplates.instance.getLogger().warning("Failed to initialize TAB!"); + tab = false; + } + if (oraxen && CustomNameplates.instance.getServer().getPluginManager().getPlugin("Oraxen") == null){ + CustomNameplates.instance.getLogger().warning("Failed to initialize Oraxen!"); + oraxen = false; + } } } + public static class Nameplate{ + + public static String default_nameplate; + public static String player_prefix; + public static String player_suffix; + public static boolean mode_team; + public static long preview; + public static boolean update; + public static int refresh; + public static boolean hidePrefix; + public static boolean hideSuffix; + public static boolean show_after; + public static boolean tryHook; + public static boolean removeTag; + public static boolean smallSize; + public static List texts; + public static void reload() { + + YamlConfiguration config = getConfig("nameplate.yml"); + default_nameplate = config.getString("nameplate.default-nameplate"); + preview = config.getLong("nameplate.preview-duration"); + show_after = config.getBoolean("nameplate.show-after-load-resourcepack"); + mode_team = config.getString("nameplate.mode","team").equalsIgnoreCase("team"); + update = config.getBoolean("nameplate.update.enable",false); + refresh = config.getInt("nameplate.update.ticks",20); + + if (mode_team) { + player_prefix = config.getString("nameplate.team.prefix",""); + player_suffix = config.getString("nameplate.team.suffix",""); + hidePrefix = config.getBoolean("nameplate.team.hide-prefix-when-equipped",false); + hideSuffix = config.getBoolean("nameplate.team.hide-suffix-when-equipped",false); + } + else { + player_prefix = ""; + player_suffix = ""; + removeTag = config.getBoolean("nameplate.entity.remove-nametag"); + tryHook = config.getBoolean("nameplate.entity.try-to-hook-cosmetics-plugin"); + texts = config.getStringList("nameplate.entity.text"); + smallSize = config.getBoolean("nameplate.entity.small-size", true); + } + } + } + + /** + * 载入消息文件 + */ public static class Message{ + public static String noPerm; public static String prefix; public static String lackArgs; @@ -184,7 +210,10 @@ public class ConfigManager { public static String cooldown; public static String preview; public static String generate; - public static void ReloadConfig(){ + public static String noNameplate; + + public static void reload(){ + YamlConfiguration messagesConfig = getConfig("messages/messages_" + MainConfig.lang +".yml"); noPerm = messagesConfig.getString("messages.no-perm"); prefix = messagesConfig.getString("messages.prefix"); @@ -202,32 +231,39 @@ public class ConfigManager { cooldown = messagesConfig.getString("messages.cooldown"); preview = messagesConfig.getString("messages.preview"); generate = messagesConfig.getString("messages.generate"); + noNameplate = messagesConfig.getString("messages.no-nameplate","messages.no-nameplate is missing"); } } + /* + 载入背景配置 + */ public static void loadBGConfig(){ backgrounds.clear(); YamlConfiguration bgConfig = getConfig("background.yml"); - bgConfig.getConfigurationSection("background").getKeys(false).forEach(key -> { - backgrounds.put(key, new BackGround(key, bgConfig.getString("background." + key + ".start"),bgConfig.getString("background." + key + ".offset_1"), - bgConfig.getString("background." + key + ".offset_2"),bgConfig.getString("background." + key + ".offset_4"),bgConfig.getString("background." + key + ".offset_8"), - bgConfig.getString("background." + key + ".offset_16"),bgConfig.getString("background." + key + ".offset_32"),bgConfig.getString("background." + key + ".offset_64"), - bgConfig.getString("background." + key + ".offset_128"),bgConfig.getString("background." + key + ".end"),bgConfig.getInt("background." + key + ".y-offset"),bgConfig.getInt("background." + key + ".x-offset") - )); - }); + bgConfig.getConfigurationSection("background").getKeys(false).forEach(key -> backgrounds.put(key, new BackGround(key, bgConfig.getString("background." + key + ".start"),bgConfig.getString("background." + key + ".offset_1"), + bgConfig.getString("background." + key + ".offset_2"),bgConfig.getString("background." + key + ".offset_4"),bgConfig.getString("background." + key + ".offset_8"), + bgConfig.getString("background." + key + ".offset_16"),bgConfig.getString("background." + key + ".offset_32"),bgConfig.getString("background." + key + ".offset_64"), + bgConfig.getString("background." + key + ".offset_128"),bgConfig.getString("background." + key + ".end"),bgConfig.getInt("background." + key + ".y-offset",0),bgConfig.getInt("background." + key + ".x-offset"),bgConfig.getInt("background." + key + ".size",14) + ))); } - public static void loadBossBar(){ + /** + * 载入bossbar配置 + */ + public static void loadBossBar() { YamlConfiguration config = getConfig("bossbar.yml"); + useAdventure = config.getString("mode").equalsIgnoreCase("Adventure"); if (useAdventure){ config.getConfigurationSection("bossbar").getKeys(false).forEach(key -> { BossBarConfigA bossbarConfig = ConfigManager.bossbarsA.get(key); - if (bossbarConfig != null){ + if (bossbarConfig != null) { bossbarConfig.setColor(BossBar.Color.valueOf(config.getString("bossbar." + key + ".color").toUpperCase())); bossbarConfig.setOverlay(BossBar.Overlay.valueOf(config.getString("bossbar." + key + ".overlay").toUpperCase())); bossbarConfig.setRate(config.getInt("bossbar." + key + ".refresh-rate") - 1); bossbarConfig.setText(config.getString("bossbar." + key + ".text")); - }else { + } + else { bossbarsA.put(key, new BossBarConfigA( config.getString("bossbar." + key + ".text"), BossBar.Overlay.valueOf(config.getString("bossbar." + key + ".overlay").toUpperCase()), @@ -239,12 +275,13 @@ public class ConfigManager { }else { config.getConfigurationSection("bossbar").getKeys(false).forEach(key -> { BossBarConfigP bossbarConfig = ConfigManager.bossbarsP.get(key); - if (bossbarConfig != null){ + if (bossbarConfig != null) { bossbarConfig.setColor(BarColor.valueOf(config.getString("bossbar."+key+".color").toUpperCase())); bossbarConfig.setRate(config.getInt("bossbar." + key + ".refresh-rate") - 1); bossbarConfig.setText(config.getString("bossbar." + key + ".text")); bossbarConfig.setOverlay(Overlay.valueOf(config.getString("bossbar."+key+".overlay").toUpperCase())); - }else { + } + else { bossbarsP.put(key, new BossBarConfigP( config.getString("bossbar." + key + ".text"), Overlay.valueOf(config.getString("bossbar."+key+".overlay").toUpperCase()), @@ -256,31 +293,55 @@ public class ConfigManager { } } - public static void loadPapi(){ + /** + * 加载自定义的papi变量 + */ + public static void loadPapi() { papiBG.clear(); papiNP.clear(); YamlConfiguration papiInfo = getConfig("custom-papi.yml"); papiInfo.getConfigurationSection("papi").getKeys(false).forEach(key -> { - if (papiInfo.contains("papi." + key + ".background")){ + if (papiInfo.contains("papi." + key + ".background")) papiBG.put(key, new BGInfo(papiInfo.getString("papi."+key+".text"), papiInfo.getString("papi." + key + ".background"))); - } - if (papiInfo.contains("papi." + key + ".nameplate")){ + if (papiInfo.contains("papi." + key + ".nameplate")) papiNP.put(key, new NPInfo(papiInfo.getString("papi."+key+".text"), papiInfo.getString("papi." + key + ".nameplate"))); - } }); } - public static class ActionbarConfig{ + /** + * 加载actionbar模块相关功能 + */ + public static class ActionbarConfig { public static int rate; public static String text; - public static void LoadConfig(){ - YamlConfiguration actionbarConfig = getConfig("actionbar.yml"); - rate = actionbarConfig.getInt("refresh-rate") - 1; - text = actionbarConfig.getString("text"); + public static void load() { + YamlConfiguration config = getConfig("actionbar.yml"); + rate = config.getInt("refresh-rate") - 1; + text = config.getString("text"); } } + /** + * 载入自定义宽度配置 + */ + public static void loadWidth() { + fontWidth.clear(); + YamlConfiguration config = getConfig("char-width.yml"); + config.getConfigurationSection("").getKeys(false).forEach(key -> fontWidth.put(key.charAt(0), config.getInt(key))); + AdventureUtil.consoleMessage("[CustomNameplates] Loaded " + fontWidth.size() + " custom char-width"); + if (MainConfig.thin_font) + for (int i = 0; i < FontWidthThin.values().length; i++) + fontWidth.put(FontWidthThin.values()[i].getCharacter(), FontWidthThin.values()[i].getLength()); + else + for (int i = 0; i < FontWidthNormal.values().length; i++) + fontWidth.put(FontWidthNormal.values()[i].getCharacter(), FontWidthNormal.values()[i].getLength()); + } + + /** + * 数据库设置 + */ public static class DatabaseConfig{ + public static String user; public static String password; public static String url; @@ -293,7 +354,9 @@ public class ConfigManager { public static int minimum_idle; public static int maximum_lifetime; public static int idle_timeout; + public static void LoadConfig(){ + YamlConfiguration databaseConfig = getConfig("database.yml"); String storage_mode = databaseConfig.getString("settings.storage-mode"); async = !databaseConfig.getBoolean("settings.disable-async", true); @@ -327,8 +390,9 @@ public class ConfigManager { maximum_lifetime = databaseConfig.getInt("Pool-Settings.maximum-lifetime"); idle_timeout = databaseConfig.getInt("Pool-Settings.idle-timeout"); } - }else { - AdventureManager.consoleMessage("[CustomNameplates] Error! No such storage mode!"); + } + else { + AdventureUtil.consoleMessage("[CustomNameplates] Error! No such storage mode!"); Bukkit.getPluginManager().disablePlugin(CustomNameplates.instance); } } diff --git a/src/main/java/net/momirealms/customnameplates/CustomNameplates.java b/src/main/java/net/momirealms/customnameplates/CustomNameplates.java index 25372f1..1a05faa 100644 --- a/src/main/java/net/momirealms/customnameplates/CustomNameplates.java +++ b/src/main/java/net/momirealms/customnameplates/CustomNameplates.java @@ -29,21 +29,19 @@ import net.momirealms.customnameplates.data.DataManager; import net.momirealms.customnameplates.data.SqlHandler; import net.momirealms.customnameplates.helper.LibraryLoader; import net.momirealms.customnameplates.hook.Placeholders; -import net.momirealms.customnameplates.listener.PacketsListener; -import net.momirealms.customnameplates.listener.PapiReload; -import net.momirealms.customnameplates.listener.PlayerListener; +import net.momirealms.customnameplates.listener.*; import net.momirealms.customnameplates.resource.ResourceManager; import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; -import net.momirealms.customnameplates.utils.UpdateConfig; +import net.momirealms.customnameplates.utils.AdventureUtil; +import net.momirealms.customnameplates.utils.ConfigUtil; import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; import org.bukkit.plugin.java.JavaPlugin; import java.util.Objects; public final class CustomNameplates extends JavaPlugin { - public static JavaPlugin instance; + public static CustomNameplates instance; public static BukkitAudiences adventure; public static ProtocolManager protocolManager; public static Placeholders placeholders; @@ -52,11 +50,9 @@ public final class CustomNameplates extends JavaPlugin { private DataManager dataManager; private ScoreBoardManager scoreBoardManager; private Timer timer; - private PacketsListener packetsListener; - - public ResourceManager getResourceManager() {return this.resourceManager;} - public DataManager getDataManager() { return this.dataManager; } - public ScoreBoardManager getScoreBoardManager() { return this.scoreBoardManager; } + private PlayerPacketsListener playerPackets; + private MountPacketListener mountPackets; + private EntityDestroyListener entityDestroy; @Override public void onLoad(){ @@ -68,58 +64,24 @@ public final class CustomNameplates extends JavaPlugin { @Override public void onEnable() { + adventure = BukkitAudiences.create(this); protocolManager = ProtocolLibrary.getProtocolManager(); - AdventureManager.consoleMessage("[CustomNameplates] Running on " + Bukkit.getVersion()); - ConfigManager.loadModule(); - ConfigManager.MainConfig.ReloadConfig(); - ConfigManager.Message.ReloadConfig(); - ConfigManager.loadWidth(); - if (ConfigManager.bossbar){ - ConfigManager.loadBossBar(); - if (ConfigManager.useAdventure){ - Bukkit.getPluginManager().registerEvents(new QuitAndJoinA(),this); - }else { - Bukkit.getPluginManager().registerEvents(new QuitAndJoinP(),this); - } - } - if (ConfigManager.actionbar){ - ConfigManager.ActionbarConfig.LoadConfig(); - timer = new Timer(); - } - if (ConfigManager.background){ - ConfigManager.loadBGConfig(); - } - if (ConfigManager.nameplate){ - ConfigManager.DatabaseConfig.LoadConfig(); - Bukkit.getPluginManager().registerEvents(new PlayerListener(this),this); - packetsListener = new PacketsListener(this); - protocolManager.addPacketListener(packetsListener); - } - if (ConfigManager.MainConfig.tab){ - AdventureManager.consoleMessage("[CustomNameplates] TAB Hooked!"); - } - if (ConfigManager.MainConfig.placeholderAPI){ - placeholders = new Placeholders(); - placeholders.register(); - Bukkit.getPluginManager().registerEvents(new PapiReload(), this); - AdventureManager.consoleMessage("[CustomNameplates] PlaceholderAPI Hooked!"); - } - Objects.requireNonNull(Bukkit.getPluginCommand("customnameplates")).setExecutor(new Execute(this)); + + AdventureUtil.consoleMessage("[CustomNameplates] Running on " + Bukkit.getVersion()); + + Objects.requireNonNull(Bukkit.getPluginCommand("customnameplates")).setExecutor(new Execute()); Objects.requireNonNull(Bukkit.getPluginCommand("customnameplates")).setTabCompleter(new TabComplete()); - this.resourceManager = new ResourceManager(this); - this.dataManager = new DataManager(this); - this.scoreBoardManager = new ScoreBoardManager(this); - resourceManager.generateResourcePack(); - if (!DataManager.create()) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to enable Data Manager! Disabling plugin..."); - instance.getPluginLoader().disablePlugin(instance); - return; + + loadConfig(); + this.resourceManager = new ResourceManager(); + this.resourceManager.generateResourcePack(); + + if (Objects.equals(ConfigManager.MainConfig.version, "2")){ + ConfigUtil.update(); } - if (ConfigManager.MainConfig.version != 1){ - UpdateConfig.update(); - } - AdventureManager.consoleMessage("[CustomNameplates] Plugin Enabled!"); + + AdventureUtil.consoleMessage("[CustomNameplates] Plugin Enabled!"); } @Override @@ -128,17 +90,22 @@ public final class CustomNameplates extends JavaPlugin { SqlHandler.saveAll(); SqlHandler.close(); } - Execute.pCache.forEach(Entity::remove); if (timer != null){ timer.stopTimer(timer.getTaskID()); } if (adventure != null) { adventure.close(); - adventure = null; } - if (packetsListener != null && protocolManager != null){ - protocolManager.removePacketListener(this.packetsListener); - protocolManager = null; + if (protocolManager != null){ + if (playerPackets != null) { + protocolManager.removePacketListener(this.playerPackets); + } + if (mountPackets != null) { + protocolManager.removePacketListener(this.mountPackets); + } + if (entityDestroy != null) { + protocolManager.removePacketListener(this.entityDestroy); + } } if (placeholders != null){ placeholders.unregister(); @@ -152,8 +119,64 @@ public final class CustomNameplates extends JavaPlugin { if (dataManager != null){ dataManager = null; } - if (instance != null){ - instance = null; + } + + private void loadConfig() { + ConfigManager.loadModule(); + ConfigManager.MainConfig.reload(); + ConfigManager.Message.reload(); + ConfigManager.loadWidth(); + + if (ConfigManager.bossbar){ + ConfigManager.loadBossBar(); + if (ConfigManager.useAdventure) Bukkit.getPluginManager().registerEvents(new QuitAndJoinA(),this); + else Bukkit.getPluginManager().registerEvents(new QuitAndJoinP(),this); + } + if (ConfigManager.actionbar){ + ConfigManager.ActionbarConfig.load(); + timer = new Timer(); + } + if (ConfigManager.background){ + ConfigManager.loadBGConfig(); + } + if (ConfigManager.nameplate){ + ConfigManager.Nameplate.reload(); + ConfigManager.DatabaseConfig.LoadConfig(); + Bukkit.getPluginManager().registerEvents(new PlayerListener(),this); + this.scoreBoardManager = new ScoreBoardManager(); + this.dataManager = new DataManager(); + if (!dataManager.create()) { + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to enable Data Manager! Disabling plugin..."); + return; + } + if (!ConfigManager.Nameplate.mode_team) { + playerPackets = new PlayerPacketsListener(this); + protocolManager.addPacketListener(playerPackets); + entityDestroy = new EntityDestroyListener(this); + protocolManager.addPacketListener(entityDestroy); + if (ConfigManager.Nameplate.tryHook) { + mountPackets = new MountPacketListener(this); + protocolManager.addPacketListener(mountPackets); + } + } + } + if (ConfigManager.MainConfig.placeholderAPI){ + placeholders = new Placeholders(); + placeholders.register(); + ConfigManager.loadPapi(); + Bukkit.getPluginManager().registerEvents(new PapiReload(), this); } } + + public ResourceManager getResourceManager() { + return this.resourceManager; + } + + public DataManager getDataManager() { + return this.dataManager; + } + + public ScoreBoardManager getScoreBoardManager() { + return this.scoreBoardManager; + } } diff --git a/src/main/java/net/momirealms/customnameplates/actionbar/ActionbarSender.java b/src/main/java/net/momirealms/customnameplates/actionbar/ActionbarSender.java index f54a01c..0adad4f 100644 --- a/src/main/java/net/momirealms/customnameplates/actionbar/ActionbarSender.java +++ b/src/main/java/net/momirealms/customnameplates/actionbar/ActionbarSender.java @@ -18,7 +18,7 @@ package net.momirealms.customnameplates.actionbar; import me.clip.placeholderapi.PlaceholderAPI; -import net.momirealms.customnameplates.AdventureManager; +import net.momirealms.customnameplates.utils.AdventureUtil; import net.momirealms.customnameplates.ConfigManager; import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitRunnable; @@ -38,9 +38,9 @@ public class ActionbarSender extends BukkitRunnable { }else { Bukkit.getOnlinePlayers().forEach(player -> { if (ConfigManager.MainConfig.placeholderAPI){ - AdventureManager.playerActionbar(player, PlaceholderAPI.setPlaceholders(player, ConfigManager.ActionbarConfig.text)); + AdventureUtil.playerActionbar(player, PlaceholderAPI.setPlaceholders(player, ConfigManager.ActionbarConfig.text)); }else { - AdventureManager.playerActionbar(player, ConfigManager.ActionbarConfig.text); + AdventureUtil.playerActionbar(player, ConfigManager.ActionbarConfig.text); } }); timer = 0; diff --git a/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/BossBarSenderP.java b/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/BossBarSenderP.java index 561ee64..e1bff88 100644 --- a/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/BossBarSenderP.java +++ b/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/BossBarSenderP.java @@ -4,11 +4,10 @@ import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.InternalStructure; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedWatchableObject; import me.clip.placeholderapi.PlaceholderAPI; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customnameplates.AdventureManager; +import net.momirealms.customnameplates.utils.AdventureUtil; import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; import org.bukkit.boss.BarColor; @@ -50,10 +49,13 @@ public class BossBarSenderP extends BukkitRunnable { internalStructure.getFloat().write(0,1F); internalStructure.getEnumModifier(BarColor.class, 2).write(0, barColor); internalStructure.getEnumModifier(Overlay.class, 3).write(0, overlay); + internalStructure.getModifier().write(5, false); + internalStructure.getModifier().write(6, false); + internalStructure.getModifier().write(4, false); try{ CustomNameplates.protocolManager.sendServerPacket(player, packet); }catch (InvocationTargetException e){ - AdventureManager.consoleMessage("[CustomNameplates] Failed to display bossbar for "+player.getName()); + AdventureUtil.consoleMessage("[CustomNameplates] Failed to display bossbar for "+player.getName()); } } @@ -82,10 +84,13 @@ public class BossBarSenderP extends BukkitRunnable { internalStructure.getChatComponents().write(0, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(text)))); internalStructure.getEnumModifier(BarColor.class, 2).write(0, barColor); internalStructure.getEnumModifier(Overlay.class, 3).write(0, overlay); + internalStructure.getModifier().write(5, false); + internalStructure.getModifier().write(6, false); + internalStructure.getModifier().write(4, false); try{ CustomNameplates.protocolManager.sendServerPacket(player, packet); }catch (InvocationTargetException e){ - AdventureManager.consoleMessage("[CustomNameplates] Failed to display bossbar for " + player.getName()); + AdventureUtil.consoleMessage("[CustomNameplates] Failed to display bossbar for " + player.getName()); } } } diff --git a/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/TimerTaskP.java b/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/TimerTaskP.java index 9e3d2b9..5f88c6a 100644 --- a/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/TimerTaskP.java +++ b/src/main/java/net/momirealms/customnameplates/bossbar/protocollib/TimerTaskP.java @@ -18,7 +18,6 @@ public class TimerTaskP { bossbar.showBossbar(); BukkitTask task = bossbar.runTaskTimerAsynchronously(CustomNameplates.instance, 1,1); bossbarCache.put(task.getTaskId(), bossbar); - }); } diff --git a/src/main/java/net/momirealms/customnameplates/commands/Execute.java b/src/main/java/net/momirealms/customnameplates/commands/Execute.java index 56a0b78..5bb5c5b 100644 --- a/src/main/java/net/momirealms/customnameplates/commands/Execute.java +++ b/src/main/java/net/momirealms/customnameplates/commands/Execute.java @@ -17,391 +17,305 @@ package net.momirealms.customnameplates.commands; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; import net.kyori.adventure.key.Key; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.kyori.adventure.text.minimessage.MiniMessage; import net.momirealms.customnameplates.ConfigManager; -import net.momirealms.customnameplates.AdventureManager; +import net.momirealms.customnameplates.utils.AdventureUtil; import net.momirealms.customnameplates.CustomNameplates; import net.momirealms.customnameplates.data.DataManager; -import net.momirealms.customnameplates.font.FontCache; +import net.momirealms.customnameplates.nameplates.NameplateInstance; import net.momirealms.customnameplates.hook.PapiHook; import net.momirealms.customnameplates.hook.TABHook; import net.momirealms.customnameplates.nameplates.NameplateUtil; import net.momirealms.customnameplates.scoreboard.NameplatesTeam; import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; +import net.momirealms.customnameplates.utils.HoloUtil; +import net.momirealms.customnameplates.utils.TeamPacketUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.scheduler.BukkitScheduler; import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; -import java.util.Optional; public class Execute implements CommandExecutor { - private final CustomNameplates plugin; private final HashMap coolDown = new HashMap<>(); - public static List pCache = new ArrayList<>(); - - public Execute(CustomNameplates plugin) { - this.plugin = plugin; - } @Override @ParametersAreNonnullByDefault public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - //参数不足 if (args.length < 1){ - if (sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); return true; } switch (args[0]) { case "reload" -> { - if (sender.hasPermission("customnameplates.reload") || sender.isOp()) { - ConfigManager.MainConfig.ReloadConfig(); - ConfigManager.Message.ReloadConfig(); - if (ConfigManager.actionbar){ - ConfigManager.ActionbarConfig.LoadConfig(); - } - if (ConfigManager.bossbar){ - ConfigManager.loadBossBar(); - } - if (sender instanceof Player) { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.reload); - } else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.reload); - } - } else { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.noPerm); + if (sender.hasPermission("nameplates.reload") || sender.isOp()) { + + ConfigManager.MainConfig.reload(); + ConfigManager.Message.reload(); + ConfigManager.loadWidth(); + + if (ConfigManager.actionbar) ConfigManager.ActionbarConfig.load(); + if (ConfigManager.bossbar) ConfigManager.loadBossBar(); + if (ConfigManager.background) ConfigManager.loadBGConfig(); + if (ConfigManager.MainConfig.placeholderAPI) ConfigManager.loadPapi(); + if (ConfigManager.nameplate) ConfigManager.Nameplate.reload(); + + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.reload); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.reload); } + else AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.noPerm); return true; } case "generate" -> { - if (sender.hasPermission("customnameplates.generate") || sender.isOp()) { - ConfigManager.MainConfig.ReloadConfig(); - plugin.getResourceManager().generateResourcePack(); - if (sender instanceof Player) { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.generate); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.generate); - } - } else { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.noPerm); + if (sender.hasPermission("nameplates.generate") || sender.isOp()) { + ConfigManager.MainConfig.reload(); + CustomNameplates.instance.getResourceManager().generateResourcePack(); + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.generate); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.generate); } + else AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.noPerm); return true; } case "equip" -> { if (sender instanceof Player player) { if (args.length < 2) { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); + AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); return true; } - if (sender.hasPermission("customnameplates.equip." + args[1]) || sender.isOp()) { - if (plugin.getResourceManager().getNameplateInfo(args[1]) == null) { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.not_exist); + if (sender.hasPermission("nameplates.equip." + args[1]) || sender.isOp()) { + if (CustomNameplates.instance.getResourceManager().getNameplateInstance(args[1]) == null) { + AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.not_exist); return true; } DataManager.cache.get(player.getUniqueId()).equipNameplate(args[1]); - if (ConfigManager.MainConfig.tab){ - ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates(); - }else { - ScoreBoardManager.teams.get(player.getName()).updateNameplates(); + CustomNameplates.instance.getDataManager().savePlayer(player.getUniqueId()); + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + ScoreBoardManager.teams.get(teamName).updateNameplates(); + if (ConfigManager.Nameplate.mode_team) { + TeamPacketUtil.sendUpdateToAll(player); } - this.plugin.getDataManager().savePlayer(player.getUniqueId()); - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.equip.replace("{Nameplate}", plugin.getResourceManager().getNameplateInfo(args[1]).getConfig().getName())); - } else { - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.notAvailable); + AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.equip.replace("{Nameplate}", CustomNameplates.instance.getResourceManager().getNameplateInstance(args[1]).getConfig().getName())); } - } else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); + else AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.notAvailable); } + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); return true; } case "forceequip" -> { if (args.length < 3){ - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); return true; } - if (sender.hasPermission("customnameplates.forceequip") || sender.isOp()){ + if (sender.hasPermission("nameplates.forceequip") || sender.isOp()){ if (Bukkit.getPlayer(args[1]) != null){ Player player = Bukkit.getPlayer(args[1]); //铭牌是否存在 - if (plugin.getResourceManager().getNameplateInfo(args[2]) == null){ - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_exist); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_exist); - } + if (CustomNameplates.instance.getResourceManager().getNameplateInstance(args[2]) == null){ + if(sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_exist); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_exist); return true; } DataManager.cache.get(player.getUniqueId()).equipNameplate(args[2]); - if (ConfigManager.MainConfig.tab){ - ScoreBoardManager.teams.get(TABHook.getTABTeam(args[1])).updateNameplates(); - }else { - ScoreBoardManager.teams.get(args[1]).updateNameplates(); - } - this.plugin.getDataManager().savePlayer(player.getUniqueId()); - if (sender instanceof Player){ - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.force_equip.replace("{Nameplate}", plugin.getResourceManager().getNameplateInfo(args[2]).getConfig().getName()).replace("{Player}", args[1])); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.force_equip.replace("{Nameplate}", plugin.getResourceManager().getNameplateInfo(args[2]).getConfig().getName()).replace("{Player}", args[1])); + CustomNameplates.instance.getDataManager().savePlayer(player.getUniqueId()); + if (ConfigManager.MainConfig.tab) ScoreBoardManager.teams.get(TABHook.getTABTeam(args[1])).updateNameplates(); + else ScoreBoardManager.teams.get(args[1]).updateNameplates(); + if (ConfigManager.Nameplate.mode_team) { + TeamPacketUtil.sendUpdateToAll(player); } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.force_equip.replace("{Nameplate}", CustomNameplates.instance.getResourceManager().getNameplateInstance(args[2]).getConfig().getName()).replace("{Player}", args[1])); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.force_equip.replace("{Nameplate}", CustomNameplates.instance.getResourceManager().getNameplateInstance(args[2]).getConfig().getName()).replace("{Player}", args[1])); }else { - //玩家不存在,不在线 - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); } - }else { - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.noPerm); } + else AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.noPerm); return true; } case "unequip" -> { if (sender instanceof Player player){ DataManager.cache.get(player.getUniqueId()).equipNameplate("none"); - if (ConfigManager.MainConfig.tab){ - ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates(); - }else { - ScoreBoardManager.teams.get(player.getName()).updateNameplates(); + CustomNameplates.instance.getDataManager().savePlayer(player.getUniqueId()); + if (ConfigManager.MainConfig.tab) ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates(); + else ScoreBoardManager.teams.get(player.getName()).updateNameplates(); + if (ConfigManager.Nameplate.mode_team) { + TeamPacketUtil.sendUpdateToAll(player); } - this.plugin.getDataManager().savePlayer(player.getUniqueId()); - AdventureManager.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.unequip); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); + AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.unequip); } + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); return true; } case "forceunequip" -> { if (args.length < 2){ - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); return true; } - if (sender.hasPermission("customnameplates.forceunequip")){ + if (sender.hasPermission("nameplates.forceunequip")){ if (Bukkit.getPlayer(args[1]) != null){ Player player = Bukkit.getPlayer(args[1]); DataManager.cache.get(player.getUniqueId()).equipNameplate("none"); - if (ConfigManager.MainConfig.tab){ - ScoreBoardManager.teams.get(TABHook.getTABTeam(args[1])).updateNameplates(); - }else { - ScoreBoardManager.teams.get(args[1]).updateNameplates(); - } - this.plugin.getDataManager().savePlayer(player.getUniqueId()); - if (sender instanceof Player){ - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.force_unequip.replace("{Player}", args[1])); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.force_unequip.replace("{Player}", args[1])); + CustomNameplates.instance.getDataManager().savePlayer(player.getUniqueId()); + if (ConfigManager.MainConfig.tab) ScoreBoardManager.teams.get(TABHook.getTABTeam(args[1])).updateNameplates(); + else ScoreBoardManager.teams.get(args[1]).updateNameplates(); + if (ConfigManager.Nameplate.mode_team) { + TeamPacketUtil.sendUpdateToAll(player); } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.force_unequip.replace("{Player}", args[1])); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.force_unequip.replace("{Player}", args[1])); }else { - //玩家不存在,不在线 - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online.replace("{Player}",args[1])); } } + return true; } case "preview" -> { if (sender instanceof Player player){ - if (player.hasPermission("customnameplates.preview") || player.isOp()){ + if (player.hasPermission("nameplates.preview") || player.isOp()){ //指令冷却 long time = System.currentTimeMillis(); //冷却时间判断 - if (time - (coolDown.getOrDefault(player, time - ConfigManager.MainConfig.preview * 1050)) < ConfigManager.MainConfig.preview * 1050) { - AdventureManager.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.cooldown); + if (time - (coolDown.getOrDefault(player, time - ConfigManager.Nameplate.preview * 1050)) < ConfigManager.Nameplate.preview * 1050) { + AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.cooldown); return true; } //重置冷却时间 coolDown.put(player, time); - AdventureManager.playerMessage(player,ConfigManager.Message.prefix + ConfigManager.Message.preview); - NameplatesTeam team = this.plugin.getScoreBoardManager().getOrCreateTeam(player); - Component full = team.getPrefix().append(Component.text(player.getName()).color(TextColor.color(color2decimal(team.getColor()))).font(Key.key("default")).append(team.getSuffix())); - showNameplate(player, full); + AdventureUtil.playerMessage(player,ConfigManager.Message.prefix + ConfigManager.Message.preview); + if (ConfigManager.Nameplate.mode_team) { + NameplatesTeam team = CustomNameplates.instance.getScoreBoardManager().getOrCreateTeam(player); + Component full = team.getPrefix().append(Component.text(player.getName()).color(TextColor.color(color2decimal(team.getColor()))).font(Key.key("default")).append(team.getSuffix())); + HoloUtil.showHolo(full, player, (int) ConfigManager.Nameplate.preview); + } + else { + ArmorStandPacketUtil.sendPreviewToOne(player); + } }else { - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.noPerm); + AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.noPerm); } - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); } + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); + return true; } case "forcepreview" -> { - if (sender.hasPermission("customnameplates.forcepreview") || sender.isOp()) { + if (sender.hasPermission("nameplates.forcepreview") || sender.isOp()) { if (args.length < 3){ - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.lackArgs); return true; } Player player = Bukkit.getPlayer(args[1]); if (player == null){ - if (sender instanceof Player){ - AdventureManager.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.not_online); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online); - } + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender, ConfigManager.Message.prefix + ConfigManager.Message.not_online); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_online); return true; } - FontCache fontCache = plugin.getResourceManager().getNameplateInfo(args[2]); - if (fontCache == null){ - if(sender instanceof Player){ - AdventureManager.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_exist); - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_exist); - } + NameplateInstance nameplateInstance = CustomNameplates.instance.getResourceManager().getNameplateInstance(args[2]); + if (nameplateInstance == null){ + if (sender instanceof Player) AdventureUtil.playerMessage((Player) sender,ConfigManager.Message.prefix + ConfigManager.Message.not_exist); + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.not_exist); return true; } long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - ConfigManager.MainConfig.preview * 1050)) < ConfigManager.MainConfig.preview * 1050) { - AdventureManager.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.cooldown); + if (time - (coolDown.getOrDefault(player, time - ConfigManager.Nameplate.preview * 1050)) < ConfigManager.Nameplate.preview * 1050) { + AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.cooldown); return true; } coolDown.put(player, time); - NameplateUtil nameplateUtil = new NameplateUtil(fontCache); - String playerPrefix; - String playerSuffix; - if (ConfigManager.MainConfig.placeholderAPI) { - playerPrefix = PapiHook.parsePlaceholders(player, ConfigManager.MainConfig.player_prefix); - playerSuffix = PapiHook.parsePlaceholders(player, ConfigManager.MainConfig.player_suffix); - }else { - playerPrefix = ConfigManager.MainConfig.player_prefix; - playerSuffix = ConfigManager.MainConfig.player_suffix; + if (ConfigManager.Nameplate.mode_team) { + String playerPrefix; + String playerSuffix; + if (ConfigManager.MainConfig.placeholderAPI) { + playerPrefix = PapiHook.parsePlaceholders(player, ConfigManager.Nameplate.player_prefix); + playerSuffix = PapiHook.parsePlaceholders(player, ConfigManager.Nameplate.player_suffix); + }else { + playerPrefix = ConfigManager.Nameplate.player_prefix; + playerSuffix = ConfigManager.Nameplate.player_suffix; + } + Component prefix = Component.text(NameplateUtil.makeCustomNameplate(MiniMessage.miniMessage().stripTags(playerPrefix), args[1], MiniMessage.miniMessage().stripTags(playerSuffix), nameplateInstance)).font(ConfigManager.MainConfig.key).append(MiniMessage.miniMessage().deserialize(playerPrefix)); + Component suffix = MiniMessage.miniMessage().deserialize(playerSuffix).append(Component.text(NameplateUtil.getSuffixChar(MiniMessage.miniMessage().stripTags(playerPrefix) + args[1] + MiniMessage.miniMessage().stripTags(playerSuffix))).font(ConfigManager.MainConfig.key)); + Component full = prefix.append(Component.text(player.getName()).color(TextColor.color(color2decimal(nameplateInstance.getConfig().getColor()))).font(Key.key("default")).append(suffix)); + HoloUtil.showHolo(full, player, (int) ConfigManager.Nameplate.preview); + } + else { + ArmorStandPacketUtil.sendPreviewToOne(player); } - Component prefix = Component.text(nameplateUtil.makeCustomNameplate(playerPrefix, args[1], playerSuffix)).font(ConfigManager.MainConfig.key).append(Component.text(playerPrefix).font(Key.key("default"))); - Component suffix = Component.text(playerSuffix).append(Component.text(nameplateUtil.getSuffixLength(playerPrefix + args[1] + playerSuffix)).font(ConfigManager.MainConfig.key)); - Component full = prefix.append(Component.text(player.getName()).color(TextColor.color(color2decimal(nameplateUtil.getColor()))).font(Key.key("default")).append(suffix)); - showNameplate(player, full); } + return true; } case "list" -> { - if (sender instanceof Player player){ - if (player.isOp()){ + if (sender instanceof Player player) { + if (player.isOp()) { StringBuilder stringBuilder = new StringBuilder(); - this.plugin.getResourceManager().caches.keySet().forEach(key ->{ - if(key.equalsIgnoreCase("none")) return; + CustomNameplates.instance.getResourceManager().NAMEPLATES.keySet().forEach(key -> { + if (key.equalsIgnoreCase("none")) return; stringBuilder.append(key).append(" "); }); - AdventureManager.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.available.replace("{Nameplates}", stringBuilder.toString())); - }else if(player.hasPermission("customnameplates.list")){ + AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.available.replace("{Nameplates}", stringBuilder.toString())); + } else if (player.hasPermission("nameplates.list")) { StringBuilder stringBuilder = new StringBuilder(); for (PermissionAttachmentInfo info : player.getEffectivePermissions()) { String permission = info.getPermission().toLowerCase(); - if (permission.startsWith("customnameplates.equip.")) { - permission = StringUtils.replace(permission, "customnameplates.equip.", ""); - if (this.plugin.getResourceManager().caches.get(permission) != null){ + if (permission.startsWith("nameplates.equip.")) { + permission = StringUtils.replace(permission, "nameplates.equip.", ""); + if (CustomNameplates.instance.getResourceManager().NAMEPLATES.get(permission) != null) { stringBuilder.append(permission).append(" "); } } } - AdventureManager.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.available.replace("{Nameplates}", stringBuilder.toString())); - }else { - AdventureManager.playerMessage(player,ConfigManager.Message.prefix + ConfigManager.Message.noPerm); + AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.available.replace("{Nameplates}", stringBuilder.toString())); } - }else { - AdventureManager.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); + else AdventureUtil.playerMessage(player, ConfigManager.Message.prefix + ConfigManager.Message.noPerm); } + else AdventureUtil.consoleMessage(ConfigManager.Message.prefix + ConfigManager.Message.no_console); + return true; } default -> { - if(sender instanceof Player player){ - if (player.hasPermission("customnameplates.help")){ - AdventureManager.playerMessage(player,"/nameplates help - show the command list"); - AdventureManager.playerMessage(player,"/nameplates reload - reload the configuration"); - AdventureManager.playerMessage(player,"/nameplates equip - equip a specified nameplate"); - AdventureManager.playerMessage(player,"/nameplates forceequip - force a player to equip a specified nameplate"); - AdventureManager.playerMessage(player,"/nameplates unequip - unequip your nameplate"); - AdventureManager.playerMessage(player,"/nameplates forceunequip - force unequip a player's nameplate"); - AdventureManager.playerMessage(player,"/nameplates preview - preview your nameplate"); - AdventureManager.playerMessage(player,"/nameplates forcepreview - force a player to preview a nameplate"); - AdventureManager.playerMessage(player,"/nameplates list - list your available nameplates"); - AdventureManager.playerMessage(player,"/nameplates generate - generate the resource pack"); + if (sender instanceof Player player){ + if (player.hasPermission("nameplates.help")){ + AdventureUtil.playerMessage(player,"/nameplates help - show the command list"); + AdventureUtil.playerMessage(player,"/nameplates reload - reload the configuration"); + AdventureUtil.playerMessage(player,"/nameplates equip - equip a specified nameplate"); + AdventureUtil.playerMessage(player,"/nameplates forceequip - force a player to equip a specified nameplate"); + AdventureUtil.playerMessage(player,"/nameplates unequip - unequip your nameplate"); + AdventureUtil.playerMessage(player,"/nameplates forceunequip - force unequip a player's nameplate"); + AdventureUtil.playerMessage(player,"/nameplates preview - preview your nameplate"); + AdventureUtil.playerMessage(player,"/nameplates forcepreview - force a player to preview a nameplate"); + AdventureUtil.playerMessage(player,"/nameplates list - list your available nameplates"); + AdventureUtil.playerMessage(player,"/nameplates generate - generate the resource pack"); } - }else { - AdventureManager.consoleMessage("/nameplates help - show the command list"); - AdventureManager.consoleMessage("/nameplates reload - reload the configuration"); - AdventureManager.consoleMessage("/nameplates equip - equip a specified nameplate"); - AdventureManager.consoleMessage("/nameplates forceequip - force a player to equip a specified nameplate"); - AdventureManager.consoleMessage("/nameplates unequip - unequip your nameplate"); - AdventureManager.consoleMessage("/nameplates forceunequip - force unequip a player's nameplate"); - AdventureManager.consoleMessage("/nameplates preview - preview your nameplate"); - AdventureManager.consoleMessage("/nameplates forcepreview - force a player to preview a nameplate"); - AdventureManager.consoleMessage("/nameplates list - list your available nameplates"); - AdventureManager.consoleMessage("/nameplates generate - generate the resource pack"); + } + else { + AdventureUtil.consoleMessage("/nameplates help - show the command list"); + AdventureUtil.consoleMessage("/nameplates reload - reload the configuration"); + AdventureUtil.consoleMessage("/nameplates equip - equip a specified nameplate"); + AdventureUtil.consoleMessage("/nameplates forceequip - force a player to equip a specified nameplate"); + AdventureUtil.consoleMessage("/nameplates unequip - unequip your nameplate"); + AdventureUtil.consoleMessage("/nameplates forceunequip - force unequip a player's nameplate"); + AdventureUtil.consoleMessage("/nameplates preview - preview your nameplate"); + AdventureUtil.consoleMessage("/nameplates forcepreview - force a player to preview a nameplate"); + AdventureUtil.consoleMessage("/nameplates list - list your available nameplates"); + AdventureUtil.consoleMessage("/nameplates generate - generate the resource pack"); } return true; } } - return true; - } - - private void showNameplate(Player player, Component component) { - ArmorStand entity = player.getWorld().spawn(player.getLocation().add(0,0.8,0), ArmorStand.class, a -> { - a.setInvisible(true); - a.setCollidable(false); - a.setInvulnerable(true); - a.setVisible(false); - a.setCustomNameVisible(false); - a.setSmall(true); - a.setGravity(false); - }); - pCache.add(entity); - - WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher(); - wrappedDataWatcher.setEntity(entity); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Boolean.class); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), Optional.of(WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(component)).getHandle())); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer), true); - PacketContainer packetContainer = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); - packetContainer.getIntegers().write(0, entity.getEntityId()); - packetContainer.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); - - try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packetContainer); - } - catch (Exception e) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to preview for "+ player.getName()+""); - e.printStackTrace(); - } - BukkitScheduler bukkitScheduler = Bukkit.getScheduler(); - for (int i = 1; i < ConfigManager.MainConfig.preview * 20; i++){ - bukkitScheduler.runTaskLater(CustomNameplates.instance,()-> entity.teleport(player.getLocation().add(0,0.8,0)), i); - } - bukkitScheduler.runTaskLater(CustomNameplates.instance, ()->{ - entity.remove(); - pCache.remove(entity); - }, ConfigManager.MainConfig.preview * 20L); } private int color2decimal(ChatColor color){ @@ -456,4 +370,4 @@ public class Execute implements CommandExecutor { } } } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/commands/TabComplete.java b/src/main/java/net/momirealms/customnameplates/commands/TabComplete.java index ea90864..1d7b0d6 100644 --- a/src/main/java/net/momirealms/customnameplates/commands/TabComplete.java +++ b/src/main/java/net/momirealms/customnameplates/commands/TabComplete.java @@ -125,7 +125,7 @@ public class TabComplete implements TabCompleter { String permission = info.getPermission().toLowerCase(); if (permission.startsWith("customnameplates.equip.")) { permission = StringUtils.replace(permission, "customnameplates.equip.", ""); - if (ResourceManager.caches.get(permission) != null){ + if (ResourceManager.NAMEPLATES.get(permission) != null){ availableNameplates.add(permission); } } @@ -135,6 +135,6 @@ public class TabComplete implements TabCompleter { } private List nameplates(){ - return new ArrayList<>(ResourceManager.caches.keySet()); + return new ArrayList<>(ResourceManager.NAMEPLATES.keySet()); } } diff --git a/src/main/java/net/momirealms/customnameplates/data/DataManager.java b/src/main/java/net/momirealms/customnameplates/data/DataManager.java index 3d39976..4ae8a1f 100644 --- a/src/main/java/net/momirealms/customnameplates/data/DataManager.java +++ b/src/main/java/net/momirealms/customnameplates/data/DataManager.java @@ -17,14 +17,13 @@ package net.momirealms.customnameplates.data; -import net.momirealms.customnameplates.AdventureManager; +import net.momirealms.customnameplates.utils.AdventureUtil; import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; -import net.momirealms.customnameplates.hook.TABHook; -import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; +import net.momirealms.customnameplates.utils.TeamPacketUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Scoreboard; import java.util.HashMap; import java.util.Map; @@ -32,32 +31,39 @@ import java.util.UUID; public class DataManager { - public static Map cache; - private final CustomNameplates plugin; - - public DataManager(CustomNameplates plugin) { - this.plugin = plugin; - cache = new HashMap<>(); - } + public static Map cache = new HashMap<>(); public void loadData(Player player) { UUID uuid = player.getUniqueId(); - if (ConfigManager.DatabaseConfig.async){ + if (ConfigManager.DatabaseConfig.async) { Bukkit.getScheduler().runTaskAsynchronously(CustomNameplates.instance, () -> { PlayerData playerData = SqlHandler.getPlayerData(uuid); if (playerData == null) { - playerData = new PlayerData(ConfigManager.MainConfig.default_nameplate, 0); + playerData = new PlayerData(ConfigManager.Nameplate.default_nameplate, 0); } cache.put(uuid, playerData); - plugin.getScoreBoardManager().getOrCreateTeam(player); + CustomNameplates.instance.getScoreBoardManager().getOrCreateTeam(player); + TeamPacketUtil.sendUpdateToOne(player); + TeamPacketUtil.sendUpdateToAll(player); + if (!ConfigManager.Nameplate.mode_team) { + ArmorStandPacketUtil.preparePackets(player); + } }); - }else { + } + else { PlayerData playerData = SqlHandler.getPlayerData(uuid); if (playerData == null) { - playerData = new PlayerData(ConfigManager.MainConfig.default_nameplate, 0); + playerData = new PlayerData(ConfigManager.Nameplate.default_nameplate, 0); } cache.put(uuid, playerData); - plugin.getScoreBoardManager().getOrCreateTeam(player); + CustomNameplates.instance.getScoreBoardManager().getOrCreateTeam(player); + Bukkit.getScheduler().runTaskAsynchronously(CustomNameplates.instance, () -> { + TeamPacketUtil.sendUpdateToOne(player); + TeamPacketUtil.sendUpdateToAll(player); + if (!ConfigManager.Nameplate.mode_team) { + ArmorStandPacketUtil.preparePackets(player); + } + }); } } @@ -67,7 +73,7 @@ public class DataManager { } PlayerData playerData = SqlHandler.getPlayerData(uuid); if (playerData == null) { - playerData = new PlayerData(ConfigManager.MainConfig.default_nameplate, 0); + playerData = new PlayerData(ConfigManager.Nameplate.default_nameplate, 0); } cache.put(uuid, playerData); return playerData; @@ -99,21 +105,16 @@ public class DataManager { } } - public static boolean create() { - if(ConfigManager.DatabaseConfig.use_mysql){ - AdventureManager.consoleMessage("[CustomNameplates] Storage Mode - MYSQL"); - }else { - AdventureManager.consoleMessage("[CustomNameplates] Storage Mode - SQLite"); - } + public boolean create() { + if (ConfigManager.DatabaseConfig.use_mysql) AdventureUtil.consoleMessage("[CustomNameplates] Storage Mode - MYSQL"); + else AdventureUtil.consoleMessage("[CustomNameplates] Storage Mode - SQLite"); if (SqlHandler.connect()) { if (ConfigManager.DatabaseConfig.use_mysql) { SqlHandler.getWaitTimeOut(); } SqlHandler.createTable(); - } else { - AdventureManager.consoleMessage("//DATA storage ERROR//"); - return false; + return true; } - return true; + else return false; } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/data/SqlHandler.java b/src/main/java/net/momirealms/customnameplates/data/SqlHandler.java index b134473..8281f80 100644 --- a/src/main/java/net/momirealms/customnameplates/data/SqlHandler.java +++ b/src/main/java/net/momirealms/customnameplates/data/SqlHandler.java @@ -17,17 +17,17 @@ package net.momirealms.customnameplates.data; -import net.momirealms.customnameplates.AdventureManager; +import net.momirealms.customnameplates.utils.AdventureUtil; import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.utils.SqlConnection; import org.bukkit.Bukkit; +import org.jetbrains.annotations.Nullable; import java.sql.*; import java.util.UUID; public class SqlHandler { - public static String tableName = ConfigManager.DatabaseConfig.tableName; public final static SqlConnection database = new SqlConnection(); public static boolean connect() { @@ -55,7 +55,7 @@ public class SqlHandler { statement.close(); database.closeHikariConnection(connection); } catch (SQLException ignored) { - AdventureManager.consoleMessage("[CustomNameplates] Failed to get wait time out"); + AdventureUtil.consoleMessage("[CustomNameplates] Failed to get wait time out"); } } } @@ -69,11 +69,11 @@ public class SqlHandler { } String query; if (ConfigManager.DatabaseConfig.use_mysql) { - query = "CREATE TABLE IF NOT EXISTS " + tableName + query = "CREATE TABLE IF NOT EXISTS " + ConfigManager.DatabaseConfig.tableName + "(player VARCHAR(50) NOT NULL, equipped VARCHAR(50) NOT NULL, accepted INT(1) NOT NULL," + " PRIMARY KEY (player)) DEFAULT charset = " + ConfigManager.DatabaseConfig.ENCODING + ";"; } else { - query = "CREATE TABLE IF NOT EXISTS " + tableName + query = "CREATE TABLE IF NOT EXISTS " + ConfigManager.DatabaseConfig.tableName + "(player VARCHAR(50) NOT NULL, equipped VARCHAR(50) NOT NULL, accepted INT(1) NOT NULL," + " PRIMARY KEY (player));"; } @@ -85,21 +85,22 @@ public class SqlHandler { } } + @Nullable public static PlayerData getPlayerData(UUID uuid) { PlayerData playerData = null; try { Connection connection = database.getConnectionAndCheck(); - String sql = "SELECT * FROM " + tableName + " WHERE player = ?"; + String sql = "SELECT * FROM " + ConfigManager.DatabaseConfig.tableName + " WHERE player = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, uuid.toString()); ResultSet rs = statement.executeQuery(); if (rs.next()) { playerData = new PlayerData(rs.getString(2), rs.getInt(3)); }else { - sql = "INSERT INTO " + tableName + "(player,equipped,accepted) values(?,?,?)"; + sql = "INSERT INTO " + ConfigManager.DatabaseConfig.tableName + "(player,equipped,accepted) values(?,?,?)"; statement = connection.prepareStatement(sql); statement.setString(1, uuid.toString()); - statement.setString(2, "none"); + statement.setString(2, ConfigManager.Nameplate.default_nameplate); statement.setInt(3, 0); statement.executeUpdate(); } @@ -116,7 +117,7 @@ public class SqlHandler { Connection connection = database.getConnectionAndCheck(); try { String query = " SET equipped = ?, accepted = ? WHERE player = ?"; - PreparedStatement statement = connection.prepareStatement("UPDATE " + tableName + query); + PreparedStatement statement = connection.prepareStatement("UPDATE " + ConfigManager.DatabaseConfig.tableName + query); statement.setString(1, playerData.getEquippedNameplate()); statement.setInt(2, playerData.getAccepted()); statement.setString(3, uuid.toString()); @@ -134,7 +135,7 @@ public class SqlHandler { try { PlayerData playerData = DataManager.cache.get(player.getUniqueId()); String query = " SET equipped = ?, accepted = ? WHERE player = ?"; - PreparedStatement statement = connection.prepareStatement("UPDATE " + tableName + query); + PreparedStatement statement = connection.prepareStatement("UPDATE " + ConfigManager.DatabaseConfig.tableName + query); statement.setString(1, playerData.getEquippedNameplate()); statement.setInt(2, playerData.getAccepted()); statement.setString(3, String.valueOf(player.getUniqueId())); diff --git a/src/main/java/net/momirealms/customnameplates/font/FontCache.java b/src/main/java/net/momirealms/customnameplates/font/FontCache.java deleted file mode 100644 index 7360b25..0000000 --- a/src/main/java/net/momirealms/customnameplates/font/FontCache.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 . - */ - -package net.momirealms.customnameplates.font; - -import net.momirealms.customnameplates.nameplates.NameplateConfig; - -public record FontCache(String name, FontChar fontChar, NameplateConfig config) { - - public static FontCache EMPTY; - static { - FontCache.EMPTY = new FontCache("none", new FontChar('小', '默', '米'), NameplateConfig.EMPTY); - } - - public String getName() { - return this.name; - } - - public FontChar getChar() { - return this.fontChar; - } - public NameplateConfig getConfig() { - return this.config; - } - - @Override - public boolean equals(final Object o) { - if (o == this) { - return true; - } - if (!(o instanceof FontCache fontCache)) { - return false; - } - if (!fontCache.canEqual(this)) { - return false; - } - final String name = this.getName(); - final String name2 = fontCache.getName(); - Label_a: - { - if (name == null) { - if (name2 == null) { - break Label_a; - } - } else if (name.equals(name2)) { - break Label_a; - } - return false; - } - FontChar info = this.getChar(); - FontChar info2 = fontCache.getChar(); - Label_b: - { - if (info == null) { - if (info2 == null) { - break Label_b; - } - } else if (info.equals(info2)) { - break Label_b; - } - return false; - } - final NameplateConfig config = this.getConfig(); - final NameplateConfig config2 = fontCache.getConfig(); - if (config == null) { - return config2 == null; - } else return config.equals(config2); - } - - @Override - public int hashCode() { - final int n = 1; - final String name = this.getName(); - final int n2 = n * 59 + ((name == null) ? 43 : name.hashCode()); - final FontChar fontChar = this.getChar(); - final int n3 = n2 * 59 + ((fontChar == null) ? 43 : fontChar.hashCode()); - final NameplateConfig config = this.getConfig(); - return n3 * 59 + ((config == null) ? 43 : config.hashCode()); - } - - @Override - public String toString() { - return "FontCache(name=" + this.getName() + ", info=" + this.getChar() + ", config=" + this.getConfig() + ")"; - } - - private boolean canEqual(final Object other) { - return other instanceof FontCache; - } -} diff --git a/src/main/java/net/momirealms/customnameplates/font/FontChar.java b/src/main/java/net/momirealms/customnameplates/font/FontChar.java index 08d5c9f..c893ef2 100644 --- a/src/main/java/net/momirealms/customnameplates/font/FontChar.java +++ b/src/main/java/net/momirealms/customnameplates/font/FontChar.java @@ -33,12 +33,8 @@ public record FontChar(char left, char middle, char right) { @Override public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof FontChar fontInfo)) { - return false; - } + if (o == this) return true; + if (!(o instanceof FontChar fontInfo)) return false; return this.getLeft() == fontInfo.getLeft() && this.getMiddle() == fontInfo.getMiddle() && this.getRight() == fontInfo.getRight(); } @@ -49,6 +45,10 @@ public record FontChar(char left, char middle, char right) { @Override public String toString() { - return "FontChar=" + this.getLeft() + this.getMiddle() + this.getRight(); + return "FontChar{" + + "left=" + left + + ", middle=" + middle + + ", right=" + right + + '}'; } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/font/FontNegative.java b/src/main/java/net/momirealms/customnameplates/font/FontNegative.java index 2170973..7840238 100644 --- a/src/main/java/net/momirealms/customnameplates/font/FontNegative.java +++ b/src/main/java/net/momirealms/customnameplates/font/FontNegative.java @@ -52,7 +52,15 @@ public enum FontNegative { StringBuilder stringBuilder = new StringBuilder(); if (n > 128) { stringBuilder.append(FontNegative.NEG_128.getCharacter()); - n -= 129; + n -= 128; + if (n > 128) { + stringBuilder.append(FontNegative.NEG_128.getCharacter()); + n -= 128; + if (n > 128) { + stringBuilder.append(FontNegative.NEG_128.getCharacter()); + n -= 128; + } + } } if (n - 64 > 0) { stringBuilder.append(FontNegative.NEG_64.getCharacter()); diff --git a/src/main/java/net/momirealms/customnameplates/font/FontUtil.java b/src/main/java/net/momirealms/customnameplates/font/FontUtil.java new file mode 100644 index 0000000..d7c362f --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/font/FontUtil.java @@ -0,0 +1,27 @@ +package net.momirealms.customnameplates.font; + +import net.momirealms.customnameplates.ConfigManager; + +import java.util.Objects; + +public class FontUtil { + + /* + 获取每个字符的像素宽度 + */ + public static int getInfo(char c) { + return Objects.requireNonNullElse(ConfigManager.fontWidth.get(c), 8); + } + + /* + 计算一个字符串的总宽度 + */ + public static int getTotalWidth(String s) { + int length = s.length(); + int n = 0; + for (int i = 0; i < length; i++) { + n += getInfo(s.charAt(i)); + } + return n + length - 1; //总长还需加上字符间距 + } +} diff --git a/src/main/java/net/momirealms/customnameplates/font/FontWidth.java b/src/main/java/net/momirealms/customnameplates/font/FontWidthNormal.java similarity index 64% rename from src/main/java/net/momirealms/customnameplates/font/FontWidth.java rename to src/main/java/net/momirealms/customnameplates/font/FontWidthNormal.java index 8b8fa5e..c1e6ee2 100644 --- a/src/main/java/net/momirealms/customnameplates/font/FontWidth.java +++ b/src/main/java/net/momirealms/customnameplates/font/FontWidthNormal.java @@ -17,11 +17,7 @@ package net.momirealms.customnameplates.font; -import net.momirealms.customnameplates.ConfigManager; - -import java.util.Objects; - -public enum FontWidth { +public enum FontWidthNormal { A('A', 5), a('a', 5), B('B', 5), b('b', 5), C('C', 5), c('c', 5), D('D', 5), d('d', 5), @@ -40,20 +36,20 @@ public enum FontWidth { NUM_5('5', 5), NUM_6('6', 5), NUM_7('7', 5), NUM_8('8', 5), NUM_9('9', 5), NUM_0('0', 5), EXCLAMATION_POINT('!', 1), AT_SYMBOL('@', 6), NUM_SIGN('#', 5), DOLLAR_SIGN('$', 5), PERCENT('%', 5), UP_ARROW('^', 5), - AMPERSAND('&', 5), ASTERISK('*', 5), LEFT_PARENTHESIS('(', 4), - RIGHT_PARENTHESIS(')', 4), MINUS('-', 5), UNDERSCORE('_', 5), PLUS_SIGN('+', 5), - EQUALS_SIGN('=', 5), LEFT_CURL_BRACE('{', 4), RIGHT_CURL_BRACE('}', 4), + AMPERSAND('&', 5), ASTERISK('*', 3), LEFT_PARENTHESIS('(', 3), + RIGHT_PARENTHESIS(')', 3), MINUS('-', 5), UNDERSCORE('_', 5), PLUS_SIGN('+', 5), + EQUALS_SIGN('=', 5), LEFT_CURL_BRACE('{', 3), RIGHT_CURL_BRACE('}', 3), LEFT_BRACKET('[', 3), RIGHT_BRACKET(']', 3), COLON(':', 1), SEMI_COLON(';', 1), DOUBLE_QUOTE('\"', 3), SINGLE_QUOTE('\'', 1), LEFT_ARROW('<', 4), RIGHT_ARROW('>', 4), QUESTION_MARK('?', 5), SLASH('/', 5), BACK_SLASH('\\', 5), LINE('|', 1), TILDE('~', 5), TICK('`', 2), PERIOD('.', 1), COMMA(',', 1), SPACE(' ', 3), - IN_BETWEEN(' ', 1), DEFAULT('默', 8); + IN_BETWEEN(' ', 3), DEFAULT('默', 8); private final char character; private final int length; - FontWidth(char character, int length) { + FontWidthNormal(char character, int length) { this.character = character; this.length = length; } @@ -65,36 +61,4 @@ public enum FontWidth { public int getLength() { return this.length; } - - public int getBoldLength() { - if (this == FontWidth.SPACE) { - return this.getLength(); - } - return this.getLength() + 1; - } - - /* - 获取每个字符的像素宽度 - */ - public static int getInfo(char c) { - for (FontWidth minecraftFontWidth : values()) { - if (minecraftFontWidth.getCharacter() == c) { - return minecraftFontWidth.length; - } - } - Integer custom = ConfigManager.fontWidth.get(c); - return Objects.requireNonNullElse(custom, 8); - } - - /* - 计算一个字符串的总宽度 - */ - public static int getTotalWidth(String s) { - int length = s.length(); - int n = 0; - for (int i = 0; i < length; i++) { - n += getInfo(s.charAt(i)); - } - return n + length - 1; //总长还需加上字符间距 - } } diff --git a/src/main/java/net/momirealms/customnameplates/font/FontWidthThin.java b/src/main/java/net/momirealms/customnameplates/font/FontWidthThin.java index 48a774a..ada4f12 100644 --- a/src/main/java/net/momirealms/customnameplates/font/FontWidthThin.java +++ b/src/main/java/net/momirealms/customnameplates/font/FontWidthThin.java @@ -17,10 +17,6 @@ package net.momirealms.customnameplates.font; -import net.momirealms.customnameplates.ConfigManager; - -import java.util.Objects; - public enum FontWidthThin { A('A', 3), a('a', 3), B('B', 3), b('b', 3), @@ -48,7 +44,7 @@ public enum FontWidthThin { RIGHT_ARROW('>', 2), QUESTION_MARK('?', 3), SLASH('/', 3), BACK_SLASH('\\', 3), LINE('|', 1), TILDE('~', 3), TICK('`', 1), PERIOD('.', 1), COMMA(',', 1), SPACE(' ', 3), - IN_BETWEEN(' ', 1), DEFAULT('默', 8); + IN_BETWEEN(' ', 3), DEFAULT('默', 8); private final char character; private final int length; @@ -65,36 +61,4 @@ public enum FontWidthThin { public int getLength() { return this.length; } - - public int getBoldLength() { - if (this == FontWidthThin.SPACE) { - return this.getLength(); - } - return this.getLength() + 1; - } - - /* - 获取每个字符的像素宽度 - */ - public static int getInfo(char c) { - for (FontWidthThin minecraftFontWidth : values()) { - if (minecraftFontWidth.getCharacter() == c) { - return minecraftFontWidth.length; - } - } - int custom = ConfigManager.fontWidth.get(c); - return Objects.requireNonNullElse(custom, 8); - } - - /* - 计算一个字符串的总宽度 - */ - public static int getTotalWidth(String s) { - int length = s.length(); - int n = 0; - for (int i = 0; i < length; i++) { - n += getInfo(s.charAt(i)); - } - return n + length - 1; //总长还需加上字符间距 - } } diff --git a/src/main/java/net/momirealms/customnameplates/hook/Placeholders.java b/src/main/java/net/momirealms/customnameplates/hook/Placeholders.java index dcb0302..a4be06e 100644 --- a/src/main/java/net/momirealms/customnameplates/hook/Placeholders.java +++ b/src/main/java/net/momirealms/customnameplates/hook/Placeholders.java @@ -20,16 +20,17 @@ package net.momirealms.customnameplates.hook; import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.momirealms.customnameplates.ConfigManager; -import net.momirealms.customnameplates.background.BackGround; -import net.momirealms.customnameplates.font.FontCache; -import net.momirealms.customnameplates.font.FontWidth; -import net.momirealms.customnameplates.font.FontWidthThin; +import net.momirealms.customnameplates.objects.BackGround; +import net.momirealms.customnameplates.data.DataManager; +import net.momirealms.customnameplates.data.PlayerData; +import net.momirealms.customnameplates.nameplates.NameplateInstance; +import net.momirealms.customnameplates.font.FontUtil; import net.momirealms.customnameplates.nameplates.NameplateUtil; import net.momirealms.customnameplates.resource.ResourceManager; import net.momirealms.customnameplates.scoreboard.NameplatesTeam; import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; -import net.momirealms.customnameplates.utils.BGInfo; -import net.momirealms.customnameplates.utils.NPInfo; +import net.momirealms.customnameplates.objects.BGInfo; +import net.momirealms.customnameplates.objects.NPInfo; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; @@ -52,33 +53,25 @@ public class Placeholders extends PlaceholderExpansion { @Override public String onRequest(OfflinePlayer player, String params) { + if (params.equals("equipped")){ + PlayerData playerData = DataManager.cache.get(player.getUniqueId()); + String nameplate = playerData.getEquippedNameplate(); + if (!nameplate.equals("none")) return ResourceManager.NAMEPLATES.get(nameplate).getName(); + else return ConfigManager.Message.noNameplate; + } if (params.equals("prefix")){ - if (ConfigManager.MainConfig.tab){ - String teamName = TABHook.getTABTeam(player.getName()); - NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); - if (nameplatesTeam != null){ - return nameplatesTeam.getPrefixText(); - } - }else { - NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(player.getName()); - if (nameplatesTeam != null){ - return nameplatesTeam.getPrefixText(); - } - } + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); + if (nameplatesTeam != null) return nameplatesTeam.getPrefixText(); + else return ""; } if (params.equals("suffix")){ - if (ConfigManager.MainConfig.tab){ - String teamName = TABHook.getTABTeam(player.getName()); - NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); - if (nameplatesTeam != null){ - return nameplatesTeam.getSuffixText(); - } - }else { - NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(player.getName()); - if (nameplatesTeam != null){ - return nameplatesTeam.getSuffixText(); - } - } + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); + if (nameplatesTeam != null) return nameplatesTeam.getSuffixText(); + else return ""; } if (params.startsWith("bg_")){ String bg = params.substring(3); @@ -86,17 +79,9 @@ public class Placeholders extends PlaceholderExpansion { if (bgInfo != null){ BackGround backGround = ConfigManager.backgrounds.get(bgInfo.getBackground()); if (backGround != null){ - String text; - if (ConfigManager.MainConfig.placeholderAPI){ - text = PlaceholderAPI.setPlaceholders(player, bgInfo.getText()); - }else { - text = bgInfo.getText(); - } - if (ConfigManager.MainConfig.thin_font){ - return backGround.getBackGround(FontWidthThin.getTotalWidth(text)); - }else { - return backGround.getBackGround(FontWidth.getTotalWidth(text)); - } + String text = bgInfo.getText(); + if (ConfigManager.MainConfig.placeholderAPI) text = PlaceholderAPI.setPlaceholders(player, text); + return backGround.getBackGround(FontUtil.getTotalWidth(text)); } } } @@ -104,13 +89,11 @@ public class Placeholders extends PlaceholderExpansion { String np = params.substring(4); NPInfo npInfo = ConfigManager.papiNP.get(np); if (npInfo != null){ - FontCache fontCache = ResourceManager.caches.get(npInfo.getNameplate()); - if (fontCache != null){ - if (ConfigManager.MainConfig.placeholderAPI){ - return new NameplateUtil(fontCache).makeCustomNameplate("", PlaceholderAPI.setPlaceholders(player, npInfo.getText()),""); - }else { - return new NameplateUtil(fontCache).makeCustomNameplate("", npInfo.getText(),""); - } + NameplateInstance nameplateInstance = ResourceManager.NAMEPLATES.get(npInfo.getNameplate()); + if (nameplateInstance != null){ + String text = npInfo.getText(); + if (ConfigManager.MainConfig.placeholderAPI) text = PlaceholderAPI.setPlaceholders(player, text); + return NameplateUtil.makeCustomNameplate("", text,"", nameplateInstance); } } } @@ -118,13 +101,11 @@ public class Placeholders extends PlaceholderExpansion { String np = params.substring(4); NPInfo npInfo = ConfigManager.papiNP.get(np); if (npInfo != null){ - FontCache fontCache = ResourceManager.caches.get(npInfo.getNameplate()); - if (fontCache != null){ - if (ConfigManager.MainConfig.placeholderAPI){ - return new NameplateUtil(fontCache).getSuffixLength(PlaceholderAPI.setPlaceholders(player, npInfo.getText())); - }else { - return new NameplateUtil(fontCache).getSuffixLength(npInfo.getText()); - } + NameplateInstance nameplateInstance = ResourceManager.NAMEPLATES.get(npInfo.getNameplate()); + if (nameplateInstance != null){ + String text = npInfo.getText(); + if (ConfigManager.MainConfig.placeholderAPI) text = PlaceholderAPI.setPlaceholders(player, text); + return NameplateUtil.getSuffixChar(text); } } } diff --git a/src/main/java/net/momirealms/customnameplates/listener/EntityDestroyListener.java b/src/main/java/net/momirealms/customnameplates/listener/EntityDestroyListener.java new file mode 100644 index 0000000..696a034 --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/listener/EntityDestroyListener.java @@ -0,0 +1,42 @@ +package net.momirealms.customnameplates.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.ListenerPriority; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import net.momirealms.customnameplates.CustomNameplates; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import java.util.HashMap; +import java.util.List; + +public class EntityDestroyListener extends PacketAdapter { + + public EntityDestroyListener(CustomNameplates plugin) { + super(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.ENTITY_DESTROY); + this.plugin = plugin; + } + + public void onPacketSending(PacketEvent event) { + PacketContainer packet = event.getPacket(); + List ids = packet.getIntLists().read(0); + Player player = event.getPlayer(); + for (int id : ids) { + int[] armor = ArmorStandPacketUtil.id2ids.get(id); + if (armor != null) { + ArmorStandPacketUtil.sendDestroyToOne(player, armor); + HashMap taskMap = ArmorStandPacketUtil.taskCache.get(player.getEntityId()); + if (taskMap != null) { + BukkitTask task = taskMap.remove(id); + if (task != null) { + task.cancel(); + } + } + } + } + } +} diff --git a/src/main/java/net/momirealms/customnameplates/listener/MountPacketListener.java b/src/main/java/net/momirealms/customnameplates/listener/MountPacketListener.java new file mode 100644 index 0000000..4a6cb38 --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/listener/MountPacketListener.java @@ -0,0 +1,36 @@ +package net.momirealms.customnameplates.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.ListenerPriority; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import net.momirealms.customnameplates.CustomNameplates; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; + +public class MountPacketListener extends PacketAdapter { + + public MountPacketListener(CustomNameplates plugin) { + super(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.MOUNT); + this.plugin = plugin; + } + + public void onPacketSending(PacketEvent event) { + PacketContainer packet = event.getPacket(); + int[] ids = ArmorStandPacketUtil.id2ids.get(packet.getIntegers().read(0)); + if (ids != null) { + int[] old = packet.getIntegerArrays().read(0); + int[] idArray = new int[ids.length + old.length]; + int i = 0; + while (i < ids.length) { + idArray[i] = ids[i]; + i ++; + } + while (i < ids.length + old.length) { + idArray[i] = old[i - ids.length]; + i ++; + } + packet.getModifier().write(1, idArray); + } + } +} diff --git a/src/main/java/net/momirealms/customnameplates/listener/PacketsListener.java b/src/main/java/net/momirealms/customnameplates/listener/PacketsListener.java deleted file mode 100644 index c48e9bc..0000000 --- a/src/main/java/net/momirealms/customnameplates/listener/PacketsListener.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 . - */ - -package net.momirealms.customnameplates.listener; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.InternalStructure; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.utility.MinecraftReflection; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customnameplates.ConfigManager; -import net.momirealms.customnameplates.CustomNameplates; -import net.momirealms.customnameplates.data.DataManager; -import net.momirealms.customnameplates.scoreboard.NameplatesTeam; -import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; -import org.bukkit.ChatColor; - -import java.util.Optional; - -public class PacketsListener extends PacketAdapter { - - public PacketsListener(CustomNameplates plugin) { - super(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.SCOREBOARD_TEAM); - this.plugin = plugin; - } - - public void onPacketSending(PacketEvent event) { - Integer n = event.getPacket().getIntegers().read(0); - if (n != 2) { - return; - } - //if (n == 0) System.out.println("对玩家" + event.getPlayer().getName() + "发送team创建包"); - //if (n == 2) System.out.println("对玩家"+ event.getPlayer().getName() + "发送team更新包"); - Optional optional = event.getPacket().getOptionalStructures().read(0); - if (optional.isEmpty()) { - return; - } - InternalStructure internalStructure = optional.get(); - String teamName = event.getPacket().getStrings().read(0); - //System.out.println("本次创建/更新的队伍名是" + teamName); - NameplatesTeam team = ScoreBoardManager.teams.get(teamName); - if (team == null) { - //System.out.println("但是这个队伍不存在于缓存中哦,说明那个玩家还没上线"); - return; - } - //System.out.println("这个队伍确实存在于缓存中呢!"); - if (ConfigManager.MainConfig.show_after && (DataManager.cache.get(event.getPlayer().getUniqueId()) == null || DataManager.cache.get(event.getPlayer().getUniqueId()).getAccepted() == 0)) { - //System.out.println("玩家" +event.getPlayer().getName() +"因为没有接受资源包所以没有被显示铭牌"); - internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson("{\"text\":\"\"}")); - internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson("{\"text\":\"\"}")); - internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,ChatColor.WHITE); - return; - } - //System.out.println("玩家" +event.getPlayer().getName() +"可以看见队伍" + teamName + "的铭牌"); - if (team.getPrefix() != null) { - internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(team.getPrefix()))); - } - if (team.getSuffix() != null) { - internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(team.getSuffix()))); - } - internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,team.getColor()); - } -} diff --git a/src/main/java/net/momirealms/customnameplates/listener/PapiReload.java b/src/main/java/net/momirealms/customnameplates/listener/PapiReload.java index a85ca08..68a3743 100644 --- a/src/main/java/net/momirealms/customnameplates/listener/PapiReload.java +++ b/src/main/java/net/momirealms/customnameplates/listener/PapiReload.java @@ -1,5 +1,6 @@ package net.momirealms.customnameplates.listener; +import me.clip.placeholderapi.events.ExpansionUnregisterEvent; import net.momirealms.customnameplates.CustomNameplates; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -7,7 +8,7 @@ import org.bukkit.event.Listener; public class PapiReload implements Listener { @EventHandler - public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){ + public void onReload(ExpansionUnregisterEvent event){ if (CustomNameplates.placeholders != null){ if (event.getExpansion().equals(CustomNameplates.placeholders)){ CustomNameplates.placeholders.register(); diff --git a/src/main/java/net/momirealms/customnameplates/listener/PlayerListener.java b/src/main/java/net/momirealms/customnameplates/listener/PlayerListener.java index 7ce2ebf..9f1abec 100644 --- a/src/main/java/net/momirealms/customnameplates/listener/PlayerListener.java +++ b/src/main/java/net/momirealms/customnameplates/listener/PlayerListener.java @@ -21,71 +21,120 @@ import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; import net.momirealms.customnameplates.data.DataManager; import net.momirealms.customnameplates.data.PlayerData; +import net.momirealms.customnameplates.data.SqlHandler; import net.momirealms.customnameplates.hook.TABHook; import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; +import net.momirealms.customnameplates.utils.TeamPacketUtil; import org.bukkit.Bukkit; +import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerResourcePackStatusEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; -public record PlayerListener(CustomNameplates plugin) implements Listener { +import java.util.HashMap; + +public class PlayerListener implements Listener { + + public static HashMap taskCache = new HashMap<>(); @EventHandler public void onJoin(PlayerJoinEvent event) { - this.plugin.getDataManager().loadData(event.getPlayer()); - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomNameplates.instance, ()-> { - if (ConfigManager.MainConfig.tab){ - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates()); - }else { - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(player.getName()).updateNameplates()); - } - }, 50); + + CustomNameplates.instance.getDataManager().loadData(event.getPlayer()); + + if (ConfigManager.Nameplate.update && ConfigManager.Nameplate.mode_team) { + Player player = event.getPlayer(); + BukkitTask task = Bukkit.getScheduler().runTaskTimerAsynchronously(CustomNameplates.instance, () -> { + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + ScoreBoardManager.teams.get(teamName).updateNameplates(); + TeamPacketUtil.sendUpdateToAll(player); + }, 20, ConfigManager.Nameplate.refresh); + taskCache.put(player, task); + } } @EventHandler public void onQuit(PlayerQuitEvent event) { - this.plugin.getDataManager().unloadPlayer(event.getPlayer().getUniqueId()); + CustomNameplates.instance.getDataManager().unloadPlayer(event.getPlayer().getUniqueId()); Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); - Team team; - String teamName; - if (ConfigManager.MainConfig.tab){ - teamName = TABHook.getTABTeam(event.getPlayer().getName()); - }else { - teamName = event.getPlayer().getName(); - } - team = scoreboard.getTeam(teamName); + Player player = event.getPlayer(); + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + Team team = scoreboard.getTeam(teamName); + if (team != null) team.unregister(); ScoreBoardManager.teams.remove(teamName); - if (team != null){ - team.unregister(); + if (ConfigManager.Nameplate.update) { + if (ConfigManager.Nameplate.mode_team) { + TeamPacketUtil.teamInfoCache.remove(player); + BukkitTask bukkitTask = taskCache.remove(player); + if (bukkitTask != null) { + bukkitTask.cancel(); + } + } + else { + int id = event.getPlayer().getEntityId(); + HashMap taskMap = ArmorStandPacketUtil.taskCache.remove(id); + if (taskMap != null) { + for (int otherID : taskMap.keySet()) { + HashMap otherTaskMap = ArmorStandPacketUtil.taskCache.get(otherID); + if (otherTaskMap != null) { + BukkitTask task = otherTaskMap.remove(id); + if (task != null) { + task.cancel(); + } + } + } + taskMap.values().forEach(BukkitTask::cancel); + } + } } } @EventHandler public void onAccept(PlayerResourcePackStatusEvent event) { - PlayerData playerData = DataManager.cache.get(event.getPlayer().getUniqueId()); - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomNameplates.instance, ()-> { - if (playerData == null) { - return; - } - if (event.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { - playerData.setAccepted(1); - if (ConfigManager.MainConfig.tab){ - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates()); - }else { - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(player.getName()).updateNameplates()); + if (!ConfigManager.Nameplate.show_after) return; + new BukkitRunnable() { + @Override + public void run() { + PlayerData playerData = DataManager.cache.get(event.getPlayer().getUniqueId()); + if (playerData == null) { + return; } - } else if(event.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED || event.getStatus() == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) { - playerData.setAccepted(0); - if (ConfigManager.MainConfig.tab){ - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(TABHook.getTABTeam(player.getName())).updateNameplates()); - }else { - Bukkit.getOnlinePlayers().forEach(player -> ScoreBoardManager.teams.get(player.getName()).updateNameplates()); + if (event.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { + playerData.setAccepted(1); + Player player = event.getPlayer(); + SqlHandler.save(playerData, player.getUniqueId()); + TeamPacketUtil.sendUpdateToOne(player); + if (!ConfigManager.Nameplate.mode_team) { + HashMap tasks = ArmorStandPacketUtil.taskCache.get(player.getEntityId()); + if (tasks == null) return; + for (Integer id : tasks.keySet()){ + ArmorStandPacketUtil.forceUpdateOneToOne(id, player); + } + } + } + else if (event.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED || event.getStatus() == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) { + playerData.setAccepted(0); + SqlHandler.save(playerData, event.getPlayer().getUniqueId()); + Player player = event.getPlayer(); + TeamPacketUtil.sendUpdateToOne(player); + if (!ConfigManager.Nameplate.mode_team) { + HashMap tasks = ArmorStandPacketUtil.taskCache.get(player.getEntityId()); + if (tasks == null) return; + for (Integer id : tasks.keySet()){ + ArmorStandPacketUtil.forceUpdateOneToOne(id, player); + } + } } } - }, 20); + }.runTaskAsynchronously(CustomNameplates.instance); } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/listener/PlayerPacketsListener.java b/src/main/java/net/momirealms/customnameplates/listener/PlayerPacketsListener.java new file mode 100644 index 0000000..fb11a9e --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/listener/PlayerPacketsListener.java @@ -0,0 +1,57 @@ +package net.momirealms.customnameplates.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.ListenerPriority; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; +import net.momirealms.customnameplates.ConfigManager; +import net.momirealms.customnameplates.CustomNameplates; +import net.momirealms.customnameplates.utils.ArmorStandPacketUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.util.HashMap; + +public class PlayerPacketsListener extends PacketAdapter { + + public PlayerPacketsListener(CustomNameplates plugin) { + super(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.NAMED_ENTITY_SPAWN); + this.plugin = plugin; + } + + public synchronized void onPacketSending(PacketEvent event) { + PacketContainer packet = event.getPacket(); + Bukkit.getScheduler().runTaskAsynchronously(CustomNameplates.instance, ()-> { + Player player = event.getPlayer(); + Player otherPlayer = Bukkit.getPlayer(packet.getUUIDs().read(0)); + if (otherPlayer != null) { + ArmorStandPacketUtil.sendSummonOneToOne(player, otherPlayer); + if (ConfigManager.Nameplate.update) { + BukkitTask bukkitTask = new BukkitRunnable() { + @Override + public void run() { + ArmorStandPacketUtil.sendUpdateOneToOne(otherPlayer, player); + } + }.runTaskTimerAsynchronously(CustomNameplates.instance, 20, ConfigManager.Nameplate.refresh); + HashMap inner = ArmorStandPacketUtil.taskCache.get(player.getEntityId()); + if (inner == null) { + inner = new HashMap<>(); + inner.put(otherPlayer.getEntityId(), bukkitTask); + ArmorStandPacketUtil.taskCache.put(player.getEntityId(), inner); + } + else { + int other = otherPlayer.getEntityId(); + BukkitTask bukkitTask2 = inner.get(other); + if (bukkitTask2 != null) { + bukkitTask2.cancel(); + } + inner.put(other, bukkitTask); + } + } + } + }); + } +} diff --git a/src/main/java/net/momirealms/customnameplates/nameplates/NameplateConfig.java b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateConfig.java index 406d9cb..27c5339 100644 --- a/src/main/java/net/momirealms/customnameplates/nameplates/NameplateConfig.java +++ b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateConfig.java @@ -19,12 +19,38 @@ package net.momirealms.customnameplates.nameplates; import org.bukkit.ChatColor; +import java.util.Objects; + public record NameplateConfig(ChatColor color, int height, String name, int yoffset) { public static NameplateConfig EMPTY = new NameplateConfig(ChatColor.WHITE, 16, "none", 12); - public ChatColor getColor() {return this.color;} - public int getHeight() {return this.height;} - public String getName() {return this.name;} - public int getyoffset() {return this.yoffset; } + public ChatColor getColor() { + return this.color; + } + + public int getHeight() { + return this.height; + } + + public String getName() { + return this.name; + } + + public int getYOffset() { + return this.yoffset; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NameplateConfig that = (NameplateConfig) o; + return height == that.height && yoffset == that.yoffset && color == that.color && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(color, height, name, yoffset); + } } diff --git a/src/main/java/net/momirealms/customnameplates/nameplates/NameplateInstance.java b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateInstance.java new file mode 100644 index 0000000..7ca1fa3 --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateInstance.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) <2022> + * + * 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 . + */ + +package net.momirealms.customnameplates.nameplates; + +import net.momirealms.customnameplates.font.FontChar; + +import java.util.Objects; + +public record NameplateInstance(String name, FontChar fontChar, NameplateConfig config) { + + public static NameplateInstance EMPTY = new NameplateInstance("none", new FontChar('小', '默', '米'), NameplateConfig.EMPTY); + + public String getName() { + return this.name; + } + + public FontChar getChar() { + return this.fontChar; + } + + public NameplateConfig getConfig() { + return this.config; + } + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof NameplateInstance nameplateInstance)) return false; + return Objects.equals(nameplateInstance.getName(), this.getName()); + } + + @Override + public int hashCode() { + int n = 1; + String name = this.getName(); + int n2 = n * 59 + ((name == null) ? 43 : name.hashCode()); + FontChar fontChar = this.getChar(); + int n3 = n2 * 59 + ((fontChar == null) ? 43 : fontChar.hashCode()); + NameplateConfig config = this.getConfig(); + return n3 * 59 + ((config == null) ? 43 : config.hashCode()); + } + + @Override + public String toString() { + return "FontCache{" + + "name='" + name + '\'' + + ", fontChar=" + fontChar + + ", config=" + config + + '}'; + } +} diff --git a/src/main/java/net/momirealms/customnameplates/nameplates/NameplateUtil.java b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateUtil.java index 73ffd5c..a9d3342 100644 --- a/src/main/java/net/momirealms/customnameplates/nameplates/NameplateUtil.java +++ b/src/main/java/net/momirealms/customnameplates/nameplates/NameplateUtil.java @@ -17,41 +17,24 @@ package net.momirealms.customnameplates.nameplates; -import net.momirealms.customnameplates.ConfigManager; -import net.momirealms.customnameplates.font.FontCache; -import net.momirealms.customnameplates.font.FontNegative; -import net.momirealms.customnameplates.font.FontWidth; -import net.momirealms.customnameplates.font.FontWidthThin; +import net.momirealms.customnameplates.font.*; import org.bukkit.ChatColor; public class NameplateUtil { - private final FontCache fontcache; - - public NameplateUtil(FontCache font) { - this.fontcache = font; - } - - public String makeCustomNameplate(String prefix, String name, String suffix) { - int totalWidth; - if (ConfigManager.MainConfig.thin_font){ - totalWidth = FontWidthThin.getTotalWidth(ChatColor.stripColor(prefix + name + suffix)); - }else { - totalWidth = FontWidth.getTotalWidth(ChatColor.stripColor(prefix + name + suffix)); - } + public static String makeCustomNameplate(String prefix, String name, String suffix, NameplateInstance nameplate) { + int totalWidth = FontUtil.getTotalWidth(ChatColor.stripColor(prefix + name + suffix)); boolean isEven = totalWidth % 2 == 0; - char left = this.fontcache.getChar().getLeft(); - char middle = this.fontcache.getChar().getMiddle(); - char right = this.fontcache.getChar().getRight(); + char left = nameplate.getChar().getLeft(); + char middle = nameplate.getChar().getMiddle(); + char right = nameplate.getChar().getRight(); char neg_1 = FontNegative.NEG_1.getCharacter(); int left_offset = totalWidth + 16 + 1; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(FontNegative.getShortestNegChars(isEven ? left_offset : left_offset + 1)); stringBuilder.append(left).append(neg_1); int mid_amount = (totalWidth + 1) / 16; - for (int i = 0; i < (mid_amount == 0 ? 1 : mid_amount); i++) { - stringBuilder.append(middle).append(neg_1); - } + for (int i = 0; i < (mid_amount == 0 ? 1 : mid_amount); i++) stringBuilder.append(middle).append(neg_1); stringBuilder.append(FontNegative.getShortestNegChars(16 - ((totalWidth + 1) % 16 + (isEven ? 0 : 1)))); stringBuilder.append(middle).append(neg_1); stringBuilder.append(right).append(neg_1); @@ -59,17 +42,8 @@ public class NameplateUtil { return stringBuilder.toString(); } - public String getSuffixLength(String name) { - int totalWidth; - if (ConfigManager.MainConfig.thin_font){ - totalWidth = FontWidthThin.getTotalWidth(ChatColor.stripColor(name)); - }else { - totalWidth = FontWidth.getTotalWidth(ChatColor.stripColor(name)); - } + public static String getSuffixChar(String name) { + int totalWidth = FontUtil.getTotalWidth(ChatColor.stripColor(name)); return FontNegative.getShortestNegChars(totalWidth + totalWidth % 2 + 1); } - - public ChatColor getColor() { - return this.fontcache.getConfig().getColor(); - } } diff --git a/src/main/java/net/momirealms/customnameplates/objects/ASInfo.java b/src/main/java/net/momirealms/customnameplates/objects/ASInfo.java new file mode 100644 index 0000000..56b6b5f --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/objects/ASInfo.java @@ -0,0 +1,34 @@ +package net.momirealms.customnameplates.objects; + +import com.comphenix.protocol.events.PacketContainer; + +public class ASInfo { + + private final String text; + private final PacketContainer entityPacket; + private final PacketContainer metaPacket; + private final int id; + + public ASInfo(int id ,String text, PacketContainer entityPacket, PacketContainer metaPacket) { + this.id = id; + this.text = text; + this.entityPacket = entityPacket; + this.metaPacket = metaPacket; + } + + public String getText() { + return text; + } + + public PacketContainer getEntityPacket() { + return entityPacket; + } + + public PacketContainer getMetaPacket() { + return metaPacket; + } + + public int getId() { + return id; + } +} diff --git a/src/main/java/net/momirealms/customnameplates/utils/BGInfo.java b/src/main/java/net/momirealms/customnameplates/objects/BGInfo.java similarity index 94% rename from src/main/java/net/momirealms/customnameplates/utils/BGInfo.java rename to src/main/java/net/momirealms/customnameplates/objects/BGInfo.java index aa37b60..f4eef01 100644 --- a/src/main/java/net/momirealms/customnameplates/utils/BGInfo.java +++ b/src/main/java/net/momirealms/customnameplates/objects/BGInfo.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customnameplates.utils; +package net.momirealms.customnameplates.objects; public record BGInfo(String text, String background) { diff --git a/src/main/java/net/momirealms/customnameplates/background/BackGround.java b/src/main/java/net/momirealms/customnameplates/objects/BackGround.java similarity index 73% rename from src/main/java/net/momirealms/customnameplates/background/BackGround.java rename to src/main/java/net/momirealms/customnameplates/objects/BackGround.java index 83c28ff..96514aa 100644 --- a/src/main/java/net/momirealms/customnameplates/background/BackGround.java +++ b/src/main/java/net/momirealms/customnameplates/objects/BackGround.java @@ -15,51 +15,38 @@ * along with this program. If not, see . */ -package net.momirealms.customnameplates.background; +package net.momirealms.customnameplates.objects; import net.momirealms.customnameplates.font.FontNegative; import net.momirealms.customnameplates.resource.ResourceManager; import java.util.HashMap; -public class BackGround { - - private final String key; - private final String start; - private final String offset_1; - private final String offset_2; - private final String offset_4; - private final String offset_8; - private final String offset_16; - private final String offset_32; - private final String offset_64; - private final String offset_128; - private final String end; - private final int offset_y; - private final int offset_x; - - public BackGround(String key, String start, String offset_1, String offset_2, - String offset_4, String offset_8, String offset_16, - String offset_32, String offset_64, String offset_128, String end, int offset_y, int offset_x){ - this.key = key; - this.start = start; this.offset_1 = offset_1; this.offset_2 = offset_2; - this.end = end; this.offset_4 = offset_4; this.offset_8 = offset_8; - this.offset_16 = offset_16; this.offset_32 = offset_32; this.offset_64 = offset_64; - this.offset_128 = offset_128; - this.offset_y = offset_y; - this.offset_x = offset_x; - } +public record BackGround(String key, String start, String offset_1, + String offset_2, String offset_4, String offset_8, + String offset_16, String offset_32, String offset_64, + String offset_128, String end, int offset_y, int offset_x, int size) { public String getBackGround(int n) { n += offset_x; String offset = FontNegative.getShortestNegChars(n); StringBuilder stringBuilder = new StringBuilder(); - HashMap chars = ResourceManager.bgCaches.get(key); + HashMap chars = ResourceManager.BACKGROUNDS.get(key); stringBuilder.append(chars.get(start)); if (n > 128) { stringBuilder.append(FontNegative.NEG_1.getCharacter()); stringBuilder.append(chars.get(offset_128)); n -= 128; + if (n > 128) { + stringBuilder.append(FontNegative.NEG_1.getCharacter()); + stringBuilder.append(chars.get(offset_128)); + n -= 128; + if (n > 128) { + stringBuilder.append(FontNegative.NEG_1.getCharacter()); + stringBuilder.append(chars.get(offset_128)); + n -= 128; + } + } } if (n - 64 > 0) { stringBuilder.append(FontNegative.NEG_1.getCharacter()); @@ -147,4 +134,8 @@ public class BackGround { public String getKey() { return key; } + + public int getSize() { + return size; + } } diff --git a/src/main/java/net/momirealms/customnameplates/utils/NPInfo.java b/src/main/java/net/momirealms/customnameplates/objects/NPInfo.java similarity index 94% rename from src/main/java/net/momirealms/customnameplates/utils/NPInfo.java rename to src/main/java/net/momirealms/customnameplates/objects/NPInfo.java index b97e459..d1d97d7 100644 --- a/src/main/java/net/momirealms/customnameplates/utils/NPInfo.java +++ b/src/main/java/net/momirealms/customnameplates/objects/NPInfo.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customnameplates.utils; +package net.momirealms.customnameplates.objects; public record NPInfo(String text, String nameplate) { diff --git a/src/main/java/net/momirealms/customnameplates/resource/ResourceManager.java b/src/main/java/net/momirealms/customnameplates/resource/ResourceManager.java index 443aa29..77a2f48 100644 --- a/src/main/java/net/momirealms/customnameplates/resource/ResourceManager.java +++ b/src/main/java/net/momirealms/customnameplates/resource/ResourceManager.java @@ -22,13 +22,14 @@ import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; -import net.momirealms.customnameplates.AdventureManager; -import net.momirealms.customnameplates.background.BackGround; -import net.momirealms.customnameplates.font.FontCache; +import net.momirealms.customnameplates.utils.AdventureUtil; +import net.momirealms.customnameplates.objects.BackGround; +import net.momirealms.customnameplates.nameplates.NameplateInstance; import net.momirealms.customnameplates.font.FontChar; import net.momirealms.customnameplates.font.FontNegative; import net.momirealms.customnameplates.nameplates.NameplateConfig; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; @@ -42,23 +43,18 @@ import static net.momirealms.customnameplates.ConfigManager.MainConfig.start; public class ResourceManager { - public static HashMap caches = new HashMap<>(); - public static HashMap> bgCaches = new HashMap<>(); - private final CustomNameplates plugin; - - public ResourceManager(CustomNameplates plugin) { - this.plugin = plugin; - } + public static HashMap NAMEPLATES = new HashMap<>(); + public static HashMap> BACKGROUNDS = new HashMap<>(); public void generateResourcePack() { - File r_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "resources"); + File r_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "nameplates"); File b_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "backgrounds"); - File g_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "generated"); + File g_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "ResourcePack"); if (!r_file.exists()) { if (!r_file.mkdir()) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to create resources folder..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to create resources folder..."); return; } saveDefaultResources(); @@ -66,7 +62,7 @@ public class ResourceManager { if (!b_file.exists()) { if (!b_file.mkdir()) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to create resources folder..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to create resources folder..."); return; } saveDefaultBGResources(); @@ -75,61 +71,76 @@ public class ResourceManager { File[] pngFiles = r_file.listFiles(file -> file.getName().endsWith(".png")); if (pngFiles == null) { - AdventureManager.consoleMessage("[CustomNameplates] Error! No png files detected in resource folder..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! No png files detected in resource folder..."); return; } Arrays.sort(pngFiles); deleteDirectory(g_file); - File f_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "generated" + File.separatorChar + ConfigManager.MainConfig.namespace + File.separatorChar + "font"); - File t_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "generated" + File.separatorChar + ConfigManager.MainConfig.namespace + File.separatorChar + "textures"); + File f_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "ResourcePack" + File.separatorChar + ConfigManager.MainConfig.namespace + File.separatorChar + "font"); + File t_file = new File(CustomNameplates.instance.getDataFolder() + File.separator + "ResourcePack" + File.separatorChar + ConfigManager.MainConfig.namespace + File.separatorChar + "textures"); if (!f_file.mkdirs() || !t_file.mkdirs()) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to generate resource pack folders..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to generate resource pack folders..."); return; } + if (ConfigManager.MainConfig.offsets != null){ + ConfigManager.MainConfig.offsets.forEach(offset -> { + JsonObject jsonObject_offset = new JsonObject(); + JsonArray jsonArray_offset = new JsonArray(); + jsonObject_offset.add("providers", jsonArray_offset); + JsonObject jsonObject_3 = new JsonObject(); + jsonObject_3.add("type", new JsonPrimitive("space")); + JsonObject jsonObject_4 = new JsonObject(); + jsonObject_4.add(" ", new JsonPrimitive(4)); + jsonObject_4.add("\\u200c", new JsonPrimitive(0)); + jsonObject_3.add("advances", jsonObject_4); + jsonArray_offset.add(jsonObject_3); + JsonObject jsonObject_2 = new JsonObject(); + jsonObject_2.add("type", new JsonPrimitive("bitmap")); + jsonObject_2.add("file", new JsonPrimitive("minecraft:font/ascii.png")); + jsonObject_2.add("ascent", new JsonPrimitive(offset)); + jsonObject_2.add("height", new JsonPrimitive(8)); + JsonArray jsonArray_2 = new JsonArray(); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000"); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000"); + jsonArray_2.add("\\u0020\\u0021\\u0022\\u0023\\u0024\\u0025\\u0026\\u0027\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f"); + jsonArray_2.add("\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f"); + jsonArray_2.add("\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f"); + jsonArray_2.add("\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\\u0058\\u0059\\u005a\\u005b\\u005c\\u005d\\u005e\\u005f"); + jsonArray_2.add("\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f"); + jsonArray_2.add("\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u0000"); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000"); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u00a3\\u0000\\u0000\\u0192"); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u00aa\\u00ba\\u0000\\u0000\\u00ac\\u0000\\u0000\\u0000\\u00ab\\u00bb"); + jsonArray_2.add("\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510"); + jsonArray_2.add("\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567"); + jsonArray_2.add("\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580"); + jsonArray_2.add("\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u2205\\u2208\\u0000"); + jsonArray_2.add("\\u2261\\u00b1\\u2265\\u2264\\u2320\\u2321\\u00f7\\u2248\\u00b0\\u2219\\u0000\\u221a\\u207f\\u00b2\\u25a0\\u0000"); + jsonObject_2.add("chars", jsonArray_2); + jsonArray_offset.add(jsonObject_2); + + try (FileWriter fileWriter = new FileWriter( + CustomNameplates.instance.getDataFolder() + + File.separator + "ResourcePack" + + File.separator + ConfigManager.MainConfig.namespace + + File.separator + "font" + + File.separator + "offset_" + offset + ".json")) { + fileWriter.write(jsonObject_offset.toString().replace("\\\\", "\\")); + } + catch (IOException e) { + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to generate offset font json..."); + } + }); + } + JsonObject jsonObject_1 = new JsonObject(); JsonArray jsonArray_1 = new JsonArray(); jsonObject_1.add("providers", jsonArray_1); - - if (ConfigManager.MainConfig.anotherFont){ - - JsonObject jsonObject_3 = new JsonObject(); - jsonObject_3.add("type", new JsonPrimitive("space")); - JsonObject jsonObject_4 = new JsonObject(); - jsonObject_4.add(" ", new JsonPrimitive(4)); - jsonObject_4.add("\\u200c", new JsonPrimitive(0)); - jsonObject_3.add("advances", jsonObject_4); - jsonArray_1.add(jsonObject_3); - - JsonObject jsonObject_2 = new JsonObject(); - jsonObject_2.add("type", new JsonPrimitive("bitmap")); - jsonObject_2.add("file", new JsonPrimitive("minecraft:font/ascii.png")); - jsonObject_2.add("ascent", new JsonPrimitive(ConfigManager.MainConfig.fontOffset)); - jsonObject_2.add("height", new JsonPrimitive(8)); - JsonArray jsonArray_2 = new JsonArray(); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonArray_2.add(" !\"#$%&'()*+,-./"); - jsonArray_2.add("0123456789:;<=>?"); - jsonArray_2.add("@ABCDEFGHIJKLMNO"); - jsonArray_2.add("PQRSTUVWXYZ[\\\\]^_"); - jsonArray_2.add("`abcdefghijklmno"); - jsonArray_2.add("pqrstuvwxyz{|}~\u0000"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonArray_2.add("\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510"); - jsonArray_2.add("\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567"); - jsonArray_2.add("\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\\u2205\\u2208\u0000"); - jsonArray_2.add("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"); - jsonObject_2.add("chars", jsonArray_2); - jsonArray_1.add(jsonObject_2); - } - + getNegativeFontEnums().forEach(jsonArray_1::add); if (ConfigManager.nameplate){ for (File png : pngFiles) { JsonObject jsonObject_2 = new JsonObject(); @@ -140,76 +151,85 @@ public class ResourceManager { FontChar fontChar = new FontChar(left, middle, right); String pngName = png.getName().substring(0, png.getName().length() - 4); NameplateConfig config = this.getConfiguration(pngName); - caches.put(pngName, new FontCache(pngName, fontChar, config)); + NAMEPLATES.put(pngName, new NameplateInstance(pngName, fontChar, config)); jsonObject_2.add("type", new JsonPrimitive("bitmap")); jsonObject_2.add("file", new JsonPrimitive(ConfigManager.MainConfig.namespace + ":" + ConfigManager.MainConfig.folder_path.replaceAll("\\\\","/") + png.getName().toLowerCase())); - jsonObject_2.add("ascent", new JsonPrimitive(config.getyoffset())); + jsonObject_2.add("ascent", new JsonPrimitive(config.getYOffset())); jsonObject_2.add("height", new JsonPrimitive(config.getHeight())); JsonArray jsonArray_2 = new JsonArray(); jsonArray_2.add(native2ascii(fontChar.getLeft()) + native2ascii(fontChar.getMiddle()) + native2ascii(fontChar.getRight())); jsonObject_2.add("chars", jsonArray_2); jsonArray_1.add(jsonObject_2); - try{ - FileUtils.copyFile(png, new File(t_file.getPath() + File.separatorChar + ConfigManager.MainConfig.folder_path + png.getName())); + FileUtils.copyFile(png, new File(t_file.getPath() + File.separatorChar + StringUtils.replace(ConfigManager.MainConfig.folder_path, "\\", String.valueOf(File.separatorChar)) + png.getName())); }catch (IOException e){ - e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to copy png files to resource pack..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to copy png files to resource pack..."); } } - caches.put("none", FontCache.EMPTY); + NAMEPLATES.put("none", NameplateInstance.EMPTY); } - if (ConfigManager.background){ ConfigManager.backgrounds.forEach((key, backGround) -> { getBackgrounds(backGround).forEach(jsonArray_1::add); }); } - getNegativeFontEnums().forEach(jsonArray_1::add); - - CustomNameplates.instance.saveResource("space_split.png", false); //复制space_split.png - try{ - FileUtils.copyFile(new File(CustomNameplates.instance.getDataFolder(),"space_split.png"), new File(t_file.getPath() + File.separator + ConfigManager.MainConfig.ss_folder_path + "space_split.png")); - }catch (IOException e){ - e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to copy space_split.png to resource pack..."); - return; + if (ConfigManager.MainConfig.extract) { + String path = "ResourcePack" + File.separator + "minecraft" + File.separator + "shaders" + File.separator + "core" + File.separator; + CustomNameplates.instance.saveResource(path + "rendertype_text.fsh", true); + CustomNameplates.instance.saveResource(path + "rendertype_text.json", true); + CustomNameplates.instance.saveResource(path + "rendertype_text.vsh", true); + CustomNameplates.instance.saveResource(path + "rendertype_text_see_through.fsh", true); + CustomNameplates.instance.saveResource(path + "rendertype_text_see_through.json", true); + CustomNameplates.instance.saveResource(path + "rendertype_text_see_through.vsh", true); } - new File(CustomNameplates.instance.getDataFolder(),"space_split.png").delete(); //删除拷贝出的默认文件 - try (FileWriter fileWriter = new FileWriter(CustomNameplates.instance.getDataFolder() + File.separator + "generated" + File.separatorChar + ConfigManager.MainConfig.namespace + File.separatorChar + "font" + File.separatorChar + ConfigManager.MainConfig.font + ".json")) { + try{ + CustomNameplates.instance.saveResource("space_split.png", false); + FileUtils.copyFile(new File(CustomNameplates.instance.getDataFolder(),"space_split.png"), new File(t_file.getPath() + File.separator + StringUtils.replace(ConfigManager.MainConfig.ss_folder_path, "\\", String.valueOf(File.separatorChar)) + "space_split.png")); + new File(CustomNameplates.instance.getDataFolder(),"space_split.png").delete(); + }catch (IOException e){ + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to copy space_split.png to resource pack..."); + } + + try (FileWriter fileWriter = new FileWriter( + CustomNameplates.instance.getDataFolder() + + File.separator + "ResourcePack" + + File.separator + ConfigManager.MainConfig.namespace + + File.separator + "font" + + File.separator + ConfigManager.MainConfig.font + ".json")) + { fileWriter.write(jsonObject_1.toString().replace("\\\\", "\\")); } catch (IOException e) { - e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to generate font json..."); - return; + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to generate font json..."); } - AdventureManager.consoleMessage("[CustomNameplates] ResourcePack has been generated! " + (this.caches.size() -1) + " nameplates loaded!"); + AdventureUtil.consoleMessage("[CustomNameplates] ResourcePack has been generated!"); + AdventureUtil.consoleMessage("[CustomNameplates] Loaded " + (NAMEPLATES.size() -1) + " nameplates"); + if (ConfigManager.MainConfig.itemsAdder){ try{ FileUtils.copyDirectory(g_file, new File(Bukkit.getPluginManager().getPlugin("ItemsAdder").getDataFolder() + File.separator + "data"+ File.separator + "resource_pack" + File.separator + "assets") ); - AdventureManager.consoleMessage("[CustomNameplates] Detected ItemsAdder! Automatically sent rp to ItemsAdder folder!"); + AdventureUtil.consoleMessage("[CustomNameplates] Detected ItemsAdder! Automatically sent rp to ItemsAdder folder!"); }catch (IOException e){ e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to copy files to ItemsAdder..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to copy files to ItemsAdder..."); } } if (ConfigManager.MainConfig.oraxen){ try{ FileUtils.copyDirectory(g_file, new File(Bukkit.getPluginManager().getPlugin("Oraxen").getDataFolder() + File.separator + "pack"+ File.separator + "assets")); - AdventureManager.consoleMessage("[CustomNameplates] Detected Oraxen! Automatically sent rp to Oraxen folder!"); + AdventureUtil.consoleMessage("[CustomNameplates] Detected Oraxen! Automatically sent rp to Oraxen folder!"); }catch (IOException e){ e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to copy files to Oraxen..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to copy files to Oraxen..."); } } } private void saveDefaultResources() { List list = Arrays.asList("cat", "egg", "cheems", "wither", "xmas", "halloween","hutao","starsky","trident","rabbit"); - list.forEach(name -> CustomNameplates.instance.saveResource("resources" + File.separatorChar + name + ".png", false)); + list.forEach(name -> CustomNameplates.instance.saveResource("nameplates" + File.separatorChar + name + ".png", false)); } private void saveDefaultBGResources() { List list = Arrays.asList("b0", "b1", "b2", "b4", "b8", "b16","b32","b64","b128"); @@ -222,43 +242,29 @@ public class ResourceManager { FileUtils.deleteDirectory(file); }catch (IOException e){ e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to delete generated folder..." ); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to delete generated folder..." ); } } } private NameplateConfig getConfiguration(String nameplate) { try { - File file = new File(CustomNameplates.instance.getDataFolder().getPath() + File.separator + "resources" + File.separator + nameplate + ".yml"); + File file = new File(CustomNameplates.instance.getDataFolder().getPath() + File.separator + "nameplates" + File.separator + nameplate + ".yml"); if (!file.exists()){ try { file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - AdventureManager.consoleMessage("铭牌配置生成出错!"); + } + catch (IOException e) { + AdventureUtil.consoleMessage("[CustomNameplates] Error occurred when generating default nameplate config!"); } } YamlConfiguration config = new YamlConfiguration(); - config.load(CustomNameplates.instance.getDataFolder().getPath() + File.separator + "resources" + File.separator + nameplate + ".yml"); - if (!config.contains("name")){ - config.set("name", nameplate); - } - if (!config.contains("color")){ - config.set("color","WHITE"); - } - if (!config.contains("size")){ - config.set("size", 16); - } - if (!config.contains("yoffset")){ - config.set("yoffset", 12); - } - ChatColor color = ChatColor.WHITE; - try { - color = ChatColor.valueOf(Objects.requireNonNull(config.getString("color")).toUpperCase()); - } - catch (IllegalArgumentException ex) { - AdventureManager.consoleMessage("[CustomNameplates] Invalid Color of " + nameplate + ""); - } + config.load(CustomNameplates.instance.getDataFolder().getPath() + File.separator + "nameplates" + File.separator + nameplate + ".yml"); + if (!config.contains("name")) config.set("name", nameplate); + if (!config.contains("color")) config.set("color","WHITE"); + if (!config.contains("size")) config.set("size", 16); + if (!config.contains("yoffset")) config.set("yoffset", 12); + ChatColor color = ChatColor.valueOf(Objects.requireNonNull(config.getString("color","WHITE")).toUpperCase()); int size = config.getInt("size"); int yoffset = config.getInt("yoffset"); String name = config.getString("name"); @@ -290,8 +296,8 @@ public class ResourceManager { return jsonObject; } - public FontCache getNameplateInfo(String nameplate) { - return caches.get(nameplate); + public NameplateInstance getNameplateInstance(String nameplate) { + return NAMEPLATES.get(nameplate); } private String native2ascii(char ch) { @@ -299,12 +305,8 @@ public class ResourceManager { StringBuilder stringBuilder_1 = new StringBuilder("\\u"); StringBuilder stringBuilder_2 = new StringBuilder(Integer.toHexString(ch)); stringBuilder_2.reverse(); - for (int n = 4 - stringBuilder_2.length(), i = 0; i < n; i++) { - stringBuilder_2.append('0'); - } - for (int j = 0; j < 4; j++) { - stringBuilder_1.append(stringBuilder_2.charAt(3 - j)); - } + for (int n = 4 - stringBuilder_2.length(), i = 0; i < n; i++) stringBuilder_2.append('0'); + for (int j = 0; j < 4; j++) stringBuilder_1.append(stringBuilder_2.charAt(3 - j)); return stringBuilder_1.toString(); } return Character.toString(ch); @@ -313,39 +315,41 @@ public class ResourceManager { private List getBackgrounds(BackGround backGround) { ArrayList list = new ArrayList<>(); int y_offset = backGround.getOffset_y(); + int size = backGround.getSize(); String name = backGround.getKey(); HashMap chars = new HashMap<>(); - list.add(setBackgrounds(backGround.getStart(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_1(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_2(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_4(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_8(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_16(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_32(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_64(),y_offset,chars)); - list.add(setBackgrounds(backGround.getOffset_128(),y_offset,chars)); - list.add(setBackgrounds(backGround.getEnd(),y_offset,chars)); - bgCaches.put(name, chars); + list.add(setBackgrounds(backGround.getStart(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_1(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_2(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_4(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_8(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_16(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_32(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_64(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getOffset_128(),y_offset,size,chars)); + list.add(setBackgrounds(backGround.getEnd(),y_offset,size,chars)); + BACKGROUNDS.put(name, chars); return list; } - private JsonObject setBackgrounds(String name, int y_offset, HashMap chars){ + private JsonObject setBackgrounds(String name, int y_offset, int size, HashMap chars){ JsonObject jsonObject_2 = new JsonObject(); jsonObject_2.add("type", new JsonPrimitive("bitmap")); jsonObject_2.add("file", new JsonPrimitive(ConfigManager.MainConfig.namespace + ":" + ConfigManager.MainConfig.bg_folder_path.replaceAll("\\\\","/") + name.toLowerCase() + ".png")); jsonObject_2.add("ascent", new JsonPrimitive(y_offset)); - jsonObject_2.add("height", new JsonPrimitive(14)); + jsonObject_2.add("height", new JsonPrimitive(size)); JsonArray jsonArray_2 = new JsonArray(); char character = start; jsonArray_2.add(native2ascii(character)); jsonObject_2.add("chars", jsonArray_2); start = (char)(start + '\u0001'); chars.put(name, character); - try{ - FileUtils.copyFile(new File(CustomNameplates.instance.getDataFolder() + File.separator + "backgrounds" + File.separator + name + ".png"), new File(CustomNameplates.instance.getDataFolder() + File.separator + "generated" + File.separator + ConfigManager.MainConfig.namespace + File.separatorChar + "textures" + File.separator + ConfigManager.MainConfig.bg_folder_path + name + ".png")); - }catch (IOException e){ + try { + FileUtils.copyFile(new File(CustomNameplates.instance.getDataFolder() + File.separator + "backgrounds" + File.separator + name + ".png"), new File(CustomNameplates.instance.getDataFolder() + File.separator + "ResourcePack" + File.separator + ConfigManager.MainConfig.namespace + File.separatorChar + "textures" + File.separatorChar + StringUtils.replace(ConfigManager.MainConfig.bg_folder_path, "\\", String.valueOf(File.separatorChar)) + name + ".png")); + } + catch (IOException e){ e.printStackTrace(); - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to copy background png files to resource pack..."); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to copy background png files to resource pack..."); } return jsonObject_2; } diff --git a/src/main/java/net/momirealms/customnameplates/scoreboard/NameplatesTeam.java b/src/main/java/net/momirealms/customnameplates/scoreboard/NameplatesTeam.java index 1e9b15a..c6f982f 100644 --- a/src/main/java/net/momirealms/customnameplates/scoreboard/NameplatesTeam.java +++ b/src/main/java/net/momirealms/customnameplates/scoreboard/NameplatesTeam.java @@ -23,7 +23,7 @@ import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; import net.momirealms.customnameplates.data.DataManager; import net.momirealms.customnameplates.data.PlayerData; -import net.momirealms.customnameplates.font.FontCache; +import net.momirealms.customnameplates.nameplates.NameplateInstance; import net.momirealms.customnameplates.hook.PapiHook; import net.momirealms.customnameplates.hook.TABHook; import net.momirealms.customnameplates.nameplates.NameplateUtil; @@ -37,7 +37,6 @@ import java.util.Optional; public class NameplatesTeam { - private final CustomNameplates plugin; private final Player player; private final Team team; private Component prefix; @@ -45,97 +44,118 @@ public class NameplatesTeam { private String prefixText; private String suffixText; private ChatColor color; - private final String teamName; public Component getPrefix() {return this.prefix;} public Component getSuffix() {return this.suffix;} public ChatColor getColor() {return this.color;} public String getPrefixText() {return prefixText;} public String getSuffixText() {return suffixText;} - public String getTeamName() {return teamName;} - public NameplatesTeam(CustomNameplates plugin, Player player) { + public NameplatesTeam(Player player) { + this.color = ChatColor.WHITE; - this.plugin = plugin; this.player = player; + Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); - String name = player.getName(); - if (ConfigManager.MainConfig.tab){ - this.teamName = TABHook.getTABTeam(name); - this.team = Optional.ofNullable(Bukkit.getScoreboardManager().getMainScoreboard().getTeam(teamName)).orElseGet(() -> scoreboard.registerNewTeam(teamName)); - team.addEntry(player.getName()); - }else { - this.teamName = name; - this.team = Optional.ofNullable(Bukkit.getScoreboardManager().getMainScoreboard().getTeam(name)).orElseGet(() -> scoreboard.registerNewTeam(name)); - team.addEntry(player.getName()); - } + String teamName = player.getName(); + + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + + Team teamTemp = scoreboard.getTeam(teamName); + if (teamTemp == null) teamTemp = scoreboard.registerNewTeam(teamName); + + this.team = teamTemp; + this.team.addEntry(player.getName()); + + updateNameplates(); } public void updateNameplates() { - Optional playerData = Optional.ofNullable(this.plugin.getDataManager().getOrCreate(this.player.getUniqueId())); + + Optional playerData = Optional.ofNullable(CustomNameplates.instance.getDataManager().getOrCreate(this.player.getUniqueId())); String nameplate; - if (playerData.isPresent()){ - nameplate = playerData.get().getEquippedNameplate(); - }else { - nameplate = "none"; - } + + if (playerData.isPresent()) nameplate = playerData.get().getEquippedNameplate(); + else nameplate = "none"; + if (nameplate.equals("none")) { if (ConfigManager.MainConfig.placeholderAPI) { - this.prefix = MiniMessage.miniMessage().deserialize(PapiHook.parsePlaceholders(this.player, ConfigManager.MainConfig.player_prefix)); - this.suffix = MiniMessage.miniMessage().deserialize(PapiHook.parsePlaceholders(this.player, ConfigManager.MainConfig.player_suffix)); - this.prefixText = ""; - this.suffixText = ""; - } else { - this.prefix = MiniMessage.miniMessage().deserialize(ConfigManager.MainConfig.player_prefix); - this.suffix = MiniMessage.miniMessage().deserialize(ConfigManager.MainConfig.player_suffix); - this.prefixText = ""; - this.suffixText = ""; + this.prefix = MiniMessage.miniMessage().deserialize(PapiHook.parsePlaceholders(this.player, ConfigManager.Nameplate.player_prefix)); + this.suffix = MiniMessage.miniMessage().deserialize(PapiHook.parsePlaceholders(this.player, ConfigManager.Nameplate.player_suffix)); } + else { + this.prefix = MiniMessage.miniMessage().deserialize(ConfigManager.Nameplate.player_prefix); + this.suffix = MiniMessage.miniMessage().deserialize(ConfigManager.Nameplate.player_suffix); + } + this.prefixText = ""; + this.suffixText = ""; this.color = ChatColor.WHITE; - this.team.setPrefix(""); return; } - FontCache fontCache = this.plugin.getResourceManager().getNameplateInfo(nameplate); - if (fontCache == null){ + + NameplateInstance nameplateInstance = CustomNameplates.instance.getResourceManager().getNameplateInstance(nameplate); + + if (nameplateInstance == null){ this.prefix = Component.text(""); this.suffix = Component.text(""); + this.prefixText = ""; + this.suffixText = ""; this.color = ChatColor.WHITE; - this.team.setPrefix(""); DataManager.cache.get(player.getUniqueId()).equipNameplate("none"); return; } - NameplateUtil nameplateUtil = new NameplateUtil(fontCache); - String name = this.player.getName(); + String playerPrefix; String playerSuffix; + if (ConfigManager.MainConfig.placeholderAPI) { - if (!ConfigManager.MainConfig.hidePrefix){ - playerPrefix = PapiHook.parsePlaceholders(this.player, ConfigManager.MainConfig.player_prefix); - }else { - playerPrefix = ""; - } - if (!ConfigManager.MainConfig.hideSuffix){ - playerSuffix = PapiHook.parsePlaceholders(this.player, ConfigManager.MainConfig.player_suffix); - }else { - playerSuffix = ""; - } - }else { - if (!ConfigManager.MainConfig.hidePrefix){ - playerPrefix = ConfigManager.MainConfig.player_prefix; - }else { - playerPrefix = ""; - } - if (!ConfigManager.MainConfig.hideSuffix){ - playerSuffix = ConfigManager.MainConfig.player_suffix; - }else { - playerSuffix = ""; - } + if (!ConfigManager.Nameplate.hidePrefix) playerPrefix = PapiHook.parsePlaceholders(this.player, ConfigManager.Nameplate.player_prefix); + else playerPrefix = ""; + if (!ConfigManager.Nameplate.hideSuffix) playerSuffix = PapiHook.parsePlaceholders(this.player, ConfigManager.Nameplate.player_suffix); + else playerSuffix = ""; } - this.prefixText = nameplateUtil.makeCustomNameplate(MiniMessage.miniMessage().stripTags(playerPrefix), name, MiniMessage.miniMessage().stripTags(playerSuffix)); - this.suffixText = nameplateUtil.getSuffixLength(MiniMessage.miniMessage().stripTags(playerPrefix) + name + MiniMessage.miniMessage().stripTags(playerSuffix)); - this.prefix = Component.text(nameplateUtil.makeCustomNameplate(MiniMessage.miniMessage().stripTags(playerPrefix), name, MiniMessage.miniMessage().stripTags(playerSuffix))).font(ConfigManager.MainConfig.key).append(MiniMessage.miniMessage().deserialize(playerPrefix)); - this.suffix = MiniMessage.miniMessage().deserialize(playerSuffix).append(Component.text(nameplateUtil.getSuffixLength(MiniMessage.miniMessage().stripTags(playerPrefix) + name + MiniMessage.miniMessage().stripTags(playerSuffix))).font(ConfigManager.MainConfig.key)); - this.color = nameplateUtil.getColor(); - this.team.setPrefix(""); + else { + if (!ConfigManager.Nameplate.hidePrefix) playerPrefix = ConfigManager.Nameplate.player_prefix; + else playerPrefix = ""; + if (!ConfigManager.Nameplate.hideSuffix) playerSuffix = ConfigManager.Nameplate.player_suffix; + else playerSuffix = ""; + } + + String name = this.player.getName(); + + this.prefixText = NameplateUtil.makeCustomNameplate( + MiniMessage.miniMessage().stripTags(playerPrefix), + name, + MiniMessage.miniMessage().stripTags(playerSuffix), + nameplateInstance + ); + + this.suffixText = NameplateUtil.getSuffixChar( + MiniMessage.miniMessage().stripTags(playerPrefix) + + name + + MiniMessage.miniMessage().stripTags(playerSuffix) + ); + + this.prefix = Component.text( + NameplateUtil.makeCustomNameplate( + MiniMessage.miniMessage().stripTags(playerPrefix), + name, + MiniMessage.miniMessage().stripTags(playerSuffix), + nameplateInstance + ) + ) + .font(ConfigManager.MainConfig.key) + .append(MiniMessage.miniMessage().deserialize(playerPrefix)); + + this.suffix = MiniMessage.miniMessage().deserialize(playerSuffix) + .append(Component.text( + NameplateUtil.getSuffixChar( + MiniMessage.miniMessage().stripTags(playerPrefix) + + name + + MiniMessage.miniMessage().stripTags(playerSuffix)) + ) + .font(ConfigManager.MainConfig.key)); + + this.color = nameplateInstance.getConfig().getColor(); } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/scoreboard/ScoreBoardManager.java b/src/main/java/net/momirealms/customnameplates/scoreboard/ScoreBoardManager.java index efb299c..6d7cf43 100644 --- a/src/main/java/net/momirealms/customnameplates/scoreboard/ScoreBoardManager.java +++ b/src/main/java/net/momirealms/customnameplates/scoreboard/ScoreBoardManager.java @@ -18,31 +18,20 @@ package net.momirealms.customnameplates.scoreboard; import net.momirealms.customnameplates.ConfigManager; -import net.momirealms.customnameplates.CustomNameplates; import net.momirealms.customnameplates.hook.TABHook; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; -public record ScoreBoardManager(CustomNameplates plugin) { +public class ScoreBoardManager{ public static Map teams = new HashMap<>(); public NameplatesTeam getOrCreateTeam(Player player) { - if (ConfigManager.MainConfig.tab){ - String tabTeamName = TABHook.getTABTeam(player.getName()); - if (!teams.containsKey(tabTeamName)) { - teams.put(tabTeamName, new NameplatesTeam(this.plugin, player)); - } - teams.get(tabTeamName).updateNameplates(); - return teams.get(tabTeamName); - } else { - if (!teams.containsKey(player.getName())) { - teams.put(player.getName(), new NameplatesTeam(this.plugin, player)); - } - teams.get(player.getName()).updateNameplates(); - return teams.get(player.getName()); - } + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + if (!teams.containsKey(teamName)) teams.put(teamName, new NameplatesTeam(player)); + return teams.get(teamName); } } diff --git a/src/main/java/net/momirealms/customnameplates/scoreboard/TeamInfo.java b/src/main/java/net/momirealms/customnameplates/scoreboard/TeamInfo.java new file mode 100644 index 0000000..c3d9523 --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/scoreboard/TeamInfo.java @@ -0,0 +1,27 @@ +package net.momirealms.customnameplates.scoreboard; + +import java.util.Objects; + +public class TeamInfo { + + private final String prefix; + private final String suffix; + + public TeamInfo(String prefix, String suffix) { + this.prefix = prefix; + this.suffix = suffix; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TeamInfo teamInfo = (TeamInfo) o; + return Objects.equals(prefix, teamInfo.prefix) && Objects.equals(suffix, teamInfo.suffix); + } + + @Override + public int hashCode() { + return Objects.hash(prefix, suffix); + } +} diff --git a/src/main/java/net/momirealms/customnameplates/AdventureManager.java b/src/main/java/net/momirealms/customnameplates/utils/AdventureUtil.java similarity index 94% rename from src/main/java/net/momirealms/customnameplates/AdventureManager.java rename to src/main/java/net/momirealms/customnameplates/utils/AdventureUtil.java index 435d17d..065d8e0 100644 --- a/src/main/java/net/momirealms/customnameplates/AdventureManager.java +++ b/src/main/java/net/momirealms/customnameplates/utils/AdventureUtil.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customnameplates; +package net.momirealms.customnameplates.utils; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; @@ -23,12 +23,13 @@ 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.customnameplates.CustomNameplates; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.time.Duration; -public class AdventureManager { +public class AdventureUtil { public static void consoleMessage(String s) { Audience au = CustomNameplates.adventure.sender(Bukkit.getConsoleSender()); diff --git a/src/main/java/net/momirealms/customnameplates/utils/ArmorStandPacketUtil.java b/src/main/java/net/momirealms/customnameplates/utils/ArmorStandPacketUtil.java new file mode 100644 index 0000000..7add5fc --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/utils/ArmorStandPacketUtil.java @@ -0,0 +1,232 @@ +package net.momirealms.customnameplates.utils; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.momirealms.customnameplates.ConfigManager; +import net.momirealms.customnameplates.CustomNameplates; +import net.momirealms.customnameplates.data.DataManager; +import net.momirealms.customnameplates.data.PlayerData; +import net.momirealms.customnameplates.hook.PapiHook; +import net.momirealms.customnameplates.objects.ASInfo; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class ArmorStandPacketUtil { + + public static ConcurrentHashMap> cache = new ConcurrentHashMap<>(); + public static ConcurrentHashMap player2ids = new ConcurrentHashMap<>(); + public static ConcurrentHashMap id2ids = new ConcurrentHashMap<>(); + public static ConcurrentHashMap> taskCache = new ConcurrentHashMap<>(); + + public static void preparePackets(Player player) { + + int size = ConfigManager.Nameplate.texts.size(); + int[] ids = new int[size]; + List asInfos = new ArrayList<>(); + + for (int i = 0; i < size; i++) { + + PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); + + int id = new Random().nextInt(1000000000); + ids[i] = id; + + String text = ConfigManager.Nameplate.texts.get(i); + entityPacket.getModifier().write(0, id); + entityPacket.getModifier().write(1, UUID.randomUUID()); + entityPacket.getEntityTypeModifier().write(0, EntityType.ARMOR_STAND); + Location location = player.getLocation(); + entityPacket.getDoubles().write(0, location.getX()); + entityPacket.getDoubles().write(1, location.getY()); + entityPacket.getDoubles().write(2, location.getZ()); + + PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + + ASInfo asInfo = new ASInfo(id, text, entityPacket, metaPacket); + + if (ConfigManager.MainConfig.placeholderAPI) text = PapiHook.parsePlaceholders(player, text); + + metaPacket.getModifier().write(0, id); + 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(0, serializer2), (byte) 0x20); + if (ConfigManager.Nameplate.smallSize) { + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), (byte) 0x01); + } + metaPacket.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); + + asInfos.add(asInfo); + } + + cache.put(player.getEntityId(), asInfos); + player2ids.put(player, ids); + id2ids.put(player.getEntityId(), ids); + } + + public static void sendPreviewToOne(Player player) { + List asInfos = cache.get(player.getEntityId()); + if (asInfos != null) { + PacketContainer ridingPacket = new PacketContainer(PacketType.Play.Server.MOUNT); + ridingPacket.getModifier().write(0, player.getEntityId()); + ridingPacket.getModifier().write(1, player2ids.get(player)); + Location location = player.getLocation(); + for (ASInfo asInfo : asInfos) { + PacketContainer entityPacket = asInfo.getEntityPacket(); + entityPacket.getDoubles().write(0, location.getX()); + entityPacket.getDoubles().write(1, location.getY() + 1.45); + entityPacket.getDoubles().write(2, location.getZ()); + PacketContainer metaPacket = asInfo.getMetaPacket().deepClone(); + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, entityPacket); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, ridingPacket); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + sendUpdateOneToOne(player, player); + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomNameplates.instance, () -> { + sendDestroyToOne(player, player2ids.get(player)); + }, ConfigManager.Nameplate.preview * 20); + } + } + } + + public static void sendSummonOneToOne(Player player, Player otherPlayer) { + List asInfos = cache.get(otherPlayer.getEntityId()); + if (asInfos != null) { + PacketContainer ridingPacket = new PacketContainer(PacketType.Play.Server.MOUNT); + ridingPacket.getModifier().write(0, otherPlayer.getEntityId()); + ridingPacket.getModifier().write(1, player2ids.get(otherPlayer)); + Location location = otherPlayer.getLocation(); + + boolean canSee = false; + if (ConfigManager.Nameplate.show_after) { + PlayerData playerData = DataManager.cache.get(player.getUniqueId()); + if (playerData == null) { + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomNameplates.instance, () -> { + sendSummonOneToOne(player, otherPlayer); + }, 20); + return; + } else if (playerData.getAccepted() == 1) { + canSee = true; + } + } else { + canSee = true; + } + + for (ASInfo asInfo : asInfos) { + PacketContainer entityPacket = asInfo.getEntityPacket(); + entityPacket.getDoubles().write(0, location.getX()); + entityPacket.getDoubles().write(1, location.getY() + 1.45); + entityPacket.getDoubles().write(2, location.getZ()); + PacketContainer metaPacket = asInfo.getMetaPacket().deepClone(); + if (!canSee) { + 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); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), (byte) 0x20); + metaPacket.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); + } + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, entityPacket); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, ridingPacket); + } catch (Exception e) { + e.printStackTrace(); + } + } + } else { + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomNameplates.instance, () -> { + sendSummonOneToOne(player, otherPlayer); + }, 20); + } + } + + //将左侧玩家的信息发送给右侧的 + public static void sendUpdateOneToOne(Player player, Player otherPlayer) { + List asInfos = cache.get(player.getEntityId()); + if (asInfos == null) return; + for (ASInfo asInfo : asInfos) { + PacketContainer metaPacket = asInfo.getMetaPacket().deepClone(); + String origin = asInfo.getText(); + if (ConfigManager.MainConfig.placeholderAPI) origin = PapiHook.parsePlaceholders(player, origin); + WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher(); + WrappedDataWatcher.Serializer serializer2 = WrappedDataWatcher.Registry.get(Byte.class); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), (byte) 0x20); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), Optional.of(WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(origin))).getHandle())); + if (ConfigManager.Nameplate.smallSize) { + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), (byte) 0x01); + } + metaPacket.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(otherPlayer, metaPacket); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public static void forceUpdateOneToOne(int id, Player player) { + List asInfos = cache.get(id); + if (asInfos == null) return; + for (ASInfo asInfo : asInfos) { + PacketContainer metaPacket = asInfo.getMetaPacket().deepClone(); + boolean canSee = false; + if (ConfigManager.Nameplate.show_after) { + PlayerData playerData = DataManager.cache.get(player.getUniqueId()); + if (playerData == null) { + return; + } else if (playerData.getAccepted() == 1) { + canSee = true; + } + } else { + canSee = true; + } + 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), canSee); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), (byte) 0x20); + if (ConfigManager.Nameplate.smallSize) { + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), (byte) 0x01); + } + metaPacket.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, metaPacket); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public static void sendDestroyToOne(Player player, int[] entities) { + List idList = new ArrayList<>(); + for (int id : entities) { + idList.add(id); + } + try { + PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); + destroyPacket.getIntLists().write(0, idList); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customnameplates/utils/UpdateConfig.java b/src/main/java/net/momirealms/customnameplates/utils/ConfigUtil.java similarity index 97% rename from src/main/java/net/momirealms/customnameplates/utils/UpdateConfig.java rename to src/main/java/net/momirealms/customnameplates/utils/ConfigUtil.java index 29f7f44..fc86550 100644 --- a/src/main/java/net/momirealms/customnameplates/utils/UpdateConfig.java +++ b/src/main/java/net/momirealms/customnameplates/utils/ConfigUtil.java @@ -12,7 +12,7 @@ import net.momirealms.customnameplates.helper.Log; import java.io.File; import java.io.IOException; -public class UpdateConfig { +public class ConfigUtil { public static void update(){ try { diff --git a/src/main/java/net/momirealms/customnameplates/utils/HoloUtil.java b/src/main/java/net/momirealms/customnameplates/utils/HoloUtil.java new file mode 100644 index 0000000..b2f61df --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/utils/HoloUtil.java @@ -0,0 +1,121 @@ +/* + * Copyright (C) <2022> + * + * 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 . + */ + +package net.momirealms.customnameplates.utils; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.momirealms.customnameplates.CustomNameplates; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +import java.util.*; + +public class HoloUtil { + + public static HashMap cache = new HashMap<>(); + + public static void showHolo(Component component, Player player, int duration){ + + if (cache.get(player) != null){ + removeHolo(player, cache.get(player)); + } + + PacketContainer packet1 = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); + + int id = new Random().nextInt(1000000000); + packet1.getModifier().write(0, id); + packet1.getModifier().write(1, UUID.randomUUID()); + packet1.getEntityTypeModifier().write(0, EntityType.ARMOR_STAND); + Location location = player.getLocation(); + packet1.getDoubles().write(0, location.getX()); + packet1.getDoubles().write(1, location.getY()+0.8); + packet1.getDoubles().write(2, location.getZ()); + + PacketContainer packet2 = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + + 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(component)).getHandle())); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer1), true); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(5, serializer1), true); + byte mask1 = 0x20; + byte mask2 = 0x01; + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), mask1); + wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), mask2); + packet2.getModifier().write(0,id); + packet2.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); + cache.put(player, id); + + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet1); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet2); + } + catch (Exception e) { + AdventureUtil.consoleMessage("[CustomNameplates] 无法为玩家 "+ player.getName()+" 展示悬浮信息!"); + e.printStackTrace(); + } + + for (int i = 1; i < duration * 20 - 1; i++){ + Bukkit.getScheduler().runTaskLater(CustomNameplates.instance, ()->{ + updatePlace(player, id); + }, i); + } + + Bukkit.getScheduler().runTaskLater(CustomNameplates.instance, ()->{ + removeHolo(player, id); + cache.remove(location); + }, duration * 20L); + } + + public static void updatePlace(Player player, int entityId){ + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT); + packet.getIntegers().write(0, entityId); + Location location = player.getLocation(); + packet.getDoubles().write(0, location.getX()); + packet.getDoubles().write(1, location.getY()+0.8); + packet.getDoubles().write(2, location.getZ()); + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + } + catch (Exception e) { + AdventureUtil.consoleMessage("[CustomNameplates] 无法为玩家 "+ player.getName()+" 更新悬浮信息!"); + e.printStackTrace(); + } + } + + public static void removeHolo(Player player, int entityId){ + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); + packet.getIntLists().write(0, List.of(entityId)); + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + } + catch (Exception e) { + AdventureUtil.consoleMessage("[CustomNameplates] 无法为玩家 "+ player.getName()+" 移除悬浮信息!"); + e.printStackTrace(); + } + } +} diff --git a/src/main/java/net/momirealms/customnameplates/utils/SqlConnection.java b/src/main/java/net/momirealms/customnameplates/utils/SqlConnection.java index 2516b0b..ab3ab51 100644 --- a/src/main/java/net/momirealms/customnameplates/utils/SqlConnection.java +++ b/src/main/java/net/momirealms/customnameplates/utils/SqlConnection.java @@ -18,7 +18,6 @@ package net.momirealms.customnameplates.utils; import com.zaxxer.hikari.HikariDataSource; -import net.momirealms.customnameplates.AdventureManager; import net.momirealms.customnameplates.ConfigManager; import net.momirealms.customnameplates.CustomNameplates; @@ -98,18 +97,18 @@ public class SqlConnection { } } if (secon) { - AdventureManager.consoleMessage("[CustomNameplates] Successfully reconnect to SQL!"); + AdventureUtil.consoleMessage("[CustomNameplates] Successfully reconnect to SQL!"); } else { secon = true; } return true; } catch (SQLException e) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to connect to SQL!"); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to connect to SQL!"); e.printStackTrace(); close(); return false; } catch (ClassNotFoundException e) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to load JDBC driver"); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to load JDBC driver"); } return false; } @@ -127,7 +126,7 @@ public class SqlConnection { return getConnectionAndCheck(); } else { isfirstry = true; - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to connect to SQL!"); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to connect to SQL!"); close(); e.printStackTrace(); return null; @@ -194,7 +193,7 @@ public class SqlConnection { hikari.close(); } } catch (SQLException e) { - AdventureManager.consoleMessage("[CustomNameplates] Error! Failed to close SQL!"); + AdventureUtil.consoleMessage("[CustomNameplates] Error! Failed to close SQL!"); e.printStackTrace(); } } diff --git a/src/main/java/net/momirealms/customnameplates/utils/TeamPacketUtil.java b/src/main/java/net/momirealms/customnameplates/utils/TeamPacketUtil.java new file mode 100644 index 0000000..2c1f640 --- /dev/null +++ b/src/main/java/net/momirealms/customnameplates/utils/TeamPacketUtil.java @@ -0,0 +1,125 @@ +package net.momirealms.customnameplates.utils; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.InternalStructure; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.utility.MinecraftReflection; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.momirealms.customnameplates.ConfigManager; +import net.momirealms.customnameplates.CustomNameplates; +import net.momirealms.customnameplates.data.DataManager; +import net.momirealms.customnameplates.data.PlayerData; +import net.momirealms.customnameplates.hook.TABHook; +import net.momirealms.customnameplates.scoreboard.NameplatesTeam; +import net.momirealms.customnameplates.scoreboard.ScoreBoardManager; +import net.momirealms.customnameplates.scoreboard.TeamInfo; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Optional; + +public class TeamPacketUtil { + + public static HashMap teamInfoCache = new HashMap<>(); + + public static void sendUpdateToOne(Player player) { + boolean accepted = DataManager.cache.get(player.getUniqueId()).getAccepted() == 1; + for (Player otherPlayer : Bukkit.getOnlinePlayers()) { + if (player == otherPlayer) return; + PacketContainer packet = new PacketContainer(PacketType.Play.Server.SCOREBOARD_TEAM); + packet.getIntegers().write(0,2); + String teamName = otherPlayer.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + packet.getStrings().write(0, teamName); + NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); + if (nameplatesTeam != null) { + Optional optional = packet.getOptionalStructures().read(0); + if (optional.isPresent()) { + InternalStructure internalStructure = optional.get(); + if (ConfigManager.Nameplate.show_after && !accepted) { + internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson("{\"text\":\"\"}")); + internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson("{\"text\":\"\"}")); + internalStructure.getStrings().write(0, "always"); + internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,ChatColor.WHITE); + } + else { + if (ConfigManager.Nameplate.removeTag) { + internalStructure.getStrings().write(0, "never"); + } + else { + internalStructure.getStrings().write(0, "always"); + } + internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getPrefix()))); + internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getSuffix()))); + internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,nameplatesTeam.getColor()); + } + try { + CustomNameplates.protocolManager.sendServerPacket(player, packet); + } + catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } + } + + public static void sendUpdateToAll(Player player) { + String teamName = player.getName(); + if (ConfigManager.MainConfig.tab) teamName = TABHook.getTABTeam(teamName); + NameplatesTeam nameplatesTeam = ScoreBoardManager.teams.get(teamName); + TeamInfo newInfo = new TeamInfo(nameplatesTeam.getPrefixText(), nameplatesTeam.getSuffixText()); + TeamInfo oldInfo = teamInfoCache.put(player, newInfo); + if (oldInfo == null || !oldInfo.equals(newInfo)) { + for (Player otherPlayer : Bukkit.getOnlinePlayers()) { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.SCOREBOARD_TEAM); + packet.getStrings().write(0, teamName); + packet.getIntegers().write(0,2); + Optional optional = packet.getOptionalStructures().read(0); + if (optional.isPresent()) { + InternalStructure internalStructure = optional.get(); + + if (ConfigManager.Nameplate.show_after) { + PlayerData playerData = DataManager.cache.get(otherPlayer.getUniqueId()); + if (playerData == null || playerData.getAccepted() == 0) { + internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson("{\"text\":\"\"}")); + internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson("{\"text\":\"\"}")); + internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,ChatColor.WHITE); + } + else { + if (ConfigManager.Nameplate.removeTag) { + internalStructure.getStrings().write(0, "never"); + } + else { + internalStructure.getStrings().write(0, "always"); + internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getPrefix()))); + internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getSuffix()))); + internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,nameplatesTeam.getColor()); + } + } + } + else { + if (ConfigManager.Nameplate.removeTag) { + internalStructure.getStrings().write(0, "never"); + } + else { + internalStructure.getStrings().write(0, "always"); + internalStructure.getChatComponents().write(1, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getPrefix()))); + internalStructure.getChatComponents().write(2, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(nameplatesTeam.getSuffix()))); + internalStructure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0,nameplatesTeam.getColor()); + } + } + } + try { + CustomNameplates.protocolManager.sendServerPacket(otherPlayer, packet); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/main/resources/module.yml b/src/main/resources/MODULES.yml similarity index 82% rename from src/main/resources/module.yml rename to src/main/resources/MODULES.yml index 6d29f54..687176d 100644 --- a/src/main/resources/module.yml +++ b/src/main/resources/MODULES.yml @@ -2,4 +2,4 @@ nameplate: true background: true bossbar: true -actionbar: true \ No newline at end of file +actionbar: false \ No newline at end of file diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/note.txt b/src/main/resources/ResourcePack/minecraft/shaders/core/note.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.fsh b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.fsh new file mode 100644 index 0000000..ae6039d --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.fsh @@ -0,0 +1,3 @@ +#version 150 +#moj_import +uniform sampler2D Sampler0;uniform vec4 ColorModulator;uniform float FogStart,FogEnd;uniform vec4 FogColor;in float vertexDistance;flat in vec4 vertexColor;in vec2 texCoord0;out vec4 fragColor;void main(){vec4 v=texture(Sampler0,texCoord0)*vertexColor*ColorModulator;if(v.a<.1){discard;}fragColor=linear_fog(v,vertexDistance,FogStart,FogEnd,FogColor);} \ No newline at end of file diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.json b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.json new file mode 100644 index 0000000..196210a --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.json @@ -0,0 +1,117 @@ +{ + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text", + "fragment": "rendertype_text", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2" + ], + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1, + 1, + 1, + 1 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0, + 0, + 0, + 0 + ] + }, + { + "name": "GameTime", + "type": "float", + "count": 1, + "values": [ + 0 + ] + } + ] +} \ No newline at end of file diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.vsh b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.vsh new file mode 100644 index 0000000..53cbf34 --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text.vsh @@ -0,0 +1,87 @@ +#version 150 +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV2; + +uniform sampler2D Sampler0,Sampler2; +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform float GameTime; + +out float vertexDistance; +flat out vec4 vertexColor; +out vec2 texCoord0; + +void main(){ + vec4 vertex=vec4(Position, 1.0); + if(Color.xyz==vec3(255., 255., 254.)/ 255.){ + //Rainbow + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=((.6+.6*cos(6.*(gl_Position.x+GameTime*1000.)+vec4(0, 23, 21, 1)))+vec4(0., 0., 0., 1.))*texelFetch(Sampler2, UV2 / 16, 0)); + }else if(Color.xyz==vec3(255., 255., 253.)/ 255.){ + //Shake + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)); + (gl_Position.y=gl_Position.y+sin(GameTime*12000.+(gl_Position.x*6))/ 150.); + }else if(Color.xyz==vec3(255., 255., 252.)/ 255.){ + //Rainbow shake + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=((.6+.6*cos(6.*(gl_Position.x+GameTime*1000.)+vec4(0, 23, 21, 1)))+vec4(0., 0., 0., 1.))*texelFetch(Sampler2, UV2 / 16, 0)); + (gl_Position.y=gl_Position.y+sin(GameTime*12000.+(gl_Position.x*6))/ 150.); + }else if(Color.xyz==vec3(255., 255., 251.)/ 255.){ + //Jump + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)); + float vertexId = mod(gl_VertexID, 4.0); + if(vertex.z <= 0.){ + if(vertexId==3.||vertexId==0.)vertex.y += cos(GameTime*12000. / 4)*0.1; + vertex.y += max(cos(GameTime*12000. / 4)*0.1, 0.); + }else{ + if(vertexId==3.||vertexId==0.)vertex.y-=cos(GameTime*12000. / 4)*3; + vertex.y-=max(cos(GameTime*12000. / 4)*4, 0.); + } + (gl_Position=ProjMat*ModelViewMat*vertex); + }else if(Color.xyz==vec3(255., 254., 254.)/ 255.){ + //Rainbow jump + float vertexId = mod(gl_VertexID, 4.0); + if(vertex.z <= 0.){ + if(vertexId==3.||vertexId==0.)vertex.y += cos(GameTime*12000. / 4)*0.1; + vertex.y += max(cos(GameTime*12000. / 4)*0.1, 0.); + }else{ + if(vertexId==3.||vertexId==0.)vertex.y-=cos(GameTime*12000. / 4)*3; + vertex.y-=max(cos(GameTime*12000. / 4)*4, 0.); + } + (vertexColor=((.6+.6*cos(6.*(gl_Position.x+GameTime*1000.)+vec4(0, 23, 21, 1)))+vec4(0., 0., 0., 1.))*texelFetch(Sampler2, UV2 / 16, 0)); + (gl_Position=ProjMat*ModelViewMat*vertex); + }else if(Color.xyz==vec3(255., 254., 253.)/ 255.){ + //Remove shadow + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)); + vertex.y+= 1; + vertex.x+= 1; + (gl_Position=ProjMat*ModelViewMat*vertex); + }else if(Color.xyz==vec3(255., 254., 250.)/ 255.){ + //Shake2 + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)); + (gl_Position.x=gl_Position.x+sin(GameTime*12000.+(gl_Position.y*6))/ 150.); + }else if(Color.xyz==vec3(255., 254., 251.)/ 255.){ + //Light + (gl_Position=ProjMat*ModelViewMat*vertex); + if (sin(GameTime*1000) > 0){ + vertexColor=((sin(GameTime*1000)))*texelFetch(Sampler2, UV2 / 16, 0); + }else{ + vertexColor=((-sin(GameTime*1000)))*texelFetch(Sampler2, UV2 / 16, 0); + } + }else if(Color.xyz==vec3(255., 254., 252.)/ 255.){ + //Remove + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)*(-1)); + } + else{ + //Default + (gl_Position=ProjMat*ModelViewMat*vertex); + (vertexColor=Color*texelFetch(Sampler2, UV2 / 16, 0)); + } + vertexDistance=length((ModelViewMat*vertex).xyz); + texCoord0=UV0; +} \ No newline at end of file diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.fsh b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.fsh new file mode 100644 index 0000000..bc1df4c --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.fsh @@ -0,0 +1,20 @@ +#version 150 + +uniform sampler2D Sampler0; +uniform sampler2D Sampler2; + +uniform vec4 ColorModulator; + +in vec4 vertexColor; +in vec2 texCoord0; +in vec2 texCoord2; + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0) * vertexColor; + if (color.a < 0.1) { + discard; + } + fragColor = vec4(0.0,0.0,0.0,0.0); +} \ No newline at end of file diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.json b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.json new file mode 100644 index 0000000..8b8e531 --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.json @@ -0,0 +1,22 @@ +{ + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_see_through", + "fragment": "rendertype_text_see_through", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { "name": "Sampler0" } + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ] +} diff --git a/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.vsh b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.vsh new file mode 100644 index 0000000..44e105d --- /dev/null +++ b/src/main/resources/ResourcePack/minecraft/shaders/core/rendertype_text_see_through.vsh @@ -0,0 +1,18 @@ +#version 150 + +in vec3 Position; +in vec4 Color; +in vec2 UV0; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; + +out vec4 vertexColor; +out vec2 texCoord0; + +void main() { + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + vertexColor = Color; + texCoord0 = UV0; +} diff --git a/src/main/resources/background.yml b/src/main/resources/background.yml index 2a15401..9144eab 100644 --- a/src/main/resources/background.yml +++ b/src/main/resources/background.yml @@ -1,5 +1,6 @@ background: bedrock_1: + size: 14 x-offset: 5 y-offset: 7 start: b0 @@ -13,8 +14,23 @@ background: offset_128: b128 end: b0 bedrock_2: + size: 14 x-offset: 5 - y-offset: 10 + y-offset: 9 + start: b0 + offset_1: b1 + offset_2: b2 + offset_4: b4 + offset_8: b8 + offset_16: b16 + offset_32: b32 + offset_64: b64 + offset_128: b128 + end: b0 + bedrock_3: + size: 14 + x-offset: 5 + y-offset: -7 start: b0 offset_1: b1 offset_2: b2 diff --git a/src/main/resources/bossbar.yml b/src/main/resources/bossbar.yml index 41c5591..981105e 100644 --- a/src/main/resources/bossbar.yml +++ b/src/main/resources/bossbar.yml @@ -3,13 +3,12 @@ # IMPORTANT NOTICE # mode: Adventure / ProtocolLib # There's a bug that font can't be applied to Adventure bossbar. This is an Adventure API bug that I can't fix for the moment. -# So I made the ProtocolLib mode and I will remove ProtocolLib mode when Adventure API is fixed! # It requires a restart to change mode mode: ProtocolLib bossbar: example_1: - text: '%nameplates_bg_player%Hello! %player_name% %nameplates_bg_pos%You are now at: %player_x%, %player_y%, %player_z%' + text: '%nameplates_bg_player%Hello! %player_name% %nameplates_bg_pos%You are now at: %player_x%, %player_y%, %player_z%' refresh-rate: 5 # PINK # YELLOW @@ -26,19 +25,7 @@ bossbar: # NOTCHED_20 overlay: PROGRESS example_2: - text: 'Another BossBar' + text: '%nameplates_bg_text%Thanks for your purchase!' refresh-rate: 5 - # PINK - # YELLOW - # WHITE - # RED - # PURPLE - # GREEN - # BLUE - color: RED - # PROGRESS - # NOTCHED_6 - # NOTCHED_10 - # NOTCHED_12 - # NOTCHED_20 - overlay: NOTCHED_10 \ No newline at end of file + color: YELLOW + overlay: PROGRESS \ No newline at end of file diff --git a/src/main/resources/char-width.yml b/src/main/resources/char-width.yml index d3b1c9e..2a19a5a 100644 --- a/src/main/resources/char-width.yml +++ b/src/main/resources/char-width.yml @@ -1,6 +1,5 @@ # Font is processed by client # Server side doesn't know the width of you custom font # So you can tell the plugin each character's width here -小: 8 -默: 8 -米: 8 \ No newline at end of file + +♥: 5 \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 15987b1..15743ea 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,5 +1,5 @@ # don't change -config-version: 1 +config-version: '2' config: # Language @@ -29,13 +29,16 @@ config: font: "default" # Another ascii font with y offset - another-ascii-font: + ascii-y-offset: enable: true - y-offset: 3 + offset: + - 3 + - 5 + - -11 + - -24 # Customize the folder where png files should be generated. # This is useful for those who want to keep their resource pack structure in order. - # if you are using Linux, use / instead nameplate-folder-path: 'font\nameplates\' background-folder-path: 'font\backgrounds\' space-split-folder-path: 'font\' @@ -45,33 +48,13 @@ config: # You can specify any Unicode Character as you want. start-char: '뀁' - # The duration (in seconds) that the nameplate preview will last for. - preview-duration: 5 - - # The default nameplate. - # "none" represents no default nameplate. - default-nameplate: 'none' - - # Recommended to keep this true, otherwise players may see weird characters - # above their heads if they have not accepted the resource pack. - # This option supports proxy when using Mysql - show-after-load-resourcepack: true - - # Placeholder based prefix and suffix system. When enabled, it is recommended - # to use PlaceholderAPI to be able to use this feature to the fullest extent. - # keep it empty if you don't want to enable this feature. - # You should make sure the papi doesn't contain "&" (legacy color code) - # Nameplates work on the custom font system where legacy color code is not supported! - # Please use minimessage format: https://docs.adventure.kyori.net/minimessage/format.html - prefix: 'Hello! ' - suffix: '' - - # should prefix/suffix be hidden when player is equipping a nameplate - hide-prefix-when-equipped: false - hide-suffix-when-equipped: false - # Thin-font support use-thin-font: false - # Extract default shader to plugin folder + # For ItemsAdder users: + # You need to override assets/minecraft/shaders/core/rendertype_text.vsh in the generated pack to apply this shader + # For Oraxen users: + # extract the shaders to Oraxen/pack/shaders/core + # + #The shader identify text by colors. You need to add to the text you want to apply this shader extract-shader: true \ No newline at end of file diff --git a/src/main/resources/custom-papi.yml b/src/main/resources/custom-papi.yml index 7a51108..4828bca 100644 --- a/src/main/resources/custom-papi.yml +++ b/src/main/resources/custom-papi.yml @@ -16,6 +16,12 @@ papi: text: text: 'Thanks for your purchase!' background: bedrock_2 + health: + text: '%player_health_rounded% Health' + background: bedrock_3 + food: + text: '%player_food_level% Hunger' + background: bedrock_3 #This papi will not return text with nameplate #It will only return the nameplate diff --git a/src/main/resources/messages/messages_cn.yml b/src/main/resources/messages/messages_cn.yml index ee87b6b..263d9a7 100644 --- a/src/main/resources/messages/messages_cn.yml +++ b/src/main/resources/messages/messages_cn.yml @@ -14,4 +14,5 @@ messages: not-available: '你还未拥有这个铭牌!' available: '可用铭牌: {Nameplates}' cooldown: '上一个预览还没结束!' - generate: '正在生成资源包...' \ No newline at end of file + generate: '正在生成资源包...' + no-nameplate: '无铭牌' \ No newline at end of file diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml index a53aa50..3ea1f67 100644 --- a/src/main/resources/messages/messages_en.yml +++ b/src/main/resources/messages/messages_en.yml @@ -14,4 +14,5 @@ messages: not-available: 'This nameplate is currently not available!' available: 'Available nameplates: {Nameplates}.' cooldown: 'Previewing is still Ongoing!' - generate: 'Resource Pack is generating..' \ No newline at end of file + generate: 'Resource Pack is generating..' + no-nameplate: 'No Nameplate' \ No newline at end of file diff --git a/src/main/resources/messages/messages_es.yml b/src/main/resources/messages/messages_es.yml index bcdee67..a4cefe2 100644 --- a/src/main/resources/messages/messages_es.yml +++ b/src/main/resources/messages/messages_es.yml @@ -13,4 +13,5 @@ messages: no-console: 'Este comando sólo puede ser ejecutado por el jugador.' not-available: 'Esta placa no está disponible actualmente.' available: 'Nameplates disponibles: {Nameplates}.' - cooldown: '¡El preestreno sigue en curso!' \ No newline at end of file + cooldown: '¡El preestreno sigue en curso!' + no-nameplate: 'No Nameplate' \ No newline at end of file diff --git a/src/main/resources/nameplate.yml b/src/main/resources/nameplate.yml new file mode 100644 index 0000000..b46e376 --- /dev/null +++ b/src/main/resources/nameplate.yml @@ -0,0 +1,75 @@ +nameplate: + # mode: Team / Entity + # ================ Team =================== + # Team is based on vanilla mechanic team + # Advantage: + # No lag + # + # Disadvantage: + # Player name's colors are limited + # Only support one-line text + # May exist conflict with other plugins that use team + # + # ================ Entity ================ + # Plugin would summon fake armorstands packets riding the player + # Advantage: + # No lag (The principle is different from TAB) + # Support multiple lines (based on resource pack side tech) + # + # Disadvantage: + # May not compatible with some cosmetics plugins + # (requires a restart) + mode: Team + + update: + # Nameplates will be updated every x ticks + # If your nameplate content is static, it's better to disable updating for better performance + enable: true + ticks: 20 + + # The duration (in seconds) that the nameplate preview will last for. + preview-duration: 5 + + # The default nameplate. + # "none" represents no default nameplate. + default-nameplate: 'none' + + # Recommended to keep this true, otherwise players may see weird characters + # above their heads if they have not accepted the resource pack. + # This option supports proxy when using Mysql + # If you meet problem with this, set it to false to always display nameplates + show-after-load-resourcepack: true + + # These option only works when using mode team + team: + # Team mode only supports one line, so it is using a prefix/suffix system to extend the player name info + + # Placeholder based prefix and suffix system. When enabled, it is recommended + # to use PlaceholderAPI to be able to use this feature to the fullest extent. + # keep it empty if you don't want to enable this feature. + # You should make sure the papi doesn't contain "&" (legacy color code) + # Nameplates work on the custom font system where legacy color code is not supported! + # Please use minimessage format: https://docs.adventure.kyori.net/minimessage/format.html + prefix: 'Hello! ' + suffix: ' %player_health_rounded%♥' + + # should prefix/suffix be hidden when player is equipping a nameplate + hide-prefix-when-equipped: false + hide-suffix-when-equipped: false + + # These option only works when using mode entity + entity: + # If you are having trouble with plugin conflict + # Set this to "true" might help (let other plugin handle armor_stand mounting) (requires a restart) + # MagicCosmetics has been tested, and it proves to work well + try-to-hook-cosmetics-plugin: false + # Remove player original name-tag (requires Vanilla Team) + # If you have another plugin that is using team please disable team management in that plugin or turn player's name off in that plugin + remove-nametag: true + # If it is the normal size, more lines can be displayed but it would go obviously abnormal when you look at it in a certain angle + small-size: true + # nameplates content + text: + - '%nameplates_prefix%%player_name%%nameplates_suffix%' + - '%nameplates_bg_health%%player_health_rounded% Health %nameplates_bg_food%<#F0E68C>%player_food_level% Hunger' + - 'Multiple lines are supported!' \ No newline at end of file diff --git a/src/main/resources/nameplates/cat.png b/src/main/resources/nameplates/cat.png new file mode 100644 index 0000000000000000000000000000000000000000..87268888e24e988ad736d9cb87bdfb3e16a17690 GIT binary patch literal 812 zcmV+{1JnG8P)(5!f$gkRAl4b!-ZgAg-{O z*ic!FTCjdV<=x~7%>4>d&jgmh3?MOEKyX9ljHwmqGFU8FRhc43P?&1K^Z~&=M!!_n z-XL%&ahb3{qV1QWr62S6ZA6QOwt(Q)1Sp;a1X%v7XL`Xf`663@YZ~G{y0*qsNdyJ~ z7EOeYIY0c^KM4|#0(Gx~)R6maTGG>DJ_KiezQFyVz|p@cpfpU(uM#cGhk%Cgf1FAb zp`t89MQqt`{Tu52I|MY4=uzNB(Eb!OUGW1UUf|KVLb*rk5bySa?!D-v!M{lPCP)C6 qPr2nYJt+>CA8G6p(TQLF7GMBun>h-hk%nym0000DSr z1<%~X^wgl##FWaylc_d9MF{~uA+9?YR32H~c6e#^_Sq$iD?N%mC0EU8?d|D0y|H`k zs^u59^p>UjE?PKm&zh;za~)7G`Y2Z_KUNtmUUJv3U@kp=5$j- zjsLpyTW031m|VJXQoOK;`2YX^Ia%sLL9Qza@(TuX@d1XI80ohR3`};OE{-7;x3)}s zUG!Lir`51yh6B^HYg-OZ_+Ee7>&V+Bx97ggJEJ98{pWd2M{ ylBhR%dc~5HvWDa zP`W|!ul|9X*MxeuysUIOylboU-|e@*buffEr5-xALu20j_^j%XcU$@rCUc8cXa*iz z5%g>~!~EPkf>-#2MHh4=EskmM{aJbF`6qcz4u`*5VtI>u*J#Y$e2e=>RboK)#zTu( zuXTDppK|4fNT>z_<8}GP$vRKxd`;9?;J|8fz$!}-S}R;Hw_j9WFA7KWn7#(uSrtfq z_Yh7}U$FJ9lbp+hjnxd>3fwJyBcB&)PEygY=DudMuz8W(7YBw{)&6ofG{PD`3E$uB zdY?f~z2V8prve|Y1WPRaV#N1AX=O714W=E3xQ-XfRYVzBwbtn0TJoSGXwR&P3>>MS z?y}05b$f2ww6%~$jPZVYOtz_PSb<=I=~;7ofeXt=n{%&v>+K6w;t34L{9No)Ub`FyraA^sS3j3^P6DSr z1<%~X^wgl##FWaylc_d9MF{~uA+G-ysC@eL_x~j6|7#8Z&rtaH```bSy1#z?{=Y)= z|56Qg7DgFq=|6w|egFRN|CdMq|NsB-+g7*cWT z&9v7=%?bjoom^g`tiHF@Vn6)7ziBtO+vR1`Cp?Qk?~_*axn@pkr0C~n)qjlt8}>6X zyewp3cs-|@r~7vEwuU#0 z{wBot9X=(n(t%C6=kgTZ2F07(H+neBW@U&sNJ=KmIjI+@bwSQ6G;6IiN6;g6wg~IK zV@Z5l+W+liSTO5Tbj;*LzJsfddn>LO^Mb{kI?YBpw@c2sUu; zu;YC2_rfPjh3_}N6!&XN6j(Rj61w^-jWvR6LfhQ*1AH6iN(d;d_VxeJV|_qW>%eba zhWNj45~Ob0vmfA8nX=>PmVd8aawW8gH2i+;w$<4t0WbILr^ zo&JlPwn>~bpVRPf+j6l}>AdCrl%OU({SQSOd1kz7o^W8!Dl6uF^*IY=yi-E8de22^hq@^SUpBd|)wnyJ$>O9< ves2?6^ zsQ~-(HX_F+WX~B7u@(R6005>IKR6CJx3QV&wBNIRn P00000NkvXXu0mjfe(m5N literal 0 HcmV?d00001 diff --git a/src/main/resources/nameplates/hutao.png b/src/main/resources/nameplates/hutao.png new file mode 100644 index 0000000000000000000000000000000000000000..81e4cd8d5d1e15d79dafd8ab78ba87a86fd88724 GIT binary patch literal 985 zcmV;~119{5P)_W4|WSV%xjhQjq-4+v*C8j1O(+G2z5EEmZ9nNKJEV{rLegFcteYbXG z9W5L$-uAUG{n)#;@t?doZ_aZ*{?9r8=Xs8h;V@aDC^EYNP*sr}lXJ+UVCwX!e0%Jh zthSFf;8>;BzM}pmcG@jjXXPVr#$E(``Lv7UTX7V(mE&7+j#a{F?;-iE(q!1XwAdT_ z8|vkof3IeoR4%yp)MXsTq_2g+i?^BdweZX3MSf`7&-1|4!Xjtxtc&ysB11yS)14dg zl8D@;`POS3_6-0~5{=O8aI*N%G62JE9stfo;$p0?S=wu$|HOo_ z_#5h_zoA}M$96F{)Sh|m8C zz*t|ieE+*^A{vCX@Ddh4xSds^rQcOFQf83KT08OSxl@ETg6yfR0bt?xRn4#!1K{d! zON_nTE$y25F|$wsl{jCzoqqO!JQ}OOZh_Tc1b~qzyKt1l7t5=ZL?aBhdFW|(@xl0y z;{5zg9}a=jUgst9Buzlt$f~c>@{8 z6(+lTceHh?c8ifNp9Gj%{sVxsQV_Pq1t2ffxJ76qC@Hb=-cueX)>im1a8XzcWb#Ww zpeXn|+9isTa;D&zNyJoo54}KdXJ$pdUa1_JSzZYqYoXptL8&d}Haqm>h8K6 zKNX6?JPCVRIUR8BBUGYM327xMRh#rZC+Dw;cfCH@R@cbCxXxy_3j6Hw00000NkvXX Hu0mjfoXzAA literal 0 HcmV?d00001 diff --git a/src/main/resources/nameplates/rabbit.png b/src/main/resources/nameplates/rabbit.png new file mode 100644 index 0000000000000000000000000000000000000000..af5e363e699b551c524333ba4c7165aa95bb6d24 GIT binary patch literal 268 zcmeAS@N?(olHy`uVBq!ia0vp^20$#p!3-qR3wWA=lw^r(L`iUdT1k0gQ7VIDN`6wR zf@f}GdTLN=VoGJ<$y6JlBB21E5Z6B^KL5Y;?fc;`K!N{YVAQhP0mxx13GxdD3ovZn zzhpm9q|VdDF{I+wo=J{;4GKIg)ARoRpT1P!a93`R`1b(McFu&Z#qBYs-9<-E%?H?XPT$|px?H6v@ z=Vu%)3fCl{2R1q@(VyH0Is#VSF=ZCo{B?|gox+|%yEmhVOCZ_0#q-coSiHL(G-RlMS`G2kVF`@a!OdczH9?rg?*-tG@lSvO0RKH4HvrWMvj6}907*qoM6N<$f>eRnQUCw| literal 0 HcmV?d00001 diff --git a/src/main/resources/resources/trident.png b/src/main/resources/nameplates/trident.png similarity index 100% rename from src/main/resources/resources/trident.png rename to src/main/resources/nameplates/trident.png diff --git a/src/main/resources/nameplates/wither.png b/src/main/resources/nameplates/wither.png new file mode 100644 index 0000000000000000000000000000000000000000..663857abcb0996b2d23c87bd5d6b8c4ccc92f49a GIT binary patch literal 636 zcmV-?0)zdDP)5|} zAP95-wf+AeE(2~7lh=c8+e1C&Ez69643y7bKILB#fM$uf z031l|LE!j8Zqj?a8>fM{X8@jVy%7M_iIpb*0LsPz=H)nNwf=rw_$L4 zcwyQr0=t0i8cCA+5`*F|D4uZ8M-{MJWMl<032Y`(6tvd+$*@^~qYNj0?~VFVvP;;% z8WG?ff+!~8nTOQ8EV6eE8@EuZ0^*V9O zIrAuYj17Fi%lM7$8hzjd?KzWar&J)O-}=aD*}BYVm^uG5t z?@pVfWY#&w>vx)YKeRNO?y>Jj?~R%BT@Lm^7yY|G#{W&eZjPZcU#jjrqCn-I@E6DJakNJW1huO)p z%nAaYYgi_{`BTEIP+dBIZtud^RufZyiYG8MBzWqD8az$|dY-}4)z4*}Q$iB}kxk&I literal 0 HcmV?d00001